Skip to content

Finance

Centralized financial management module for tracking invoices, payments, balances, and transaction history across all platform operations.

Overview

The Finance module provides the administrative team with a unified view of all financial activity on the platform. It consolidates data from shipments, recharges, and adjustments into a single ledger-like system where operators can review balances, generate invoices, process payments, and export financial reports.

Key Concepts

ConceptDescription
BalanceThe current financial state of a customer account (available credit)
TransactionAny financial movement: charge, payment, refund, or adjustment
InvoiceA formal billing document generated from accumulated transactions
PaymentA recorded inflow of funds from a customer (bank transfer, card, etc.)
AdjustmentA manual correction to an account balance (credit or debit)
Billing CycleThe period over which transactions are accumulated before invoicing

Data Flow

Main Flow: Invoice Generation

Main Flow: Payment Registration

Background Flow: Automatic Billing

Backend Structure

Route Files

backend/routes/
└── finance/
    ├── invoices.js      # Invoice CRUD and generation
    ├── payments.js       # Payment registration and history
    ├── transactions.js   # Transaction listing and filters
    ├── balances.js       # Balance queries and adjustments
    └── reports.js        # Financial report exports

Service Layer

backend/services/
└── finance/
    ├── invoiceService.js       # Invoice generation logic
    ├── paymentService.js       # Payment processing
    ├── transactionService.js   # Transaction recording
    ├── balanceService.js       # Balance calculations
    └── reportService.js        # Report generation (Excel/PDF)

Background Jobs

JobQueueScheduleDescription
generateMonthlyInvoicesfinance-billing1st of month, 6:00 AMAuto-generates invoices for all customers with monthly billing
sendPaymentReminderfinance-notificationsDaily, 9:00 AMSends reminders for overdue invoices
reconcileBalancesfinance-maintenanceWeekly, Sunday 2:00 AMVerifies balance consistency across transactions

Validation Schemas

All request payloads are validated with Joi. Schemas are located in:

backend/schemas/
└── finance/
    ├── invoiceSchema.js
    ├── paymentSchema.js
    └── transactionSchema.js

Database

Tables

TablePurpose
invoicesInvoice headers (customer, dates, totals, status, PDF URL)
invoice_itemsLine items within an invoice (description, amount, tax)
paymentsPayment records (customer, amount, method, reference)
transactionsFinancial ledger: all movements with type, amount, and balance snapshot
customer_balancesDenormalized current balance per customer (updated on each transaction)
billing_configsPer-customer billing settings (cycle, payment terms, tax rules)

Entity Relationship

Key Fields

transactions

ColumnTypeDescription
idINT (PK)Auto-increment
customer_idINT (FK)Reference to customers
typeENUMcharge, payment, refund, adjustment
amountDECIMAL(12,2)Transaction amount (positive = debit, negative = credit)
balance_afterDECIMAL(12,2)Customer balance snapshot after this transaction
reference_typeVARCHARSource entity type (shipment, recharge, manual)
reference_idINTSource entity ID
invoice_idINT (FK, nullable)NULL until billed
descriptionVARCHARHuman-readable description
created_atDATETIMETransaction timestamp
created_byINT (FK)Admin user who created it

invoices

ColumnTypeDescription
idINT (PK)Auto-increment
customer_idINT (FK)Reference to customers
invoice_numberVARCHARSequential invoice number (e.g., INV-2026-001234)
statusENUMdraft, issued, paid, overdue, cancelled
subtotalDECIMAL(12,2)Sum before taxes
tax_amountDECIMAL(12,2)Tax amount
totalDECIMAL(12,2)Final amount
pdf_urlVARCHARS3 URL to the generated PDF
issued_atDATETIMEWhen the invoice was issued
due_dateDATEPayment due date
paid_atDATETIME (nullable)When fully paid

Key Decisions

DecisionReasoningAlternatives Considered
Denormalized customer_balances tableAvoids recalculating balance from all transactions on every query. Updated transactionally with each new transaction.Calculated view (too slow for dashboards), Redis cache (consistency risk)
balance_after snapshot in transactionsEnables audit trail and debugging without recalculating from history. Critical for financial accuracy.Only storing deltas (harder to debug, requires full scan for balance at point in time)
Separate invoice_items tableInvoices can contain items from different sources (shipments, adjustments). Flexible line-item structure.Storing items as JSON in invoices (loses queryability)
Bull queue for billing jobsMonthly billing can process thousands of customers. Queue provides retry logic, failure handling, and monitoring via Arena.Cron-only (no retry, no monitoring), external service (unnecessary complexity)
PDF stored in S3Invoices are legal documents that must be preserved as-is. S3 provides durability and CDN-ready URLs.Database BLOB (expensive, slow), filesystem (not scalable)

Dependencies

  • Internal: Shipments module (generates charges), Customers module (account data), Auth module (admin permissions)
  • External: AWS S3 (PDF storage), Mailgun (invoice emails), Excel4node (report generation)

Envia Admin