@companyio/accounting
v0.2.2
Published
Reusable accounting domain package for multi-tenant business applications
Readme
@companyio/accounting
Installable double-entry General Ledger for multi-tenant CompanyIO products (Fuel, POS, School, ERP).
Accounting owns the financial truth. Operational packages own business documents and post through adapters.
Sales / Purchasing / Payments / Expenses / HR / Fuel
↓
accounting adapters (domain packages)
↓
@companyio/accounting
↓
Chart of Accounts → Journal → Journal Lines → ReportsThis package does not create a second database or its own Prisma Client. The host owns PostgreSQL, DATABASE_URL, schema composition, migrations, auth, and tenant context.
What Accounting owns
| Owns | Does not own | | --------------------------------- | ------------------------------ | | Chart of accounts (one GL) | Invoices, POs, bills, stock | | Journals + balanced lines | Customers/suppliers masters | | Parties (AR/AP control links) | Fuel tanks/meters/dips | | Reversals + idempotency | Payment infrastructure | | Trial balance / P&L / BS / ledger | Tax engines, multi-currency FX | | Fiscal periods (open/close) | Product-specific ledgers |
Domain adapters (outside this package)
Adapters live in the domain packages, not here:
| Domain | Adapter | Typical effect |
| ---------- | ----------------------------------------------------------------- | --------------------------------- |
| Sales | createAccountingSalesAdapter | Dr AR / Cr Revenue; payment Cr AR |
| Purchasing | createAccountingPurchasingAdapter | Dr Expense/Inventory / Cr AP |
| Payments | createAccountingPaymentsAdapter | Cash/Bank ↔ AR/AP |
| Expenses | createAccountingExpensesAdapter | Approve AP; pay cash |
| HR | createAccountingHRAdapter | Salary / payable |
| Fuel | posts via Sales/Payments/Purchasing/Expenses or operations.post | Never owns a FuelLedger |
One business event → one journal (idempotency key). Do not also post the same cash/AR effect from Sales and Payments for the same payment.
Inventory owns quantity and WAC. COGS / adjustment journals are posted by the Inventory→Accounting adapter (createAccountingInventoryAdapter) when hosts wire it — not by recalculating cost inside Accounting. Account roles (Inventory Asset, COGS, stock-loss expense, stock-gain income) resolve via resolveInventoryPostingAccounts from seeded STANDARD_CHART_CODES or OperationalAccountMapping overrides (ACTIVE + type + tenant checks; no silent substitutes).
Money
Major currency units, 2 decimal places, rounded via integer cents (toCents / roundMoney / addMoney).
Standard chart codes
STANDARD_CHART_CODES (seeded by accounts.seedDefaults):
1110 Cash · 1120 Bank · 1200 AR · 1300 Inventory · 2100 AP · 2200 Tax Payable
4100 Sales · 5100 COGS · 6600 Operating expense · …Adapters resolve accounts by code, not hard-coded UUIDs.
Install
pnpm add @companyio/accounting
pnpm exec accounting init --schema apps/api/prisma/schema.prisma
pnpm --filter @companyio/api exec prisma migrate deploy --config prisma7.config.ts
pnpm prisma generateFastify
attachAccounting(app, {
prisma,
prefix: '/api/v1/accounting',
authenticate: async (request) => getUser(request),
getContext: (_request, user) => ({
main_business_id: user.main_business_id,
branch_id: user.branch_id,
user_id: user.id,
}),
});Tenant ids come from the session. Books are not shared across branch_id values of the same business.
Posting
await accounting.journals.post(context, {
entryType: 'CREDIT_SALE',
sourceModule: 'sales',
referenceId: invoiceId,
transactionDate: '2026-09-21',
description: invoiceNumber,
idempotencyKey: `sales:invoice:${invoiceId}`,
lines: [
{ accountId: ar.id, debit: 1000, credit: 0 },
{ accountId: revenue.id, debit: 0, credit: 1000 },
],
});Invariants:
Σ debit = Σ creditor rejectUNBALANCED_JOURNAL- Posted journals are immutable; corrections use reversal
- Inactive accounts cannot receive new posts
- Closed periods reject posts
- Idempotent retries return the same journal
Operational shortcut: POST /post / operations.post with kinds (cash_sale, credit_sale, payment, expense, …) and opaque sourceModule.
Reports
GET /reports/trial-balance · /pnl · /balance-sheet · /receivables · /payables · ledger · party statement — all derived from posted journals.
Frontend adapter
The browser UI ships from client-safe subpaths — never import the package root in a bundle:
@companyio/accounting/client— HTTP client + view-model contracts (createAccountingApi), including operational posting contracts (OPERATIONAL_KINDS,OperationalEvent).@companyio/accounting/react—AccountingProvider, hooks, Platform-UI pages,accountingQueryKeys, andAccountingHostExtensions.@companyio/accounting/operational— deprecated alias of the client operational contracts only. Prefer/client. Server posting (OperationalPostingService,operationalEventSchema) stays on the package root.
A host wires three things and renders the shared pages (each page draws its own AccountNav):
// 1. createApi — map the host's authed requester into the package contract
const api = createAccountingApi({
request: async (path, init) => myAuthedJson(path, init), // throws AccountingApiError on failure
basePath: '/accounting',
});
// 2. Provider — api + presentation config + host extensions
<AccountingProvider
api={api}
config={{
currencyDisplay: 'PKR',
costOfGoodsLabel: 'Cost of fuel', // product wording for COGS
routesBase: '/accounts',
canEditBooks, // host RBAC gate for post/seed/pay
capabilities: { periods: false }, // optional section toggles (default: all on)
journalProcessOptions, // optional per-product process labels
}}
extensions={{
// 3. extensions — things outside the accounting HTTP surface. Omit a callback to hide its UI.
listExpenseJournalLinks, // collapse expense recognition + payment legs
listSupplierPayments, // host /payments read for Payables
createSupplierPayment, // host /payments write for "Pay"
onBooksChanged, // optional: invalidate host `['accounts']` (or similar) caches
}}
>
<AccountsListPage documentTitle="Chart of accounts" />
</AccountingProvider>;Income statement COGS is IncomeStatementView.costOfGoods; product wording is only the
costOfGoodsLabel config (e.g. Fuel: "Cost of fuel").
Operational journals keep the host's sourceModule and idempotency scheme, so hosts post via
their own helper (e.g. postAccountingEvent) rather than the generic POST /accounting/post.
Host screens that live outside the provider can call createAccountingApi(...) directly as a thin
service facade. Prefer onBooksChanged (or dual-invalidate accountingQueryKeys.all from host
mutations) so package and host caches stay aligned.
Canonical UI labels (shared screens): Chart of accounts, Add account, Add journal entry, Reverse journal, Add payment (Payables). Prefer these over product-specific synonyms for the same actions.
Reference adapters: ContractFlow (products/contractflow/frontend/src/features/accounts) and Fuel
Management (products/fuel-management/frontend/src/features/accounts).
API Routes
Mounted at /api/v1/accounting. Full detail: docs/API_ROUTE_INVENTORY.md.
| Method | Route | Auth | Purpose | | -------------- | ----------------------------- | ------- | ------------------------- | | GET | /accounting/health | Public | Health | | GET/POST/PATCH | /accounting/accounts… | Session | Chart of accounts | | GET | /accounting/ledger/:accountId | Session | Ledger | | GET/POST | /accounting/journal… | Session | Journals (+ reverse) | | GET | /accounting/transactions… | Session | Transactions | | GET/POST | /accounting/parties… | Session | AR/AP parties | | GET | /accounting/reports/* | Session | TB, P&L, BS, AR/AP, recon | | GET/POST | /accounting/periods… | Session | Fiscal periods | | POST | /accounting/seed-defaults | Session | Seed chart | | POST | /accounting/opening-balance | Session | Opening balance | | POST | /accounting/post | Session | Operations post |
Known gaps
- Multi-currency FX and tax calculation engines are deferred (single-currency practice).
- Inventory COGS journals: use
@companyio/inventorycreateAccountingInventoryAdapter(operational kindcogs), keyed by movement id. - Explicit non-postable COA header accounts not enforced separately from seed defaults.
- Host production migrate verification remains the app owner’s responsibility (
apps/api).
Build / test
pnpm --filter @companyio/accounting test
pnpm --filter @companyio/accounting buildPackage tests cover posting invariants, adapters, fiscal periods, CLI init, and HTTP routes with session-scoped tenant isolation (in-memory store).
