Skip to content

Latest commit

 

History

20 Commits

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

🏗️ InvoiceForge — Backend Invoice Management Engine

InvoiceForge is a self-hosted invoice management backend API designed for freelancers and small businesses. It enables users to securely manage clients, generate professional invoices with atomic line items, track payment installments, and automatically derive billing statuses.

This project is built using a clean, layered architecture designed to show engineering maturity, secure data modeling, and robust business logic.


🗺️ System Design & Architecture

A request passes through clean, structured layers where each component does exactly one job:

flowchart LR
    Client["Client (Postman / Frontend)"]
    subgraph Server["Node.js + Express API"]
        MW["Middleware (parse, log, auth)"]
        R["Routers"]
        C["Controllers"]
        S["Services"]
        Repo["Repositories"]
        EH["Error handler"]
    end
    DB[("PostgreSQL")]
    FS["File storage"]

    Client -->|"HTTP request"| MW --> R --> C --> S --> Repo --> DB
    S --> FS
    C -.->|"throws error"| EH -.->|"JSON error"| Client
Loading

The Architectural Layers:

  • Router: Maps the URL and HTTP method to the correct controller.
  • Controller: Reads client requests, extracts parameters, delegates to a Service, and formats HTTP responses. Contains zero business logic.
  • Service: Handles business rules, computations (like invoice totals), and transactional safety. Entirely decoupled from HTTP protocol details.
  • Repository: Houses the database queries. The only layer authorized to write SQL queries.

🗄️ Database Relational Model

The database schema enforces strict relational constraints and indexing to optimize queries like filtering by invoice status or client listings.

erDiagram
    USERS ||--o{ CLIENTS : owns
    USERS ||--o{ INVOICES : issues
    CLIENTS ||--o{ INVOICES : receives
    INVOICES ||--o{ LINE_ITEMS : contains
    INVOICES ||--o{ PAYMENTS : records

    USERS {
        uuid id PK
        string email UK
        string password_hash
        string full_name
        string business_name
        timestamptz created_at
        timestamptz deleted_at
    }
    CLIENTS {
        uuid id PK
        uuid user_id FK
        string name
        string email
        string address
        timestamptz created_at
        timestamptz deleted_at
    }
    INVOICES {
        uuid id PK
        uuid user_id FK
        uuid client_id FK
        string invoice_number
        string status
        numeric subtotal
        numeric tax_rate
        numeric total
        string currency
        date issue_date
        date due_date
        string logo_url
        timestamptz created_at
        timestamptz deleted_at
    }
    LINE_ITEMS {
        uuid id PK
        uuid invoice_id FK
        string description
        numeric quantity
        numeric unit_price
        numeric line_total
    }
    PAYMENTS {
        uuid id PK
        uuid invoice_id FK
        numeric amount
        string method
        timestamptz paid_at
    }
Loading

🚦 Project Status & Roadmap

Here is the progress tracker mapping out what is already completed and what will be implemented next:

✅ Phase 1: Project Setup (Completed)

  • Initialized NPM workspace with ESM (ES Modules) support ("type": "module").
  • Set up initial scripts and installed developer dependencies (nodemon, dotenv, express).
  • Built the folder skeleton.
  • Configured Git and created .gitignore to prevent tracking environment secrets.

✅ Phase 2: Express Skeleton (Completed)

  • Separated app configuration (app.js) from server listen execution (server.js) for easier future testing.
  • Integrated morgan for developer-friendly request logging.
  • Created a lightweight /health check routing system.
  • Implemented a clean, graceful shutdown sequence listening for SIGINT/SIGTERM signals.

✅ Phase 3: PostgreSQL Database Setup & Schema (Completed)

  • Configured PostgreSQL 16 via Docker Compose.
  • Implemented database migrations with node-pg-migrate to manage structural changes.
  • Created schemas and primary tables for Users, Clients, Invoices, Line Items, and Payments.
  • Configured cascading deletes and index constraints to keep the database fast and clean.
  • Created a database connection pooling service (pool.js) and database seeding script.

🚀 Upcoming Tasks (In Progress)

🧰 Phase 4: Error Handling & Validation

  • Create typed error classes (NotFoundError, ValidationError, UnauthorizedError).
  • Implement central error-handling middleware to avoid leaking database details to the client.
  • Create an asyncHandler wrapper to forward errors safely without manual try-catch blocks in routes.
  • Integrate Zod validation middleware for boundary checks.

🔐 Phase 5: Authentication & JWT

  • Build bcrypt password hashing helpers.
  • Set up JSON Web Token (JWT) sign and verify middleware.
  • Build /auth/register and /auth/login endpoints.
  • Create a protected /auth/me profile route.

👤 Phase 6: Clients Module

  • Implement full CRUD operations for Clients.
  • Enforce ownership controls so users can only view/edit clients they own.
  • Add pagination, text search (ILIKE), and sorting with allow-lists.

🧾 Phase 7: Invoices & Atomic Transactions

  • Implement multi-table ACID transactions for invoice creation.
  • Compute subtotal, tax, and final totals on the server-side only (never trust client input).
  • Require schemas checking for negative values, empty lists, and invalid dates.

🔄 Phase 8: Invoice State Transitions & Payments

  • Define legal invoice status transitions (e.g. draft ➡️ sent ➡️ paid).
  • Implement partial payment support and automatically transition invoice status to paid or overdue.
  • Freeze invoices from modifications once sent.

📎 Phase 9: File Uploads

  • Implement safe logo image uploading using Multer.
  • Validate uploaded files by magic bytes (content type) instead of extension name only.

🛡️ Phase 10: Security Hardening

  • Add helmet security headers.
  • Set up rate limiters on authentication paths.
  • Perform a full IDOR (Insecure Direct Object Reference) security audit across all routes.

🧪 Phase 11: Automated Testing

  • Set up vitest or jest and write integration tests with supertest.
  • Write unit tests for invoice pricing logic and payment status state transitions.

🚀 Phase 12: Containerization & Cloud Deployment

  • Containerize the app using a multi-stage Dockerfile.
  • Deploy database to a managed cloud database (Railway/Render/Neon).
  • Configure startup migration steps.

🛠️ Tech Stack & Packages Used

  • Web Framework: Express.js
  • Database: PostgreSQL
  • Containerization: Docker Compose
  • Logging & Configuration: Morgan, Dotenv
  • Database Migrations: Node-pg-migrate

About

No description, website, or topics provided.

Resources

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages