progalaxyelabs / stonescriptphp-accounting
Double-entry accounting and a fixed-asset register for StoneScriptPHP apps: chart of accounts (Indian small-business template with GST ledgers), an immutable balanced journal, idempotent posting functions for sales, credit notes, purchases, expenses, receipts and payments, cash/bank/day books, trial
Package info
github.com/progalaxyelabs/stonescriptphp-accounting
pkg:composer/progalaxyelabs/stonescriptphp-accounting
Requires
- php: ^8.2
Requires (Dev)
- phpunit/phpunit: ^11.0
Suggests
- progalaxyelabs/stonescriptphp: ^16.0 - the app framework whose `php stone gateway:migrate-tenant` deploys the staged schema. This package itself has no runtime PHP dependency.
Provides
None
Conflicts
None
Replaces
None
README
Double-entry accounting and a fixed-asset register for StoneScriptPHP apps, in PostgreSQL functions.
- Chart of accounts. The default template is for an Indian small business: cash, banks, debtors, creditors, sales, purchases, common expense heads, and the GST ledgers (Output/Input CGST, SGST, IGST, cess, and RCM payable). A tenant may add accounts. System accounts cannot be deleted or deactivated.
- Journal. Every entry is balanced and immutable:
- the debit total must equal the credit total, enforced in SQL at COMMIT;
- a correction is a reversal entry, never an update or a delete;
- every entry keeps its
source_type,source_id,created_byandcreated_at.
- Posting functions for apps to call from their own events. Each is idempotent on
(source_type, source_id), and the GST split comes from the caller's tax lines. - Reports, for any period (the Indian financial year, April to March, is the default):
- ledger statement for an account;
- cash book, bank book and day book;
- trial balance;
- profit and loss;
- balance sheet;
- party balances.
- Fixed-asset register:
- WDV and SLM depreciation, pro rata by days;
- one depreciation run per financial year, which posts a journal entry;
- disposal or sale, with gain or loss posting.
- No hard deletes anywhere. Triggers refuse DELETE and TRUNCATE on every
accounting_*table.
All amounts are numeric(14,2) in INR. The package targets StoneScriptPHP 16.x and the StoneScriptDB Gateway. It was rehearsed against gateway 4.13.0, see Testing.
Where it lives: the tenant database
The books belong to each tenant, so every object goes into the tenant database. The framework's sync-vendor-schema / gateway:migrate-vendor-main stage vendor schema for the main database only, so this package ships its own stager:
composer require progalaxyelabs/stonescriptphp-accounting vendor/bin/accounting-stage-tenant-schema src/postgresql/tenant/postgresql # copies accounting_* tables + functions git add src/postgresql/tenant/postgresql && git commit # the staged files are app source php stone gateway:migrate-tenant --database-id=<uuid> # per live tenant (never migrate-all)
Run the stager again after every composer update progalaxyelabs/stonescriptphp-accounting, and commit the .accounting-staged.json manifest it keeps:
- It updates a file only when that file is missing, identical, or still exactly what the stager wrote last time.
- Any other same-named file, such as an app file or a hand edit, is a conflict. Nothing is written and the command exits 1. Use
--forceonly after checking the file. - It only reports files it staged before that the package no longer ships.
- A changed table file prints a warning. The gateway creates tables only when missing, so existing tenants get a table change only through the package's migration.
Deploy order: why it is safe
The gateway deploys types first, then tables, then functions (every function file, on every migrate), then migrations:
- Tables. 8 declarative files, one table each, sorted so that a parent comes before its child. They are created when missing.
- Functions. There is one function per file, named like the file, because the gateway tracks one signature per file. All of them are
LANGUAGE plpgsql, so a body is not validated against tables at CREATE time. The trigger-creatingDOblocks are guarded and idempotent. - Seeders: none. The gateway runs seeders only when a database is registered, never on migrate. Instead,
accounting_ensure_setup()inserts the chart of accounts and the asset categories idempotently. Every publicaccounting_*function calls it first, so an existing tenant gets its books on first use. Apps may also call it at tenant provisioning. - Migrations: none in v0.1.0. A future schema change ships as a NEW forward-only migration. A shipped table file is never edited.
Posting from app events
| App event | Call | Default accounts |
|---|---|---|
| Invoice / bill issued | accounting_post_sale_invoice(source_id, date, lines, party_name, party_id, receivable='sundry_debtors', round_off=0, expected_total, narration, created_by) |
Dr receivable, Cr sales + output GST |
| Counter sale paid on the spot | same, with receivable='cash' or the bank account code |
Dr cash/bank |
| Credit note / sales return | accounting_post_sale_credit_note(...) |
Dr sales_returns + output GST, Cr receivable |
| Supplier bill / purchase invoice | accounting_post_purchase_bill(source_id, date, lines, party_name, party_id, payable='sundry_creditors', ...) |
Dr purchases + input GST, Cr payable |
| Purchase return / debit note | accounting_post_purchase_return(...) |
Dr payable, Cr purchase_returns + input GST |
| Expense | accounting_post_expense(source_id, date, lines, paid_from='cash', party_name, ...) |
Dr line account (rent, electricity, ...) + input GST, Cr paid-from |
| Money received | accounting_post_receipt(source_id, date, amount, deposit='cash', from='sundry_debtors', party_name, party_id, ...) |
Dr deposit, Cr from |
| Money paid | accounting_post_payment(source_id, date, amount, paid_from='cash', to='sundry_creditors', ...) |
Dr to, Cr paid-from |
| Manual / opening entry | accounting_post_journal(source_id, date, lines, narration, created_by, voucher_type='journal'|'opening') |
lines as given |
| Document cancelled | accounting_reverse_source(source_type, source_id, date, reason, created_by) (intent 'cancel', the default) |
mirror entry |
| Document edited | accounting_reverse_source(..., intent => 'amend'), then post the corrected document (revision 2) |
created_byis required on every posting. Pass the app user. As a fallback the session settingaccounting.actoris used. Without either, the post is refused (BK006).source_idis the app's own document id; pass it as text. It must be unique persource_typewithin the tenant, because two documents with one key are one document to the books.source_typedefaults per function (sale_invoice,receipt, ...). Give each module its ownsource_type(for example'wholesale_invoice'), and never use a supplier's bill number as the id.- Reversals are dated like the original entry by default. The reversal and a corrected re-post then land in the original period, and that period's figures are right. If that period is locked, pass a date after the lock.
- Cancel vs amend:
- After a cancel, a late retry of the original event returns
{"status":"cancelled"}and posts nothing. A different document under that source raisesBK012. - After an amend, the next post of that source is revision 2.
- After a cancel, a late retry of the original event returns
- Account references are a system key (
cash,bank,sales,output_cgst, ...) or an account code, such as a tenant bank account created withaccounting_create_account('HDFC-01', 'HDFC current', 'asset', 'bank'). - Tax lines (
lines, a JSON array, which the gateway binds tojsonb) look like this:[{"taxable": "1000.00", "cgst": "90.00", "sgst": "90.00", "igst": "0", "cess": "0", "account": "sales", "reverse_charge": false, "narration": "optional"}]Each line follows these rules:- The GST split is the caller's: the package never computes a rate.
- A line carries IGST or CGST+SGST, never both.
reverse_charge: trueis allowed on purchases and expenses only. It books Dr input GST and Crgst_rcm_payable, and the supplier is owed the taxable value only.
expected_total: pass the document's stored grand total. If the lines plus round-off do not add up to it, the call is refused withBK007, which catches a wrong split before it reaches the books.- Idempotency. A retried call returns
{"status":"existing"}only when it would book exactly the same thing: the date, the voucher and every line's account, amount and party. Any other change raisesBK011, even when the total is the same: reverse with intent'amend'first. Concurrent calls for one source are serialised by an advisory lock and a unique key.
Reports
| Function | Returns |
|---|---|
accounting_account_ledger(account, from, to) |
opening row, lines with running balance, closing row |
accounting_cash_book(from, to) / accounting_bank_book(account?, from, to) |
the same, over every cash account / one or all bank accounts |
accounting_day_book(from, to) |
every line of every entry, with its audit trail |
accounting_trial_balance(from, to) |
per account: opening, period debit, period credit, closing. Income and expense restart each FY, and earlier years' result is carried in retained earnings. The closing column sums to 0. |
accounting_profit_and_loss(from, to) |
income and expense per account, plus gross_profit and net_profit |
accounting_balance_sheet(as_of) |
assets, liabilities and equity, plus profit of earlier years and of the current year. total_assets equals total_liabilities_and_equity. |
accounting_party_balances(account='sundry_debtors', as_of) |
outstanding per customer (or per supplier, with 'sundry_creditors') |
accounting_list_accounts(include_inactive, as_of) |
chart of accounts with balances |
accounting_asset_register(as_of), accounting_depreciation_schedule(fy) |
the asset register; the CA's depreciation chart |
When the dates are left out, to is today and from is the start of that financial year. "Today" is computed in accounting_settings.timezone (Asia/Kolkata by default), never in the database server's zone. Balances are signed debit − credit, with a Dr/Cr side column. Income and expense ledgers open each financial year at zero.
Inventory: purchases are expensed when posted. Post the closing-stock adjustment as a manual journal (Dr stock_in_hand / Cr purchases) so the P&L shows cost of goods sold.
Fixed assets
SELECT accounting_add_asset('LAP-01', 'Billing laptop', 'COMPUTER_END_USER', '2026-05-02', '2026-05-03', 65000, 'Dell', 'Counter', NULL, NULL, NULL, NULL, NULL, 'bank'); -- WDV 40% from the category SELECT accounting_run_depreciation('2026-27', 'ca@firm'); -- after 31 Mar 2027; posts Dr depreciation / Cr accumulated SELECT accounting_dispose_asset('LAP-01', '2028-06-30', 30000, 'bank', 2700, 2700); -- part-year dep + gain/loss
Method. The default method comes from accounting_settings.default_depreciation_method:
WDV(the default) is the Income-tax rate pro rata by days. It is a simplified book method that many non-company businesses use. It is neither the Companies Act Schedule II computation nor the income-tax block computation.- Companies should set
SLMwithaccounting_update_settings(default_depreciation_method => 'SLM'). That uses the Schedule II useful life.
SLM's residual value defaults to 5% of cost. Pass method, wdv_rate_pct, useful_life_years or residual_value to override them.
Calculation.
- WDV is opening book value × rate × days used ÷ days in the FY.
- SLM is (cost − residual) ÷ life × days used ÷ days in the FY. It stops at the residual value.
Posting the purchase. With credit_account (bank, cash, sundry_creditors, or opening_balance_equity for assets owned before the books started), the purchase is posted as Dr fixed_assets. Leave it NULL if the bill was already posted with the line account fixed_assets.
Other ledger. asset_account puts the cost in a tenant fixed-asset ledger, such as a "Vehicles" account. Disposal credits that same ledger.
An asset brought in mid-life takes opening_accumulated_depreciation, opening_as_of and a credit_account (usually opening_balance_equity). It is posted on opening_as_of. An asset that was in use before the books' first depreciation year must come with opening figures (BK009). Otherwise the year-by-year check would block every later run.
Registration mistakes are corrected with accounting_void_asset(code, reason) while the asset is in no active run. It reverses the purchase entry and keeps the row as void. Register the asset again under a new code.
Run rules. Runs go year by year, with no gaps and no earlier year after a later one (BK010). A run is undone only by accounting_reverse_depreciation_run(fy), after which the year can be run again (revision 2).
What is refused:
- an asset added inside a year that already has a run (
BK009); - a disposal inside a year that already has a run (
BK009): reverse the run first.
The tax computation is not done here. This register posts book depreciation. The Income-tax block-of-assets computation, including any part-year rule, is not done by this package.
Rates: official sources
The 24 default categories carry two numbers. They were read from the primary official sources on 2026-11-25:
| Field | Source |
|---|---|
it_wdv_rate_pct |
Income-tax Rules, 2026, Appendix I (see rule 25), "Table of rates at which depreciation is admissible", Central Board of Direct Taxes: https://incometaxindia.gov.in/w/appendix-i-1 (upload date 05/05/2026). The same rates for these entries appear in the Income-tax Rules 1962 New Appendix I: https://incometaxindia.gov.in/w/new-appendix-i |
useful_life_years |
Companies Act, 2013, Schedule II, Part C, Ministry of Corporate Affairs consolidated Act (last update 29-7-2022, pp. 277-282): https://www.mca.gov.in/content/dam/mca/pdf/CompaniesAct2013.pdf. Cross-checked with https://incometaxindia.gov.in/w/schedule-ii |
Each row's source_note cites its entry, for example IT App.I Part A III(5): 40%; Sch.II C XII(ii): 3 years. Some asset types are not named in Appendix I (office equipment, two-wheelers, goods vehicles not on hire, lab and medical equipment). They are mapped to III(1), general plant and machinery, at 15% and flagged (general P&M). The tenant's CA should confirm those mappings. An admin can change any rate or life, or add categories, with accounting_upsert_asset_category. Existing assets keep the values copied when they were registered.
Errors
Every refusal raises ACCOUNTING_<REASON>: ... with SQLSTATE BKnnn. The gateway returns it as a non-2xx response whose message contains that text. Map them to user messages:
| SQLSTATE | Meaning |
|---|---|
BK001 |
unbalanced, or fewer than 2 lines |
BK002 |
immutable (posted entry or detail) |
BK003 |
delete or truncate refused |
BK004 |
account not found or inactive |
BK005 |
period locked (accounting_update_settings(lock_until)) |
BK006 |
invalid input |
BK007 |
lines ≠ document total |
BK008 |
not reversible |
BK009 |
asset rule |
BK010 |
depreciation year order / gap |
BK011 |
source already posted with different content (reverse with intent 'amend' first) |
BK012 |
source was cancelled; a different document under the same source needs intent 'amend' or a new source id |
Operational notes
-
Internal functions. Functions named
accounting__*(two underscores) are internal.accounting__post_entryvalidates its own reversal and asset-entry pairing, so a direct call cannot forge a package entry. Apps should still call only the single-underscore API. Configure the gateway to deny*__*names on/callwhere it supports that. -
Report functions call
accounting_ensure_setup(), which writes the default chart once per tenant. Callaccounting_ensure_setup()at provisioning if reports are served from a read-only role. -
Function signatures. The gateway tracks one signature per file. A future release that changes a function's parameters will drop the old signature in a migration, so no overload is left behind.
-
Direct table writes. Some guarantees are enforced by triggers and constraints, so they also hold for a direct INSERT:
- balance at COMMIT;
- immutability;
- no deletes;
- the lock date;
- the FY label and transaction id;
- the reversal shape;
- a required
created_by.
Other rules are enforced by the functions: the asset-entry pairing, reversal mirroring, and the content fingerprint. Apps must write through the functions. A superuser can disable triggers.
Testing
bash tests/run-sql-tests.sh # throwaway postgres:16; deploys in gateway order (functions twice); 7 files, 334 assertions bash tests/run-php.sh # stager + SQL layout lint (one fn per file, plpgsql, no destructive DDL, no psql meta) GATEWAY_BIN=... WORK=... bash tests/rehearsal/gateway_rehearsal.sh # a REAL gateway: fresh + pre-existing tenant, /call
Not in this package
- UI pages. Each app builds its own pages from the report functions above.
- Voucher numbering per series. The entry id is the voucher number.
- Multi-currency. Convert to INR before posting.
- Inventory valuation.
- Tax-depreciation computation.
- GSTR returns.
Licence
MIT.