سامانه صدور فاکتور و حسابداری
docs: actionable Issue229 server and purchase Save acceptance handoff
davoodmehraban89 committed
Nov 22, 2026 at 15:50 UTC
299893e1e0e8f6b5232ea8d98306f0449caf1c55
1 file changed
+45
docs/ISSUE229_FIX_ACCEPTANCE_HANDOFF_2026-11-22.md
new
+45
@@ -0,0 +1,45 @@
1
+# Issue229 / ADR216 — precise P0 fix handoff to Codex-main
2
+
3
+**Status:** implementation guidance and accepted QA evidence only; **NOT IMPLEMENTED**. This document is subordinate to `PROJECT_STATE.md`, accepted `docs/adr/0216-draft-first-document-identity.md` and `docs/superpowers/specs/2026-11-13-draft-first-accounting.md`. It is neither a competing accounting engine nor permission to migrate posted financial history. Review the cited *current PR231 candidate*, not just protected main.
4
+
5
+## Proven outcome (do not confuse CI SUCCESS with product acceptance)
6
+
7
+Code SHA `bd244962915824d0ad825e99b5cda4d530f18402` of [Draft PR231](https://github.com/davoodmehraban89/Factor-easy/pull/231) passed [WP2 45019982974](https://github.com/davoodmehraban89/Factor-easy/actions/runs/45019982974), [WP1 45019983033](https://github.com/davoodmehraban89/Factor-easy/actions/runs/45019983033), [Quality 45019982985](https://github.com/davoodmehraban89/Factor-easy/actions/runs/45019982985), and [Security 45019982983](https://github.com/davoodmehraban89/Factor-easy/actions/runs/45019982983) (conditional Dependency Review SKIPPED). Two existing Issue229 browser cases are intentionally `test.fail`. Those green runs are **successful reproduction of a P0 contract failure**.
8
+
9
+The same **real, non-owner Auth JWT** with `commerce:create`, **without** `accounting:approve` or reusable assigned roles, successfully POSTED both a sale and a credit purchase. PostgreSQL readback verified source `posted`, one linked posted voucher each, balanced journal lines, matching actor audit and server final-number counter. The WP2 job emitted both `FINORA_ISSUE229_APPROVAL_EXPECTED_RED` and `FINORA_ISSUE229_PURCHASE_APPROVAL_EXPECTED_RED`. The purchase account mapping is expense debit 170 / payable credit 170. This is not a simulated RLS-only result.
10
+
11
+## Exact, verified integration and permission fault line
12
+
13
+| Owner target | Current candidate anchor | Proven failure / required intervention |
14
+| --- | --- | --- |
15
+| Purchase Save (new) | `js/purchases.js:282-352`, especially **327-340** | `purSave` inserts a locally marked `draft` purchase but immediately calls `jeRpcAutoPost('purchase', record.id)` at **332**, then reports posted. **Save must instead atomically commit source + linked journal draft, without posting or final number.** |
16
+| Purchase correction Save | `js/purchases.js:100-115` | `purchaseSaveSeamless` reverses and then calls `finalizePurchasePilotDraft(newId)` at **113**, coupling ordinary correction Save to posting. Keep original posted and reversal history immutable, but make correction draft finalization explicit and separately authorized. |
17
+| Purchase explicit Finalize | `js/purchases.js:189-205` and `230-235` | Existing `finalizePurchasePilotDraft` only tests client `requireWrite` and `jeRpcAutoPost`; a client guard is **not** a server approval boundary. |
18
+| Sales draft vs posting | `js/invoices.js:383-405`, `513-632` | New sale Save persists a business-only draft; `finalizeInvoiceDocument` posts with `jeRpcAutoPost`. Bring it into the same **source + linked journal draft** contract as purchases, not a separate engine. |
19
+| Display projection | `js/invoices.js:367-375`; `js/purchases.js:64-72` | Sales treats **any** `journalVoucherId` as posted, even if linked voucher is still draft. Purchase returns `legacy_review` for a linked draft. Treat linked effective `draft` as draft only after scope/link validation. Never infer posted from link existence alone. |
20
+| Shared client RPC | `js/journal-rpc.js:211-239`, `241-313` | `jeRpcPersistSourceRecord` flushes a **business source alone** via generic sync, then `jeRpcAutoPostOnce` calls `finora_journal_autopost` at **285-288**, creating + posting in one separate call. Replace with server atomic draft-saving and separate finalize RPC; retain freeze/reconcile for ambiguous transport outcomes. |
21
+| Source-linking SQL | `supabase/migrations/20261117110000_wp1_autopost_source_link_atomic.sql:3-104` | The existing `SECURITY DEFINER` autopost RPC accepts `private.finora_phase1a_authorize(org,'create',typ)` at **21**, creates journal at **77**, calls `private.finora_phase1a_post_core(...,true)` at **91**, then writes source `posted` at **94-101**. Its source-link atomicity is a useful invariant; its **authorization and direct-post semantics violate draft-first**. |
22
+| SQL authorization split | `supabase/migrations/20261016101500_phase1a_journal_core.sql:40-68,228-298`; later override `20261016103100_phase1a_autopost_server_authority.sql:49-122` | `finora_phase1a_authorize` resolves sale/purchase to **commerce**, and `post_core(p_auto=true)` chooses `create` for source vouchers (later override **63-79**), while `p_auto=false` requires accounting `approve`. **An approver-only Finalize path must check approval server-side regardless of client flag or sourceType.** Do not edit applied historical migration files; use controlled additive migration after preflight/rollback review. |
23
+
24
+### Required atomic command contracts (implementation owner: Codex-main)
25
+
26
+1. **Save/Create/Edit commercial source with generated draft**: one server transaction, scoped to Auth user + active organization/company/fiscal year. Validate source identity, fields, version, required accounts/dimensions, and approved immutable posting-profile snapshot. Generate/upsert **exactly one draft** journal with matching source/version and balanced journal lines, bidirectional link, provisional number and permanent attachment reservation per ADR216. No posted timestamp, posted actor or **final-number consumption** on Save. Retry with stable idempotency identity; concurrent Save gets deterministic winner/version error. Failed call rolls back **both** source and draft; never show false success.
27
+2. **Finalize existing source-linked draft**: distinct explicit server RPC, requiring `accounting:approve` on actual membership/entitlement **for every** sale/purchase path, not merely `commerce:create` or any JS `requireWrite`. Validate source and voucher version under lock; check organization/company/owner linkage, fiscal locks, debit/credit, dimensions, source state, and number reservation. In **one transaction** change voucher and source to posted; allocate exactly one final number; audit the real approver. A legitimate accounting-only approver may need a scoped accounting read path to validate the source; do not silently require commerce CREATE to approve.
28
+3. **Block legacy bypass**: once draft-first RPCs exist, no direct `finora_journal_autopost` entry may allow `commerce:create`-only JWT to finalize. Prefer explicit versioned deprecation/restriction of the public RPC over a client-only toggle. Audit all other paths that reach `post_core(p_auto=true)` (including reversal workflows) for intended independent permissions; avoid blanket changes that silently break other source types.
29
+4. **Update/Delete**: only linked drafts can mutate with optimistic versions, atomic recomputation and audit. Source deletion and generated draft tombstone are one transaction. Direct generated-voucher delete is rejected. Posted and reversed source/voucher/lines stay immutable; corrections use approved reversal + new linked draft, never mass `posted`→`draft` rewrites. Keep permanent attachment numbers reserved after deletion and separate fiscal numbering.
30
+5. **UI/report projections**: on successful Save, show *source draft + linked journal draft*, route explicit Finalize to authorized approver with clear denial for seller, and render draft/posted/reversed accurately in purchase/sale/report filters. Avoid duplicate stock or expense effects by counting a single business event once. Prevent edited drafts from being mistaken for posted because they have `journalVoucherId`.
31
+
32
+### Executable acceptance matrix — product acceptance, not xfail success
33
+
34
+| Probe | Mandatory result |
35
+| --- | --- |
36
+| Real JWT seller: commerce:create yes, accounting:approve no; **purchase + sale Save** | 2xx **linked draft** only; exactly one matching journal draft per source; valid balanced lines, source+draft audit, **no posted journal/final number** |
37
+| Same seller: Finalize, including **old autopost RPC** | 403/SQLSTATE `42501` for approval boundary; source/journal/lines/audit/final counter **unchanged** |
38
+| Real distinct approver: accounting:approve yes, source linked draft | Explicit Finalize 2xx, **one** posted voucher + consistent source status, original business fields unchanged, actor = approver, counter +1; correct debit/credit and fiscal lock |
39
+| Replay / same idempotency key / lost-response retry | Original source/voucher/attachment/final-number identity returned, no duplicate posting or audit; state reconciled |
40
+| Stale version, concurrent approvals, wrong tenant/company, locked year, invalid lines | Deterministic reject and complete rollback; zero partial posting or counter consumption |
41
+| Draft edit/delete; posted mutation/reversal | Atomic draft and generated-voucher update/tombstone; immutable posted history, audited reversal/correction and permanent attachment retention |
42
+| Legacy history conversion | **No** mass `posted`/reversed downgrade or silent deletion; graph inventory, fingerprints, dry-run reconciliation, rollback and owner release approval |
43
+| Browser + real DB | Remove BOTH `test.fail` annotations from `scripts/accounting-document-workflow.spec.js` only after actual fixed behaviour is shown. Convert `scripts/wp2-source-approval-boundary-jwt-e2e.mjs` from two expected-product-RED probes into normal negative-seller/positive-approver contract tests. Then re-run exact SHA Quality, WP1, WP2, Security and independent review. |
44
+
45
+**Safety/rollback:** run migration UP/DOWN/UP and historical snapshot comparison **only on disposable database** first. Before any authorized production cutover, perform read-only source graph inventory, backup + verified restoration point, existing old-RPC caller census, controlled feature-flag rollout and rollback plan that does not reverse posted history or reuse numbers. Keep [Issue216](https://github.com/davoodmehraban89/Factor-easy/issues/216) and [Issue229](https://github.com/davoodmehraban89/Factor-easy/issues/229) P0 OPEN until these criteria pass. PR231 remains Draft/unmerged. No real financial data accessed or modified while writing this handoff.