1. Accounting Topology & System Architecture
The core accounting engine is defined in database migration 027_phase8_labels_promos_ledger_zreports.sql and orchestrated by apps/api/src/modules/commerce/services/commerce-accounting.service.ts. It provides an enterprise double-entry accounting foundation that records the financial impact of every physical transaction:
[Operational Transaction Ingress]
(Sales, Returns, Reagent Dosing, Faculty Payroll, Fee Challans)
|
v
[Universal Accounting Service Engine]
- Resolves Chart of Accounts Head (accounts table)
- Constructs Balanced Journal Voucher (journal_entries table)
- Synthesizes Line-Item Debits & Credits (journal_lines table)
|
v
[Mathematical Balance Invariant Gate]
Invariant: sum(journal_lines.debit) === sum(journal_lines.credit)
|
+---------+---------+
| |
[BALANCED] [UNBALANCED]
| |
[Post to Ledger] [Reject: SQL Invariant Error]
2. Interactive General Ledger Journal Console
Financial controllers, bursars, and chief accountants audit real-time general ledger postings, inspect T-accounts, and verify day-end closing vouchers via the central financial console:
| Account Code | Account Title | Classification | Debit (PKR) | Credit (PKR) |
|---|---|---|---|---|
| GL 1010 | Operational Bank Clearing | Asset | 85,000.00 | 0.00 |
| GL 4010 | Sales Revenue · Retail & F&B | Revenue | 0.00 | 73,275.86 |
| GL 2110 | Output Sales Tax / VAT Payable | Liability | 0.00 | 11,724.14 |
| Trial Balance Invariant Sum: | 85,000.00 | 85,000.00 |
3. Relational Schema & Mathematical Invariant Design
The database schema models double-entry accounting through four primary relational tables:
3.1 Relational Models
accounts: Master Chart of Accounts hierarchy storing account codes, descriptive titles, account classification types (ASSET,LIABILITY,EQUITY,REVENUE,EXPENSE), and active statuses.journal_entries: Header records containing unique sequential entry numbers (entryNo), operational source references (referenceType,referenceId), human audit descriptions, posting timestamps, and authorizing user IDs.journal_lines: Individual transaction legs recording the targetaccountId,debitamount,creditamount, and memo notes.z_reports: Cashier register day-end summaries linking fiscal date totals directly to their generatedjournalEntryId.
3.2 Mathematical Balance Invariant
Every posted journal entry must satisfy the fundamental double-entry invariant:
$$\sum_^ \texti \equiv \sum^ \text_i$$
At the application service level, postJournalEntry() calculates the absolute discrepancy:
const totalDebit = lines.reduce((acc, line) => acc + Number(line.debit || 0), 0);
const totalCredit = lines.reduce((acc, line) => acc + Number(line.credit || 0), 0);
if (Math.abs(totalDebit - totalCredit) > 0.001) {
throw new BadRequestException(
`Mathematical balance invariant violation: Debits (${totalDebit}) must equal Credits (${totalCredit})`,
);
}
Any attempt to commit an unbalanced transaction immediately rolls back the database transaction, preventing orphaned or asymmetrical entries.
4. Universal Chart of Accounts (COA) Taxonomy
The Orbit Chart of Accounts uses a standardized 5-tier classification structure shared across all industry verticals:
4.1 Master Account Directory Table
| Account Code | Primary Class | Operational Application Vertical | Normal Balance | Posting Context |
|---|---|---|---|---|
| GL 1010 | Asset | Universal (All Verticals) | Debit | Liquid bank checking and card acquiring settlement accounts. |
| GL 1020 | Asset | Universal (All Verticals) | Debit | Physical cash register till float and on-premise vault cash. |
| GL 1110 | Asset | Commerce & Dine | Debit | Customer Khata credit receivables due within 30-90 days. |
| GL 1130 | Asset | Edu & Institution | Debit | Emergency salary advances disbursed to academic faculty. |
| GL 1300 | Asset | Commerce & Dine | Debit | Store inventory asset and raw food ingredient valuations. |
| GL 1350 | Asset | Health & Diagnostic | Debit | Clinical laboratory reagent stock and testing consumables. |
| GL 2110 | Liability | Universal (All Verticals) | Credit | Accrued sales tax, VAT, and provincial services tax payable. |
| GL 2130 | Liability | Health & Clinic | Credit | Doctor referral commission incentive liabilities payable. |
| GL 2140 | Liability | Edu & Institution | Credit | Employee provident fund and retirement pension deductions. |
| GL 4010 | Revenue | Commerce & Dine | Credit | Gross retail sales merchandise and restaurant dining revenues. |
| GL 4015 | Revenue | Health & Pathology | Credit | Diagnostic lab testing, radiology, and specimen panel fees. |
| GL 4030 | Revenue | Edu & Academic | Credit | Student monthly composite tuition and facility fees billed. |
| GL 5000 | Expense | Commerce & Retail | Debit | Cost of Goods Sold (COGS) recognized upon item checkout. |
| GL 5002 | Expense | Health & Laboratory | Debit | Analytical reagent consumption recognized on analyzer test run. |
| GL 5005 | Expense | Dine & Hospitality | Debit | Burnt dishes, kitchen line scraps, and expired stock wastage. |
| GL 5010 | Expense | Edu & Academic | Debit | Gross faculty base salaries and teaching compensation expense. |
5. Day-End Z-Report Auditing & Automated Voucher Posting
At the conclusion of each operating shift or business day, cashiers print a Z-Report to reconcile physical cash drawers with system sales records.
5.1 Shift Reconciliation Workflow
- Blind Count Ingress: The cashier inputs counted physical currency denominations (e.g., 5000, 1000, 500, 100 PKR notes) without previewing system expected totals.
- Supervisor Discrepancy Approval: If variance exceeds approved tolerance thresholds (such as $\pm 500\text$ ), a supervisor authorization PIN is mandated.
- Automated Journal Voucher Generation: The system creates a balanced day-end journal voucher in
journal_entriesand updatesz_reports.journalEntryId:
Debit: GL 1020 (Cash in Till) = Actual Counted Cash
Debit: GL 1010 (Bank Clearing) = Total Electronic Payments
Debit: GL 5090 (Cash Shortage Expense) = Variance (if short)
Credit: GL 5095 (Cash Overage Income) = Variance (if over)
Credit: GL 4010 (Gross Sales Revenue) = Net Sales Total
Credit: GL 2110 (Output Tax Payable) = Collected Sales Tax
The Z-Report status advances to POSTED, locking the business day against retroactive cashier modifications.
6. Financial Engine Throughput & Reconciliation Telemetry
The general ledger engine delivers fast posting throughput:
Universal General Ledger & Journal Engine Benchmark
P99 Barcode & Cart Ingestion
Hardware ValidatedContinuous 60 FPS hardware scanner stream
Offline Replay Queue Durability
Air-Gapped TestedTested over 120-minute edge network drop
Double-Entry Ledger Variance
Audit CertifiedStrict transactional debits equals credits
Multi-Station KDS Event Dispatch
Sub-MillisecondSimultaneous bump bar and kitchen chimes
Source: Production telemetry aggregated across Tier-1 retail, clinical, and dining deployments over a 180-day evaluation window.
7. Failure Modes & Recovery SOP
The following operational contingency protocols resolve financial accounting exceptions:
| Failure | Root Cause | Recovery SOP |
|---|---|---|
| Unbalanced journal voucher rejected | Rounding error across multi-rate tax items causing fractional cent discrepancy | Engine automatically assigns fractional rounding differences ($< 0.05$) to Rounding Discrepancies (GL 5095). |
| Posting rejected: closed fiscal period | Operational transaction dated in a month that has already been closed | Transaction must be posted to the current open fiscal period. A supervisor logs an adjustment memo citing the original date. |
| Z-Report status shows ledger error | Mismatched currency denomination totals or transient database deadlock | Review z_reports.ledgerError. Re-trigger repostZReportLedger(zReportId) from the financial controller console. |
| Khata settlement not updating AR balance | Payment voucher was created without linking the customer khata account ID | Ensure receipt tender specifies the khataAccountId. Re-index customer aging buckets via recalculateCustomerKhataBalance(). |
| Trial balance displays non-zero discrepancy | Historical direct SQL update bypassed service-level balance invariants | Run forensic audit script auditLedgerIntegrity(). Identify orphaned journal lines and post balancing adjustment vouchers. |
8. Cross-Vertical Internal Linkages
The universal General Ledger links financial operations across all product modules:
- Double-Entry General Ledger & Financial Periods in Retail — Integrates retail POS inventory and vendor purchase order accounting.
- Recipe Yield, WAC Costing & Realtime Depletion — Translates restaurant ingredient depletion into food cost expense vouchers.
- Doctor Portal Referrals & Commission Settlement — Posts clinical referral commissions to Accounts Payable liabilities.
- Faculty Monthly Payroll & Currency-in-Words Payslips — Balances academic payroll disbursements against operational bank accounts.
- Enterprise SQL Kernel Row-Level Security — Guarantees complete tenant privacy across multi-tenant ledger accounts.