@dzayr/accounting
v0.0.11-alpha.2
Published
Effect-native, transaction-scoped double-entry accounting SDK
Readme
@dzayr/accounting
Effect-native accounting SDK. This package is currently in alpha (0.0.11-alpha.1). Distribution rights are not yet specified (UNLICENSED in package metadata); resolve licensing before external distribution.
For setup and integration from a consumer application, see the consumer app integration guide.
Boundaries
- Accounting-only: company books, chart of accounts, generic journals with optional manual transaction-currency annotations, line dimensions, budgets, posting, reversals, receivable invoices, payable bills, cash receipts, supplier payments, posting-period close, accruals, finite deferral schedules/releases, fixed-asset registration/depreciation/disposal, reciprocal intercompany mappings and paired journals, same-currency consolidated reports and manual elimination worksheets, and audit.
- Callers provide the Drizzle PostgreSQL transaction. The SDK never opens, commits, or rolls it back.
- The host application owns authentication and authorization policy.
- No inventory or payroll domain models are included. External systems may submit generic accounting postings.
- The SDK exposes append-only journal, document, settlement, period-close, accrual, deferral-schedule, fixed-asset lifecycle, dimension type/value/assignment, budget, intercompany mapping/pair, installment, release, and audit records. Reversals are new entries except fixed-asset lifecycle journals, which require an asset-level correction workflow not yet provided; intercompany pair reversals remain caller-managed and are not automatic. Consolidation worksheets are ephemeral and never post or persist adjustments. Functional amounts, manual transaction-currency annotations, budget amounts, and intercompany pair amounts are exact decimal strings, never JavaScript floating-point values. A book's functional currency is immutable. Apply the supplemental SQL guards to enforce these invariants against direct database writes.
Generic-journal transaction-currency annotations
Ledger.postJournal optionally accepts one transactionCurrency and a positive exact-decimal functionalPerTransactionUnit rate (functional-currency units per one transaction-currency unit). When present, every line supplies exact transactionAmounts.debit and transactionAmounts.credit; each line is one-sided, and native debits and credits must balance independently of the functional debit/credit amounts.
These are caller-supplied manual annotations only. Functional debit/credit remains canonical for posting and all reports. The SDK does not convert or round amounts, calculate native values from the rate, validate a mathematical relationship between the rate/native amounts and functional amounts, or post FX gains/losses. The annotation is limited to generic journals; receivable/payable documents, customer receipts, supplier payments, accruals, deferrals, and fixed-asset workflows continue to use the book's functional currency. This release has no foreign-currency subledger, settlement, or conversion policy.
Localized charts and Algeria SCF profile
Ledger.applyChartProfile installs a versioned profile into a book, with parent/child account hierarchy, English-default base names, en/fr/ar labels, a profile hash, and an audit event. The dz-scf-general starter profile requires a book created with framework: "dz-scf" and functionalCurrency: "DZD". Reapplying the same profile is idempotent; conflicting account codes or a different installed profile version return typed errors rather than silently merging or changing accounts. Use Ledger.setAccountLabel with a locale key (en, fr, or ar) to add or update a localized label, and parentAccountId when creating a custom subaccount.
The included chart is a starter hierarchy of SCF classes 1–7 and representative accounts, not the complete statutory catalogue. French titles are based on the Algerian Official Journal, issue 19 of 25 March 2009; Arabic labels are SDK-maintained translations, not official legal text. This profile is for general entities, not regulated banks; banking institutions have a separate chart regulation (Official Journal, issue 64 of 25 September 2025). No inventory or payroll subledger workflows are included.
Localization
The SDK uses language keys en, fr, and ar; omitted locale options default to English. Static display, generated journal-text, typed-error, and SCF profile translations are exported as constant maps through TRANSLATIONS (and algeriaScfTranslations). Use translateDisplayMessage and translateJournalMessage for host presentation, and getLocalizedErrorMessage(error, localeKey) for a safe translated error message without exposing raw causes. Machine tags and structured error fields remain stable. Optional localeTag command fields on reports, budget comparison, and journal-generating workflows accept only these three keys. Report and budget account-name lookup defaults to the canonical en label; if a marked dz-scf-general book has no English row (including a v1 installation), it uses the built-in English SCF name before falling back to accounts.name. French and Arabic lookup can read historical fr-DZ/ar-DZ labels, while new label writes use canonical keys. Caller-provided names, descriptions, reasons, references, and memos are never translated; only SDK-generated text is localized.
Accounts receivable
Receivables.issueReceivableInvoice issues an invoice immediately: it stores an immutable invoice register and posts a matching balanced journal entry using the same caller-owned transaction. The command takes a host-supplied opaque customerReference and invoice number, an asset/debit receivables-control account, and one or more income/credit allocations. Invoice currency is the book's functional currency; amounts are exact decimal strings. Equivalent decimal spellings normalize for idempotency; reusing a key with changed invoice content or actor identity returns a typed conflict. Invoice numbering and customer identity remain host-owned.
This is an invoice register, not a complete customer balance, statement, or aging API: generic journal postings can also use the selected control account. Customer receipts and invoice allocations are provided separately by CashAndBank. Invoices are never edited in place. A full general-ledger reversal can use Ledger.reverseJournal, but the invoice remains in the immutable issued register and this release does not mark it void/reversed; follow its linked journal entry. Customer master/CRM data, draft workflows, partial credits, transaction tax calculation/determination, and foreign currency are intentionally excluded. Concurrent duplicate requests serialize under PostgreSQL's default READ COMMITTED isolation. With REPEATABLE READ or SERIALIZABLE, callers must retry the entire host-owned transaction after serialization or unique-key conflicts; the SDK never retries or manages transactions.
import { Effect } from "effect";
import { Receivables } from "@dzayr/accounting";
await db.transaction(async (transaction) => {
await Effect.runPromise(
Effect.gen(function* () {
const receivables = yield* Receivables;
return yield* receivables.issueReceivableInvoice(transaction, command);
}).pipe(Effect.provide(Receivables.layer)),
);
});Accounts payable
Payables.recordPayableBill records a supplier bill immediately and posts a matching balanced journal entry through the same caller-owned transaction. The host supplies an opaque supplierReference, vendor bill number, liability/credit payables-control account, and debit allocations to asset or expense accounts. Bill numbers are unique per supplier reference and book. Bills use the book's functional currency, positive exact decimal strings, and canonicalized idempotency; changed bill content or actor identity on a reused key returns a typed conflict. Supplier identity and bill numbering remain host-owned.
This is an immutable bill register, not a complete supplier balance or aging API: generic postings can also use the selected control account. Supplier payments and bill allocations are provided separately by CashAndBank. Full GL reversals do not change the bill register. No supplier master/CRM data, payment batching, tax, FX, inventory quantities/products/stock, or payroll models are included. Concurrent duplicate requests serialize under PostgreSQL's default READ COMMITTED isolation. With REPEATABLE READ or SERIALIZABLE, callers must retry the entire host-owned transaction after serialization or unique-key conflicts; the SDK never retries or manages transactions.
import { Effect } from "effect";
import { Payables } from "@dzayr/accounting";
await db.transaction(async (transaction) => {
await Effect.runPromise(
Effect.gen(function* () {
const payables = yield* Payables;
return yield* payables.recordPayableBill(transaction, command);
}).pipe(Effect.provide(Payables.layer)),
);
});Cash and bank settlements
CashAndBank.recordCustomerReceipt records a receipt allocated to one or more issued invoices; recordSupplierPayment records a supplier payment allocated to one or more recorded bills. Each operation posts an immutable, balanced entry in the same caller-owned transaction: debit the selected cash/bank asset and credit receivables for receipts; debit payables and credit cash/bank for supplier payments. The host selects the cash/bank chart account and supplies the receipt number or payment reference. Each settlement is denominated in the book's functional currency, and each allocation is an exact decimal amount.
Each receipt/payment total is the exact sum of its allocations, so no unapplied cash is accepted; an individual invoice/bill may be paid partially or in full. Allocations must match the source party and control account. The SDK rejects duplicate allocations, allocations dated before the source document, and cumulative allocations exceeding a document's total. Reused idempotency keys are actor- and content-bound. This is not a complete customer/supplier balance or statement: generic journal postings can also affect control-account balances. Advances, bank transfers, bank-account/IBAN master data, statement imports/reconciliation, foreign currency, and payments outside issued invoices/bills are excluded. Concurrent settlements serialize on the book under PostgreSQL's default READ COMMITTED. A versioned book write forces stale REPEATABLE READ/SERIALIZABLE transactions to fail rather than commit an over-allocation; the host must retry the entire transaction after serialization or unique-key conflicts. The database role used for settlement writes must be allowed to update the internal accounting_books.settlement_lock_version column. The SDK never owns or retries the transaction.
import { Effect } from "effect";
import { CashAndBank } from "@dzayr/accounting";
await db.transaction(async (transaction) => {
await Effect.runPromise(
Effect.gen(function* () {
const cashAndBank = yield* CashAndBank;
return yield* cashAndBank.recordCustomerReceipt(transaction, command);
}).pipe(Effect.provide(CashAndBank.layer)),
);
});Financial reports and tax-account summary
Reports.trialBalance, incomeStatement, balanceSheet, and taxAccountSummary are read-only methods that use the caller's Drizzle transaction. Each report runs as one account-grained query over posted journal entries and lines. Trial balance and balance sheet are inclusive as of asOfDate; income-statement and tax-account movements use inclusive fromDate/toDate accounting-date bounds. Reversal entries are included on their own accounting date. Trial balance returns gross movements and closing debit/credit balances. Statement signs follow account class (assets/expenses debit minus credit; liabilities/equity/income credit minus debit), so contra balances remain negative. Amounts are exact decimal strings in the book's functional currency; accounts are reported individually, without parent-account rollups. Every report command accepts an optional localeTag (en, fr, or ar); when supplied, account names use that book's matching account label and fall back to the stored base name when no translation exists. Omitted locale defaults to English. Budgets.compareBudgetToActual uses the same locale-aware account-name lookup.
The balance sheet reports unclosedEarnings: cumulative income less expenses still held in P&L accounts through the as-of date. It does not infer a fiscal year or closing policy. Tax-account summaries use only caller-selected, debit-normal asset accounts (recoverable tax) and credit-normal liability accounts (tax payable), and return their movements inside the requested date range. netTaxPosition is totalRecoverable - totalPayable for those selected period movements; it is not a closing tax balance or tax-return calculation. The SDK does not define tax codes or rates, calculate transaction tax, determine tax treatment, or prepare statutory returns; tax postings remain host-defined ledger entries.
import { Effect } from "effect";
import { Reports } from "@dzayr/accounting";
await db.transaction(async (transaction) => {
await Effect.runPromise(
Effect.gen(function* () {
const reports = yield* Reports;
return yield* reports.trialBalance(transaction, command);
}).pipe(Effect.provide(Reports.layer)),
);
});Intercompany and consolidation
Intercompany.createIntercompanyMapping creates an immutable mapping local to one accounting book, with a distinct counterparty legal entity/book and local debit-normal asset due-from and credit-normal liability due-to accounts. Create reciprocal mappings in both books before recording a pair. Intercompany.recordIntercompanyJournalPair posts two ordinary balanced journals plus an immutable pair record through the same caller-owned transaction. Both legs must use the reciprocal mappings, share the accounting date and actor, and contain exactly one complementary mapped control line for the same positive functional-currency amount. Pair legs do not accept the generic journal's transaction-currency annotations. The host authorizes both entities and owns commit/rollback; deferred SQL guards reject partial or mismatched pair records. Reversals remain caller-managed and are not paired automatically.
Reports.consolidatedTrialBalance requires an explicit, nonempty, duplicate-free list of { companyId, bookId } members. Every selected book must exist and use the same functional currency before activity is aggregated. The report returns detail per company/book/account and exact overall totals; equal account codes remain separate because this release has no group chart or account crosswalk.
Reports.eliminationWorksheet accepts caller-authored, balanced, one-sided manual adjustment lines scoped to active, postable leaf accounts in the selected books. It returns unadjusted results, the supplied adjustments, and adjusted detail/totals using exact decimal arithmetic. The worksheet is read-only and ephemeral: it does not persist adjustments, post journals, calculate automatic eliminations, or translate currencies. This release has no ownership tree, persisted consolidation group, automatic FX translation, or account-code rollup.
Period close, accruals, and deferrals
Ledger.closeAccountingPeriod is a one-way open → closed posting cutoff with immutable close metadata and an audit event. It does not generate a P&L-to-retained-earnings closing journal; reports continue to show unclosed earnings. The host decides when to close a period, and subsequent postings dated in it are rejected.
Accruals.recordAccrual posts a two-line expense or revenue accrual with a required future reversalDate. Accruals.reverseAccrual uses the date stored with that accrual, so callers cannot silently change the planned reversal date; the reversal still requires an open accounting period. Accrual entries and their reversal metadata are immutable and idempotent.
Deferrals.createDeferralSchedule posts the initial expense or revenue reclassification and stores a finite schedule supplied by the caller. Each installment has an exact amount and accounting date, and the schedule total must equal the sum of its installments. Deferrals.releaseDeferralInstallment posts only the stored installment amount and date; each installment can be released once, with idempotent retries. The SDK does not generate schedules, round residuals, or run a scheduler/background job: the host decides when to call each release operation and must provide an open period for each posting. All operations use the caller-provided transaction; authentication and authorization remain host responsibilities.
Fixed assets
FixedAssets.registerFixedAsset posts acquisition cost as a debit to a debit-normal asset account and a credit to a different active, postable leaf offset account in the same book. The offset account may be an expense account for capitalization adjustments. Registration stores an immutable asset reference, acquisition date, in-service date, account mappings, exact acquisition cost and residual value, and useful-life months. The host owns asset identity, authorization, and the transaction.
FixedAssets.createDepreciationSchedule stores a finite, nonempty schedule explicitly supplied by the caller. Installment amounts must be positive exact decimals whose sum equals acquisition cost minus residual value; dates must be on or after the in-service date. The SDK sorts and stores the schedule but does not choose a depreciation method, calculate or prorate amounts, round residuals, or generate future installments. usefulLifeMonths is descriptive input and is not used to calculate the schedule.
FixedAssets.releaseDepreciationInstallment accepts an asset and stored installment identifier only. It posts the persisted amount and date to debit depreciation expense and credit accumulated depreciation; each installment can be released once. FixedAssets.disposeFixedAsset performs one full disposal per asset, deriving accumulated depreciation only from posted installment releases. It posts the proceeds (if positive), gain or loss, accumulated depreciation, and gross asset cost; disposal accounting date must be on or after the latest released installment. Proceeds use a debit-normal asset account distinct from the gross asset account; gain and loss accounts use credit-normal income and debit-normal expense roles respectively. Generic Ledger.reverseJournal rejects fixed-asset lifecycle entries because this release has no asset-level reversal or correction workflow.
All fixed-asset commands use the caller-owned Drizzle transaction and host-owned authentication/authorization. There is no depreciation scheduler, partial disposal, impairment, tax/FX calculation, inventory, or payroll workflow. Apply the supplemental SQL guards for database-enforced lifecycle, journal mapping, release, disposal, reversal, and append-only invariants.
import { Effect } from "effect";
import { FixedAssets } from "@dzayr/accounting";
await db.transaction(async (transaction) => {
await Effect.runPromise(
Effect.gen(function* () {
const fixedAssets = yield* FixedAssets;
return yield* fixedAssets.registerFixedAsset(transaction, command);
}).pipe(Effect.provide(FixedAssets.layer)),
);
});Schema synchronization
The package exports Drizzle tables from @dzayr/accounting/schema; generated migration files are not committed or shipped. The host owns database DDL. To push the Drizzle schema directly to a development database, set DATABASE_URL and run:
DATABASE_URL='postgres://user:password@localhost:5432/accounting' pnpm db:pushdrizzle-kit push applies tables, indexes, and declared constraints. The supplemental trigger guards in sql/postgres-guards.sql are not represented in Drizzle metadata; run that script as a standalone operation after the push for database-enforced book functional-currency immutability, journal transaction-currency metadata and native-balance integrity, functional-currency balancing, posting eligibility, account hierarchy, period overlap/close safety, accrual, deferral, fixed-asset journal mappings, schedule totals/dates, release and disposal integrity, lifecycle reversal protection, installment sums and release dates, invoice/bill/receipt/payment-to-journal and allocation integrity, settlement over-allocation safety, same-book dimension assignment and reversal integrity, budget scope and same-transaction line integrity, intercompany mapping scope/account roles and paired-entry/control-line integrity, and protection against UPDATE, DELETE, or TRUNCATE on ledger, period-close, accrual, deferral, fixed-asset, receivable, payable, settlement, dimension, budget, intercompany, audit, and installed-profile rows. The repository ignores Drizzle migration output (migrations/). Review schema changes and target the intended database before applying either step.
Usage
The host opens the transaction and decides whether to commit or roll back. Provide the Ledger layer and pass the transaction into an operation:
import { Effect } from "effect";
import { Ledger } from "@dzayr/accounting";
await db.transaction(async (transaction) => {
await Effect.runPromise(
Effect.gen(function* () {
const ledger = yield* Ledger;
return yield* ledger.postJournal(transaction, command);
}).pipe(Effect.provide(Ledger.layer)),
);
});General-ledger posting validates command schemas, decimal amounts, balancing, the open accounting period, active journal, and active/postable leaf accounts; closed periods reject later postings. Generic journal entries may include optional manual transaction-currency annotations; these do not alter canonical functional-currency posting or reports. Receivable invoices use a debit-normal asset control with credit-normal income allocations; payable bills use a credit-normal liability control with debit-normal asset/expense allocations; customer receipts debit a cash/bank asset and credit receivables; supplier payments debit payables and credit cash/bank. Accruals and deferrals use typed two-line mappings, and deferral and fixed-asset depreciation releases are limited to stored schedule amounts and dates. Fixed assets map cost to a debit-normal asset, accumulated depreciation to a credit-normal asset, depreciation to a debit-normal expense, and disposals to proceeds plus a gain or loss based on posted releases. Settlement allocations must match the source party/control account, cannot predate invoices/bills, and cannot cumulatively exceed their recorded totals. When the host applies sql/postgres-guards.sql, triggers independently enforce account hierarchy, entry balance, posting eligibility, reversal and adjustment integrity, period close safety, fixed-asset lifecycle and source-document-to-journal/allocation integrity, over-allocation safety, intercompany pair and mapped-control integrity (including later line inserts), and append-only journal, period-close, adjustment, fixed-asset, document, settlement, intercompany, audit, and installed-profile records. Authorization remains the host's responsibility.
Dimension types and values are immutable and book-scoped. Ledger.postJournal accepts up to 16 optional line-level { dimensionTypeId, dimensionValueId } assignments, ordered by dimensionTypeId; reversal entries copy those assignments. This release exposes dimension assignment through generic journal posting only—built-in invoice, bill, settlement, accrual, deferral, and fixed-asset posting commands remain untagged. Dimensions.createDimensionType and Dimensions.createDimensionValue create the catalog.
Budgets.createBudget creates an immutable code/revision plan over existing accounting periods and postable accounts, in the book's functional currency. A budget set is either account-wide or scoped to one dimension type; a null dimension value in a scoped set means no assignment for that type. Budgets.compareBudgetToActual returns budgeted lines with exact-string budget, normal-balance actual, and actual-minus-budget amounts. It is read-only: budget revisions do not impose spending limits, approvals, or encumbrances.
Development
pnpm test— PGlite transaction/invariant tests using Drizzle KitpushSchemapnpm check— formatting and lintpnpm build— package build and TypeScript declaration/type checksDATABASE_URL=... pnpm db:push— direct Drizzle schema push to the selected database
The PGlite suite verifies service invariants and SQL guards but does not exercise true multi-session PostgreSQL concurrency. Run integration tests against the target PostgreSQL version before relying on the documented READ COMMITTED serialization and settlement-lock behavior.
Alpha release roadmap
| Release | Scope |
| ---------------- | ------------------------------------------------------------------------------------------------------------------------- |
| 0.0.1-alpha.0 | Ledger foundation (companies/books, accounts, journals, periods, posting, reversals, idempotency, audit) |
| 0.0.2-alpha.0 | Localized chart hierarchy, versioned Algeria SCF starter profile, and installation safeguards |
| 0.0.3-alpha.0 | Issued customer invoice register and balanced GL integration (no receipts or tax) |
| 0.0.4-alpha.0 | Supplier bill register and balanced GL integration (no payments, tax, or inventory workflows) |
| 0.0.5-alpha.0 | Invoice receipts and supplier payments with partial settlement allocation (no reconciliation or transfers) |
| 0.0.6-alpha.0 | Financial reports and caller-selected tax-account movement summaries (no tax rules or returns) |
| 0.0.7-alpha.0 | Close, accruals, and deferrals |
| 0.0.8-alpha.0 | Fixed assets |
| 0.0.9-alpha.0 | Book-scoped journal-line dimensions, immutable period budgets, and budget-vs-actual comparisons |
| 0.0.10-alpha.0 | Manual generic-journal transaction-currency annotations; functional-currency postings and reports remain canonical |
| 0.0.11-alpha.0 | Reciprocal intercompany journal pairs; same-currency consolidated reporting and an ephemeral manual elimination worksheet |
| 0.0.11-alpha.1 | Audit patch: localized report account labels, immutable budget transaction identity, and the direct-SQL dimension cap |
No inventory or payroll models or dependencies are planned.
