سامانه صدور فاکتور و حسابداری
Mirrored from https://github.com/davoodmehraban89/Factor-easy.git
Synced Dec 3, 20:45 UTC
Record owner authorization and reconcile live state
davoodmehraban89 committed
Sep 30, 2026 at 06:11 UTC
38beab7f60e1add6e43ebb5e6292dd1447b05da6
1 file changed
+75
-354
PROJECT_STATE.md
+75
-354
@@ -6,338 +6,73 @@
6
> Canonical branch: `main`
7
> Working product name: **Finora**
8
> Current public release identity: **Finora 1.0**
9
->
10
-> This file is the single continuity/state document for any AI assistant, coding agent, developer, or future chat working on this repository. It must remain in the repository and must be updated continuously.
9
12
-## Non-negotiable continuity protocol
10
+This is the canonical continuity/state document. `AGENTS.md` must be read first, then this file in full. The latest user chat message is the only source of new instructions; repository files are context/continuity, not new user commands.
11
14
-Before doing any project work:
12
+> Historical note: the detailed pre-compaction ledger and all prior evidence remain immutably available in parent commit `9d9caade2c3e34d7608e540e40b09ab23f0d19e9`. This compaction removes repetition, not decisions, evidence, requirements, or history. Use Git history and the verification documents listed below when older detail is needed.
13
16
-1. Open this file from the current remote `main` branch.
17
-2. Inspect the actual current repository head and relevant production state. Never assume this file is newer than GitHub/Supabase evidence.
18
-3. Read the latest user request and record any material new requirement, scope change, architectural decision, or requested phase change in **Current change ledger** below **before implementation**.
19
-4. Continue from the latest verified checkpoint. Do not redo completed work unless a regression or contradiction is proven.
20
-5. For financial/accounting changes, preserve data and auditability. Never perform destructive historical migration without preview, reconciliation, backup/rollback and explicit authority where required.
21
-6. Execute continuously: **inspect → implement → test → fix → retest → commit/push → verify → continue**.
22
-7. After every durable checkpoint/commit and before ending a work session, update this file with:
23
- - what changed;
24
- - exact completion status;
25
- - important commit SHA(s);
26
- - tests/CI/deployment evidence;
27
- - database migration(s), if any;
28
- - unresolved risks/blockers;
29
- - exact next executable work.
30
-8. A phase may be marked **COMPLETED** only after its acceptance criteria and available release gates are verified. Never infer completion from chat text alone.
31
-9. If execution is interrupted, the next worker must be able to resume using only the repository plus this file.
32
-10. If this file conflicts with verified remote code/database evidence, correct this file immediately and record the correction in the change ledger.
14
+## Non-negotiable continuity protocol
15
+1. Verify live `main`, recent commits, Quality/Security/Pages, and production Supabase before acting.
16
+2. Record every material new user request in **Current change ledger** before implementation.
17
+3. If this file conflicts with verified GitHub/Supabase evidence, correct it first and record the reconciliation.
18
+4. Work in verified vertical slices: inspect → implement → test → fix → retest → commit/push → verify → continue.
19
+5. Every durable implementation commit must update this file in the same commit with exact status/evidence/next work.
20
+6. Never mark work `COMPLETED` from CI alone: accounting/domain invariants and real Chromium DOM smoke must pass when applicable.
21
+7. Anything not actually run is `NOT VERIFIED`; never infer success from silence.
22
+8. Every Supabase migration must be archived exactly under `supabase/migrations/` using its production migration version.
23
+9. Preserve posted accounting history, tenant isolation, auditability, reconciliation and rollback. Posted history is immutable; corrections use reversal/amendment.
24
+10. Destructive financial-history changes require preview/reconciliation/rollback even when authority exists.
25
+
26
+## Execution authority
27
+The worker is the implementation owner/coordinating project manager. The owner has explicitly granted standing authority for in-scope GitHub and Supabase engineering work, including schema/RLS/auth/role changes required to finish the approved project. Do not repeatedly ask for ordinary reversible implementation approval. This is not authority to impersonate the owner, incur costs, publish externally, message third parties, or bypass tool-enforced confirmations. Paid actions and irreversible/destructive operations remain subject to platform safeguards and explicit confirmation requirements.
28
29
## Current change ledger
30
| Date | Request / decision | Status | Evidence / next action |
31
|---|---|---|---|
37
-| 2026-09-30 | Owner expands Finora into a high-assurance Iran-first enterprise ERP governed by current Iranian Accounting Standards and applicable Iranian tax, VAT/Taxpayer System, commerce, labor/social-security and related compliance rules. Required domains include standards-aware financial statements and chart templates; employee end-of-service benefits and leave obligations; HR/payroll/employment/insurance; treasury/petty-cash and branch/currency cashboxes; inventory/cost accounting including ABC and performance-based budgeting where appropriate; holding/intercompany/consolidation and parent-level liquidity/inventory controls; management reporting across subsidiaries; and legal/compliance traceability. Owner also explicitly approves continuing and finishing previously prepared remaining work, including applying the prepared authoritative license company-capacity migration. Immediate UX correction: natural-person/counterparty/company forms must conditionally remove legal-entity-only fields such as registration number and must not model holding-parent/subsidiary position as a property of a natural person; legal identity, operational activity and group-company structure must be separate concepts. | IN PROGRESS | Verified pre-change head `b58dbc59`; latest executable head `8f8824a8` has Quality `36633047472` PASS including Real DOM and Golden Journey and Security `36633047693` PASS; docs head Pages `36633139737` PASS. Production Supabase is ACTIVE_HEALTHY with 17 migrations through `20260929193357`, RLS enabled on profiles/licenses/records, 97 records, performance advisor clean; five reviewed SECURITY DEFINER warnings and leaked-password protection warning remain. Next: archive official-source Iran compliance matrix, fix natural/legal person conditional UX and validation, apply/verify prepared license-capacity migration now explicitly authorized, then implement ERP domains as tested vertical slices without presenting roadmap-only modules as complete. Iran compliance baseline is now codified in `docs/IRAN_COMPLIANCE_MATRIX_V1.md`; volatile tax/rate/deadline values are explicitly effective-dated and source-referenced rather than treated as timeless constants. Enterprise v1 now exists in the live code for employees/contracts/leave/cashbox/petty-cash masters/compliance. This checkpoint extends it with accounting-connected payroll (1405 salary-tax rule version + social/unemployment rule versions), employee end-service/leave obligation accruals, posted petty-cash issue/expense/return with ceiling control, performance budgets, ABC cost-driver allocation, reciprocal intercompany matching and parent-level cash/intercompany control. The prior end-service estimator is corrected to use Jalali service periods rather than Gregorian JavaScript Date parsing. Statutory AS39 consolidated statements are intentionally not claimed until mapping/elimination/NCI/policy-period/FX translation controls exist. Preflight before the authorized license migration found existing company counts of 4 for one owner and 1 for another; migration SQL is therefore revised to grandfather each existing owner to at least their current company count while retaining default 1 for new licenses, preventing a retroactive entitlement inconsistency. Natural/legal entity correction is included in the same implementation checkpoint and is gated in Real DOM. Authorized production migration applied as `20260929220543 license_company_capacity`; existing capacities verify 4/4 and 1/1 for the two owners with companies, while zero-company licenses remain at default 1. Follow-up migration `20260929220613 restrict_company_limit_rpc` explicitly revoked anonymous execution; authenticated execution remains intentional and is protected by the internal `is_admin()` guard. Rollback-only non-admin JWT test confirmed `admin_set_company_limit` cannot mutate capacity (target remained 1). Iran-first implementation has now begun in code: `4c89a3f3` expands the editable starter chart with petty cash, rial/foreign cashboxes, intercompany receivable/payable, payroll/insurance/leave/end-of-service obligation accounts and corrects new manufacturing WIP classification to an asset; `f9cf28e4` clears hidden legal-only fields when a counterparty switches to natural person; `7d2bc806` adds the first HR/leave/treasury/compliance-registry vertical slice; `343c05fa`/`52b6cd55` expose and Real-DOM-gate the organization workspace. These are foundations, NOT a claim that payroll, tax submission, consolidation, ABC/ABB or all Iranian legal rules are complete. Production reconciliation correction: the owner’s current instruction to apply and finish these ERP changes was acted on for this non-destructive collection expansion. Production migration `20260929221252 iran_enterprise_foundation_collections` is APPLIED and archived exactly as `supabase/migrations/20260929221252_iran_enterprise_foundation_collections.sql`; it expands the existing owner-scoped `records` collection constraint and adds uniqueness indexes for personnel number, nonblank national ID, employee/year leave and cashbox code. The later prepared `20260930222500` placeholder is neutralized as a no-op to prevent duplicate DDL. Production index verification PASS; performance advisor remains clean. Enterprise v2 code head `cf428a93` adds accounting-connected payroll, employee benefit accruals, posted petty-cash lifecycle, performance budgets, ABC allocation and intercompany/parent controls. Production also contains migration `20260929221754 iran_enterprise_financial_controls`; this transfer checkpoint archives that exact production version and neutralizes the later prepared `20260930223000` duplicate. Quality run `36638709409` on `cf428a93` failed at JavaScript syntax only because `scripts/quality-check.mjs` contained a literal `\\n` between two test statements; product JavaScript had already parsed before that point. This checkpoint repairs that test-script syntax. Security run `36638709566` was still in progress when the transfer checkpoint was prepared. Therefore the enterprise-v2 slice remains IN PROGRESS / final CI NOT VERIFIED, not completed. A second generated literal `\\n` remained between the v1/v2 script tags in `index.html`; this checkpoint removes it before rerunning the combined gate. The first replacement targeted two backslashes rather than the single literal backslash sequence actually stored; Quality attempt 2 of `36639039078` proved the invariant still failed. This checkpoint performs the byte-correct replacement and verifies the in-memory result no longer contains `</script>\\n<script`. A dedicated deterministic enterprise behavior gate is added for 1405 payroll-tax bracket boundaries and Jalali service-period calculations, so these legal/accounting calculations are not protected only by static/DOM tests. Quality run `36639392719` passed syntax, application invariants, Phase 2–6, the new enterprise behavior gate and Golden Journey; Real DOM then exposed a browser global collision on generic constant name `IR_RULES`. This checkpoint namespaces the v1 registry as `FINORA_IR_RULES` to remove that collision without changing rule semantics. Run `36639665234` proved the browser still evaluated the v1 script more than once in the smoke environment, so renaming a lexical `const` was insufficient. This checkpoint makes both enterprise scripts idempotent under repeated evaluation by storing registries/render base on `window` and avoiding top-level lexical declarations that throw on a second load. |\n| 2026-09-30 | Owner directs Finora toward a daily-use accountant-first ERP, with defect elimination and Chart-of-Accounts UX as highest priorities. Immediate product requirements: rename the primary `پروژه` subsystem to `پیمانها`; after a new user verifies/signs in, collect their real display name and non-privileged professional usage role (e.g. owner/manager, financial manager, accountant) without allowing self-escalation to system admin; make license company capacity commercially controllable by the central system admin with default 1 company and explicit N-company licenses; distinguish ordinary multi-company licensing from a true holding/group model; research holding/company classification (private/public/government/cooperative/etc. and parent/subsidiary structures); expand ERP roadmap to integrated CRM and payroll/HR plus other evidence-backed gaps from leading Iranian/international ERP products. | IN PROGRESS | Live DB confirms `profiles.full_name` already exists, so display-name onboarding needs no schema change. `profiles.role` is intentionally only `user/admin`; professional role must remain separate and must never self-grant admin. Current `licenses` has no company-capacity field, so authoritative max-company enforcement requires a prepared DB migration/RPC update and must NOT be applied until the required explicit schema/role-change approval checkpoint. Holding is architecturally distinct from N independent companies: benchmark evidence from Dynamics/Acumatica/Odoo/SAP shows legal entities/subsidiaries, intercompany entries, consolidation, eliminations and currency translation as separate concerns. Immediate executable slice: rename rail to `پیمانها`, implement first-login name/professional-role onboarding using existing profile/records storage, strengthen company creation with a default-one client guard ready to consume authoritative license capacity, improve Chart-of-Accounts daily workflow, and archive a benchmark-backed ERP gap/holding roadmap. This code checkpoint implements the non-schema portion: primary rail/panel is visibly `پیمانها`; first-login onboarding stores display name + non-privileged professional role in the existing owner-scoped `settings` record (system `user/admin` role is untouched); company master gains organizational position (`standalone`/`holding_parent`/`subsidiary`) and parent-company relation metadata with an explicit warning that consolidation is separate; company creation enforces the current license capacity with default 1; admin UI is capacity-aware but keeps the capacity field disabled until the server column/RPC exists; Chart of Accounts gains search/level/type/status filters, hierarchy path, safe unused-account editing, and deactivate/reactivate for historical accounts. No DB/auth/RLS/role mutation in this checkpoint. Real-DOM fixture is updated so its synthetic admin has completed professional onboarding; this prevents the intentional first-login modal from masking unrelated shell acceptance while preserving a production onboarding path. Superseded Quality run `36632890281` on `7e7e5264` passed JavaScript syntax and failed only because the new static gate incorrectly searched `index.html` for Chart-of-Accounts controls that are intentionally generated by `accounting-foundation-ui.js`; this checkpoint corrects that gate to inspect the owning module. The prepared trigger function also has PUBLIC/anon/authenticated EXECUTE revoked because it is trigger-only. Superseded run `36632957187` on `22040d37` also stopped at the same already-corrected static-gate defect before later phases. Latest executable/test head `8f8824a8` is now verified: Quality run `36633047472` PASS including JavaScript syntax, application invariants, Phase 2–6, Golden Accounting Journey and Real DOM smoke; Security run `36633047693` PASS. The following docs-only head `78af1011` deployed successfully via Pages run `36633139737`. Prepared schema/RPC migration remains unapplied. Prepare (do not apply) the server migration for license company capacity. Prepared migration `supabase/migrations/20260930213000_license_company_capacity.sql` adds `licenses.max_companies default 1`, guarded admin RPC `admin_set_company_limit`, and a server-side AFTER INSERT company-count trigger so direct/sync inserts cannot bypass entitlement. It is intentionally NOT APPLIED pending the mandatory explicit schema/RPC approval. ERP/holding/CRM/payroll research and prioritization is archived in `docs/FINORA_ERP_EXPANSION_ROADMAP_V4.md`; CRM and payroll are P1 after financial-control P0, while true holding consolidation is P2 because it requires intercompany, mapping, translation, eliminations and consolidated close rather than just parent IDs. CRM/payroll/holding are roadmap modules until their lifecycle/persistence/accounting/permissions/tests exist; do not expose fake operational modules. |
38
-| 2026-09-30 | Owner rejects the current first-pass accountant UX as insufficient and requests a broader evidence-based redesign synthesis from strong Iranian and international accounting/ERP products. Apply the best compatible patterns to Finora without cloning a vendor: preserve the narrow primary rail + adjacent contextual subsystem panel; remove repeated/unrelated accounting-document surfaces leaking into other subsystem workspaces; replace the disappearing `×` close affordance with a persistent edge-mounted collapse/expand handle so the contextual panel is always recoverable; and extend company definition so operational activity type (trading/service/manufacturing/etc.) is separate from person/legal identity and legal form (natural person, joint-stock/private/public, LLC, partnership, etc., plus institution/public/government/other where applicable). User supplied four current Finora screenshots as direct defect/design evidence. | IMPLEMENTED / FINAL CI VERIFICATION PENDING | Benchmark reviewed across Iranian patterns (Rahkaran/System Group, Sepidar, Parmis Star, Mahak and prior repo research) and international official structures (Microsoft Dynamics 365 Finance, Oracle Fusion Financials, SAP S/4HANA Finance, Xero, Zoho Books, QuickBooks, Sage Intacct, Acumatica, Odoo/NetSuite references). Strong recurring pattern: stable top-level financial domains, task-focused contextual navigation, global create/search, separation of master/setup vs transactions vs reports, and legal-entity/company context distinct from operational accounting classification. Current screenshots prove `اسناد حسابداری` is leaking below Inventory and Settings task content and the contextual panel uses a top `×` that becomes unavailable after collapse. Root cause confirmed in code: `ensureJournalView()` created `#view-journal` with class `view` instead of the shell's canonical `view-pane`, so `switchView()` never hid it; this is why the screenshots show Accounting Journal under unrelated modules. Implementation in this checkpoint converts it to a true view pane, removes the internal `فاز ۳` production badge, adds the persistent edge handle and global quick-create menu, and separates company person/sector/legal-form/activity metadata without a database schema change. Benchmark synthesis is archived in `docs/FINORA_UX_ACCOUNTING_BENCHMARK_V3.md`. Information architecture is also normalized around the recurring benchmark pattern: Accounting now groups `ساختار مالی` → `ثبت و عملیات` → `دفاتر و کنترل` → `صورتهای مالی و تحلیل`; expense/income is owned by Accounting instead of Commerce; Commerce is reduced to people/items + sales + purchasing; Treasury keeps operational receive/pay/cheques plus contextual aging/cash-flow links. These are navigation ownership changes over existing implemented capabilities, not new fake modules. Static and real-DOM navigation expectations are updated in the same checkpoint so CI validates the new accountant-first IA instead of preserving obsolete labels. Before product edits, reconcile latest CI: run `36627449874` on `fb275453` passed syntax + application + Phase 2–6 + Golden Journey; only Real-DOM failed on non-formal paper-kind expectation and a brittle raw-PDF regex parser. Implemented through code head `db7784d1`: benchmark archive `docs/FINORA_UX_ACCOUNTING_BENCHMARK_V3.md`; persistent edge collapse/reopen handle; global quick-create over existing workflows; journal `view-pane` isolation and removal of the internal Phase-3 badge; accountant-first Accounting/Commerce/Treasury grouping; company person type + ownership/sector + legal form + operational activity metadata; non-formal print accepts both `non_formal` and legacy `informal`; PDF acceptance now uses `pdf-lib` instead of raw-byte regex. Superseded run `36629795213` on `4df0825f` passed repository syntax but failed the old static IA labels; `db7784d1` updates those stale static/DOM expectations. Local connector-side parse checks PASS for `ui.js`, `companies.js`, `journal-ui.js`, `print.js` and `dom-smoke.spec.js`. No failure notification has appeared yet for `db7784d1`, but its exact push-run ID/result is not exposed, so Quality/real-DOM/PDF remains NOT VERIFIED rather than assumed PASS. Supabase rechecked ACTIVE_HEALTHY, 17 migrations through `20260929193357`, RLS enabled on all three public tables, performance advisor clean; known 5 SECURITY DEFINER warnings + leaked-password warning unchanged. No schema/RLS/auth/role mutation was made. Physical-printer validation remains NOT VERIFIED. No schema/RLS/auth/role change is planned; company metadata remains inside the existing records model. |
39
-| 2026-09-29 | Owner clarified the navigation interaction after reviewing Rahkaran web: primary modules must NOT expand accordion-style beneath themselves; selecting Accounting/another module must populate the adjacent vertical contextual panel, matching the approved screenshot. Owner also supplied three real browser-print PDFs proving a severe print-isolation regression: formal invoice and pre-invoice include application UI pages before the invoice; non-formal A5 also includes UI pages and opens with incorrect A4/default behavior. Research Rahkaran web/module concepts, then repair all invoice print modes so only the print document enters the print tree with deterministic paper/orientation/pagination. | IMPLEMENTED / CI FINAL VERIFICATION PENDING | External review confirms Rahkaran Cloud is web-delivered and organized as modular financial/sales/logistics/etc. solutions; Rahkaran accounting training exposes distinct account-definition, voucher-entry and reporting tasks rather than one dumped workspace. User PDFs are stronger direct evidence for the print defect: UI is printed before the invoice in all three samples. Rahkaran review confirms the useful pattern is modular task separation (base information/account structure, voucher operations, reporting) while the owner explicitly rejects Rahkaran-style cascading expansion for Finora. Current Finora desktop already renders those groups in the adjacent vertical `module-panel` rather than nested beneath the rail, so that interaction is retained and now treated as a contract. Print root cause confirmed: browser printing still depended on hiding the live application DOM; the supplied PDFs demonstrate that this isolation is not reliable enough. This checkpoint moves invoice/electronic-document printing into a dedicated same-origin iframe document containing only invoice pages, with explicit CSS `@page` A4-landscape for formal/pre-invoice and A5-landscape for non-formal, plus a strict live-DOM fallback. Real-DOM tests now assert zero application-shell nodes in the print document and Chromium PDF generation checks actual A4/A5 landscape MediaBox dimensions. Immediate pre-CI syntax review caught over-escaped regex literals in the newly added PDF MediaBox test itself (product print code parsed cleanly); `6686c9ed` replaced them with explicit RegExp constructors and the full DOM smoke script parses successfully. Superseded Quality run `36627088224` on `49c16bcf` then passed the repository syntax gate and failed only because `quality-check.mjs` still required the removed legacy local-page-size variable `const a4Landscape=isFormal||isPreInvoice`. `cc4fa1f` updated the general quality contract. Quality run `36627278247` then passed syntax, application invariants and Phase 2, and its Phase 3 engine checks themselves printed PASS before a second stale print needle in `phase3-check.mjs` stopped the workflow. This checkpoint updates that remaining Phase 3 static print contract to the isolated-frame/A4/A5 invariants; no accounting behavior is changed. Final implementation head before this docs-only checkpoint is `fb275453`: isolated print implementation `49c16bcf`, test-syntax repair `6686c9ed`, general print gate `cc4fa1f`, Phase 3 print gate `fb275453`. Superseded runs `36627088224` and `36627278247` are fully diagnosed stale-gate failures, not product-print failures. No failure notification is currently present for `fb275453`, but push-run IDs/success notifications are not exposed by the connector, so latest Quality/real-DOM/PDF acceptance remains NOT VERIFIED rather than assumed PASS. Supabase was rechecked ACTIVE_HEALTHY with 17 migrations through `20260929193357`, and RLS remains enabled on profiles/licenses/records; this slice made no database/schema/RLS/auth changes. Physical printer behavior remains NOT VERIFIED even after browser-PDF acceptance. |
40
-| 2026-09-29 | Owner rejected the current workspace-dump navigation. Redesign Finora around the approved two-tier enterprise shell shown in the canonical screenshot: primary module rail + rich contextual subsystem menu; replace `خانه` with `داشبورد`; keep owner-approved domain grouping such as sales/purchases/contacts under بازرگانی; give accounting and every major module organized groups (e.g. پایه/عملیات/دفاتر و گزارشها/ابزارها) with one clear action/view per menu item. Before implementation, research multiple Iranian accounting/ERP products (not one vendor), official product structures/demos plus user/accounting-community feedback, synthesize patterns without copying a vendor, then migrate existing working views into the hierarchy without feature loss or fake modules. | IMPLEMENTED / CI FINAL VERIFICATION PENDING | Research completed across the approved screenshot, live shell, Sepidar official system/accounting pages and training UI, Rahkaran/System Group module structure, Holoo task/report material, Gheyas/user feedback and independent review feedback. Synthesis is recorded in `docs/FINORA_INFORMATION_ARCHITECTURE_V2.md`: nine primary business modules, rich grouped contextual menus, task-level navigation, no `خانه`, no standalone `کالا`, no generic `ERP`, and no fake future modules. IA contract committed at `9631f6ef`. This implementation checkpoint replaces the rail with Dashboard/Accounting/Commerce/Treasury/Projects/Inventory/Fixed Assets/Reports/Settings; removes `خانه`, standalone `کالا` and generic `ERP`; expands Accounting into grouped base/operations/books-report commands; and introduces task-level workspace focusing so account chart, floating dimensions, rules, fiscal years, branches, projects, journal entry/register, reports, inventory/assets/data-center tasks no longer dump unrelated cards together. Commerce retains contacts/products/sales/purchases. Real-DOM gates are extended to verify the new hierarchy and focused task behavior. Pre-CI review found and corrected one contradictory legacy `erp` rail assertion, added task-aware command-search routing/context, and hides the empty fiscal/branch grid wrapper when another accounting task is focused. Quality run `36624026541` on `dcb0d4ab` proved JavaScript syntax PASS but exposed a stale Phase 5 gate that still required every Phase 5 view to map to the removed generic `erp` module. The gate is updated in this checkpoint to verify the new canonical ownership (`inventory`, `assets`, accounting currency, settings data/integrations), reject deprecated `home/catalog/erp` rail entries, and require the new accounting hierarchy. Dashboard is also rebuilt in this checkpoint to match the approved analytical direction without fabricated values: white enterprise KPI cards for assets/cash/receivables/payables, six-month cash-in/out SVG from actual payment records, account-status bars, task-level quick access and latest journal vouchers. All values are derived from the existing ledger/operational data and remain zero/empty when no production accounting data exists. Quality run `36624183478` on the pre-dashboard `c254e5f1` passed syntax, application invariants, Phase 2–6, Golden Journey and browser installation; Real-DOM alone failed because `openModule()` rendered the selected task and then `switchView()` reset the contextual panel before the non-rerendering navigation returned. The product navigation state bug is fixed here by making `openModule()` complete the canonical task navigation/rerender path. The analytical dashboard checkpoint `96adf600` is retained. Direct-view compatibility is hardened: switchView clears any previous task filter; task navigation then reapplies the requested focus. Real-DOM verifies focused mode and reset-to-full-view behavior. Settings is also decomposed into task-level routes: company, account/password, invoice defaults, operational settings, data/backup, integrations, about, and admin/license. Topbar company and fiscal-year pills now deep-link directly to their canonical tasks instead of dumping the full settings page. Real-DOM adds a focused company-settings assertion. Run `36624545469` on `f3f15aa` proved the new enterprise shell/task navigation Real-DOM PASS; the only failure was the separate expired-license test because the dashboard visual rebuild had removed the legacy `user-license-status-badge` element that `updateLicenseDisplay()` owns. This is a real UI regression, not a test-only issue. The badge is restored inside the new dashboard header in this checkpoint, preserving license visibility/enforcement while keeping the new analytical layout. Real-DOM acceptance is extended once more to render the redesigned dashboard under the stubbed authenticated session and require the assets KPI, cash-flow SVG and recent-journal surface to exist before continuing accounting/inventory/print checks. CI verification is required next. Durable implementation chain: IA research/contract `9631f6ef`; shell/task routing `22bb7a27`; navigation/search gates `dcb0d4ab`; stale CI ownership gate repair `c254e5f1`; analytical dashboard `96adf600`; module-open state fix `4cecc1f6`; direct-view task reset `f3f15aa2`; focused settings `b2fff128`; restored license badge `9b99e7e1`; dashboard DOM gate `761131c6`. Run `36624545469` proved the enterprise shell/task navigation itself passes real DOM and all Phase 2–6/Golden gates; its remaining expired-license failure was caused by the dashboard badge regression fixed at `9b99e7e1`. No failure notification has been observed yet for the latest code head `761131c6`, but the exact latest push-run ID is unavailable through the connector, so final combined CI remains NOT VERIFIED. |
41
-| 2026-09-29 | Continue post-release hardening after the executable accounting/database fixes; close remaining verifiable acceptance gaps without claiming external/manual checks. | IN PROGRESS | Browser checkpoint `2c6bab32` adds real-Chromium expired-license enforcement: expired subscription renders expired, `canWrite()` is false and `requireWrite()` blocks mutation. This checkpoint also adds a deterministic 20,008-line Phase 6 reporting workload covering rollup/trial-balance equality, P&L correctness, ledger row preservation and a 5-second CI regression ceiling. Pre-CI review caught that the dated ledger filter correctly excludes the two February seed lines, so the expected January workload is 20,006 rather than 20,008; the assertion is corrected in this checkpoint before acceptance. Latest executable code head is `9822bad8`: it corrects the dated performance expectation before acceptance. The prior superseded run `36621990092` on `b992e486` confirms syntax, application invariants and Phase 2–5 (including depreciation reversal) all PASS, then fails only on the now-corrected January ledger-row expectation before Golden/DOM steps. Additional live production rollback-only security QA exercised all three admin license mutation RPCs (`cancel`, `extend`, `set`) under a non-admin authenticated JWT; all were denied with the shared internal admin guard, while `is_admin=false`; transaction rolled back. Supabase performance advisor remains clean; security advisor still reports the five intentional SECURITY DEFINER-callability warnings plus leaked-password protection disabled. Latest `9822bad8` push-run ID remains unavailable through the connector and no failure notification has appeared yet, so combined Quality/real-DOM remains NOT VERIFIED. |
42
-| 2026-09-29 | Owner supplied another GitHub Actions failure (`golden-accounting-core-check.mjs`: `revenue report mismatch`) and asked for exact current progress plus continuous diagnosis/fix until the hardening work reaches a verified conclusion. Treat repeated run failures as blockers, distinguish superseded-run failures from current-head failures, and do not stop after a single fix while executable work remains. | IMPLEMENTATION COMPLETE / FINAL EXTERNAL VERIFICATION REMAINS | The supplied failure at `19:25:15Z` maps to the custom-chart transition around `d6b293e4`, not the later documentation head. Root accounting/report defect identified: Phase 6 `rollup()` discarded the account-master `accountType`, so `financials()` could not actually use the explicit classification promised by the earlier custom-chart hardening and silently fell back to code/title heuristics. This checkpoint preserves `accountType/systemRole` in report rollups, makes cash-flow use the explicit cash system role, and strengthens the Golden Journey with neutral arbitrary account titles plus diagnostic expected/actual values. CI run `36620001387` on `768f97ab` proves JavaScript syntax, application invariants, Phase 2–6 behavior, Golden Accounting Journey and browser-runtime install all PASS. Its only failure was the new print DOM assertion using Playwright `toContainText()` on a `<style>` element; GitHub log showed the style element actually contained `A4 landscape`. Commit `9d0a3122` corrected the assertion to inspect style `innerHTML`, archived/applied production migrations under exact versions `20260929193348` and `20260929193357`, and production rollback-only QA proved settled-cheque immutability plus case-insensitive account-code uniqueness with zero QA rows left. Depreciation reversal was then implemented without weakening immutable source history at `e70b07a1`; run `36620902948` exposed only a Node-VM harness omission (`getMyJournalVouchers` absent), corrected at `521b0de7`. No GitHub failure notification for `521b0de7` was present in the connected mailbox after the normal failure-notification window, but the exact push-run ID is unavailable through the current connector, so latest-head CI/real-DOM is NOT VERIFIED rather than assumed PASS. |
43
-| 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. | FIXED / CI VERIFICATION PENDING | 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. Root cause fixed at `78c6a071`; follow-up CI repair `20294e31` removed the hidden duplicate Phase 2 declaration, checks syntax of all MJS gates and avoids duplicate Phase 6 execution. `18ea5c8b` added Quality/Security concurrency cancellation plus real-Chromium A4/A5 pagination/page-break checks, reducing superseded-run noise. Subsequent requirement hardening: legacy-company starter-chart fix `3b3ffba2`; custom-chart system posting roles + arbitrary-code Golden Journey `d6b293e4`; role-aware AR/AP/cash-flow/project-contract reporting and prepared role uniqueness `dbe9170c`; incremental self-healing posting profiles `73bd9f3f`. Push-run IDs remain unavailable through the current connector, so latest CI/real-DOM is still NOT VERIFIED; any new failure log must be diagnosed before acceptance. |
44
-| 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. Server-side source immutability migration is now APPLIED in production as `20260929193348 posted_source_immutability_guard`; trigger `trg_finora_guard_posted_source_records` is verified present. The repository archive is normalized to the exact production migration version in this checkpoint. 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 implementation checkpoint `e70b07a1` initially exposed a Node-VM harness omission in Quality run `36620902948`: the isolated Phase 5 test context did not provide `getMyJournalVouchers()`, so the conservative production fallback treated the depreciation as active. Product code was not the failing path. The harness is corrected in the next checkpoint to supply the same journal accessor available in the real app. Depreciation reversal design gap is closed without weakening the production immutability trigger: the posted depreciation source remains immutable, while its journal voucher is reversed; active depreciation/book value and duplicate-period checks now derive effectiveness from the linked voucher status. The UI exposes depreciation history and a controlled `برگشت سند` action, and Phase 5 behavior verifies that reversal removes the accounting effect while preserving the original posted source record. 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. Accounting/master uniqueness migration is now APPLIED in production as `20260929193357 accounting_master_uniqueness` after a duplicate-key preflight returned zero conflicts. All eight intended indexes, including unique account `systemRole` per company, are verified present. The repository archive is normalized to the exact production migration version in this checkpoint. 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. Custom-chart audit found a deeper requirement gap: imported/manual charts could exist, but automatic posting still resolved cash/AR/AP/revenue/purchase/expense/VAT mainly by Finora codes/title heuristics. The next batched checkpoint introduces explicit unique default system-posting roles on posting accounts, seeds them on company-type templates, supports them in manual/Excel chart setup, resolves posting accounts by role before legacy code/title fallback, and changes the Golden Journey to arbitrary account codes so CI proves a genuinely custom chart can still auto-post sale/purchase/receipt/payment/expense/income/VAT and reconcile reports. Custom-chart reporting follow-up: AR/AP aging and cash-flow cash detection were still title-based. The next checkpoint resolves AR/AP/cash through the same explicit system roles first, extends Phase 6 behavior to custom-title AR/AP aging plus project/contract consolidation, and extends the already PREPARED/NOT-APPLIED master-uniqueness migration with unique account system roles per company. No schema change is applied. Manual-chart audit found another functional gap: `jeEnsureDefaultProfiles()` previously returned as soon as any posting profile existed, so opening Journal midway through manual chart setup could permanently leave later receipt/payment/expense/income mappings missing. The next checkpoint makes profile seeding incremental/non-destructive and invokes it before every automatic post; behavior tests prove missing kinds are filled without replacing an existing active profile. Current hardening CI/real-DOM remain NOT VERIFIED until the latest head run completes. |
45
-| 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. |
46
-| 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. |
47
-| 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. |
48
-| 2026-09-29 | Consolidate top-level Sales, Purchases, and People navigation into a single `بازرگانی` module while preserving the underlying views and workflows. | COMPLETED | Top-level `sales`, `purchases`, `people` rail entries removed; `commerce`/بازرگانی added with فروش، خرید، اشخاص submenu and canonical view mappings. Quality run 36545021724 success; Pages run 36545024472 success; Security/CodeQL run 36545021744 success. |
49
-| 2026-09-29 | Restore invoice print contract: formal sales invoice = A4 landscape, pre-invoice = A4 landscape, non-formal invoice = A5 landscape; preserve standard print margins and page fit. | COMPLETED | `js/print.js` fixed on main: formal/pre-invoice A4 landscape with 5mm print margin; non-formal A5 landscape with 5mm margin; page-fit widths set to printable landscape areas. Regression gates updated in `scripts/quality-check.mjs` and `scripts/phase3-check.mjs`. Implementation commits `a7e14ec1`, `baa46715`, gate correction `4550f239`; Quality run 36544154873 success; Pages run 36544154397 success. Final checkpoint head `75cf79e5` re-verified: Quality run 36544278076 success; Security/CodeQL run 36544278147 success; Pages deployment run 36544277692 success. |
50
-| 2026-09-29 | Reopen and fully harden Phase 3 after independent accounting review; fix fiscal-date posting, non-accounting document posting, reversal reconciliation, atomic persistence, server-side ledger guards, concurrency uniqueness and behavioral verification. | COMPLETED | Supabase migration `20260929083130 phase3_hardening_atomic_sync_and_ledger_guards` applied. Final implementation/evidence head before state closure: `c02e714c`; Quality run 36543480690 success; Security run 36543480544 success; Pages run 36543480478 success; Supabase migration/functions/unique indexes verified; Performance advisor clean. |
51
-| 2026-09-29 | Establish a permanent in-repository continuity file so any future AI/chat can resume without relying on conversation history. Every material request must be recorded here before implementation and every durable checkpoint must update this file. | COMPLETED | `PROJECT_STATE.md` created in commit `9436b9014f8ce59e1a8c8dc238d1050831785c8f`; root `AGENTS.md` discovery instructions added in `dcabf31e7f9454ff84441cadb1e9aef85fff964c`. |
52
-| 2026-09-29 | Continue product under working name Finora; final commercial brand may change later. Do not block engineering on naming. | ACTIVE DECISION | Rebrand must be a controlled migration when a final name is chosen. |
53
-| 2026-09-29 | Six-phase redesign/ERP roadmap supersedes older phase numbering. | COMPLETED ROADMAP | Phases 1–6 are verified complete; current work is post-release validation/hardening and source-contract reconciliation. |
54
-| 2026-09-29 | Owner reaffirmed permanent autonomous-manager behavior, five high-assurance specialist workstreams, mandatory pre/post change capture, and the approved Finora dashboard image as the visual source of truth for every future AI/chat. | COMPLETED | Root `AGENTS.md` + `PROJECT_STATE.md` are mandatory; visual path `docs/reference/finora-ui-target-v1.jpg`; original owner-upload SHA-256 `6bef9d5bbf7e309455b1014864c80026c2ed50fa716e9fa6b0554dacec4f12db`; portable bootstrap stored in `AI_BOOTSTRAP.md`. |
55
-| 2026-09-29 | Owner reaffirmed durable cross-chat project continuity, five specialist workstreams, mandatory change capture, and the approved Finora dashboard as the visual source of truth. | COMPLETED | State/governance `69d0640c` + `041e6da4`; portable bootstrap `5dfb95ea`; UI reference docs `13def61f`; legacy pointer `897b7ad5`; README discovery `14effed9`. Canonical visual: `docs/reference/finora-ui-target-v1.jpg`; original screenshot SHA-256 `6bef9d5bbf7e309455b1014864c80026c2ed50fa716e9fa6b0554dacec4f12db`. Quality and Pages succeeded on `14effed9`; Security/CodeQL was still running when this checkpoint was written and must be rechecked by the next worker if not yet complete. |
56
-| 2026-09-29 | Make the repository itself the durable brain for every future chat/agent; add autonomous execution governance, five specialist workstreams, and a canonical UI visual so no successor drifts from the approved product direction. | COMPLETED | Governance is encoded in this file and `AGENTS.md`; canonical visual is `docs/reference/finora-ui-target-v1.jpg`. The owner re-supplied the same approved 16:9 target on 2026-09-29; successors must use the repository reference and must not invent a replacement. |
57
-
58
-
59
-## Execution authority and engineering standard
60
-
61
-The worker reading this file is the **implementation owner and coordinating project manager for the current task**. Within the user's already-approved project scope, make normal, reversible engineering decisions autonomously and keep moving. Do not repeatedly ask the user to choose ordinary implementation details that can be resolved from requirements, evidence, accounting correctness, maintainability, security and UX.
62
-
63
-This authority is operational authority inside the project; it is **not permission to impersonate the user** in external/legal/public contexts. Destructive irreversible actions, paid actions, public publication, messages to third parties, sensitive access changes, or decisions outside the approved project scope still require the appropriate explicit authority.
64
-
65
-This is financial/accounting software. Treat correctness as safety-critical:
66
-- prefer rejecting an invalid financial state over silently accepting it;
67
-- preserve auditability and historical identity;
68
-- enforce critical invariants at the data/domain boundary, not only in UI;
69
-- use atomic writes/transactions where supported;
70
-- posted accounting history is immutable; corrections use reversal/amendment;
71
-- fiscal locks, authorization/RLS, source-to-ledger traceability and reconciliation are mandatory;
72
-- never fabricate test results, migrations, deployment status or connector access;
73
-- never present mock/demo data or an incomplete form as a completed accounting capability.
74
-
75
-Quality target: build as if the system will be relied on for high-consequence professional financial work. Use the strongest engineering/design reasoning available, while keeping architecture proportional, maintainable and testable.
76
-
77
-## Coordinated specialist workstreams
78
-
79
-For substantial work, coordinate these five specialist responsibilities. If the execution environment has real sub-agent support, delegate independent tasks with one clear owner each. If it does not, execute the same responsibilities as explicit internal workstreams and **do not claim independent agents were created**.
80
-
81
-1. **Architecture & Accounting Rules** — owns domain model, accounting invariants, posting contracts, migrations, compatibility and acceptance criteria.
82
-2. **Implementation & Integration** — owns production code, schema/data integration, source-document flows, synchronization and maintainable implementation.
83
-3. **UX/UI & Product Design** — owns information architecture, workflows, RTL/responsive/accessibility, visual consistency and the canonical design direction below.
84
-4. **QA & Reconciliation** — independently validates behavior, regression, accounting balance/reconciliation, edge cases, migration fixtures and reproducible failures.
85
-5. **Security, Data Integrity & Release** — owns RLS/permissions, immutable history, backup/rollback, performance/security gates, deployment evidence and release readiness.
86
-
87
-The coordinating manager resolves conflicts by: accounting/data correctness -> user requirement -> security/auditability -> maintainability -> UX -> implementation convenience. Every task has one primary owner even when other workstreams review it.
32
+| 2026-09-30 | Owner authorizes `@GitHub` and `@Supabase` to perform the required remaining work without further routine permission prompts and directs the project to continue until executable remaining work is finished. | IN PROGRESS | Pre-implementation reconciliation: live head `9d9caade2c3e34d7608e540e40b09ab23f0d19e9`; Quality `36639873677` FAIL only at Real-DOM company natural/legal test ordering; all syntax, application, Phase 2–6, enterprise payroll/service-period and Golden Accounting Journey gates PASS; Security `36639873830` PASS; Pages `36639873547` PASS. Supabase `hcsixhqbyuhpshfwqpjx` is `ACTIVE_HEALTHY`, PostgreSQL 17.6.1, 21 migrations through `20260929221754`, RLS enabled on `profiles/licenses/records`, 97 records, performance advisor clean. Security advisor currently has 6 authenticated-callable SECURITY DEFINER warnings (the prior five plus `admin_set_company_limit`) and leaked-password protection disabled. Immediate executable action: fix the Real-DOM test ordering without weakening the product invariant, rerun full gates, then continue only with remaining work that can be verified with available tools. |
33
+| 2026-09-30 | Expand Finora into a high-assurance Iran-first enterprise ERP governed by current Iranian accounting/tax/VAT/Taxpayer-System/commerce/labor/social-security requirements; include standards-aware statements/chart templates, HR/payroll/benefits/leave, treasury/petty cash, inventory/costing/ABC/performance budgets, intercompany/group controls and compliance traceability. Natural/legal identity, operational activity and group-company structure must remain separate concepts. | IN PROGRESS | Iran compliance baseline: `docs/IRAN_COMPLIANCE_MATRIX_V1.md`. Implemented foundations include starter-chart roles, natural/legal cleanup, employees/contracts/leave/cashboxes/petty-cash/compliance registry, accounting-connected payroll, benefit accruals, petty-cash lifecycle, performance budgets, ABC allocation and intercompany/parent controls. Production migrations `20260929220543`, `20260929220613`, `20260929221252`, `20260929221754` are applied and archived. Do **not** claim statutory consolidation, full tax submission, full HR/CRM, or every Iranian rule complete until their lifecycle/accounting/permissions/tests exist. |
34
+| 2026-09-30 | Daily-use accountant-first ERP: primary `پروژه` becomes `پیمانها`; first-login display name + non-privileged professional role; commercial company-capacity licensing; distinguish multi-company licensing from true holding; improve Chart of Accounts workflow and expand evidence-backed ERP roadmap. | IN PROGRESS | License capacity is live (`licenses.max_companies`, admin RPC, server company-count enforcement); professional role remains separate from system `user/admin`; Chart of Accounts search/filter/hierarchy/safe edit/deactivate exists; roadmap: `docs/FINORA_ERP_EXPANSION_ROADMAP_V4.md`. Final current-head Real-DOM verification is pending the test-order fix above. |
35
+| 2026-09-30 | Preserve approved accountant-first two-tier shell, persistent contextual-panel handle, task-focused navigation, isolated printing, and separate company legal identity/legal form/activity/group metadata. | IMPLEMENTED / FINAL VERIFICATION PENDING | Canonical UX evidence: `docs/FINORA_UX_ACCOUNTING_BENCHMARK_V3.md`; current failure is a Playwright fixture-order defect, not a proven product regression. Browser-PDF tests for A4/A5 isolation pass in run `36639873677`; physical-printer validation remains `NOT VERIFIED`. |
36
+
37
+## Current verified live state — 2026-09-30
38
+- Pre-request live head: `9d9caade2c3e34d7608e540e40b09ab23f0d19e9` (`Make Iran enterprise scripts idempotent in browser`).
39
+- Quality `36639873677`: **FAIL** only at Real-DOM. Failure: test selects `natural`, which immediately hides `#company-reg-input`, then attempts to `fill` that hidden legal-only field. Other two DOM tests (expired-license enforcement and isolated CSS-paper PDF) pass.
40
+- In that same Quality run: JavaScript syntax PASS; application invariants PASS; Phase 2 PASS; Phase 3 static + behavioral PASS; Phase 4 PASS; Phase 5 PASS; Iran enterprise behavior PASS; Phase 6 PASS; 20k reporting performance PASS; Golden Accounting Journey PASS.
41
+- Security `36639873830`: PASS. Pages `36639873547`: PASS.
42
+- Supabase project `hcsixhqbyuhpshfwqpjx`: `ACTIVE_HEALTHY`, PostgreSQL `17.6.1.166`, 21 migrations through `20260929221754 iran_enterprise_financial_controls`.
43
+- Public tables: `profiles` 4 rows, `licenses` 4 rows, `records` 97 rows; RLS enabled on all three. `licenses.max_companies` exists with default 1.
44
+- Performance advisor: no findings.
45
+- Security advisor: 6 WARN findings for authenticated-callable SECURITY DEFINER functions (`admin_cancel_license`, `admin_extend_license`, `admin_set_company_limit`, `admin_set_license`, `has_active_license`, `is_admin`) plus leaked-password protection disabled. Admin mutation functions have previously passed non-admin negative authorization checks; do not blindly revoke required authenticated admin RPC access merely to silence the linter.
46
+- Supabase Sep-2026 changelog review: project is still PostgreSQL 17.6.1 while 17.11 is available; upgrade/reindex implications must be assessed separately if/when platform upgrade tooling is available. No upgrade was performed here.
47
+
48
+## Master roadmap status
49
+The original six-phase roadmap remains accepted and must not be reopened without verified regression or proven requirement gap:
50
+1. Phase 1 UX/product shell — COMPLETED.
51
+2. Phase 2 master data + accounting foundation — COMPLETED.
52
+3. Phase 3 double-entry operational accounting — COMPLETED/HARDENED.
53
+4. Phase 4 projects/contracts/contractor accounting — COMPLETED/RE-VERIFIED.
54
+5. Phase 5 inventory/costing/assets/multi-currency/import/integrations — COMPLETED.
55
+6. Phase 6 professional reports/reconciliation/release — COMPLETED.
56
+
57
+Current work is **post-release hardening + Iran-first enterprise expansion**, not a reset of Phases 1–6.
58
+
59
+## Accounting/data invariants
60
+- Posted journal lines are accounting truth; operational documents are traceable source documents.
61
+- Posted/reversed vouchers and posted source history are immutable; correction uses reversal/amendment.
62
+- Every posted voucher balances debit = credit and obeys fiscal lock/date rules.
63
+- Source event/version uniqueness prevents duplicate posting; failed posting must not leave orphan drafts/lines.
64
+- Account classification/system posting roles must support custom/manual/Excel charts; reports must not depend only on Persian titles/codes.
65
+- Counterparties/projects/branches/contracts are global masters/analytic identities, not one ledger account per entity.
66
+- Analytic dimensions remain normalized/generic; configured floating slots are a compatible product contract, not fixed storage columns.
67
+- Group/non-leaf analytic nodes are non-postable when leaf-only rules apply.
68
+- Tenant isolation is mandatory at RLS/data boundary; authorization must not rely on user-editable metadata.
69
+- Restore/sync must preserve immutable financial history and resolve server uniqueness/immutability conflicts authoritatively.
70
+- No destructive historical migration without preview, reconciliation and rollback evidence.
71
72
## Canonical UI / visual source of truth
73
+Approved target: `docs/reference/finora-ui-target-v1.jpg` (owner-upload SHA-256 `6bef9d5bbf7e309455b1014864c80026c2ed50fa716e9fa6b0554dacec4f12db`). Preserve the narrow RTL primary rail, adjacent contextual subsystem panel, topbar context/search/actions, task-focused workspaces and restrained enterprise financial visual language. Do not expose roadmap-only modules as operational.
74
91
-**Approved visual reference (fixed canonical path):** `docs/reference/finora-ui-target-v1.jpg`
92
-
93
-
94
-
95
-The repository JPG is the canonical durable visual copy of the owner-approved 1536×864 (16:9) screenshot supplied on 2026-09-29. The original uploaded JPEG is fingerprinted by SHA-256 `6bef9d5bbf7e309455b1014864c80026c2ed50fa716e9fa6b0554dacec4f12db`; do not substitute another design or generated dashboard. This image is the canonical visual target for the current Finora desktop shell. When the user asks “محیط نرمافزار الان چجوره؟”, “طرح مورد تأیید چی بود؟”, or asks to continue the redesign, open this repository image first. Do not substitute a remembered/generated/random dashboard.
96
-
97
-The owner re-confirmed this exact 16:9 design direction on 2026-09-29. The repository image is the durable visual artifact; do not rely on chat memory. If the file is missing/corrupt, treat it as a project-continuity defect and restore the approved artifact before redesign work.
98
-
99
-The image defines the direction, not fake functionality:
100
-- RTL professional financial dashboard;
101
-- narrow right module rail with compact icons;
102
-- second contextual submenu panel;
103
-- top bar for user, notifications, quick action, active company, fiscal year and global search;
104
-- spacious central workspace with compact KPI cards, charts/status panels, quick access and recent accounting records;
105
-- light, restrained enterprise visual language suitable for dense accounting workflows;
106
-- desktop-first information density with responsive behavior required on smaller screens.
107
-
108
-When implementing new modules, preserve this shell language and extend it consistently. Existing working features must be migrated into the unified architecture; do not create a separate “old” and “new” product. Do not expose future modules as operational until their actual lifecycle, persistence, accounting integration, permissions and tests exist.
109
-
110
-## Mandatory request/change capture
111
-
112
-A material user request is not allowed to live only in chat. **Before implementation**, update the Current change ledger in this file with the new requirement/decision and mark it `REQUESTED` or `IN PROGRESS`. If the request changes roadmap, accounting rules, UX target, scope or acceptance criteria, update the relevant canonical section here at the same time.
113
-
114
-After a durable implementation checkpoint, update the same ledger row with `COMPLETED`, `BLOCKED` or `DEFERRED` plus exact commit/migration/test/deployment evidence. If work is interrupted, the repository must still describe both what was requested and what remains.
115
-
116
-## User communication mode
117
-
118
-When the user explicitly says to execute without interim text/progress messages, honor that mode: perform tool work silently and send only the final completion notice, unless a genuine blocker requires a user decision. Do not substitute status chatter for execution.
119
-
120
-## Continuous execution rule
121
-
122
-For an approved phase/task, do not stop at planning, one file, one subtask, one commit or a progress explanation. Continue while executable work remains:
123
-
124
-**verify remote state -> record request -> select highest-priority unfinished dependency -> implement -> test -> diagnose -> fix -> retest -> commit/push -> verify CI/database/deployment as applicable -> update this file -> continue**
125
-
126
-Stop only for a real blocker that cannot be resolved with available authorized tools, or an action requiring authority not already granted. Before stopping for a blocker, finish all independent executable work and record the blocker and exact next action here.
127
-
128
-
129
-## Current verified project state
130
-
131
-The detailed handoff below has been reconciled through the completed six-phase roadmap. The accepted Phase 6 implementation/evidence head is `6dcb65f1`; the pre-hardening live main baseline verified on 2026-09-29 is `9159108a`. Always re-check the live `main` head before modifying code.
132
-
133
-# Finora / Factor-easy — Durable Handoff
134
-
135
-Date: 2026-09-29
136
-Repository: davoodmehraban89/Factor-easy
137
-Canonical branch: main
138
-Accepted Phase 6 implementation/evidence head: 6dcb65f1305939ba719da9b8c83ff3d43c0e292e
139
-Working product name: Finora
140
-Current public release identity: Finora 1.0
141
-
142
-## Source-of-truth rule
143
-A successor must verify GitHub and Supabase before changing anything. This file is a recovery map, not a substitute for remote evidence.
144
-
145
-## Master six-phase roadmap
146
-1. UX/product architecture redesign and scalable navigation shell.
147
-2. Master Data + Accounting Core foundation: chart, fiscal years, branches, global projects, generic hierarchical analytic dimensions, templates.
148
-3. Double-entry operational accounting: journal engine, automatic postings, ledgers/trial balance, source immutability.
149
-4. Projects, contracts, deductions, guarantees and contractor accounting.
150
-5. Complementary ERP + integrations: inventory, costing, fixed assets, multi-currency/cost centers, import/backup/permissions/settings redesign.
151
-6. Reports, control, migration and final release: professional accounting statements/reports, reconciliation/cutover of Finora 1.0 history, QA/security/performance/audit/backup/rollback/release.
152
-
153
-The older docs/ACCOUNTING_CORE_ROADMAP_V1.md contains historical labels “Phase 5..8”. Do not treat those numbers as the current master phase numbering. Preserve its accounting decisions, but follow the six-phase roadmap above.
154
-
155
-## Verified completion state
156
-
157
-### Phase 1 — COMPLETED
158
-Verification: docs/PHASE_1_REDESIGN_VERIFICATION.md
159
-Acceptance commit: c51e49a3f7863886e8a997858d6f2c44165eb5de
160
-
161
-Delivered:
162
-- compact RTL module rail
163
-- contextual second-level panel
164
-- collapsible desktop navigation with persisted preference
165
-- command/menu search and Ctrl/Cmd+K
166
-- topbar company/fiscal context and quick action
167
-- canonical view-to-module mapping
168
-- responsive/mobile compatibility
169
-- print isolation
170
-- existing operational capabilities retained
171
-
172
-### Phase 2 — COMPLETED
173
-Verification: docs/PHASE_2_REDESIGN_VERIFICATION.md
174
-Acceptance commit: 39702975a08ded8997787858383e20dab7d9afa9
175
-Acceptance CI: Quality success 36438531727; Security success 36438531722; Pages success 36438530674.
176
-
177
-Delivered:
178
-- three fixed account levels: GL/کل, Subsidiary/معین, Detail/تفصیلی
179
-- generic user-defined analytic dimensions
180
-- configurable hierarchy depth 1..8
181
-- leaf/terminal-only posting semantics
182
-- depth locked after values exist
183
-- safe delete/reference guards
184
-- account-dimension required/optional/unavailable rules
185
-- entity-backed contacts/projects/branches
186
-- fiscal years and locks
187
-- branch master
188
-- global projects and legacy contact-project migration
189
-- company activity types and optional starter templates
190
-- sync/backup/Supabase collection support
191
-
192
-Critical dimension invariant:
193
-A dimension’s hierarchy depth is explicitly configured. Once values exist, depth cannot be changed directly. Used financial identities are not destructively deleted; they are deactivated/versioned/migrated. Group nodes are non-postable when leaf-only is enabled. Storage is normalized and not limited to floating1..floating4.
194
-
195
-### Phase 3 — COMPLETED (HARDENED & RE-VERIFIED)
196
-Verification: docs/PHASE_3_REDESIGN_VERIFICATION.md
197
-Final evidence commit: 8761d21189d9c4058c3019ea6e42d4103fc83556
198
-Final head CI: Quality success 36443016075; Security success 36443016203; Pages success 36443015338.
199
-Implementation head documented in Phase 3 verification: b0f3e2587c6cc04beaf579505cb975a939459d6e.
200
-
201
-Delivered:
202
-- journal vouchers/lines and normalized line dimensions
203
-- draft -> posted -> reversed lifecycle
204
-- balanced debit/credit validation
205
-- posting-account and analytic-dimension validation
206
-- fiscal-year resolution/lock
207
-- sequential voucher numbering
208
-- source event/version uniqueness
209
-- immutable posted vouchers; reversal instead of destructive edit
210
-- manual journal UI with dynamic dimensions
211
-- journal register and trial balance
212
-- automatic posting profiles for sale, purchase, receipt, payment, expense and other income
213
-- cash/credit aware sales/purchases
214
-- VAT split behavior
215
-- source-to-voucher adapter
216
-- sync/backup persistence
217
-- source-document immutability when linked to posted vouchers
218
-- protection of used accounting masters/rules from destructive mutation
219
-
220
-Important correction:
221
-Earlier chat messages said Phase 3 was incomplete while execution was still catching up. GitHub remote evidence later closed and verified Phase 3. Current verified truth is Phase 3 COMPLETED.
222
-
223
-## Production Supabase
224
-Project ref: hcsixhqbyuhpshfwqpjx
225
-Public tables: profiles, licenses, records; RLS enabled.
226
-At handoff: profiles 4 rows, licenses 4 rows, records 84 rows.
227
-
228
-Relevant migrations:
229
-- 20260928141512 allow_accounting_foundation_collections
230
-- 20260928145306 allow_phase3_double_entry_collections
231
-
232
-Phase 3 allowed collections:
233
-- postingProfiles
234
-- journalVouchers
235
-- journalLines
236
-- journalLineDimensions
237
-
238
-At final Phase 3 verification there were no Phase 3 journal rows requiring conversion/backfill. Historical Finora 1.0 accounting cutover was intentionally deferred.
239
-
240
-Security advisor at handoff:
241
-- five WARN findings for authenticated-callable SECURITY DEFINER functions: admin_cancel_license, admin_extend_license, admin_set_license, has_active_license, is_admin. These are known and were previously reviewed as intentional with internal authorization/RLS dependencies; do not blindly revoke authenticated execute.
242
-- leaked password protection disabled in Supabase Auth; still an external/manual hardening item.
243
-Performance advisor: no findings.
244
-
245
-## Existing operational capabilities that must not regress
246
-Sales invoices, purchase invoices, contacts/counterparties, products/services, receipts/payments with partial settlement, cheques, expenses/income, companies, global projects, reporting, formal/nonformal printing, Excel import, backup/cloud sync, admin/license controls, dashboard/drilldowns.
247
-
248
-## Phase 4 — COMPLETED (RE-VERIFIED)
249
-Phase 4 implementation and acceptance were re-verified under the stricter owner rule: real Chromium DOM smoke and actual accounting-invariant tests passed in Quality run `36600894426` on `55b62db0`. Delivered implementation scope:
250
-- first-class contracts
251
-- contract amendments/status/lifecycle
252
-- employer/contractor/subcontractor relationships
253
-- contract/project links
254
-- deduction masters and schedules: retention, insurance, withholding tax, advance recovery, penalties, configurable other deductions
255
-- guarantees: type, issuer/beneficiary, bank/institution, number, amount, issue/expiry, collateral, extension/release history
256
-- optional memorandum/off-balance posting profiles for guarantees
257
-- project/contract profitability and deduction/guarantee reporting
258
-- source-to-voucher traceability for all new operations
259
-- permissions, audit, reversal, sync/backup, migration, tests
260
-
261
-Phase 4 acceptance must require master data + transaction lifecycle + posting + reversal + permissions + audit + reports + migration + tests + reconciliation. Forms alone do not complete a module.
262
-
263
-## Phase 5 — COMPLETED
264
-Complementary ERP/integration:
265
-- inventory/warehouse and costing
266
-- standard item/service master refinement
267
-- fixed assets
268
-- multi-currency
269
-- cost centers/advanced analytics
270
-- Excel/import center
271
-- backup/restore
272
-- company settings/permissions redesign
273
-- integration/API architecture
274
-
275
-## Phase 6 — COMPLETED
276
-- journal/GL/subsidiary/detail/analytic ledgers
277
-- trial balance variants
278
-- P&L, financial position, cash flow
279
-- AR/AP aging
280
-- project/contract reports
281
-- historical Finora 1.0 reconciliation and controlled cutover
282
-- QA/security/performance
283
-- audit/backup/rollback
284
-- production release
285
-
286
-## Accounting architecture decisions that are not to be casually reversed
287
-- posted journal lines become accounting truth; operational documents remain source documents
288
-- posted vouchers are immutable; corrections use reversal/amendment
289
-- counterparties/projects/branches/contracts are global masters, not cloned into account trees
290
-- do not create one ledger account per customer/supplier
291
-- analytic dimensions are generic normalized assignments, not fixed four columns
292
-- account determines which dimensions are required/optional/unavailable
293
-- group/non-leaf analytic nodes are not postable when leaf-only rules apply
294
-- historical identity/meaning must survive structural changes
295
-- templates are optional/editable setup accelerators, not hard-coded accounting rules
296
-- bank design supports stable ledger account + Bank Account master/dimension as scalable default
297
-- no destructive historical migration without preview/reconciliation/rollback
298
-
299
-## Known verification boundary
300
-A real Chromium DOM smoke is now required in CI for completion claims; it exercises the rendered login shell, stubbed post-login transition and the Phase 5 inventory workspace without production credentials. Authenticated production-user E2E and physical-printer validation remain NOT VERIFIED unless explicitly run.
301
-
302
-## Successor startup procedure
303
-1. Connect official GitHub and Supabase tools.
304
-2. Verify repository main head and read this file.
305
-3. Read docs/PHASE_1_REDESIGN_VERIFICATION.md, docs/PHASE_2_REDESIGN_VERIFICATION.md, docs/PHASE_3_REDESIGN_VERIFICATION.md, docs/PHASE_4_REDESIGN_VERIFICATION.md, docs/PHASE_5_VERIFICATION.md, docs/PHASE_6_VERIFICATION.md, docs/ACCOUNTING_CORE_ROADMAP_V1.md, docs/RD_IRAN_ACCOUNTING_ERP_2026-09-28.md.
306
-4. Verify latest Quality/Security/Pages results.
307
-5. Verify Supabase migrations/RLS/advisors.
308
-6. Do not redo Phases 1–3 unless a regression is found.
309
-7. The six-phase roadmap is complete. Continue post-release hardening/source-contract reconciliation from current remote evidence; reopen earlier functionality only for a verified regression or a proven requirement gap.
310
-8. Work continuously: inspect -> implement -> test -> fix -> retest -> commit/push -> verify -> continue.
311
-9. Never report a phase complete until its acceptance criteria and release gates are actually verified.
312
-
313
-
314
-## Mandatory interpretation of roadmap status
315
-
316
-The **current master roadmap is six phases**, regardless of older historical documents that use four phases or labels such as Phase 5–8.
317
-
318
-- **Phase 1 — COMPLETED:** scalable UX/product shell and information architecture.
319
-- **Phase 2 — COMPLETED:** master data + accounting-core foundation.
320
-- **Phase 3 — COMPLETED:** double-entry operational accounting and automatic source posting.
321
-- **Phase 4 — COMPLETED:** re-verified with real-DOM smoke plus accounting-invariant execution at `55b62db0` / Quality `36600894426`.
322
-- **Phase 5 — COMPLETED:** complementary ERP/integrations, inventory/costing/assets/multi-currency/settings/permissions/import; production migration applied and behavior/real-DOM/security gates passed.
323
-- **Phase 6 — COMPLETED:** professional reports, controlled historical reconciliation/cutover, QA/security/performance/audit/backup/rollback/release gates; accepted at `6dcb65f1` with Quality `36610113205`, Security `36610113296`, Pages `36610112562`.
324
-
325
-Do not confuse the older completed Finora 1.0 four-phase delivery with this current six-phase redesign roadmap.
326
-
327
-## How to record future work
328
-
329
-For every new material user request, add a row to **Current change ledger** before implementation using one of:
330
-- `REQUESTED`
331
-- `IN PROGRESS`
332
-- `COMPLETED`
333
-- `BLOCKED`
334
-- `DEFERRED`
335
-
336
-When completing it, update the same row with commit/migration/test evidence and adjust **Current verified project state / roadmap status / next work** if affected. Do not create a separate private handoff that can drift from this file.
337
-
338
-## Required companion evidence
339
-
340
-When relevant, verify rather than merely trust:
75
+## Required evidence / companion documents
76
- `docs/PHASE_1_REDESIGN_VERIFICATION.md`
77
- `docs/PHASE_2_REDESIGN_VERIFICATION.md`
78
- `docs/PHASE_3_REDESIGN_VERIFICATION.md`
@@ -346,36 +81,22 @@ When relevant, verify rather than merely trust:
81
- `docs/PHASE_6_VERIFICATION.md`
82
- `docs/ACCOUNTING_CORE_ROADMAP_V1.md`
83
- `docs/RD_IRAN_ACCOUNTING_ERP_2026-09-28.md`
84
+- `docs/IRAN_COMPLIANCE_MATRIX_V1.md`
85
+- `docs/FINORA_ERP_EXPANSION_ROADMAP_V4.md`
86
+- `docs/FINORA_UX_ACCOUNTING_BENCHMARK_V3.md`
87
- `docs/PRODUCTION_RUNBOOK.md`
350
-- GitHub Actions Quality/Security/Pages results
351
-- production Supabase migrations, RLS, advisors and data compatibility
352
-
353
-## End-of-session requirement
354
-
355
-**Do not leave the project after making durable changes without updating `PROJECT_STATE.md`.**
356
-If a session is interrupted before the final update, the next worker must first reconcile this file against GitHub/Supabase evidence, then continue.
357
-
358
-
359
-- 2026-09-29 — **COMPLETED** — Phase 6 implementation is complete through head `6dcb65f1`: professional GL/subsidiary/detail/analytic ledger filtering/drillback, trial balance, P&L, financial position, cash flow, AR/AP aging, project/contract consolidation, and controlled legacy cutover preview/posting. Production reconciliation found 5 formal legacy invoices totaling 3,371,160,000, 2 non-posting pre-invoices totaling 3,570,000,000, 0 account masters and 0 journal vouchers; therefore no unsafe automatic historical posting was performed. Cutover/rollback evidence is in `docs/PHASE_6_CUTOVER_MANIFEST.md`. Quality `36610113205` PASS including Phase 6 behavior and real Chromium DOM; Pages `36610112562` PASS; Security/CodeQL `36610113296` PASS. Phase 6 is accepted under the repository completion rule. Supabase remains at 15 migrations through `20260929172129`; Phase 6 made no schema/RLS/auth mutation; RLS is enabled on profiles/licenses/records.
360
-
361
-## Current next executable phase
362
-
363
-**Six-phase master roadmap is COMPLETED; post-release source-contract hardening is IN PROGRESS.** Baseline Phase 6 evidence remains `6dcb65f1` / Quality `36610113205` / Security `36610113296` / Pages `36610112562`. The current hardening slice has added Chart-of-Accounts Excel import, four-slot floating-detail compatibility over the generic dimension engine, Contract analytic propagation, account classification, recoverable VAT starter account, negative accounting tests, atomic restore/posted-history protection, expense/income ledger posting, reversed-source immutability and live RLS/admin/license negative evidence. Production now includes migrations `20260929193348 posted_source_immutability_guard` and `20260929193357 accounting_master_uniqueness`; exact SQL is archived under those production versions. Quality run `36620001387` on `768f97ab` passed syntax, application invariants, Phase 2–6 behavior and the Golden Accounting Journey; its only failure was a Playwright style-element text assertion in the newly added print smoke, which is corrected in the next checkpoint and still requires rerun before hardening acceptance. Authenticated production-user browser E2E, physical-printer validation, live third-party webhook delivery, expired-license E2E and leaked-password-protection enablement remain NOT VERIFIED.
364
-
365
-## Portable one-line bootstrap
366
-
367
-When the owner starts a new ChatGPT/Claude/Gemini/Grok/Codex or other coding session, the minimum bootstrap instruction may be:
368
-
369
-`Open GitHub repo davoodmehraban89/Factor-easy on main; read AGENTS.md then PROJECT_STATE.md in full, inspect docs/reference/finora-ui-target-v1.jpg, verify live repo/Supabase state, record my latest request in PROJECT_STATE.md, then resume the exact next executable work autonomously under its five-workstream/high-assurance accounting rules; after every durable checkpoint update PROJECT_STATE.md, and do not stop while approved executable work remains.`
370
-
371
-This short prompt is only a pointer. The repository files are authoritative and must contain the full current roadmap, decisions, evidence and next work.
372
-
373
-
374
-## Transfer checkpoint — 2026-09-30
375
-
376
-The owner is moving continuation to a new chat/session. The successor must treat this repository, especially AGENTS.md then PROJECT_STATE.md, as the continuity source. All material requests through the Iran-first enterprise ERP expansion are captured above. Do not rely on chat memory.
377
-
378
-Latest executable enterprise-v2 head before this transfer repair: `cf428a93fb2af4b96ae836307c9605874204deeb`.
379
-Production Supabase migrations are applied through `20260929221754 iran_enterprise_financial_controls` (21 total at this checkpoint). The exact SQL is archived under the production version by this transfer commit; the future-version duplicate is a no-op marker.
380
-Immediate successor action: verify this transfer commit's Quality/Security/Pages runs; if Quality is green, continue the IN PROGRESS Iran-first ERP ledger item. Do not claim full payroll/tax submission/statutory consolidation/ABC/ABB/HR/CRM completeness merely from the current foundation; close each as a tested vertical slice.
381
-Known external/manual boundary remains physical-printer validation and Supabase leaked-password protection unless separately verified.
88
+- exact SQL under `supabase/migrations/`
89
+
90
+## Verification boundary / NOT VERIFIED unless explicitly changed below
91
+- Authenticated production-user browser E2E: NOT VERIFIED (no production user credential/session supplied to this execution environment).
92
+- Physical-printer behavior: NOT VERIFIED.
93
+- Live third-party webhook delivery: NOT VERIFIED (no approved target endpoint/credential available here).
94
+- Supabase leaked-password-protection enablement: NOT VERIFIED; current advisor says disabled and available connector actions do not expose Auth password-policy configuration.
95
+- PostgreSQL 17.11 platform upgrade/reindex checks: NOT PERFORMED.
96
+
97
+## Exact next executable work
98
+1. Repair `scripts/dom-smoke.spec.js` so legal-only fields are populated while entity type is legal, then switch to natural and verify they are hidden/cleared and organization role resets to standalone.
99
+2. Commit the test repair **with this file updated in the same commit**.
100
+3. Verify fresh Quality/Security/Pages on the resulting head; completion requires Real-DOM + accounting invariants PASS.
101
+4. Recheck Supabase migrations/RLS/advisors and record any drift.
102
+5. Continue the active Iran-first enterprise ledger only where a complete vertical slice can be implemented and verified; external/manual boundaries stay explicitly NOT VERIFIED.