سامانه صدور فاکتور و حسابداری
Mirrored from https://github.com/davoodmehraban89/Factor-easy.git
Synced Dec 3, 22:00 UTC
Fix legacy company starter-chart onboarding
davoodmehraban89 committed
Sep 29, 2026 at 22:52 UTC
3b3ffba2a489fd38466aae872a623916893f08ca
4 files changed
+13
-7
PROJECT_STATE.md
+1
-1
@@ -35,7 +35,7 @@ Before doing any project work:
35
| Date | Request / decision | Status | Evidence / next action |
36
|---|---|---|---|
37
| 2026-09-29 | Owner reported repeated GitHub Actions `run failed` notifications and supplied a Quality log failing on stale static needle `v.status==='posted'`. Diagnose the live CI failure first, repair the gate without weakening accounting safety, verify current CI, then continue the approved hardening backlog. Reduce avoidable CI churn by batching subsequent related durable changes where practical. | IN PROGRESS | Root cause confirmed: `journal-engine.js` was intentionally hardened from posted-only source locking to posted+reversed locking, while `quality-check.mjs` still searched for the obsolete literal `v.status==='posted'`. The gate is being corrected to require `jeSourceLocked` plus `['posted','reversed'].includes`, which is stronger and matches live semantics. Fix commit `78c6a071` replaced the obsolete posted-only literal with the stronger `jeSourceLocked` + posted/reversed invariant. Follow-up inspection exposed a hidden Phase 2 test-script syntax defect (duplicate `const companies`) that the old syntax gate could not detect because it only parsed `js/*.js`; the next batched checkpoint removes that duplicate, makes syntax CI check every `scripts/*.mjs`, and removes duplicate Phase 6 behavior execution from `quality-check.mjs` now that Phase 6 has its own named workflow step. Fix commit `78c6a071` corrected the stale source-lock assertion; batched CI repair `20294e31` also removed the hidden duplicate declaration in Phase 2 tests, made syntax CI parse all MJS test scripts, and stopped duplicate Phase 6 execution inside the static checker. Next checkpoint adds Quality/Security concurrency cancellation to reduce redundant notifications from superseded pushes and adds real-Chromium print pagination/orientation checks. CI result remains pending verification. |
38
-| 2026-09-29 | Reconcile the D.M/Finora source contract against the implemented product and execute the post-release high-assurance hardening backlog (60-item audit), beginning with accounting-core safety and closing verified requirement gaps such as company-type starter charts, floating analytic dimensions and account-chart import. Preserve the generic normalized dimension engine; expose the owner-agreed four floating analytic slots as a compatible product contract. No destructive historical cutover or schema/RLS/auth/role mutation without the required explicit approval. | IN PROGRESS | Baseline: main `9159108a`; Supabase ACTIVE_HEALTHY with 15 migrations and RLS on all public tables. D.M source confirms GL/معین/تفصیلی + four configurable floating slots while storage remains generic. Core checkpoint `a22422bd`: safe empty-chart Excel import/validation/template helpers; compatible slots Branch=1, Counterparty=2, Project=3, Contract=4; Contract entity-backed dimension; contracting Project+Contract rules; template v2 and posting-profile seeding hook. UI checkpoint `f65fb577`: accounting UI now exposes safe Chart-of-Accounts Excel import/template download, explicit four-slot compatibility guidance, and Contract as an entity-backed analytic source. Rendering checkpoint `fdf65e49`: configured slot numbers are now visible as تفصیلی شناور ۱..۴ while generic dimensions remain unlimited. Posting checkpoint `e6067b83`: generic posting context now carries `contractId` for entity-backed Contract dimensions. Phase 4 checkpoint `39470402`: contractor statement postings now pass the active contract identity into analytic assignment. Test checkpoint `87dcf6e9`: Phase 2 gate now behavior-tests valid Excel chart normalization and invalid-parent rejection, and statically gates four-slot/Contract UI + posting integration. A1 negative-test checkpoint `f7d9b033`: behavior gate now explicitly rejects unbalanced journals, missing required analytic dimensions and non-postable analytic values, in addition to existing duplicate-source, reversal and fiscal-lock scenarios. Contract traceability test checkpoint `2d433cf3`: Phase 4 behavior gate now requires both Project and Contract analytic identities on every contractor statement posting line. Account-classification checkpoint `d7b7274b`: chart masters now persist account type/classification for templates, manual creation and Excel imports, aligned with the source Account entity. UI checkpoint `4eb0a451`: chart editor now explicitly captures asset/liability/equity/revenue/expense/memorandum/control account type. Chart table checkpoint `8a7996a2`: account type is now a first-class visible chart column. Row-render checkpoint `9008ec4f`: account classifications are rendered in the chart with legacy-safe fallback. Account-type gate `e8926876`: Phase 2 acceptance now requires classification logic, UI field/table column and import normalization. Security read-only review: production RLS policies are owner-scoped for `records` and admin/self-scoped for profiles/licenses; all 5 warned SECURITY DEFINER functions pin `search_path=public`, and the 3 admin mutation RPCs internally call `is_admin()` before mutation. Therefore advisor warnings are not by themselves proof of privilege escalation; authenticated cross-user negative E2E remains NOT VERIFIED. No RLS/auth/role change was made. Security workflow review: `Dependency review` is intentionally guarded by `if: github.event_name == 'pull_request'`; its skipped status on the prior push run is expected, not a failed security gate. CodeQL remains the push security gate. Starter-chart checkpoint `1a92a060`: added recoverable VAT (`1108 مالیات و عوارض دریافتنی`) so purchase VAT can resolve to a dedicated debit account instead of being folded into gross purchase cost. VAT account gate `40042e80` now prevents regression of the recoverable-VAT starter account. Critical restore/immutability checkpoint `4e5ad967`: `absorbRecords` now stages the entire merge and swaps datastore only after all validation succeeds (atomic in-memory restore); conflicts now protect posted/reversed vouchers, their journal lines/dimensions, posted source records, posted/reversed contract statements, posted inventory/depreciation records and audit rows. This closes a real partial-restore/posted-history overwrite risk in client restore logic. Restore regression gate `8aec35b8`: Phase 5 behavior test now proves a conflicting posted journal restore is rejected, earlier mutable changes are rolled back atomically, and a safe mutable merge still succeeds. Master-data checkpoint `42178d64` + gate `4c216040`: accounts referenced by automatic posting profiles can no longer be deleted, closing a setup-integrity hole before first journal use. Critical source-posting fix `6bb2dabd`: expense/income entry previously only wrote an operational record and ignored the selected counterparty/project; it now persists company/date/contact/project context and atomically creates the corresponding journal voucher, rolling the source back if posting fails. Source-posting gate `a10bcf64`: Phase 3 behavior now requires successful balanced posting for both expense and other-income sources. Reversal/immutability checkpoint `5b10463e` + gate `d0c61db6`: source records remain immutable after their voucher is reversed and cannot be silently reposted under the same source identity/version; corrections must use a new corrective source. This closes the UI-level post-reversal rewrite hole. Server-side source immutability beyond journal/Phase5 triggers still requires a DB migration and therefore explicit schema-change approval. Real-DOM gate checkpoint `423e38a6`: Chromium smoke now enters the accounting foundation and asserts the Chart-of-Accounts Excel import surface, four-slot contract guidance, account-type control and Contract dimension source before continuing existing ERP/report smoke. Prepared-but-NOT-APPLIED migration `20260929190000_posted_source_immutability_guard.sql` at `c5241502` to enforce source-document immutability server-side for invoices/purchases/payments/expenses/contract statements linked to posted/reversed accounting history. Applying it is intentionally blocked pending explicit schema-change approval. Phase 3 static gate `d4ed8811` now requires expense/income posting semantics, reversed-source locking, and the prepared server immutability migration to remain present. Production RLS negative read test executed safely with transaction-local `authenticated` role/JWT simulation for both record owners: owner A saw 46/46 own and 0 of owner B; owner B saw 39/39 own and 0 of owner A. This verifies cross-user SELECT isolation on live `records`; write isolation remains structurally enforced by WITH CHECK but not mutation-tested. Production privilege negative test executed: under transaction-local authenticated context a normal user resolved `is_admin=false`, while the known admin resolved `is_admin=true`; a normal-user call to `admin_cancel_license` was rejected with PostgreSQL `42501 forbidden` before mutation. This materially validates the internal authorization guard behind the SECURITY DEFINER warning; the other admin RPCs use the same `is_admin()` precondition but were not mutation-called. Production license gate test: active monthly/lifetime contexts return active, current trial returns active, and the existing cancelled account returns `has_active_license=false`; expired-date behavior is present in the function predicate but no expired production fixture exists, so expired E2E remains NOT VERIFIED. Concurrency checkpoint `e80306d4`: sync now treats DB uniqueness/immutability conflicts as authoritative financial conflicts instead of retrying forever; it discards the conflicting local pending state by reloading the server snapshot and requires user review before retry. Live unique indexes for journal number and source/version were re-verified present. Conflict regression gate `a060e38b`: Phase 5 behavior now proves both DB unique-conflict (`23505`) and immutable-history conflict paths reload authoritative server state and stop unsafe retry loops. Custom-chart/master-data checkpoint `b2e0bbc1` + `734e074a` + gate `ff85a711`: the contractual floating slots 1–4 are now initialized even when the user rejects the starter chart and chooses manual/Excel chart setup; company deletion now refuses any company with dependent chart/fiscal/dimension/journal/ERP records rather than checking only a few operational modules. Company-type semantic checkpoint `ad2a75d9` + gate `0dddd62c`: once a starter chart has been applied, direct activity-type changes are blocked because they would leave the company classification inconsistent with its accounting chart; such a change now requires a controlled chart migration. Analytic invariant gate `91e62bb1`: Phase 2 behavior now proves parent/non-terminal analytic nodes are non-postable, terminal leaf nodes are postable, and hierarchy depth cannot change after values exist. Analytic-assignment checkpoint `aeed833b` + behavior gate `894ab15a`: journal lines now reject duplicate assignments of the same dimension type; tests explicitly cover required, forbidden, non-postable and duplicate analytic cases. Duplicate-source atomicity checkpoint `e8eeeaf8` + gate `261107d0`: duplicate source/version is now rejected before any draft voucher/line mutation; regression test proves failed duplicate posting leaves no orphan draft or journal lines. CI clarity correction at `bf3c5c99`: Phase 6 behavior was still executed indirectly because `quality-check.mjs` imports `phase6-behavior-check.mjs`; however it was missing as a named workflow step. The workflow now runs it explicitly as a separately visible Phase 6 gate as well. Custom-chart reporting checkpoint `d0d0116b` + Phase 6 gate `7aff1083`: P&L/financial-position classification now uses explicit account-master `accountType` first, with legacy title/code inference only as fallback. This prevents custom/Excel charts from being misclassified merely because titles differ from Finora defaults. Excel classification checkpoint `5553ecab` + gate `45dd08e9`: Persian/English account types in imported charts are normalized to canonical financial classifications, blank types infer safely from known code families, and unknown explicit types are rejected instead of silently corrupting report classification. Golden-journey checkpoint `2a4872ac` + CI gate `5d5c2eb7`: Quality now executes a deterministic accounting core journey covering credit sale+VAT → receipt/AR settlement → credit purchase+recoverable VAT → payment/AP settlement → expense+other income → reversal → trial-balance reconciliation → P&L verification. Purchase-VAT posting defect fixed at `81144314` + static gate `b48e7253`: Posting Engine now resolves the dedicated recoverable-VAT starter account by code `1108` before title fallback, preventing custom titles from folding recoverable VAT into purchase cost. Test-harness correction `1537b1d5`: the new sync behavior test now supplies the browser event stubs required when evaluating `sync.js` under Node VM; this removes a harness-only `window/document.addEventListener` failure before CI verification. Analytic applicability coverage `ef796b76`: behavior gate now covers optional omission and rejects undefined analytic types in addition to required/forbidden/non-postable/duplicate cases. Integration security checkpoint `99b0b549` + behavior gate `be4c445e`: integration metadata now accepts HTTPS only, rejects URL-embedded credentials and local/private-network endpoints, reducing secret leakage and future server-side SSRF exposure; no external webhook was sent. Production authorization evidence: JWT-simulated admin/active/trial/cancelled identities returned expected `is_admin`/`has_active_license` states; a non-admin call to `admin_extend_license` was denied with SQLSTATE 42501 before mutation; empty atomic sync succeeded for an active user and was denied for a cancelled user with `active license required`. No production data was changed by these checks. Production RLS write-negative evidence: an authenticated non-owner attempted a direct cross-user `records` INSERT inside an explicit rollback transaction and PostgreSQL rejected it with SQLSTATE 42501 (`new row violates row-level security policy`). Combined with the prior 46/46 vs 0 and 39/39 vs 0 SELECT isolation checks, live tenant isolation is now verified for read and cross-owner insert paths; no test row persisted. Master-data history checkpoint `2839b3d2` + `1a98374f` + gate `6b727b3a`: counterparties and products can no longer be deleted when referenced anywhere in financial/operational history, closing destructive orphaning paths across invoices, payments, cheques, projects/contracts, inventory and analytics. Untrusted-file resource hardening: chart/sales/purchase/product Excel imports are capped at 5 MiB and 10,000 rows; backup/restore JSON inputs are capped at 20 MiB (`648b8fb0`, `a5b6766c`, `e3b68693`, `7a6ba9e3`, `49fbe3ab`, `814ac639`) with regression gates `a6ca42d5` and `2f0a0d42`. This reduces malformed/oversized import DoS exposure. Quality-gate maintenance `60da9fd6`: stale company-deletion assertions were updated to the new dependency-wide guard, and the static security gate now requires escaping of `& < > \" '` in the canonical `esc()` helper. Cheque-history checkpoint `568acd76` + `c2c35752` + gate `d4426d68`: cheques may transition while registered, but once cleared/bounced/cancelled they can no longer be edited or deleted through the UI, preserving settled instrument history. Prepared server guard extended at `88d282b1` + gate `cdfb7188` so the pending migration will also make cleared/bounced/cancelled cheques immutable at the database boundary. It remains PREPARED/NOT APPLIED because applying any schema trigger still requires explicit schema-change approval. Phase 5 semantic checkpoint `8d314917` + gate `85623aef`: auto-created fixed-asset/depreciation accounts now carry financial account classification, negative salvage value is rejected, and base currency cannot be changed directly after exchange rates exist (controlled migration required). Project/contract reconciliation checkpoint `86c6b2e4` + gate `abf422f9`: contract profitability now counts expense/purchase sources only when their accounting voucher is actively posted (when journal integration is available), so reversed source costs no longer remain in project profit after ledger reversal. Inventory policy gate `bc5ec91d`: Phase 5 acceptance now explicitly requires the application-level insufficient-stock check for transfer/adjustment-out, alongside existing weighted-average and movement-domain tests. Depreciation reversal remains a verified design gap because the current production immutability trigger does not permit a posted→reversed depreciation transition; fixing it requires a schema-trigger change and is therefore pending explicit schema approval. Starter-chart semantic checkpoint `8972838d` + behavior `315be83f`/`845e7562` + static gate `4260d223`: automatic postings now prefer the activity-specific starter accounts (e.g. trading sale `4107`, trading purchase `5102`, service revenue `4106`, retail/distribution/etc. revenue codes) instead of always bypassing them through generic `4101/5101`. Concurrency audit found no current duplicate business keys in production for accounts/dimensions/branches/projects/cost centers/contracts. PREPARED/NOT-APPLIED migration `20260929190500_accounting_master_uniqueness.sql` at `045ee66b` (gate `d8325060`) adds DB uniqueness for those keys to close cross-client race conditions; application requires explicit schema approval. Documentation continuity checkpoint `e4f406ca` repaired the malformed change-ledger table; `07ff3b24` labels `docs/PHASE_4_VERIFICATION.md` as legacy four-phase evidence and points to the canonical current `PHASE_4_REDESIGN_VERIFICATION.md`; successor/required-evidence lists now include Phase 4–6 verification docs. CI regression follow-up: after fixing the stale Quality assertion, inspection found `scripts/phase2-check.mjs` had a duplicate top-level `const companies` declaration that would have become the next failure. The batched CI repair removes it, extends syntax validation to all MJS test scripts, and avoids double-running Phase 6 behavior inside the static Quality script. CI regression follow-up `20294e31` repaired the hidden Phase 2 test-script syntax issue and broadened syntax coverage to all MJS gates. The next batched QA checkpoint adds real Chromium verification for 25-line formal/non-formal invoice pagination (3 pages), A4/A5 landscape orientation and print page breaks, while workflow concurrency cancels superseded Quality/Security runs to reduce avoidable notification noise. Current hardening CI/real-DOM remain NOT VERIFIED until the latest head run completes. |
38
+| 2026-09-29 | Reconcile the D.M/Finora source contract against the implemented product and execute the post-release high-assurance hardening backlog (60-item audit), beginning with accounting-core safety and closing verified requirement gaps such as company-type starter charts, floating analytic dimensions and account-chart import. Preserve the generic normalized dimension engine; expose the owner-agreed four floating analytic slots as a compatible product contract. No destructive historical cutover or schema/RLS/auth/role mutation without the required explicit approval. | IN PROGRESS | Baseline: main `9159108a`; Supabase ACTIVE_HEALTHY with 15 migrations and RLS on all public tables. D.M source confirms GL/معین/تفصیلی + four configurable floating slots while storage remains generic. Core checkpoint `a22422bd`: safe empty-chart Excel import/validation/template helpers; compatible slots Branch=1, Counterparty=2, Project=3, Contract=4; Contract entity-backed dimension; contracting Project+Contract rules; template v2 and posting-profile seeding hook. UI checkpoint `f65fb577`: accounting UI now exposes safe Chart-of-Accounts Excel import/template download, explicit four-slot compatibility guidance, and Contract as an entity-backed analytic source. Rendering checkpoint `fdf65e49`: configured slot numbers are now visible as تفصیلی شناور ۱..۴ while generic dimensions remain unlimited. Posting checkpoint `e6067b83`: generic posting context now carries `contractId` for entity-backed Contract dimensions. Phase 4 checkpoint `39470402`: contractor statement postings now pass the active contract identity into analytic assignment. Test checkpoint `87dcf6e9`: Phase 2 gate now behavior-tests valid Excel chart normalization and invalid-parent rejection, and statically gates four-slot/Contract UI + posting integration. A1 negative-test checkpoint `f7d9b033`: behavior gate now explicitly rejects unbalanced journals, missing required analytic dimensions and non-postable analytic values, in addition to existing duplicate-source, reversal and fiscal-lock scenarios. Contract traceability test checkpoint `2d433cf3`: Phase 4 behavior gate now requires both Project and Contract analytic identities on every contractor statement posting line. Account-classification checkpoint `d7b7274b`: chart masters now persist account type/classification for templates, manual creation and Excel imports, aligned with the source Account entity. UI checkpoint `4eb0a451`: chart editor now explicitly captures asset/liability/equity/revenue/expense/memorandum/control account type. Chart table checkpoint `8a7996a2`: account type is now a first-class visible chart column. Row-render checkpoint `9008ec4f`: account classifications are rendered in the chart with legacy-safe fallback. Account-type gate `e8926876`: Phase 2 acceptance now requires classification logic, UI field/table column and import normalization. Security read-only review: production RLS policies are owner-scoped for `records` and admin/self-scoped for profiles/licenses; all 5 warned SECURITY DEFINER functions pin `search_path=public`, and the 3 admin mutation RPCs internally call `is_admin()` before mutation. Therefore advisor warnings are not by themselves proof of privilege escalation; authenticated cross-user negative E2E remains NOT VERIFIED. No RLS/auth/role change was made. Security workflow review: `Dependency review` is intentionally guarded by `if: github.event_name == 'pull_request'`; its skipped status on the prior push run is expected, not a failed security gate. CodeQL remains the push security gate. Starter-chart checkpoint `1a92a060`: added recoverable VAT (`1108 مالیات و عوارض دریافتنی`) so purchase VAT can resolve to a dedicated debit account instead of being folded into gross purchase cost. VAT account gate `40042e80` now prevents regression of the recoverable-VAT starter account. Critical restore/immutability checkpoint `4e5ad967`: `absorbRecords` now stages the entire merge and swaps datastore only after all validation succeeds (atomic in-memory restore); conflicts now protect posted/reversed vouchers, their journal lines/dimensions, posted source records, posted/reversed contract statements, posted inventory/depreciation records and audit rows. This closes a real partial-restore/posted-history overwrite risk in client restore logic. Restore regression gate `8aec35b8`: Phase 5 behavior test now proves a conflicting posted journal restore is rejected, earlier mutable changes are rolled back atomically, and a safe mutable merge still succeeds. Master-data checkpoint `42178d64` + gate `4c216040`: accounts referenced by automatic posting profiles can no longer be deleted, closing a setup-integrity hole before first journal use. Critical source-posting fix `6bb2dabd`: expense/income entry previously only wrote an operational record and ignored the selected counterparty/project; it now persists company/date/contact/project context and atomically creates the corresponding journal voucher, rolling the source back if posting fails. Source-posting gate `a10bcf64`: Phase 3 behavior now requires successful balanced posting for both expense and other-income sources. Reversal/immutability checkpoint `5b10463e` + gate `d0c61db6`: source records remain immutable after their voucher is reversed and cannot be silently reposted under the same source identity/version; corrections must use a new corrective source. This closes the UI-level post-reversal rewrite hole. Server-side source immutability beyond journal/Phase5 triggers still requires a DB migration and therefore explicit schema-change approval. Real-DOM gate checkpoint `423e38a6`: Chromium smoke now enters the accounting foundation and asserts the Chart-of-Accounts Excel import surface, four-slot contract guidance, account-type control and Contract dimension source before continuing existing ERP/report smoke. Prepared-but-NOT-APPLIED migration `20260929190000_posted_source_immutability_guard.sql` at `c5241502` to enforce source-document immutability server-side for invoices/purchases/payments/expenses/contract statements linked to posted/reversed accounting history. Applying it is intentionally blocked pending explicit schema-change approval. Phase 3 static gate `d4ed8811` now requires expense/income posting semantics, reversed-source locking, and the prepared server immutability migration to remain present. Production RLS negative read test executed safely with transaction-local `authenticated` role/JWT simulation for both record owners: owner A saw 46/46 own and 0 of owner B; owner B saw 39/39 own and 0 of owner A. This verifies cross-user SELECT isolation on live `records`; write isolation remains structurally enforced by WITH CHECK but not mutation-tested. Production privilege negative test executed: under transaction-local authenticated context a normal user resolved `is_admin=false`, while the known admin resolved `is_admin=true`; a normal-user call to `admin_cancel_license` was rejected with PostgreSQL `42501 forbidden` before mutation. This materially validates the internal authorization guard behind the SECURITY DEFINER warning; the other admin RPCs use the same `is_admin()` precondition but were not mutation-called. Production license gate test: active monthly/lifetime contexts return active, current trial returns active, and the existing cancelled account returns `has_active_license=false`; expired-date behavior is present in the function predicate but no expired production fixture exists, so expired E2E remains NOT VERIFIED. Concurrency checkpoint `e80306d4`: sync now treats DB uniqueness/immutability conflicts as authoritative financial conflicts instead of retrying forever; it discards the conflicting local pending state by reloading the server snapshot and requires user review before retry. Live unique indexes for journal number and source/version were re-verified present. Conflict regression gate `a060e38b`: Phase 5 behavior now proves both DB unique-conflict (`23505`) and immutable-history conflict paths reload authoritative server state and stop unsafe retry loops. Custom-chart/master-data checkpoint `b2e0bbc1` + `734e074a` + gate `ff85a711`: the contractual floating slots 1–4 are now initialized even when the user rejects the starter chart and chooses manual/Excel chart setup; company deletion now refuses any company with dependent chart/fiscal/dimension/journal/ERP records rather than checking only a few operational modules. Company-type semantic checkpoint `ad2a75d9` + gate `0dddd62c`: once a starter chart has been applied, direct activity-type changes are blocked because they would leave the company classification inconsistent with its accounting chart; such a change now requires a controlled chart migration. Analytic invariant gate `91e62bb1`: Phase 2 behavior now proves parent/non-terminal analytic nodes are non-postable, terminal leaf nodes are postable, and hierarchy depth cannot change after values exist. Analytic-assignment checkpoint `aeed833b` + behavior gate `894ab15a`: journal lines now reject duplicate assignments of the same dimension type; tests explicitly cover required, forbidden, non-postable and duplicate analytic cases. Duplicate-source atomicity checkpoint `e8eeeaf8` + gate `261107d0`: duplicate source/version is now rejected before any draft voucher/line mutation; regression test proves failed duplicate posting leaves no orphan draft or journal lines. CI clarity correction at `bf3c5c99`: Phase 6 behavior was still executed indirectly because `quality-check.mjs` imports `phase6-behavior-check.mjs`; however it was missing as a named workflow step. The workflow now runs it explicitly as a separately visible Phase 6 gate as well. Custom-chart reporting checkpoint `d0d0116b` + Phase 6 gate `7aff1083`: P&L/financial-position classification now uses explicit account-master `accountType` first, with legacy title/code inference only as fallback. This prevents custom/Excel charts from being misclassified merely because titles differ from Finora defaults. Excel classification checkpoint `5553ecab` + gate `45dd08e9`: Persian/English account types in imported charts are normalized to canonical financial classifications, blank types infer safely from known code families, and unknown explicit types are rejected instead of silently corrupting report classification. Golden-journey checkpoint `2a4872ac` + CI gate `5d5c2eb7`: Quality now executes a deterministic accounting core journey covering credit sale+VAT → receipt/AR settlement → credit purchase+recoverable VAT → payment/AP settlement → expense+other income → reversal → trial-balance reconciliation → P&L verification. Purchase-VAT posting defect fixed at `81144314` + static gate `b48e7253`: Posting Engine now resolves the dedicated recoverable-VAT starter account by code `1108` before title fallback, preventing custom titles from folding recoverable VAT into purchase cost. Test-harness correction `1537b1d5`: the new sync behavior test now supplies the browser event stubs required when evaluating `sync.js` under Node VM; this removes a harness-only `window/document.addEventListener` failure before CI verification. Analytic applicability coverage `ef796b76`: behavior gate now covers optional omission and rejects undefined analytic types in addition to required/forbidden/non-postable/duplicate cases. Integration security checkpoint `99b0b549` + behavior gate `be4c445e`: integration metadata now accepts HTTPS only, rejects URL-embedded credentials and local/private-network endpoints, reducing secret leakage and future server-side SSRF exposure; no external webhook was sent. Production authorization evidence: JWT-simulated admin/active/trial/cancelled identities returned expected `is_admin`/`has_active_license` states; a non-admin call to `admin_extend_license` was denied with SQLSTATE 42501 before mutation; empty atomic sync succeeded for an active user and was denied for a cancelled user with `active license required`. No production data was changed by these checks. Production RLS write-negative evidence: an authenticated non-owner attempted a direct cross-user `records` INSERT inside an explicit rollback transaction and PostgreSQL rejected it with SQLSTATE 42501 (`new row violates row-level security policy`). Combined with the prior 46/46 vs 0 and 39/39 vs 0 SELECT isolation checks, live tenant isolation is now verified for read and cross-owner insert paths; no test row persisted. Master-data history checkpoint `2839b3d2` + `1a98374f` + gate `6b727b3a`: counterparties and products can no longer be deleted when referenced anywhere in financial/operational history, closing destructive orphaning paths across invoices, payments, cheques, projects/contracts, inventory and analytics. Untrusted-file resource hardening: chart/sales/purchase/product Excel imports are capped at 5 MiB and 10,000 rows; backup/restore JSON inputs are capped at 20 MiB (`648b8fb0`, `a5b6766c`, `e3b68693`, `7a6ba9e3`, `49fbe3ab`, `814ac639`) with regression gates `a6ca42d5` and `2f0a0d42`. This reduces malformed/oversized import DoS exposure. Quality-gate maintenance `60da9fd6`: stale company-deletion assertions were updated to the new dependency-wide guard, and the static security gate now requires escaping of `& < > \" '` in the canonical `esc()` helper. Cheque-history checkpoint `568acd76` + `c2c35752` + gate `d4426d68`: cheques may transition while registered, but once cleared/bounced/cancelled they can no longer be edited or deleted through the UI, preserving settled instrument history. Prepared server guard extended at `88d282b1` + gate `cdfb7188` so the pending migration will also make cleared/bounced/cancelled cheques immutable at the database boundary. It remains PREPARED/NOT APPLIED because applying any schema trigger still requires explicit schema-change approval. Phase 5 semantic checkpoint `8d314917` + gate `85623aef`: auto-created fixed-asset/depreciation accounts now carry financial account classification, negative salvage value is rejected, and base currency cannot be changed directly after exchange rates exist (controlled migration required). Project/contract reconciliation checkpoint `86c6b2e4` + gate `abf422f9`: contract profitability now counts expense/purchase sources only when their accounting voucher is actively posted (when journal integration is available), so reversed source costs no longer remain in project profit after ledger reversal. Inventory policy gate `bc5ec91d`: Phase 5 acceptance now explicitly requires the application-level insufficient-stock check for transfer/adjustment-out, alongside existing weighted-average and movement-domain tests. Depreciation reversal remains a verified design gap because the current production immutability trigger does not permit a posted→reversed depreciation transition; fixing it requires a schema-trigger change and is therefore pending explicit schema approval. Starter-chart semantic checkpoint `8972838d` + behavior `315be83f`/`845e7562` + static gate `4260d223`: automatic postings now prefer the activity-specific starter accounts (e.g. trading sale `4107`, trading purchase `5102`, service revenue `4106`, retail/distribution/etc. revenue codes) instead of always bypassing them through generic `4101/5101`. Concurrency audit found no current duplicate business keys in production for accounts/dimensions/branches/projects/cost centers/contracts. PREPARED/NOT-APPLIED migration `20260929190500_accounting_master_uniqueness.sql` at `045ee66b` (gate `d8325060`) adds DB uniqueness for those keys to close cross-client race conditions; application requires explicit schema approval. Documentation continuity checkpoint `e4f406ca` repaired the malformed change-ledger table; `07ff3b24` labels `docs/PHASE_4_VERIFICATION.md` as legacy four-phase evidence and points to the canonical current `PHASE_4_REDESIGN_VERIFICATION.md`; successor/required-evidence lists now include Phase 4–6 verification docs. CI regression follow-up: after fixing the stale Quality assertion, inspection found `scripts/phase2-check.mjs` had a duplicate top-level `const companies` declaration that would have become the next failure. The batched CI repair removes it, extends syntax validation to all MJS test scripts, and avoids double-running Phase 6 behavior inside the static Quality script. CI regression follow-up `20294e31` repaired the hidden Phase 2 test-script syntax issue and broadened syntax coverage to all MJS gates. The next batched QA checkpoint adds real Chromium verification for 25-line formal/non-formal invoice pagination (3 pages), A4/A5 landscape orientation and print page breaks, while workflow concurrency cancels superseded Quality/Security runs to reduce avoidable notification noise. Legacy-company onboarding audit found two requirement-level defects: starter-template application checked the currently active company's chart instead of the target company, and its `finally` block left the target company active instead of restoring the prior context. Also, existing empty-chart companies could not opt into a recommended chart from Edit. The next batched checkpoint fixes all three and adds a behavior test proving a service starter chart can be applied to a non-active empty company without changing the active-company context. Current hardening CI/real-DOM remain NOT VERIFIED until the latest head run completes. |
39
| 2026-09-29 | Execute master roadmap Phase 5 end-to-end: inventory/warehouse and costing; item/service master refinement; fixed assets; multi-currency; cost centers/advanced analytics; Excel/import center; backup/restore; company settings/permissions redesign; integration/API architecture. Preserve Phase 1–4 accounting invariants and require real-DOM, accounting/domain behavior, security and deployment gates before completion. | COMPLETED | Owner granted standing authorization for in-scope repository/Supabase changes. Delivered refined goods/services master; explicit sales/purchase warehouse routing; warehouse master, immutable stock movements, transfers, stock counts and weighted-average costing; valued inventory-adjustment journals; fixed assets and balanced depreciation journals; currency/rate masters; cost-center analytic source; company operational settings and explicit owner-RLS permission boundary; validated full restore with posted-history conflict protection; v5 backup/import preview; integration metadata/outbox without browser secrets; Phase 5 audit/navigation/sync/backup. Production migration `20260929172129_phase5_complementary_erp_collections` applied and archived under the exact production version; collection constraint, posted-record immutability trigger and five uniqueness indexes verified; records RLS remains enabled/owner-scoped; performance advisor clean. Import/restore hardening then added controlled validated merge (`16796d3d`, `ae40f5dc`, `4ede2d15`, `ce4c7dcb`); its first gate exposed a quoting syntax regression, fixed at `6abf95ca`. Final code-head verification at `6abf95ca`: Quality `36606240438` PASS including syntax, Phase 2–5 invariants/behavior and real Chromium DOM; Security/CodeQL `36606240384` PASS; Pages `36606238776` PASS. Authenticated production-user E2E, live third-party webhook delivery and physical-printer validation remain NOT VERIFIED and are not Phase 5 acceptance gates. |
40
| 2026-09-29 | Adopt owner-specified high-assurance execution protocol: verify live GitHub/Supabase before work; latest chat is the only source of new instructions; record requests before implementation; vertical slices; PROJECT_STATE in every durable commit; archive every future Supabase migration SQL; require real-DOM smoke + accounting-invariant tests before COMPLETED; explicitly list NOT VERIFIED items. | COMPLETED | Live reconciliation found head `7d054dfa` (post-login/admin-shell fix) was not recorded here; its CI is green but real-DOM smoke was not run. Phase 4 CI workflow also did not actually execute `phase4-behavior-check.mjs` because the command was folded onto the Phase 3 command, and no `supabase/migrations/` SQL archive exists. Phase 4 completion is therefore reopened pending real-DOM + accounting-invariant verification. Verification slice prepared atomically: corrected CI command separation, strengthened Phase 4 posting/reversal accounting test, added Playwright real-DOM post-login/shell smoke, and backfilled exact historical SQL files from `supabase_migrations.schema_migrations`. No database/schema/RLS/auth/role mutation was performed. Verification slice commit `55b62db0`: all 14 existing Supabase migration statements were archived exactly from migration history under `supabase/migrations/`; no database mutation occurred. Quality run `36600894426` succeeded, including Phase 3 behavior, actual Phase 4 accounting invariants and Playwright real-DOM smoke; Security/CodeQL `36600894268` succeeded; Pages `36600893196` succeeded. Live head discrepancy `7d054dfa` is now accounted for. Authenticated production-user E2E and physical-printer validation remain NOT VERIFIED. Live reconciliation before Phase 5: current head `deedea67` is documentation-only (`PROJECT_STATE.md`); Quality `36601108479` and Security `36601108485` succeeded on its parent `312fe95a`. Pages run `36601106234` on that parent failed only after a manual partial rerun created two `github-pages` artifacts; last clean Pages deployment remains `36600893196` on `55b62db0`. Head Pages run `36601145056` was cancelled. This deployment discrepancy is recorded and must be cleared by the next normal code commit/deployment before Phase 5 completion. |
41
| 2026-09-29 | Execute master roadmap Phase 4 end-to-end: projects/contracts, amendments/lifecycle, employer/contractor/subcontractor links, deductions, guarantees, contractor statements/accounting, traceability, reporting, permissions/audit/sync/backup/migration/tests/reconciliation. | COMPLETED | Re-accepted under the stricter verification rule at `55b62db0`: Playwright real-DOM smoke PASS and Phase 4 accounting invariants PASS in Quality `36600894426`; Security `36600894268` PASS; Pages `36600893196` PASS. Prior implementation evidence: domain/UI `c2100228`; persistence/navigation/backup through `172aeb59`; referential guards `44154769`; behavioral CI gate `fe29b817`; deduction-specific accounting/template migration `dd3b78ed`; verification doc `e5b814a7`. Supabase migration `20260929091743 phase4_contracting_collections` applied; RLS owner isolation verified; production had zero pre-existing Phase 4 rows requiring backfill; performance advisor clean; known pre-existing security warnings unchanged. Acceptance checkpoint `95e6de99`: Quality 36549015911 success; Security/CodeQL 36549015935 success; Pages 36549015796 success. |
js/accounting-foundation.js
+2
-2
@@ -66,7 +66,7 @@ function afEnsureFloatingSlotCompatibility(){
66
}
67
function afApplyTemplate(companyId,type){
68
if(!requireWrite()||!companyId)return false;const company=getMyCompanies().find(x=>x.id===companyId);if(!company)return false;
69
- if(getMyAccounts().some(x=>x.companyId===companyId)){alert('برای این شرکت کدینگ وجود دارد؛ قالب روی کدینگ موجود اعمال نشد.');return false}
69
+ if((datastore.accounts||[]).some(x=>x.ownerUserId===currentUser.id&&x.companyId===companyId)){alert('برای این شرکت کدینگ وجود دارد؛ قالب روی کدینگ موجود اعمال نشد.');return false}
70
const previous=getMySettings().default_company_id;getMySettings().default_company_id=companyId;
71
try{
72
const rows=[...AF_BASE_ACCOUNTS,...(AF_SPECIAL_ACCOUNTS[type]||[])],byCode={};
@@ -81,7 +81,7 @@ function afApplyTemplate(companyId,type){
81
if(type==='contracting'){['4301','5301','5302','1105','1106','1107','2104','2105','6109'].forEach(c=>{addRule(c,project,'required');addRule(c,contract,'required')})}
82
if(['service','manufacturing','contracting','professional'].includes(type)){['6101','6102','6103','5101'].forEach(c=>addRule(c,cost,'optional'))}
83
company.activityType=type;company.accountingTemplate={type,appliedAt:new Date().toISOString(),version:2};saveDatastore();if(typeof jeEnsureDefaultProfiles==='function')jeEnsureDefaultProfiles();return true;
84
- }finally{getMySettings().default_company_id=companyId;saveDatastore()}
84
+ }finally{getMySettings().default_company_id=previous;saveDatastore()}
85
}
86
function afImportCell(row,names){for(const n of names){if(Object.prototype.hasOwnProperty.call(row,n)&&String(row[n]??'').trim()!=='')return String(row[n]).trim()}return ''}
87
function afNormalizeAccountImportRows(rows){
js/companies.js
+4
-2
@@ -20,7 +20,7 @@ function editCompany(id){
20
editingCompanyId=id;
21
const values={'company-entity-type':comp.entity_type||'legal','company-activity-type':comp.activityType||'trading','company-name-input':comp.name||'','company-phone-input':comp.phone||'','company-national-input':comp.national_id||'','company-economic-input':comp.economic_code||'','company-reg-input':comp.reg_number||'','company-postal-input':comp.postal_code||'','company-address-input':comp.address||'','company-footer-input':comp.footer||''};
22
Object.keys(values).forEach(id=>{const el=document.getElementById(id);if(el)el.value=values[id];});
23
- const template=document.getElementById('company-accounting-template');if(template){template.value=comp.accountingTemplate?'recommended':'empty';template.disabled=true;}
23
+ const template=document.getElementById('company-accounting-template');if(template){const hasChart=(datastore.accounts||[]).some(a=>a.ownerUserId===currentUser.id&&a.companyId===comp.id);template.value=comp.accountingTemplate?'recommended':'empty';template.disabled=!!comp.accountingTemplate||hasChart;}
24
const saveBtn=document.getElementById('company-save-btn');
25
if(saveBtn){saveBtn.innerHTML='💾 ذخیره اصلاحات';saveBtn.className='btn btn-primary';}
26
const cancelBtn=document.getElementById('company-edit-cancel-btn');if(cancelBtn)cancelBtn.style.display='inline-flex';
@@ -43,9 +43,11 @@ function commitSaveCompany(){
43
const comp=datastore.companies.find(c=>c.id===editingCompanyId&&c.ownerUserId===currentUser.id);
44
if(!comp){alert('شرکت موردنظر پیدا نشد.');resetCompanyForm();refreshAllSurfaces();return;}
45
if(comp.accountingTemplate&&comp.activityType&&comp.activityType!==activityType){alert('نوع فعالیت این شرکت مبنای کدینگ پیشنهادی اعمالشده است و تغییر مستقیم آن میتواند معنای حسابها را ناسازگار کند. ابتدا باید مهاجرت کنترلشده کدینگ انجام شود.');return;}
46
+ const hadChart=(datastore.accounts||[]).some(a=>a.ownerUserId===currentUser.id&&a.companyId===comp.id),hadTemplate=!!comp.accountingTemplate;
47
Object.assign(comp,payload);
48
saveDatastore();
48
- alert('اطلاعات شرکت با موفقیت اصلاح شد.');
49
+ if(!hadChart&&!hadTemplate&&templateChoice==='recommended'&&typeof afApplyTemplate==='function')afApplyTemplate(comp.id,activityType);
50
+ alert(templateChoice==='recommended'&&!hadChart&&!hadTemplate?'اطلاعات شرکت اصلاح شد و کدینگ پیشنهادی متناسب با نوع فعالیت اعمال گردید.':'اطلاعات شرکت با موفقیت اصلاح شد.');
51
}else{
52
const newComp={id:'COMP_'+Date.now(),ownerUserId:currentUser.id,...payload};
53
datastore.companies.push(newComp);
scripts/phase2-check.mjs
+6
-2
@@ -21,9 +21,9 @@ must(journal,["t.sourceEntity==='contract'","contractId:source.contractId||''"],
21
must(phase4,['contractId:c.id'],'contracting analytic source context');
22
must(masterUnique,['ux_finora_account_code','ux_finora_dimension_type_code','ux_finora_dimension_value_code','ux_finora_branch_code','ux_finora_project_code','ux_finora_cost_center_code','ux_finora_contract_number'],'prepared master uniqueness migration');
23
must(companies,['afEnsureFloatingSlotCompatibility','Object.entries(datastore)','دارای کدینگ، سال مالی، تفصیلی، اسناد یا سایر سوابق وابسته است'],'company master integrity');
24
-must(companies,['comp.accountingTemplate&&comp.activityType&&comp.activityType!==activityType','مهاجرت کنترلشده کدینگ'],'company activity/chart semantic guard');
24
+must(companies,['comp.accountingTemplate&&comp.activityType&&comp.activityType!==activityType','مهاجرت کنترلشده کدینگ','template.disabled=!!comp.accountingTemplate||hasChart',"templateChoice==='recommended'"],'company activity/chart semantic guard');
25
if(af.includes('!d&&company.accountingTemplate'))throw new Error('four contractual floating slots must not depend on accepting a starter chart');
26
-must(contacts,['Object.entries(datastore)',"key!=='contacts'",'برای حفظ تاریخچه قابل حذف نیست'],'counterparty deletion integrity');must(products,['Object.entries(datastore)',"key!=='products'",'برای حفظ تاریخچه قابل حذف نیست','5*1024*1024','rows.length>10000'],'product deletion/import integrity');must(invoiceExcel,['5*1024*1024','rows.length>10000'],'sales Excel resource bounds');must(purchases,['5*1024*1024','rows.length>10000'],'purchase Excel resource bounds');must(af,['5*1024*1024','rows.length>10000'],'chart Excel resource bounds');
26
+must(contacts,['Object.entries(datastore)',"key!=='contacts'",'برای حفظ تاریخچه قابل حذف نیست'],'counterparty deletion integrity');must(products,['Object.entries(datastore)',"key!=='products'",'برای حفظ تاریخچه قابل حذف نیست','5*1024*1024','rows.length>10000'],'product deletion/import integrity');must(invoiceExcel,['5*1024*1024','rows.length>10000'],'sales Excel resource bounds');must(purchases,['5*1024*1024','rows.length>10000'],'purchase Excel resource bounds');must(af,['5*1024*1024','rows.length>10000','default_company_id=previous',"x.companyId===companyId"],'chart Excel resource/context bounds');
27
for(const coll of ['fiscalYears','accounts','dimensionTypes','dimensionValues','accountDimensionRules','branches','projects','projectLinks']){
28
if(!core.includes("'"+coll+"'")||!sync.includes(coll)||!backup.includes(coll))throw new Error('Phase 2 persistence missing '+coll);
29
}
@@ -40,6 +40,10 @@ if(imported.length!==3||imported[2].level!=='detail'||imported[2].parentCode!=='
40
let badParent=false;try{vm.runInContext(`afNormalizeAccountImportRows([{'کد':'1101','عنوان':'بانک','سطح':'تفصیلی','کد والد':'99'}])`,ctx)}catch(_){badParent=true}
41
if(!badParent)throw new Error('Chart import must reject invalid hierarchy');
42
let badType=false;try{vm.runInContext(`afNormalizeAccountImportRows([{'کد':'1','عنوان':'نمونه','سطح':'کل','نوع حساب':'نامعتبر'}])`,ctx)}catch(_){badType=true}if(!badType)throw new Error('Chart import must reject unknown account types');
43
+ctx.datastore={accounts:[{id:'OLD_ACC',ownerUserId:'u',companyId:'OLD',code:'999'}],dimensionTypes:[],accountDimensionRules:[]};ctx.currentUser={id:'u'};ctx.companies=[{id:'OLD',activityType:'trading'},{id:'TARGET'}];ctx.settings={default_company_id:'OLD'};Object.assign(ctx,{requireWrite:()=>true,saveDatastore:()=>true,alert:()=>{}});vm.runInContext("getMyCompanies=()=>companies;getMySettings=()=>settings;getMyAccounts=()=>datastore.accounts.filter(x=>x.companyId===settings.default_company_id);getMyDimensionTypes=()=>datastore.dimensionTypes.filter(x=>x.companyId===settings.default_company_id);",ctx);
44
+if(vm.runInContext("afApplyTemplate('TARGET','service')",ctx)!==true)throw new Error('starter chart failed for non-active empty company');
45
+if(ctx.settings.default_company_id!=='OLD')throw new Error('starter chart changed active company context');
46
+if(!ctx.datastore.accounts.some(x=>x.companyId==='TARGET'&&x.code==='4106'))throw new Error('service starter chart not applied to target company');
47
ctx.values=[{id:'ROOT',dimensionTypeId:'D1',depth:1,active:true},{id:'LEAF',dimensionTypeId:'D1',parentId:'ROOT',depth:2,active:true}];ctx.dimTypes=[{id:'D1',sourceEntity:'manual',maxDepth:2,active:true}];ctx.alerts=[];Object.assign(ctx,{requireWrite:()=>true,alert:m=>ctx.alerts.push(m),prompt:()=>3,saveDatastore:()=>true,renderAccountingFoundation:()=>{}});vm.runInContext("getMyDimensionValues=()=>values;getMyDimensionTypes=()=>dimTypes;",ctx);
48
const leafState=vm.runInContext("({root:afDimensionValuePostable(values[0],dimTypes[0]),leaf:afDimensionValuePostable(values[1],dimTypes[0])})",ctx);
49
if(leafState.root!==false||leafState.leaf!==true)throw new Error('leaf-only analytic posting behavior failed');