@davoodmehraban89 / Factor-easy / commits / 8209c6f
Fork 0

سامانه صدور فاکتور و حسابداری

fix: verify phase 3 accounting behavior and reopen acceptance

davoodmehraban89 committed Sep 28, 2026 at 20:07 UTC 8209c6f13eb6389260c8528744e5e282d1dd90f3
24 files changed +668 -83
.github/workflows/quality.yml
+3 -1
@@ -20,5 +20,7 @@ jobs:
20 run: node scripts/quality-check.mjs
21 - name: Phase 2 accounting foundation invariants
22 run: node scripts/phase2-check.mjs
23 - - name: Phase 3 double-entry invariants
23 + - name: Phase 3 wiring checks
24 run: node scripts/phase3-check.mjs
25 + - name: Phase 3 behavioral accounting and UI regressions
26 + run: node --test scripts/phase3-engine.test.mjs scripts/phase3-ui.test.mjs
PROJECT_STATUS.md new
+19
@@ -0,0 +1,19 @@
1 +# Project status — 2026-09-28
2 +
3 +**Phase 3: IN PROGRESS / NOT ACCEPTED.**
4 +
5 +The user's last handoff said Phase 3 was incomplete. A remote document said
6 +COMPLETED at `8761d21189d9c4058c3019ea6e42d4103fc83556`. Independent behavioral
7 +verification found real defects, so the completion claim was reopened.
8 +
9 +- Current roadmap: [six phases](docs/SIX_PHASE_ROADMAP.md), not the older four-phase plan.
10 +- Implemented recovery: client ledger/source/import/UI fixes with 55 behavioral tests.
11 +- Preserved: original financial records, server configuration, main branch/release boundary.
12 +- Not claimed: authenticated production E2E, database transaction/immutability
13 + enforcement, complete cheque accounting, controlled ledger restore or migration.
14 +- Supabase target `hcsixhqbyuhpshfwqpjx` is not available in the current connection.
15 +- Recovery changes are prepared on `fix/phase3-behavioral-verification`; production
16 + acceptance is withheld. See the latest Git commit/PR for publication evidence.
17 +
18 +Details: [Phase 3 verification](docs/PHASE_3_REDESIGN_VERIFICATION.md) and
19 +[latest handoff](docs/handoff/LATEST_HANDOFF.md).
README.md
+5
@@ -1,5 +1,10 @@
1 # فینورا (Finora) — نسخه ۱.۰
2
3 +> وضعیت جاری: فاز ۳ برنامه شش‌فازی «در حال اجرا / تأیید نهایی نشده» است.
4 +> آزمون‌های رفتاری، نقص‌هایی فراتر از کنترل‌های متنی قبلی پیدا کردند.
5 +> مرجع ادامه: [وضعیت پروژه](PROJECT_STATUS.md)، [برنامه شش‌فازی](docs/SIX_PHASE_ROADMAP.md) و [آخرین تحویل](docs/handoff/LATEST_HANDOFF.md).
6 +> کنترل‌های سمت مرورگر جایگزین تراکنش و کنترل‌های امنیتی پایگاه‌داده نیستند.
7 +
8 سامانه ابری صدور فاکتور و مدیریت مالی. داده‌ها و لایسنس روی Supabase نگهداری می‌شوند، ورود با Google یا کد یک‌بارمصرف ایمیل انجام می‌شود، و کنترل دسترسی و نقش مدیر کاملاً سمت سرور (RLS) است.
9
10 ## راه‌اندازی یک‌بار مصرف (Supabase)
docs/ACCOUNTING_CORE_ROADMAP_V1.md
+4 -1
@@ -1,5 +1,9 @@
1 # Finora Accounting Core Roadmap — v1.x
2
3 +Current execution numbering is defined in [SIX_PHASE_ROADMAP.md](SIX_PHASE_ROADMAP.md).
4 +The Phase 5-8 numbering below is historical architecture context, not the
5 +current phase status. Preserve architectural requirements; do not infer completion.
6 +
7 Date: 2026-09-28
8 Status: Architecture approved for implementation planning
9 Baseline: Finora 1.0
@@ -417,4 +421,3 @@ draft -> active -> inactive/closed
421 Historical journal lines retain the original identity and label snapshot/reference.
422
423 Account-structure changes affecting required dimensions must pass a validation/migration preview before activation.
420 -
docs/COMPLETION_PHASES.md
+7 -2
@@ -1,6 +1,11 @@
1 -# Finora / Factor Easy — Four-Phase Completion Plan
1 +# Finora / Factor Easy — Historical Four-Phase Completion Plan
2
3 -## Phase 1 — Foundation, correctness, and data integrity (ACTIVE)
3 +Superseded for current execution by [SIX_PHASE_ROADMAP.md](SIX_PHASE_ROADMAP.md).
4 +The phase numbers below describe the earlier Finora 1.0 work, not the current
5 +six-phase redesign. In particular, this document's UX Phase 3 is not the
6 +current double-entry/treasury Phase 3. Retained for traceability only.
7 +
8 +## Phase 1 — Foundation, correctness, and data integrity (historical)
9 Owner: Architecture & implementation. Review: QA + security.
10 Exit criteria:
11 - Cloud collections, backup, sync, authentication and license boundaries are internally consistent.
docs/PHASE_3_REDESIGN_VERIFICATION.md
+48 -10
@@ -1,7 +1,45 @@
1 # Finora — Phase 3 Verification
2
3 Date: 2026-09-28
4 -Status: COMPLETED — final operational integration verified
4 +Status: IN PROGRESS — reopened by behavioral verification; NOT production-accepted
5 +
6 +## Recovery correction — 2026-09-28
7 +
8 +The earlier COMPLETED claim was not supported by adequate behavioral coverage.
9 +The former phase3-check script tested source-string presence, not actual journal
10 +results. Fresh Node VM tests execute the real foundation, synchronization/import,
11 +and journal modules. Separate UI boundary tests execute the actual form handlers.
12 +
13 +Verified client repairs include reversal netting; Gregorian-to-Jalali conversion
14 +and invalid-date rejection; duplicate/invalid posting rejection; company-safe
15 +source locks; automatic posting profiles independent of visiting the journal UI;
16 +atomic in-memory source correction and versioned reposting after reversal;
17 +pro-forma exclusion; no cheque-to-cash misclassification; history-safe import;
18 +dimension-rule mutation protection; and journal navigation/form reset.
19 +
20 +Current test command:
21 +`node --test scripts/phase3-engine.test.mjs scripts/phase3-ui.test.mjs`
22 +
23 +This client patch has 55 passing behavioral tests. This is not production E2E
24 +or proof of database transaction/security guarantees.
25 +
26 +### Open acceptance blockers
27 +
28 +1. The configured Supabase project `hcsixhqbyuhpshfwqpjx` is not listed by the
29 + current official connection. No substitute project was queried or changed.
30 +2. `saveDatastore` schedules asynchronous sync; `jeAtomic` is only an in-memory
31 + rollback boundary. The generic 200-record upsert chunks are not a financial
32 + transaction. Posting, reversal, numbering, idempotency, fiscal/company checks,
33 + and immutable-history enforcement must be verified/enforced server-side.
34 +3. Cheque registration remains an operational tracker. Accounting lifecycle for
35 + registration, clearance, bounce and cancellation is incomplete. Cheque-method
36 + settlement is rejected in configured accounting rather than recognized as cash.
37 +4. Controlled ledger restore, legacy cutover/reconciliation, and authenticated
38 + device/browser E2E remain unverified. Import may not introduce/overwrite journal
39 + records; unchanged existing journal backup content is allowed as a no-op.
40 +
41 +No production data or schema was changed during this recovery. The patch does
42 +not represent completion of Phase 3 or permission to claim release acceptance.
43
44 ## Scope
45 Phase 3 introduces the first operational double-entry ledger on top of the Phase 2 accounting foundation.
@@ -41,16 +79,16 @@ Implemented:
79 9. A locked fiscal year rejects new posting.
80 10. Trial balance is derived only from posted/reversed ledger history, never from draft lines.
81
44 -## Production persistence
82 +## Historical production-persistence report (not reverified in this recovery)
83 Supabase project: hcsixhqbyuhpshfwqpjx
84
47 -The records collection constraint was extended by migration:
85 +The prior report states that the records constraint was extended for:
86 - postingProfiles
87 - journalVouchers
88 - journalLines
89 - journalLineDimensions
90
53 -Existing production financial rows were not rewritten or deleted. At migration verification, production contained the existing companies, contacts, invoices, products and settings and no Phase 3 journal records yet.
91 +The prior report states that no existing financial rows were rewritten/deleted and no Phase 3 journals existed then. These are historical claims, not current database evidence.
92
93 ## Compatibility
94 Existing Finora source documents remain operational. Phase 3 does not bulk-post historical documents automatically because that would create accounting history without an explicit reconciliation/cutover. The adapter can post source records under the configured chart; controlled historical reconciliation remains a later release/cutover responsibility.
@@ -64,19 +102,19 @@ Existing Finora source documents remain operational. Phase 3 does not bulk-post
102 - GitHub Pages deployment
103
104 ## Boundary
67 -Interactive authenticated browser/device E2E is not available in the current execution environment and is not claimed. Production release acceptance is based on source verification, CI gates, Supabase schema verification/advisors and deployment status.
105 +Interactive authenticated browser/device E2E is not claimed. Source checks and successful CI/deployment alone do not establish production release acceptance. See the open blockers above.
106
107
108 ## Final operational integration
109
110 Final Phase 3 integration verifies automatic balanced posting for newly created sales, purchases, receipts, payments, expenses and other income when the accounting foundation is configured. Operational records linked to a posted voucher are protected from direct edit/delete until the accounting voucher is reversed. Accounts referenced by journal history are protected from destructive deletion, and account-dimension rules with ledger history are protected from destructive removal.
111
74 -The trial balance uses active posted movements. A reversed original is excluded while its posted reversal supplies the opposite movement, avoiding double counting.
112 +The trial balance includes both the reversed original and its posted opposite entry. Their balances cancel; excluding the original incorrectly leaves an opposite balance. Reversing a reversal is rejected until a complete reversal-chain workflow exists.
113
76 -Production verification confirmed that the Phase 3 collections are allowed by the records constraint and there were no pre-existing production journal records requiring conversion during this final integration.
114 +The current recovery did not reverify the production collections or journal counts because the configured project is unavailable to the connector.
115
116
79 -## Final release evidence — 2026-09-28
117 +## Historical CI/deployment evidence — 2026-09-28 (not acceptance)
118
119 Implementation head verified: `b0f3e2587c6cc04beaf579505cb975a939459d6e`.
120
@@ -85,6 +123,6 @@ Release gates on that head:
123 - Pages build and deployment: success (run 36441163803)
124 - Security checks: success (run 36441164870)
125
88 -Production verification confirms migration `20260928145306 allow_phase3_double_entry_collections` is applied, RLS remains enabled on `public.records`, and the records constraint accepts all four Phase 3 ledger collections. Production currently has no Phase 3 ledger rows, so this verification did not rewrite or backfill historical accounting data. Performance advisor returned no findings.
126 +The prior report claimed migration `20260928145306 allow_phase3_double_entry_collections`, RLS and advisor verification. Those database claims could not be independently reverified during recovery. RLS ownership alone would not prove balanced or immutable accounting.
127
90 -Phase 3 is closed for the implemented scope. Historical cutover and reconciliation remain intentionally assigned to the later migration/release phase.
128 +Phase 3 remains OPEN. Historical cutover and reconciliation belong to Phase 6, but transaction integrity and the core treasury acceptance gaps must not be deferred merely to close Phase 3.
docs/PROJECT_LOG.md new
+29
@@ -0,0 +1,29 @@
1 +# Project log
2 +
3 +## 2026-09-28 — Phase 3 recovery
4 +
5 +Owner: coordinating implementer. Independent integration QA and server/persistence
6 +review performed by separate agents; final integration checks by the coordinator.
7 +
8 +Input: user's contradictory handoff (unfinished Phase 3) versus baseline
9 +`8761d21189d9c4058c3019ea6e42d4103fc83556` completion report.
10 +
11 +Decision: reopen Phase 3; recover the approved six-phase sequence; repair
12 +reproducible client defects without production financial-data writes.
13 +
14 +Result: 55 behavioral tests pass. Baseline tests only checked source strings and
15 +missed operational defects. Tests cover actual ledger arithmetic, rollback,
16 +source versioning, dates, import guards and form integration. Full server E2E is
17 +not implied. Reviewer's final full-diff verdict was interrupted by a usage limit.
18 +
19 +Files: journal engine/UI, accounting-foundation rule guard, operational source
20 +handlers, sync import/backup, cache versions, CI behavioral gate, test fixtures,
21 +current roadmap/status/handoff documentation.
22 +
23 +Scope exclusion: no rewrite of the ERP, no new Phase 4-6 implementation, no
24 +production migration, no change to auth/RLS or public release acceptance.
25 +
26 +Blocker: configured Supabase project not present in current official connection.
27 +Next: reconnect exact project, verify database rules and implement/test server
28 +transaction boundary before phase acceptance. Continue complete cheque accounting
29 +and authenticated E2E after that boundary is established.
docs/SIX_PHASE_ROADMAP.md new
+31
@@ -0,0 +1,31 @@
1 +# Current six-phase execution roadmap
2 +
3 +Recovered on 2026-09-28 from the latest project conversation and confirmed
4 +against the existing Phase 1/2/3 redesign modules. This restores numbering;
5 +it does not expand scope or mark untested functionality complete.
6 +
7 +Canonical repository: `davoodmehraban89/Factor-easy`; base branch: `main`.
8 +Product: Finora / Factor Easy. Do not switch to Finora-Invoice or Aram.
9 +
10 +| Phase | Scope | Current evidence/status |
11 +|---|---|---|
12 +| 1 | Application shell and UX | Implemented in repo; previous completion report exists; no new full device E2E |
13 +| 2 | Accounting foundation, chart, hierarchical analytic dimensions | Implemented in repo; previous completion report exists; production enforcement not reverified |
14 +| 3 | Double-entry accounting and treasury | IN PROGRESS; client defects reproduced and repaired; server and treasury acceptance gaps remain |
15 +| 4 | Projects, contracting, contracts, deductions, guarantees | Future work; existing global project masters do not establish phase completion |
16 +| 5 | Inventory, fixed assets, supplementary accounting | Future work; existing stock summaries do not establish phase completion |
17 +| 6 | Professional reports, controls, reconciliation, migration, release | Future work; existing trial balance/CI do not establish phase completion |
18 +
19 +## Acceptance discipline
20 +
21 +- Each phase requires implementation, behavioral tests, fixes, retest and a
22 + persisted handoff. A document title or green source-string checks is not proof.
23 +- Preserve existing operational documents and historical IDs; no silent backfill.
24 +- Dimensions are user-defined, hierarchical, leaf-postable, and have required,
25 + optional or unavailable account rules. Depth is locked while values exist.
26 +- Referenced/posting history must not be rewritten by CRUD, import, sync or API.
27 +- Database atomicity, permissions and concurrency must be tested independently
28 + of browser guards before accounting is accepted for production.
29 +- Do not start dependent phases by assuming the current Phase 3 blockers are closed.
30 +
31 +Current recovery and safest next action: [handoff/LATEST_HANDOFF.md](handoff/LATEST_HANDOFF.md).
docs/handoff/LATEST_HANDOFF.md new
+78
@@ -0,0 +1,78 @@
1 +# Latest handoff — Phase 3 recovery
2 +
3 +Date: 2026-09-28
4 +Repository: `davoodmehraban89/Factor-easy`
5 +Baseline: `8761d21189d9c4058c3019ea6e42d4103fc83556`
6 +Working branch: `fix/phase3-behavioral-verification`
7 +Status: client recovery patch tested; Phase 3 remains IN PROGRESS / NOT ACCEPTED.
8 +
9 +## Start here
10 +
11 +Read PROJECT_STATUS.md, docs/SIX_PHASE_ROADMAP.md and
12 +docs/PHASE_3_REDESIGN_VERIFICATION.md. Do not repeat old four-phase numbering.
13 +Resolve the actual remote branch/commit and PR before making status claims.
14 +
15 +## Work performed
16 +
17 +- Reproduced wrong reversal balances and retained both original/reversal movements.
18 +- Rejected reversal-of-reversal, invalid calendar dates, non-finite/negative
19 + amounts, duplicate voucher numbers/active source posting and duplicate dimensions.
20 +- Normalized ISO payment dates to the Jalali ledger calendar using Asia/Tehran.
21 +- Added local rollback around source+voucher operations; failed corrections leave
22 + the old source intact; successful corrections increment source version and repost.
23 +- Wired actual invoice/purchase/payment/expense create AND edit handlers to this path.
24 +- Preserved legacy document creation before accounting is configured; partially
25 + configured accounting fails closed. Pro formas do not create revenue journals.
26 +- Initialized profiles without requiring a prior journal-page visit; sales use
27 + configured profile accounts rather than guessing revenue from a cost-account title.
28 +- Protected source history even after company selection changes or missing pointers.
29 +- Blocked generic backup merge from altering/introducing journal history or
30 + overwriting protected source/master records; full-file preflight precedes mutation.
31 +- Fixed journal pane routing, cleared successful manual submissions, reset stale
32 + company account selectors, and retained settled-invoice allocation during edits.
33 +- Added explicit cheque tracker limitation; unsupported cheque accounting cannot
34 + masquerade as a cash receipt/payment.
35 +
36 +## Verification
37 +
38 +Behavioral suite: 55 tests passing in Node. Engine fixtures execute real app
39 +modules; UI boundary fixtures execute actual handlers with controlled DOM and a
40 +rejecting save boundary. This is not a real-browser or authenticated server test.
41 +
42 +Commands required before publishing:
43 +
44 +```sh
45 +node scripts/syntax-check.mjs
46 +node scripts/quality-check.mjs
47 +node scripts/phase2-check.mjs
48 +node scripts/phase3-check.mjs
49 +node --test scripts/phase3-engine.test.mjs scripts/phase3-ui.test.mjs
50 +git diff --check
51 +```
52 +
53 +Independent review found reversal-chain and date-validation issues; both were
54 +reproduced and repaired. The reviewer could not deliver a final whole-diff verdict
55 +because its execution hit a usage limit; do not claim independent final approval.
56 +
57 +## Real blocker / next action
58 +
59 +Restore official access to the exact configured Supabase project
60 +`hcsixhqbyuhpshfwqpjx`. The available connection listed other project IDs only;
61 +no alternate project was queried or substituted. No credentials should be pasted
62 +into chat. No production database write or permission change was attempted.
63 +
64 +Then inspect target policies/triggers/functions and implement/test a transactional
65 +posting/reversal API with owner/company checks, fiscal locks, immutable history,
66 +source uniqueness, revision/idempotency and numbering concurrency. Existing
67 +generic 200-record upserts are NOT a database transaction; jeAtomic only protects
68 +in-memory state. Authenticated device E2E and complete cheque lifecycle remain open.
69 +
70 +Controlled ledger restore and historical cutover require staging, reconciliation,
71 +backup and rollback. Never rewrite historical records as a convenience migration.
72 +
73 +## Integration / rollback
74 +
75 +Publish this patch as a branch/PR, not a production-complete release. No schema
76 +migration is part of the patch. A revert can remove the code change, but would
77 +restore the identified bugs; it must not delete or rewrite posted financial data.
78 +No main merge or production deployment is claimed by this document.
index.html
+9 -9
@@ -822,16 +822,16 @@ body{background:#f6f9fc}
822
823 <script src="js/core.js?v=20260928-security-v4"></script>
824 <script src="js/admin.js"></script>
825 -<script src="js/sync.js?v=20260928-data-v4"></script>
825 +<script src="js/sync.js?v=20260928-phase3-recovery-v2"></script>
826 <script src="js/ui.js?v=20260928-phase1-shell-final"></script>
827 -<script src="js/invoices.js?v=20260928-phase3-final"></script>
827 +<script src="js/invoices.js?v=20260928-phase3-recovery-v2"></script>
828 <script src="js/print.js?v=20260928-layout-v4"></script>
829 <script src="js/products.js"></script>
830 <script src="js/contacts.js?v=20260928-roles-v3"></script>
831 <script src="js/cheques.js"></script>
832 <script src="js/expenses.js"></script>
833 <script src="js/companies.js?v=20260928-integrity-v4"></script>
834 -<script src="js/backup.js?v=20260928-data-v3"></script>
834 +<script src="js/backup.js?v=20260928-phase3-recovery-v2"></script>
835 <script src="js/words.js"></script>
836 <script src="js/bootstrap.js"></script>
837
@@ -844,18 +844,18 @@ body{background:#f6f9fc}
844 <script src="js/money-format.js"></script>
845 <script src="js/projects.js?v=20260928-projects-v7"></script>
846 <script src="js/invoice-excel-import.js"></script>
847 -<script src="js/purchases.js?v=20260928-phase3-final"></script>
848 -<script src="js/operations.js?v=20260928-phase3-final"></script>
849 -<script src="js/payments.js?v=20260928-phase3-final"></script>
847 +<script src="js/purchases.js?v=20260928-phase3-recovery-v2"></script>
848 +<script src="js/operations.js?v=20260928-phase3-recovery-v2"></script>
849 +<script src="js/payments.js?v=20260928-phase3-recovery-v2"></script>
850 <script src="js/accounting.js?v=20260928-accounting-v3"></script>
851 <style id="phase2-accounting-style">
852 .af-head{display:flex;justify-content:space-between;align-items:flex-start;gap:12px;margin-bottom:16px}.af-head h1{font-size:20px;color:#0f172a}.af-head p,.af-hint{font-size:12px;color:#64748b;margin-top:5px}.af-grid{display:grid;grid-template-columns:1fr 1fr;gap:14px}.af-space,.af-list{margin-top:14px}.af-chip{display:inline-flex;align-items:center;gap:6px;background:#eef7f8;color:#0b6874;border:1px solid #cce9ec;border-radius:999px;padding:6px 10px;margin:3px;font-size:11px}.af-chip button{border:0;background:transparent;color:#b91c1c;cursor:pointer;font-size:15px}.af-master-row{display:flex;align-items:center;justify-content:space-between;gap:10px;padding:10px;border-bottom:1px solid #edf1f5}.af-master-row:last-child{border-bottom:0}.af-master-row small{display:block;color:#64748b;margin-top:3px}.af-empty{text-align:center;padding:18px;color:#64748b}@media(max-width:820px){.af-grid{grid-template-columns:1fr}}
853 </style>
854 -<script src="js/accounting-foundation.js?v=20260928-phase3-final"></script>
855 -<script src="js/journal-engine.js?v=20260928-phase3-final"></script>
854 +<script src="js/accounting-foundation.js?v=20260928-phase3-recovery-v2"></script>
855 +<script src="js/journal-engine.js?v=20260928-phase3-recovery-v2"></script>
856 <script src="js/accounting-foundation-ui.js?v=20260928-phase2-v1"></script>
857 <script src="js/accounting-foundation-render.js?v=20260928-phase2-v1"></script>
858 -<script src="js/journal-ui.js?v=20260928-phase3-final"></script>
858 +<script src="js/journal-ui.js?v=20260928-phase3-recovery-v2"></script>
859 <script src="js/drilldown.js?v=20260928-drill-v10"></script>
860 <script src="js/selfcheck.js?v=20260928-release-1-0"></script>
861
js/accounting-foundation.js
+1 -1
@@ -77,7 +77,7 @@ function afSaveAccount(){
77 datastore.accounts.push({id:afId('ACC'),ownerUserId:currentUser.id,companyId:cid,code,title,level,parentId:parentId||'',normalBalance,postingAllowed:level==='detail',active:true});saveDatastore();renderAccountingFoundation();
78 }
79 function afDeleteAccount(id){if(!requireWrite())return;if((datastore.journalLines||[]).some(x=>x.accountId===id))return alert('این حساب در دفتر حسابداری استفاده شده و قابل حذف نیست؛ فقط غیرفعال‌سازی مجاز است.');if(getMyAccounts().some(x=>x.parentId===id))return alert('حساب دارای زیرحساب است.');if(getMyAccountDimensionRules().some(x=>x.accountId===id))return alert('ابتدا قواعد تفصیلی حساب را حذف کنید.');if(confirm('حساب حذف شود؟')){datastore.accounts=datastore.accounts.filter(x=>x.id!==id);saveDatastore();renderAccountingFoundation()}}
80 -function afSaveRule(){if(!requireWrite())return;const cid=afNeedCompany(),accountId=document.getElementById('af-rule-account').value,dimensionTypeId=document.getElementById('af-rule-dimension').value,applicability=document.getElementById('af-rule-app').value,a=getMyAccounts().find(x=>x.id===accountId),d=getMyDimensionTypes().find(x=>x.id===dimensionTypeId);if(!cid||!a?.postingAllowed||!d?.active)return alert('حساب ثبت‌پذیر و تفصیلی فعال انتخاب کنید.');let r=getMyAccountDimensionRules().find(x=>x.accountId===accountId&&x.dimensionTypeId===dimensionTypeId);if(r)r.applicability=applicability;else datastore.accountDimensionRules.push({id:afId('ADR'),ownerUserId:currentUser.id,companyId:cid,accountId,dimensionTypeId,applicability,allowedValuesMode:'all',active:true});saveDatastore();renderAccountingFoundation()}
80 +function afSaveRule(){if(!requireWrite())return;const cid=afNeedCompany(),accountId=document.getElementById('af-rule-account').value,dimensionTypeId=document.getElementById('af-rule-dimension').value,applicability=document.getElementById('af-rule-app').value,a=getMyAccounts().find(x=>x.id===accountId),d=getMyDimensionTypes().find(x=>x.id===dimensionTypeId);if(!cid||!a?.postingAllowed||!d?.active)return alert('حساب ثبت‌پذیر و تفصیلی فعال انتخاب کنید.');let r=getMyAccountDimensionRules().find(x=>x.accountId===accountId&&x.dimensionTypeId===dimensionTypeId);if((!r||r.applicability!==applicability)&&(datastore.journalLines||[]).some(l=>l.ownerUserId===currentUser.id&&l.accountId===accountId))return alert('حساب دارای سابقه دفتر است؛ تغییر قواعد تفصیلی نیاز به نسخه‌بندی دارد.');if(r)r.applicability=applicability;else datastore.accountDimensionRules.push({id:afId('ADR'),ownerUserId:currentUser.id,companyId:cid,accountId,dimensionTypeId,applicability,allowedValuesMode:'all',active:true});saveDatastore();renderAccountingFoundation()}
81 function afDeleteRule(id){if(!requireWrite())return;const rule=getMyAccountDimensionRules().find(x=>x.id===id);if(rule&&(datastore.journalLines||[]).some(l=>l.accountId===rule.accountId))return alert('این حساب دارای سابقه دفتر است؛ تغییر ساختار تفصیلی باید از مسیر نسخه‌بندی/دوره جدید انجام شود.');datastore.accountDimensionRules=datastore.accountDimensionRules.filter(x=>x.id!==id);saveDatastore();renderAccountingFoundation()}
82 function afSaveDimension(){if(!requireWrite())return;const cid=afNeedCompany(),code=afCode(document.getElementById('af-dim-code').value).toUpperCase(),title=document.getElementById('af-dim-title').value.trim(),sourceEntity=document.getElementById('af-dim-source').value,maxDepth=Math.max(1,Math.min(8,+document.getElementById('af-dim-depth').value||1));if(!cid||!code||!title)return alert('کد و عنوان الزامی است.');if(getMyDimensionTypes().some(x=>x.code===code))return alert('کد تکراری است.');if(sourceEntity!=='manual'&&maxDepth!==1)return alert('تفصیلی متصل به داده پایه در این فاز عمق ۱ دارد؛ برای ساختار چندسطحی نوع «دستی» را انتخاب کنید.');datastore.dimensionTypes.push({id:afId('DIM'),ownerUserId:currentUser.id,companyId:cid,code,title,maxDepth,depthLocked:false,leafOnlyPosting:true,active:true,sourceType:sourceEntity==='manual'?'manual':'entity-backed',sourceEntity});saveDatastore();renderAccountingFoundation()}
83 function afChangeDimensionDepth(id){
js/backup.js
+2 -2
@@ -20,8 +20,8 @@ function importDataBlob(event){
20 if(!imported||typeof imported!=='object')throw new Error('bad');
21 absorbRecords(imported);
22 saveDatastore();refreshAllSurfaces();
23 - alert('اطلاعات با موفقیت به حساب کاربری شما اضافه شد.');
24 - }catch(err){alert('فایل نامعتبر است.');}
23 + alert('اطلاعات وارد شد؛ وضعیت ذخیره ابری را از نشانگر ذخیره بررسی کنید.');
24 + }catch(err){alert(err.message||'فایل نامعتبر است.');}
25 };
26 reader.readAsText(file);
27 }
js/invoices.js
+4 -4
@@ -386,15 +386,15 @@ function commitSaveInvoice(){
386 if(existingIndex!==-1){
387 const prev=datastore.invoices[existingIndex];
388 const finalEdoc=edoc?edoc:(prev.electronicDoc||null);
389 - datastore.invoices[existingIndex]={...prev,ownerUserId:currentUser.id,number,date,companyId,companyName,kind,kindLabel:kindLabels[kind],contactId,contactName,projectId,projectName,contractNumber,paymentMethod,paymentMethodLabel,subtotal:totals.subtotal,discount:totals.fixedDiscount,discountType:totals.discountType,discountInput:totals.discountInput,vat:totals.vatAmount,vatType:totals.vatType,vatRate:totals.vatRate,grandTotal:totals.grandTotal,description,items,currencyLabel:cur,electronicDoc:finalEdoc};
389 + const candidate={...prev,ownerUserId:currentUser.id,number,date,companyId,companyName,kind,kindLabel:kindLabels[kind],contactId,contactName,projectId,projectName,contractNumber,paymentMethod,paymentMethodLabel,subtotal:totals.subtotal,discount:totals.fixedDiscount,discountType:totals.discountType,discountInput:totals.discountInput,vat:totals.vatAmount,vatType:totals.vatType,vatRate:totals.vatRate,grandTotal:totals.grandTotal,description,items,currencyLabel:cur,electronicDoc:finalEdoc};
390 + try{jeSaveOperationalRecord('sale',candidate);}catch(e){alert('فاکتور ثبت نشد: '+e.message);return;}
391 alert('فاکتور با موفقیت ویرایش شد.');
392 }
393 cancelInvoiceEdit();
394 }else{
395 const record={id:'INV_'+Date.now(),ownerUserId:currentUser.id,number,date,companyId,companyName,kind,kindLabel:kindLabels[kind],contactId,contactName,projectId,projectName,contractNumber,paymentMethod,paymentMethodLabel,subtotal:totals.subtotal,discount:totals.fixedDiscount,discountType:totals.discountType,discountInput:totals.discountInput,vat:totals.vatAmount,vatType:totals.vatType,vatRate:totals.vatRate,grandTotal:totals.grandTotal,description,items,currencyLabel:cur,electronicDoc:edoc};
395 - datastore.invoices.push(record);
396 - if(typeof jePostSourceRecord==='function'){try{jePostSourceRecord('sale',record);}catch(e){datastore.invoices=datastore.invoices.filter(x=>x.id!==record.id);alert('فاکتور ثبت نشد: '+e.message);return;}}
397 - alert('فاکتور و سند حسابداری با موفقیت ثبت شد.');
396 + try{jeSaveOperationalRecord('sale',record);}catch(e){alert('فاکتور ثبت نشد: '+e.message);return;}
397 + alert('فاکتور با موفقیت ثبت شد.');
398 cancelInvoiceEdit();
399 renderAndPrintDirect(record.id);
400 }
js/journal-engine.js
+104 -26
@@ -1,17 +1,62 @@
1 /* Phase 3 — immutable double-entry journal engine */
2 const JE_EPSILON=0.0001;
3 -function jeOwned(k){const cid=afCompanyId();return(datastore[k]||[]).filter(x=>x.ownerUserId===currentUser?.id&&(!x.companyId||x.companyId===cid))}
3 +let jeMutationDepth=0;
4 +// This is an in-memory unit of work, not a database transaction. Cloud atomicity
5 +// and concurrent posting still require the server gate documented in the handoff.
6 +function jeSave(){if(!jeMutationDepth&&saveDatastore()===false)throw new Error('ذخیره تغییرات مجاز نیست.');}
7 +function jeAtomic(work){
8 + if(jeMutationDepth)return work();
9 + const keys=['postingProfiles','journalVouchers','journalLines','journalLineDimensions','invoices','purchases','payments','expenses'];
10 + const snapshot=Object.fromEntries(keys.map(k=>[k,JSON.parse(JSON.stringify(datastore[k]||[]))]));
11 + jeMutationDepth++;
12 + try{const result=work();if(saveDatastore()===false)throw new Error('ذخیره تغییرات مجاز نیست.');return result;}
13 + catch(error){keys.forEach(k=>{datastore[k]=snapshot[k]});throw error;}
14 + finally{jeMutationDepth--;}
15 +}
16 +const JE_DATE_FORMAT=new Intl.DateTimeFormat('en-US-u-ca-persian',{timeZone:'Asia/Tehran',year:'numeric',month:'2-digit',day:'2-digit'});
17 +function jePersianDate(date){
18 + const parts=JE_DATE_FORMAT.formatToParts(date),get=type=>parts.find(p=>p.type===type).value;
19 + return get('year')+'/'+get('month')+'/'+get('day');
20 +}
21 +function jeDate(value){
22 + const raw=toEnDigits(String(value||getJalaliNumeric()).trim());
23 + const j=raw.match(/^(\d{4})\/(\d{1,2})\/(\d{1,2})$/);
24 + if(j){
25 + const y=Number(j[1]),m=Number(j[2]),d=Number(j[3]);if(y<1000||y>1700||m<1||m>12||d<1||d>(m<=6?31:30))throw new Error('تاریخ شمسی سند معتبر نیست.');
26 + const canonical=j[1]+'/'+j[2].padStart(2,'0')+'/'+j[3].padStart(2,'0');
27 + // ICU calendar roundtrip rejects Esfand 30 in non-leap years. No guessed leap cycle.
28 + for(let day=18;day<=23;day++){
29 + const start=Date.UTC(y+621,2,day,12);
30 + if(jePersianDate(new Date(start))===j[1]+'/01/01'){
31 + const offset=(m<=7?(m-1)*31:186+(m-7)*30)+d-1;
32 + if(jePersianDate(new Date(start+offset*86400000))===canonical)return canonical;
33 + break;
34 + }
35 + }
36 + throw new Error('تاریخ شمسی سند معتبر نیست.');
37 + }
38 + if(/^\d{4}-\d{2}-\d{2}(T.*)?$/.test(raw)){
39 + const [year,month,day]=raw.slice(0,10).split('-').map(Number),check=new Date(Date.UTC(year,month-1,day));
40 + const date=new Date(raw);if(!Number.isFinite(date.getTime())||check.getUTCFullYear()!==year||check.getUTCMonth()+1!==month||check.getUTCDate()!==day)throw new Error('تاریخ سند معتبر نیست.');
41 + return jePersianDate(date);
42 + }
43 + throw new Error('تاریخ سند معتبر نیست.');
44 +}
45 +function jeMoney(value){const n=Number(value??0);if(!Number.isFinite(n)||n<0||!Number.isSafeInteger(Math.round(n)))throw new Error('مبلغ سند باید عدد معتبر و غیرمنفی باشد.');return Math.round(n);}
46 +function jeSourceScope(source){if(!source?.id||source.ownerUserId!==currentUser?.id||source.companyId!==afCompanyId())throw new Error('مالک یا شرکت سند با شرکت فعال مطابقت ندارد.');}
47 +
48 +function jeOwned(k){const cid=afCompanyId();return(datastore[k]||[]).filter(x=>x.ownerUserId===currentUser?.id&&x.companyId===cid)}
49 function getMyPostingProfiles(){return jeOwned('postingProfiles')} function getMyJournalVouchers(){return jeOwned('journalVouchers')}
50 function getMyJournalLines(){return jeOwned('journalLines')} function getMyJournalLineDimensions(){return jeOwned('journalLineDimensions')}
51 function jeNum(v){const n=Number(v);return Number.isFinite(n)?Math.round(n):0}
7 -function jeFiscalForDate(date){const ds=toEnDigits(String(date||getJalaliNumeric()).slice(0,10));return getMyFiscalYears().find(f=>ds>=f.startDate&&ds<=f.endDate)||null}
8 -function jePostingAccount(id){const a=getMyAccounts().find(x=>x.id===id);return a&&a.active!==false&&a.postingAllowed?a:null}
52 +function jeFiscalForDate(date){const ds=jeDate(date);return getMyFiscalYears().find(f=>f.companyId===afCompanyId()&&ds>=f.startDate&&ds<=f.endDate)||null}
53 +function jePostingAccount(id){const a=getMyAccounts().find(x=>x.id===id);return a&&a.companyId===afCompanyId()&&a.active!==false&&a.postingAllowed&&a.level==='detail'?a:null}
54 function jeAccountByCode(code){return getMyAccounts().find(x=>x.code===String(code)&&x.active!==false&&x.postingAllowed)}
55 function jeFindAccountByTitle(words){const A=getMyAccounts().filter(x=>x.active!==false&&x.postingAllowed);return A.find(a=>words.some(w=>String(a.title||'').includes(w)))||null}
56 function jeCashAccount(){return jeAccountByCode('1101')||jeFindAccountByTitle(['صندوق','بانک','نقد'])}
57 function jeReceivableAccount(){return jeAccountByCode('1102')||jeFindAccountByTitle(['دریافتنی','بدهکاران'])}
58 function jePayableAccount(){return jeAccountByCode('2101')||jeFindAccountByTitle(['پرداختنی','بستانکاران'])}
14 -function jeRevenueAccount(){return jeAccountByCode('4101')||jeAccountByCode('4107')||jeAccountByCode('4106')||jeFindAccountByTitle(['فروش','درآمد خدمات'])}
59 +function jeRevenueAccount(){return jeAccountByCode('4101')||jeAccountByCode('4107')||jeAccountByCode('4106')}
60 function jePurchaseAccount(){return jeAccountByCode('5101')||jeAccountByCode('5102')||jeFindAccountByTitle(['بهای تمام','خرید'])}
61 function jeExpenseAccount(){return jeAccountByCode('6103')||jeFindAccountByTitle(['هزینه عمومی','هزینه'])}
62 function jeOtherIncomeAccount(){return jeAccountByCode('4201')||jeFindAccountByTitle(['سایر درآمد'])}
@@ -19,11 +64,13 @@ function jeVatPayableAccount(){return jeAccountByCode('2102')||jeFindAccountByTi
64 function jeVatRecoverableAccount(){return jeFindAccountByTitle(['مالیات بر ارزش افزوده خرید','مالیات و عوارض دریافتنی'])}
65 function jeRulesForAccount(accountId){return getMyAccountDimensionRules().filter(r=>r.accountId===accountId&&r.active!==false)}
66 function jeDimensionValueValid(type,valueId){
22 - const t=getMyDimensionTypes().find(x=>x.id===type);if(!t||t.active===false)return false;
67 + const t=getMyDimensionTypes().find(x=>x.id===type);if(!t||t.companyId!==afCompanyId()||t.active===false)return false;
68 return afResolvedValues(t).some(v=>v.id===valueId&&v.postable!==false);
69 }
70 function jeValidateDimensions(accountId,assignments){
26 - const rules=jeRulesForAccount(accountId),map=new Map((assignments||[]).map(x=>[x.dimensionTypeId,x.dimensionValueId]));
71 + const rules=jeRulesForAccount(accountId),map=new Map();
72 + if(!Array.isArray(assignments))throw new Error('ساختار تفصیلی معتبر نیست.');
73 + for(const item of assignments){if(!item?.dimensionTypeId||!item.dimensionValueId||map.has(item.dimensionTypeId))throw new Error('تفصیلی ناقص یا تکراری است.');map.set(item.dimensionTypeId,item.dimensionValueId);}
74 for(const r of rules){
75 if(r.applicability==='unavailable'&&map.has(r.dimensionTypeId))throw new Error('تفصیلی غیرمجاز برای حساب انتخاب شده است.');
76 if(r.applicability==='required'&&!map.get(r.dimensionTypeId))throw new Error('تفصیلی الزامی حساب تکمیل نشده است.');
@@ -35,64 +82,95 @@ function jeValidateDimensions(accountId,assignments){
82 function jeValidateLines(lines){
83 if(!Array.isArray(lines)||lines.length<2)throw new Error('سند باید حداقل دو آرتیکل داشته باشد.');
84 let dr=0,cr=0;
38 - lines.forEach((l,i)=>{const d=jeNum(l.debit),c=jeNum(l.credit);if(!jePostingAccount(l.accountId))throw new Error('حساب ثبت‌پذیر ردیف '+(i+1)+' معتبر نیست.');if(d<0||c<0||(!d&&!c)||(d&&c))throw new Error('هر آرتیکل باید فقط بدهکار یا فقط بستانکار باشد.');jeValidateDimensions(l.accountId,l.dimensions||[]);dr+=d;cr+=c});
39 - if(Math.abs(dr-cr)>JE_EPSILON||dr<=0)throw new Error('سند تراز نیست. جمع بدهکار و بستانکار باید برابر باشد.');
85 + lines.forEach((l,i)=>{const d=jeMoney(l.debit),c=jeMoney(l.credit);if(!jePostingAccount(l.accountId))throw new Error('حساب ثبت‌پذیر ردیف '+(i+1)+' معتبر نیست.');if(d<0||c<0||(!d&&!c)||(d&&c))throw new Error('هر آرتیکل باید فقط بدهکار یا فقط بستانکار باشد.');jeValidateDimensions(l.accountId,l.dimensions||[]);dr+=d;cr+=c});
86 + if(!Number.isSafeInteger(dr)||!Number.isSafeInteger(cr)||Math.abs(dr-cr)>JE_EPSILON||dr<=0)throw new Error('سند تراز نیست. جمع بدهکار و بستانکار باید برابر باشد.');
87 return {debit:dr,credit:cr};
88 }
89 function jeNextNumber(fiscalYearId){const nums=getMyJournalVouchers().filter(v=>v.fiscalYearId===fiscalYearId).map(v=>Number(v.number)||0);return String(Math.max(0,...nums)+1)}
90 function jeCreateDraft(input){
91 if(!requireWrite())throw new Error('write denied');const cid=afCompanyId(),fy=jeFiscalForDate(input.date);if(!cid||!fy)throw new Error('سال مالی متناظر با تاریخ سند پیدا نشد.');if(fy.status==='locked')throw new Error('سال مالی قفل است.');
45 - const totals=jeValidateLines(input.lines),id=afId('JV'),voucher={id,ownerUserId:currentUser.id,companyId:cid,fiscalYearId:fy.id,number:input.number||jeNextNumber(fy.id),date:input.date||getJalaliNumeric(),description:String(input.description||''),status:'draft',sourceType:input.sourceType||'manual',sourceId:input.sourceId||'',sourceVersion:Number(input.sourceVersion||1),totalDebit:totals.debit,totalCredit:totals.credit,createdAt:new Date().toISOString(),createdBy:currentUser.id};
46 - datastore.journalVouchers.push(voucher);input.lines.forEach((l,n)=>{const lineId=afId('JL');datastore.journalLines.push({id:lineId,ownerUserId:currentUser.id,companyId:cid,voucherId:id,lineNo:n+1,accountId:l.accountId,debit:jeNum(l.debit),credit:jeNum(l.credit),description:String(l.description||''),counterpartyId:l.counterpartyId||'',projectId:l.projectId||''});(l.dimensions||[]).forEach(d=>datastore.journalLineDimensions.push({id:afId('JLD'),ownerUserId:currentUser.id,companyId:cid,voucherId:id,journalLineId:lineId,dimensionTypeId:d.dimensionTypeId,dimensionValueId:d.dimensionValueId}))});saveDatastore();return voucher;
92 + const number=String(input.number||jeNextNumber(fy.id)).trim();if(!/^\d+$/.test(number)||Number(number)<=0||!Number.isSafeInteger(Number(number)))throw new Error('شماره سند معتبر نیست.');
93 + if(getMyJournalVouchers().some(v=>v.fiscalYearId===fy.id&&Number(v.number)===Number(number)))throw new Error('شماره سند در سال مالی تکراری است.');
94 + const totals=jeValidateLines(input.lines),id=afId('JV'),voucher={id,ownerUserId:currentUser.id,companyId:cid,fiscalYearId:fy.id,number,date:jeDate(input.date),description:String(input.description||''),status:'draft',sourceType:input.sourceType||'manual',sourceId:input.sourceId||'',sourceVersion:Number(input.sourceVersion||1),totalDebit:totals.debit,totalCredit:totals.credit,createdAt:new Date().toISOString(),createdBy:currentUser.id};
95 + datastore.journalVouchers.push(voucher);input.lines.forEach((l,n)=>{const lineId=afId('JL');datastore.journalLines.push({id:lineId,ownerUserId:currentUser.id,companyId:cid,voucherId:id,lineNo:n+1,accountId:l.accountId,debit:jeNum(l.debit),credit:jeNum(l.credit),description:String(l.description||''),counterpartyId:l.counterpartyId||'',projectId:l.projectId||''});(l.dimensions||[]).forEach(d=>datastore.journalLineDimensions.push({id:afId('JLD'),ownerUserId:currentUser.id,companyId:cid,voucherId:id,journalLineId:lineId,dimensionTypeId:d.dimensionTypeId,dimensionValueId:d.dimensionValueId}))});jeSave();return voucher;
96 }
97 function jePost(voucherId){
98 if(!requireWrite())throw new Error('write denied');const v=getMyJournalVouchers().find(x=>x.id===voucherId);if(!v||v.status!=='draft')throw new Error('فقط سند پیش‌نویس قابل قطعی‌سازی است.');const fy=getMyFiscalYears().find(x=>x.id===v.fiscalYearId);if(!fy||fy.status==='locked')throw new Error('سال مالی قفل است.');
99 + if(jeFiscalForDate(v.date)?.id!==fy.id)throw new Error('تاریخ سند خارج از سال مالی است.');
100 + if(getMyJournalVouchers().some(x=>x.id!==v.id&&x.fiscalYearId===fy.id&&Number(x.number)===Number(v.number)))throw new Error('شماره سند در سال مالی تکراری است.');
101 const lines=getMyJournalLines().filter(x=>x.voucherId===v.id).map(l=>({...l,dimensions:getMyJournalLineDimensions().filter(d=>d.journalLineId===l.id)}));const totals=jeValidateLines(lines);
102 if(v.sourceId&&getMyJournalVouchers().some(x=>x.id!==v.id&&x.status==='posted'&&x.sourceType===v.sourceType&&x.sourceId===v.sourceId&&Number(x.sourceVersion||1)===Number(v.sourceVersion||1)))throw new Error('برای این رویداد منبع قبلاً سند قطعی ثبت شده است.');
52 - Object.assign(v,{status:'posted',totalDebit:totals.debit,totalCredit:totals.credit,postedAt:new Date().toISOString(),postedBy:currentUser.id});saveDatastore();return v;
103 + Object.assign(v,{status:'posted',totalDebit:totals.debit,totalCredit:totals.credit,postedAt:new Date().toISOString(),postedBy:currentUser.id});jeSave();return v;
104 }
54 -function jeReverse(voucherId,date,reason){
105 +function jeReverse(voucherId,date,reason){return jeAtomic(()=>{
106 if(!requireWrite())throw new Error('write denied');const v=getMyJournalVouchers().find(x=>x.id===voucherId);if(!v||v.status!=='posted')throw new Error('فقط سند قطعی قابل برگشت است.');if(v.reversalVoucherId)throw new Error('این سند قبلاً برگشت شده است.');
107 + if(v.sourceType==='reversal')throw new Error('سند برگشت دوباره برگشت نمی‌شود؛ منبع اصلی را با نسخه جدید اصلاح کنید.');
108 const lines=getMyJournalLines().filter(x=>x.voucherId===v.id).map(l=>({accountId:l.accountId,debit:l.credit,credit:l.debit,description:'برگشت: '+(l.description||v.description||''),dimensions:getMyJournalLineDimensions().filter(d=>d.journalLineId===l.id).map(d=>({dimensionTypeId:d.dimensionTypeId,dimensionValueId:d.dimensionValueId}))}));
57 - const rv=jeCreateDraft({date:date||getJalaliNumeric(),description:'برگشت سند '+v.number+(reason?' — '+reason:''),sourceType:'reversal',sourceId:v.id,lines});jePost(rv.id);v.status='reversed';v.reversalVoucherId=rv.id;v.reversedAt=new Date().toISOString();saveDatastore();return rv;
58 -}
59 -function jeDeleteDraft(voucherId){if(!requireWrite())return false;const v=getMyJournalVouchers().find(x=>x.id===voucherId);if(!v||v.status!=='draft')throw new Error('سند قطعی/برگشتی حذف‌پذیر نیست.');const ids=getMyJournalLines().filter(x=>x.voucherId===voucherId).map(x=>x.id);datastore.journalLineDimensions=datastore.journalLineDimensions.filter(x=>!ids.includes(x.journalLineId));datastore.journalLines=datastore.journalLines.filter(x=>x.voucherId!==voucherId);datastore.journalVouchers=datastore.journalVouchers.filter(x=>x.id!==voucherId);saveDatastore();return true}
60 -function jeLedgerRows(){return getMyJournalLines().flatMap(l=>{const v=getMyJournalVouchers().find(x=>x.id===l.voucherId);return v&&v.status==='posted'?[{...l,voucher:v,account:jePostingAccount(l.accountId)}]:[]})}
109 + const rv=jeCreateDraft({date:date||getJalaliNumeric(),description:'برگشت سند '+v.number+(reason?' — '+reason:''),sourceType:'reversal',sourceId:v.id,lines});jePost(rv.id);v.status='reversed';v.reversalVoucherId=rv.id;v.reversedAt=new Date().toISOString();jeSave();return rv;
110 +});}
111 +function jeDeleteDraft(voucherId){if(!requireWrite())return false;const v=getMyJournalVouchers().find(x=>x.id===voucherId);if(!v||v.status!=='draft')throw new Error('سند قطعی/برگشتی حذف‌پذیر نیست.');const ids=getMyJournalLines().filter(x=>x.voucherId===voucherId).map(x=>x.id);datastore.journalLineDimensions=datastore.journalLineDimensions.filter(x=>!ids.includes(x.journalLineId));datastore.journalLines=datastore.journalLines.filter(x=>x.voucherId!==voucherId);datastore.journalVouchers=datastore.journalVouchers.filter(x=>x.id!==voucherId);jeSave();return true}
112 +function jeLedgerRows(){return getMyJournalLines().flatMap(l=>{const v=getMyJournalVouchers().find(x=>x.id===l.voucherId);return v&&['posted','reversed'].includes(v.status)?[{...l,voucher:v,account:getMyAccounts().find(a=>a.id===l.accountId)}]:[]})}
113 function jeTrialBalance(){const m={};jeLedgerRows().forEach(l=>{if(!m[l.accountId])m[l.accountId]={accountId:l.accountId,code:l.account?.code||'',title:l.account?.title||'',debit:0,credit:0};m[l.accountId].debit+=jeNum(l.debit);m[l.accountId].credit+=jeNum(l.credit)});return Object.values(m).map(x=>({...x,balance:x.debit-x.credit})).sort((a,b)=>String(a.code).localeCompare(String(b.code),undefined,{numeric:true}))}
114 function jeDimensionAssignmentsForContext(accountId,ctx){
115 const rules=jeRulesForAccount(accountId),out=[];rules.forEach(r=>{if(r.applicability==='unavailable')return;const t=getMyDimensionTypes().find(x=>x.id===r.dimensionTypeId);if(!t)return;let id='';if(t.sourceEntity==='contact')id=ctx.contactId||'';else if(t.sourceEntity==='project')id=ctx.projectId||'';else if(t.sourceEntity==='branch')id=ctx.branchId||'';if(id)out.push({dimensionTypeId:t.id,dimensionValueId:id})});return out;
116 }
117 function jeProfile(kind){return getMyPostingProfiles().find(x=>x.kind===kind&&x.active!==false)||null}
118 function jeEnsureDefaultProfiles(){
67 - if(!currentUser||!afCompanyId()||getMyPostingProfiles().length)return;const cid=afCompanyId(),A=code=>jeAccountByCode(code)?.id||'';
119 + if(!currentUser||!afCompanyId())return;const cid=afCompanyId(),A=code=>jeAccountByCode(code)?.id||'';
120 const rows=[['sale','فروش',jeReceivableAccount()?.id||'',jeRevenueAccount()?.id||''],['purchase','خرید',jePurchaseAccount()?.id||'',jePayableAccount()?.id||''],['receipt','دریافت',jeCashAccount()?.id||'',jeReceivableAccount()?.id||''],['payment','پرداخت',jePayableAccount()?.id||'',jeCashAccount()?.id||''],['expense','هزینه',jeExpenseAccount()?.id||'',jeCashAccount()?.id||''],['income','درآمد متفرقه',jeCashAccount()?.id||'',jeOtherIncomeAccount()?.id||'']];
69 - rows.filter(x=>x[2]&&x[3]).forEach(x=>datastore.postingProfiles.push({id:afId('PP'),ownerUserId:currentUser.id,companyId:cid,kind:x[0],title:x[1],debitAccountId:x[2],creditAccountId:x[3],active:true}));if(rows.some(x=>x[2]&&x[3]))saveDatastore();
121 + rows.filter(x=>x[2]&&x[3]&&!getMyPostingProfiles().some(p=>p.kind===x[0])).forEach(x=>datastore.postingProfiles.push({id:afId('PP'),ownerUserId:currentUser.id,companyId:cid,kind:x[0],title:x[1],debitAccountId:x[2],creditAccountId:x[3],active:true}));if(rows.some(x=>x[2]&&x[3]))jeSave();
122 }
71 -function jeAutoPost(kind,source){
72 - const amount=jeNum(source.amount??source.grandTotal);if(amount<=0)throw new Error('مبلغ سند منبع معتبر نیست.');
123 +function jeAutoPost(kind,source){return jeAtomic(()=>{
124 + jeSourceScope(source);
125 + if(kind==='sale'&&source.kind==='pre_invoice')throw new Error('پیش‌فاکتور سند مالی نیست و ثبت حسابداری ندارد.');
126 + if((kind==='receipt'||kind==='payment')&&source.method==='cheque')throw new Error('تسویه با چک هنوز به چرخه حسابداری وصول/برگشت متصل نیست؛ ثبت نقدی برای آن مجاز نیست.');
127 + if(getMyJournalVouchers().some(v=>v.status==='posted'&&v.sourceType===kind&&v.sourceId===source.id))throw new Error('این منبع سند قطعی فعال دارد؛ ابتدا برگشت ثبت کنید.');
128 + jeEnsureDefaultProfiles();
129 + const amount=jeMoney(source.amount??source.grandTotal);if(amount<=0)throw new Error('مبلغ سند منبع معتبر نیست.');
130 const ctx={contactId:source.contactId||source.supplierId||'',projectId:source.projectId||source.costCenterId||'',branchId:source.branchId||''},dims=a=>jeDimensionAssignmentsForContext(a,ctx);
131 let lines=[],title='';
132 if(kind==='sale'){
76 - const cash=jeCashAccount(),ar=jeReceivableAccount(),rev=jeRevenueAccount(),vat=jeVatPayableAccount(),gross=jeNum(source.grandTotal),tax=jeNum(source.vat),net=Math.max(0,gross-tax),debit=source.paymentMethod==='credit'?ar:cash;if(!debit||!rev)throw new Error('حساب‌های فروش/دریافتنی/نقد در کدینگ تکمیل نیست.');
133 + const profile=jeProfile(kind),cash=jeCashAccount(),ar=profile?jePostingAccount(profile.debitAccountId):jeReceivableAccount(),rev=profile?jePostingAccount(profile.creditAccountId):jeRevenueAccount(),vat=jeVatPayableAccount(),gross=jeMoney(source.grandTotal),tax=jeMoney(source.vat),net=Math.max(0,gross-tax),debit=source.paymentMethod==='credit'?ar:cash;if(!debit||!rev)throw new Error('حساب‌های فروش/دریافتنی/نقد در کدینگ تکمیل نیست.');
134 title='فروش';lines=[{accountId:debit.id,debit:gross,credit:0,description:title,dimensions:dims(debit.id)},{accountId:rev.id,debit:0,credit:net,description:title,dimensions:dims(rev.id)}];if(tax){if(!vat)throw new Error('برای مالیات فروش حساب مالیات پرداختنی تعریف کنید.');lines.push({accountId:vat.id,debit:0,credit:tax,description:'مالیات فروش',dimensions:dims(vat.id)})}
135 }else if(kind==='purchase'){
79 - const cash=jeCashAccount(),ap=jePayableAccount(),buy=jePurchaseAccount(),vat=jeVatRecoverableAccount(),gross=jeNum(source.grandTotal),tax=jeNum(source.vat),net=Math.max(0,gross-tax),credit=source.paymentMethod==='credit'?ap:cash;if(!credit||!buy)throw new Error('حساب‌های خرید/پرداختنی/نقد در کدینگ تکمیل نیست.');
136 + const profile=jeProfile(kind),cash=jeCashAccount(),ap=profile?jePostingAccount(profile.creditAccountId):jePayableAccount(),buy=profile?jePostingAccount(profile.debitAccountId):jePurchaseAccount(),vat=jeVatRecoverableAccount(),gross=jeMoney(source.grandTotal),tax=jeMoney(source.vat),net=Math.max(0,gross-tax),credit=source.paymentMethod==='credit'?ap:cash;if(!credit||!buy)throw new Error('حساب‌های خرید/پرداختنی/نقد در کدینگ تکمیل نیست.');
137 title='خرید';lines=[{accountId:buy.id,debit:vat?net:gross,credit:0,description:title,dimensions:dims(buy.id)}];if(tax&&vat)lines.push({accountId:vat.id,debit:tax,credit:0,description:'مالیات خرید',dimensions:dims(vat.id)});else if(tax)lines[0].debit=gross;lines.push({accountId:credit.id,debit:0,credit:gross,description:title,dimensions:dims(credit.id)})
138 }else{
139 const profile=jeProfile(kind);if(!profile)throw new Error('پروفایل ثبت خودکار '+kind+' تعریف نشده است.');title=profile.title;lines=[{accountId:profile.debitAccountId,debit:amount,credit:0,description:title,dimensions:dims(profile.debitAccountId)},{accountId:profile.creditAccountId,debit:0,credit:amount,description:title,dimensions:dims(profile.creditAccountId)}];
140 }
141 const v=jeCreateDraft({date:source.date||getJalaliNumeric(),description:title+' — '+(source.number||source.reference||source.id),sourceType:kind,sourceId:source.id,sourceVersion:Number(source.accountingVersion||1),lines});return jePost(v.id);
85 -}
86 -function jeActiveSourceVoucher(source){return source?.journalVoucherId?getMyJournalVouchers().find(v=>v.id===source.journalVoucherId&&v.status==='posted'):null}
142 +});}
143 +function jeSourceHistory(source){return source?(datastore.journalVouchers||[]).filter(v=>v.ownerUserId===currentUser?.id&&v.companyId===source.companyId&&(v.id===source.journalVoucherId||(v.sourceId===source.id&&v.sourceType!=='reversal'))):[];}
144 +function jeActiveSourceVoucher(source){return jeSourceHistory(source).find(v=>v.status==='posted')||null;}
145 function jeSourceLocked(source){return !!jeActiveSourceVoucher(source)}
146 function jeGuardSourceMutation(source,label){if(jeSourceLocked(source))throw new Error((label||'رکورد مالی')+' دارای سند حسابداری قطعی است؛ ابتدا سند را برگشت بزنید و سپس اصلاح کنید.');return true}
147 +function jeGuardSourceDeletion(source,label){if(jeSourceHistory(source).length)throw new Error((label||'رکورد مالی')+' دارای سابقه حسابداری است و حذف نمی‌شود؛ اصلاح را با برگشت و نسخه جدید انجام دهید.');return true;}
148 function jePostSourceRecord(kind,source){
90 - if(!source)throw new Error('رکورد منبع پیدا نشد.');
149 + jeSourceScope(source);
150 if(jeActiveSourceVoucher(source))return jeActiveSourceVoucher(source);
92 - const v=jeAutoPost(kind,source);source.journalVoucherId=v.id;source.accountingVersion=Number(source.accountingVersion||1);source.accountingStatus='posted';source.accountingPostedAt=v.postedAt;saveDatastore();return v;
151 + const v=jeAutoPost(kind,source);source.journalVoucherId=v.id;source.accountingVersion=Number(source.accountingVersion||1);source.accountingStatus='posted';source.accountingPostedAt=v.postedAt;jeSave();return v;
152 }
153 function jePostLegacySource(kind,id){
154 let source;if(kind==='sale')source=getMyInvoices().find(x=>x.id===id);else if(kind==='purchase')source=getMyPurchases().find(x=>x.id===id);else if(kind==='receipt'||kind==='payment')source=getMyPayments().find(x=>x.id===id);else if(kind==='expense'||kind==='income')source=getMyExpenses().find(x=>x.id===id);if(!source)throw new Error('رکورد منبع پیدا نشد.');
155 if(kind==='receipt'||kind==='payment')kind=source.direction==='outbound'?'payment':'receipt';if(kind==='expense'||kind==='income')kind=source.kind==='income'?'income':'expense';
156 return jePostSourceRecord(kind,source);
157 }
158 +
159 +function jeSaveOperationalRecord(kind,input){return jeAtomic(()=>{
160 + if(!requireWrite())throw new Error('write denied');
161 + const collection={sale:'invoices',purchase:'purchases',receipt:'payments',payment:'payments',expense:'expenses',income:'expenses'}[kind];
162 + if(!collection)throw new Error('نوع منبع حسابداری معتبر نیست.');
163 + jeSourceScope(input);
164 + const list=datastore[collection],index=list.findIndex(x=>x.id===input.id&&x.ownerUserId===currentUser.id),old=index<0?null:list[index];
165 + if(old&&old.companyId!==input.companyId)throw new Error('شرکت رکورد موجود قابل تغییر نیست.');
166 + if(old)jeGuardSourceMutation(old);
167 + const record={...old,...input},history=jeSourceHistory(old||record);
168 + record.accountingVersion=history.length?Math.max(...history.map(v=>Number(v.sourceVersion)||1))+1:Number(old?.accountingVersion||1);
169 + delete record.journalVoucherId;delete record.accountingPostedAt;
170 + const configured=getMyAccounts().length||getMyPostingProfiles().length||getMyJournalVouchers().length;
171 + if(kind==='sale'&&record.kind==='pre_invoice')record.accountingStatus='non_financial';
172 + else if(!configured)record.accountingStatus='not_configured';
173 + else jePostSourceRecord(kind,record);
174 + if(index<0)list.push(record);else list[index]=record;
175 + return record;
176 +});}
js/journal-ui.js
+3 -3
@@ -1,6 +1,6 @@
1 /* Phase 3 — journal UI */
2 function ensureJournalView(){
3 - if(document.getElementById('view-journal'))return;const s=document.createElement('section');s.id='view-journal';s.className='view';s.innerHTML=`<div class="af-head"><div><h1>اسناد حسابداری</h1><p>ثبت دوبل، قطعی‌سازی، برگشت و تراز آزمایشی</p></div><span class="badge badge-info">فاز ۳</span></div>
3 + if(document.getElementById('view-journal'))return;const s=document.createElement('section');s.id='view-journal';s.className='view-pane';s.innerHTML=`<div class="af-head"><div><h1>اسناد حسابداری</h1><p>ثبت دوبل، قطعی‌سازی، برگشت و تراز آزمایشی</p></div><span class="badge badge-info">فاز ۳</span></div>
4 <div class="card"><h3>سند دستی</h3><div class="form-row"><div class="form-group"><label>تاریخ</label><input id="je-date" class="form-control"></div><div class="form-group"><label>شرح</label><input id="je-desc" class="form-control"></div></div><div id="je-lines"></div><div style="display:flex;gap:8px;flex-wrap:wrap"><button class="btn btn-secondary" onclick="jeAddRow()">+ آرتیکل</button><button class="btn btn-success" onclick="jeSaveManual()">ثبت پیش‌نویس</button></div></div>
5 <div class="card"><h3>دفتر اسناد</h3><div class="table-responsive"><table><thead><tr><th>شماره</th><th>تاریخ</th><th>شرح</th><th>وضعیت</th><th>بدهکار</th><th>بستانکار</th><th>عملیات</th></tr></thead><tbody id="je-vouchers"></tbody></table></div></div>
6 <div class="card"><h3>تراز آزمایشی</h3><div class="table-responsive"><table><thead><tr><th>کد</th><th>حساب</th><th>بدهکار</th><th>بستانکار</th><th>مانده</th></tr></thead><tbody id="je-trial"></tbody></table></div></div>`;const main=document.querySelector('.main-surface'),p=document.getElementById('printable-invoice');p?main.insertBefore(s,p):main.appendChild(s);
@@ -12,11 +12,11 @@ function jeRenderDims(row){
12 const aid=row.querySelector('.je-account').value,box=row.querySelector('.je-dims'),rules=jeRulesForAccount(aid).filter(x=>x.applicability!=='unavailable');box.innerHTML=rules.map(r=>{const t=getMyDimensionTypes().find(x=>x.id===r.dimensionTypeId),vals=t?afResolvedValues(t).filter(v=>v.postable!==false):[];return t?'<label style="display:inline-block;margin:5px 8px">'+esc(t.title)+(r.applicability==='required'?' *':'')+' <select class="form-control je-dim" data-type="'+t.id+'" style="min-width:180px"><option value="">— انتخاب —</option>'+vals.map(v=>'<option value="'+v.id+'">'+esc(v.title||v.name)+'</option>').join('')+'</select></label>':''}).join('');
13 }
14 function jeCollectRows(){return[...document.querySelectorAll('#je-lines .je-line')].map(r=>({accountId:r.querySelector('.je-account').value,debit:parseFormattedNumber(r.querySelector('.je-debit').value),credit:parseFormattedNumber(r.querySelector('.je-credit').value),description:r.querySelector('.je-line-desc').value,dimensions:[...r.querySelectorAll('.je-dim')].filter(x=>x.value).map(x=>({dimensionTypeId:x.dataset.type,dimensionValueId:x.value}))}))}
15 -function jeSaveManual(){try{const v=jeCreateDraft({date:document.getElementById('je-date').value||getJalaliNumeric(),description:document.getElementById('je-desc').value,lines:jeCollectRows()});alert('پیش‌نویس سند '+v.number+' ثبت شد.');renderJournal()}catch(e){alert(e.message)}}
15 +function jeSaveManual(){try{const v=jeCreateDraft({date:document.getElementById('je-date').value||getJalaliNumeric(),description:document.getElementById('je-desc').value,lines:jeCollectRows()});alert('پیش‌نویس سند '+v.number+' ثبت شد.');document.getElementById('je-lines').innerHTML='';document.getElementById('je-desc').value='';renderJournal()}catch(e){alert(e.message)}}
16 function jePostUi(id){try{jePost(id);renderJournal()}catch(e){alert(e.message)}} function jeReverseUi(id){const why=prompt('علت برگشت سند:','اصلاح ثبت');if(why===null)return;try{jeReverse(id,getJalaliNumeric(),why);renderJournal()}catch(e){alert(e.message)}}
17 function jeDeleteUi(id){if(!confirm('پیش‌نویس حذف شود؟'))return;try{jeDeleteDraft(id);renderJournal()}catch(e){alert(e.message)}}
18 function renderJournal(){
19 - ensureJournalView();if(!currentUser)return;jeEnsureDefaultProfiles();const body=document.getElementById('je-vouchers'),vs=getMyJournalVouchers().slice().sort((a,b)=>String(b.createdAt).localeCompare(String(a.createdAt)));if(body)body.innerHTML=vs.length?vs.map(v=>'<tr><td>'+esc(v.number)+'</td><td>'+esc(v.date)+'</td><td>'+esc(v.description)+'</td><td>'+esc(v.status)+'</td><td>'+Number(v.totalDebit).toLocaleString('fa-IR')+'</td><td>'+Number(v.totalCredit).toLocaleString('fa-IR')+'</td><td>'+(v.status==='draft'?'<button class="btn btn-success btn-inline" onclick="jePostUi(\''+v.id+'\')">قطعی</button> <button class="btn btn-danger btn-inline" onclick="jeDeleteUi(\''+v.id+'\')">حذف</button>':v.status==='posted'?'<button class="btn btn-secondary btn-inline" onclick="jeReverseUi(\''+v.id+'\')">برگشت</button>':'—')+'</td></tr>').join(''):'<tr><td colspan="7" class="af-empty">سندی ثبت نشده است.</td></tr>';
19 + ensureJournalView();if(!currentUser)return;const box=document.getElementById('je-lines'),scope=currentUser.id+'|'+afCompanyId();if(box&&box.dataset.scope!==scope){box.innerHTML='';box.dataset.scope=scope;document.getElementById('je-desc').value='';document.getElementById('je-date').value='';}jeEnsureDefaultProfiles();const body=document.getElementById('je-vouchers'),vs=getMyJournalVouchers().slice().sort((a,b)=>String(b.createdAt).localeCompare(String(a.createdAt)));if(body)body.innerHTML=vs.length?vs.map(v=>'<tr><td>'+esc(v.number)+'</td><td>'+esc(v.date)+'</td><td>'+esc(v.description)+'</td><td>'+esc(v.status)+'</td><td>'+Number(v.totalDebit).toLocaleString('fa-IR')+'</td><td>'+Number(v.totalCredit).toLocaleString('fa-IR')+'</td><td>'+(v.status==='draft'?'<button class="btn btn-success btn-inline" onclick="jePostUi(\''+v.id+'\')">قطعی</button> <button class="btn btn-danger btn-inline" onclick="jeDeleteUi(\''+v.id+'\')">حذف</button>' :v.status==='posted'&&v.sourceType!=='reversal'?'<button class="btn btn-secondary btn-inline" onclick="jeReverseUi(\''+v.id+'\')">برگشت</button>':'—')+'</td></tr>').join(''):'<tr><td colspan="7" class="af-empty">سندی ثبت نشده است.</td></tr>';
20 const tb=document.getElementById('je-trial'),rows=jeTrialBalance();if(tb)tb.innerHTML=rows.length?rows.map(x=>'<tr><td>'+esc(x.code)+'</td><td>'+esc(x.title)+'</td><td>'+x.debit.toLocaleString('fa-IR')+'</td><td>'+x.credit.toLocaleString('fa-IR')+'</td><td>'+x.balance.toLocaleString('fa-IR')+'</td></tr>').join(''):'<tr><td colspan="5" class="af-empty">گردشی وجود ندارد.</td></tr>';
21 const d=document.getElementById('je-date');if(d&&!d.value)d.value=getJalaliNumeric();if(!document.querySelector('#je-lines .je-line')){jeAddRow();jeAddRow()}
22 }
js/operations.js
+14 -6
@@ -36,10 +36,10 @@ const rp=window.renderProducts;window.renderProducts=function(){rp();document.qu
36 function resetCheque(){eq='';clr(['chq-sayad-input','chq-bank-input','chq-amount-input','chq-due-input']);if($('chq-direction-input'))$('chq-direction-input').value='inbound';if($('chq-status-input'))$('chq-status-input').value='registered';btn('cheque-save-btn','cheque-edit-cancel-btn',false,'➕ ثبت چک','💾 ذخیره اصلاحات');}
37 window.cancelChequeEdit=resetCheque;
38 window.editCheque=function(id){const q=getMyCheques().find(x=>x.id===id);if(!q)return;eq=id;const v={'chq-direction-input':q.direction||'inbound','chq-contact-select':q.contactId||'','chq-sayad-input':q.sayad_id||'','chq-bank-input':q.bank||'','chq-amount-input':fmt(q.amount),'chq-due-input':q.due_date||'','chq-status-input':q.status||'registered'};Object.keys(v).forEach(k=>{if($(k))$(k).value=v[k];});btn('cheque-save-btn','cheque-edit-cancel-btn',true,'','💾 ذخیره اصلاحات');switchView('view-cheques');};
39 -window.commitSaveCheque=function(){if(!requireWrite()||!currentUser)return;const s=$('chq-contact-select'),amount=parseFormattedNumber($('chq-amount-input').value),sayad=$('chq-sayad-input').value.trim();if(!sayad||amount<=0){alert('اطلاعات چک نامعتبر است.');return;}const companyId=getMySettings().default_company_id||getMyCompanies()[0]?.id||'';const p={direction:$('chq-direction-input').value,companyId,contactId:s?.value||'',contactName:s?.options[s.selectedIndex]?.text||'',sayad_id:sayad,bank:$('chq-bank-input').value||'',amount,due_date:$('chq-due-input').value||'',status:$('chq-status-input').value};if(getMyCheques().some(x=>x.id!==eq&&String(x.sayad_id||'')===sayad)){alert('شناسه صیادی تکراری است.');return;}if(eq){const q=datastore.cheques.find(x=>x.id===eq&&x.ownerUserId===currentUser.id);if(!q)return;Object.assign(q,p);alert('چک اصلاح شد.');}else datastore.cheques.push({id:'CHQ_'+Date.now(),ownerUserId:currentUser.id,...p});saveDatastore();resetCheque();refreshAllSurfaces();};
40 -window.deleteCheque=function(id){if(!requireWrite()||!confirm('این چک حذف شود؟'))return;if(eq===id)resetCheque();datastore.cheques=datastore.cheques.filter(x=>!(x.id===id&&x.ownerUserId===currentUser.id));saveDatastore();refreshAllSurfaces();};
39 +window.commitSaveCheque=function(){if(!requireWrite()||!currentUser)return;const s=$('chq-contact-select'),amount=parseFormattedNumber($('chq-amount-input').value),sayad=$('chq-sayad-input').value.trim();if(!sayad||amount<=0){alert('اطلاعات چک نامعتبر است.');return;}const companyId=getMySettings().default_company_id||getMyCompanies()[0]?.id||'';const p={direction:$('chq-direction-input').value,companyId,contactId:s?.value||'',contactName:s?.options[s.selectedIndex]?.text||'',sayad_id:sayad,bank:$('chq-bank-input').value||'',amount,due_date:$('chq-due-input').value||'',status:$('chq-status-input').value};if(getMyCheques().some(x=>x.id!==eq&&String(x.sayad_id||'')===sayad)){alert('شناسه صیادی تکراری است.');return;}if(eq){const q=datastore.cheques.find(x=>x.id===eq&&x.ownerUserId===currentUser.id);if(!q)return;try{jeGuardSourceMutation(q,'چک');}catch(e){alert(e.message);return;}Object.assign(q,p);alert('چک اصلاح شد.');}else datastore.cheques.push({id:'CHQ_'+Date.now(),ownerUserId:currentUser.id,...p});saveDatastore();resetCheque();refreshAllSurfaces();};
40 +window.deleteCheque=function(id){if(!requireWrite())return;const q=getMyCheques().find(x=>x.id===id);try{jeGuardSourceDeletion(q,'چک');}catch(e){alert(e.message);return;}if(!confirm('این چک حذف شود؟'))return;if(eq===id)resetCheque();datastore.cheques=datastore.cheques.filter(x=>!(x.id===id&&x.ownerUserId===currentUser.id));saveDatastore();refreshAllSurfaces();};
41 function chequeStatusLabel(status){return status==='cleared'?'وصول / پرداخت شده':status==='bounced'?'برگشتی / ناموفق':status==='cancelled'?'باطل شده':'در جریان';}
42 -window.renderCheques=function(){const tb=$('cheques-ledger-table-body'),list=getMyCheques();if(!tb)return;tb.innerHTML=list.length?list.map(q=>`<tr><td>${q.direction==='inbound'?'دریافتی':'پرداختی'}</td><td>${esc(q.contactName||'—')}</td><td>${esc(q.bank)} - ${esc(q.sayad_id)}</td><td>${fmt(q.amount)}</td><td>${esc(q.due_date)}</td><td>${esc(chequeStatusLabel(q.status))}</td><td><button class="btn btn-secondary btn-inline" onclick="editCheque('${q.id}')">✏️ اصلاح</button> <button class="btn btn-danger btn-inline" onclick="deleteCheque('${q.id}')">حذف</button></td></tr>`).join(''):'<tr><td colspan="7" style="text-align:center;padding:20px">چکی ثبت نشده است.</td></tr>';};
42 +window.renderCheques=function(){const tb=$('cheques-ledger-table-body'),list=getMyCheques();if(!tb)return;const view=$('view-cheques');if(view&&!$('cheque-accounting-notice')){const note=document.createElement('p');note.id='cheque-accounting-notice';note.className='text-muted';note.textContent='این دفتر برای پیگیری چک است؛ ثبت یا تغییر وضعیت چک سند حسابداری و تسویه فاکتور ایجاد نمی‌کند.';view.prepend(note);}tb.innerHTML=list.length?list.map(q=>`<tr><td>${q.direction==='inbound'?'دریافتی':'پرداختی'}</td><td>${esc(q.contactName||'—')}</td><td>${esc(q.bank)} - ${esc(q.sayad_id)}</td><td>${fmt(q.amount)}</td><td>${esc(q.due_date)}</td><td>${esc(chequeStatusLabel(q.status))}</td><td><button class="btn btn-secondary btn-inline" onclick="editCheque('${q.id}')">✏️ اصلاح</button> <button class="btn btn-danger btn-inline" onclick="deleteCheque('${q.id}')">حذف</button></td></tr>`).join(''):'<tr><td colspan="7" style="text-align:center;padding:20px">چکی ثبت نشده است.</td></tr>';};
43
44 // هزینه/درآمد
45 function refreshExpenseProjects(){
@@ -58,12 +58,20 @@ window.refreshExpenseProjects=refreshExpenseProjects;
58 function resetExpense(){ee='';clr(['trx-amount-input','trx-desc-input']);if($('trx-contact-select'))$('trx-contact-select').value='';refreshExpenseProjects();btn('expense-save-btn','expense-edit-cancel-btn',false,'➕ ثبت سند','💾 ذخیره اصلاحات');}
59 window.cancelExpenseEdit=resetExpense;
60 window.editExpense=function(id){const e=getMyExpenses().find(x=>x.id===id);if(!e)return;ee=id;refreshExpenseContacts();$('trx-kind-input').value=e.kind;$('trx-category-input').value=e.category;$('trx-contact-select').value=e.contactId||'';refreshExpenseProjects();$('trx-project-select').value=e.projectId||'';$('trx-amount-input').value=fmt(e.amount);$('trx-desc-input').value=e.desc||'';btn('expense-save-btn','expense-edit-cancel-btn',true,'','💾 ذخیره اصلاحات');switchView('view-expenses');};
61 -window.commitSaveExpense=function(){if(!requireWrite()||!currentUser)return;const amount=parseFormattedNumber($('trx-amount-input').value);if(amount<=0){alert('مبلغ معتبر نیست.');return;}const contactId=$('trx-contact-select')?.value||'',contact=getMyContacts().find(x=>x.id===contactId),projectId=$('trx-project-select')?.value||'',companyId=getMySettings().default_company_id||getMyCompanies()[0]?.id||'';const p={kind:$('trx-kind-input').value,category:$('trx-category-input').value,companyId,contactId,contactName:contact?.name||'',projectId,amount,desc:$('trx-desc-input').value||''};if(ee){const e=datastore.expenses.find(x=>x.id===ee&&x.ownerUserId===currentUser.id);if(!e)return;if(typeof jeGuardSourceMutation==='function'){try{jeGuardSourceMutation(e,'هزینه/درآمد');}catch(err){alert(err.message);return;}}Object.assign(e,p);alert('سند اصلاح شد.');}else{const rec={id:'TRX_'+Date.now(),ownerUserId:currentUser.id,...p,date:getJalaliNumeric()};datastore.expenses.push(rec);if(typeof jePostSourceRecord==='function'){try{jePostSourceRecord(rec.kind==='income'?'income':'expense',rec);}catch(err){datastore.expenses=datastore.expenses.filter(x=>x.id!==rec.id);alert('رکورد ثبت نشد: '+err.message);return;}}}saveDatastore();resetExpense();refreshAllSurfaces();};
62 -window.deleteExpense=function(id){if(!requireWrite())return;const source=getMyExpenses().find(x=>x.id===id);if(typeof jeGuardSourceMutation==='function'){try{jeGuardSourceMutation(source,'هزینه/درآمد');}catch(e){alert(e.message);return;}}if(!confirm('این سند حذف شود؟'))return;if(ee===id)resetExpense();datastore.expenses=datastore.expenses.filter(x=>!(x.id===id&&x.ownerUserId===currentUser.id));saveDatastore();refreshAllSurfaces();};
61 +window.commitSaveExpense=function(){
62 + if(!requireWrite()||!currentUser)return;
63 + const amount=parseFormattedNumber($('trx-amount-input').value);if(amount<=0){alert('مبلغ معتبر نیست.');return;}
64 + const contactId=$('trx-contact-select')?.value||'',contact=getMyContacts().find(x=>x.id===contactId),projectId=$('trx-project-select')?.value||'',companyId=getMySettings().default_company_id||getMyCompanies()[0]?.id||'';
65 + const old=ee?datastore.expenses.find(x=>x.id===ee&&x.ownerUserId===currentUser.id):null;if(ee&&!old)return;
66 + const rec={...old,id:old?.id||('TRX_'+Date.now()),ownerUserId:currentUser.id,kind:$('trx-kind-input').value,category:$('trx-category-input').value,companyId,contactId,contactName:contact?.name||'',projectId,amount,desc:$('trx-desc-input').value||'',date:old?.date||getJalaliNumeric()};
67 + try{jeSaveOperationalRecord(rec.kind==='income'?'income':'expense',rec);}catch(err){alert('رکورد ثبت نشد: '+err.message);return;}
68 + alert('رکورد ثبت شد.');resetExpense();refreshAllSurfaces();
69 +};
70 +window.deleteExpense=function(id){if(!requireWrite())return;const source=getMyExpenses().find(x=>x.id===id);if(typeof jeGuardSourceDeletion==='function'){try{jeGuardSourceDeletion(source,'هزینه/درآمد');}catch(e){alert(e.message);return;}}if(!confirm('این سند حذف شود؟'))return;if(ee===id)resetExpense();datastore.expenses=datastore.expenses.filter(x=>!(x.id===id&&x.ownerUserId===currentUser.id));saveDatastore();refreshAllSurfaces();};
71 window.renderExpenses=function(){const tb=$('expenses-ledger-table-body'),list=getMyExpenses();if(!tb)return;refreshExpenseContacts();const projectName=e=>{const c=getMyContacts().find(x=>x.id===e.contactId);for(const p of (c?.projects||[])){if(p.id===e.projectId)return p.name;const s=(p.subprojects||[]).find(x=>x.id===e.projectId);if(s)return p.name+' / '+s.name;}return e.projectId?'پروژه حذف/تغییر یافته':'—';};tb.innerHTML=list.length?list.map(e=>`<tr><td>${esc(e.kind)}</td><td>${esc(e.category)}</td><td>${esc(e.contactName||'—')}</td><td>${esc(projectName(e))}</td><td>${esc(e.desc)}</td><td>${fmt(e.amount)}</td><td><button class="btn btn-secondary btn-inline" onclick="editExpense('${e.id}')">✏️ اصلاح</button> <button class="btn btn-danger btn-inline" onclick="deleteExpense('${e.id}')">حذف</button></td></tr>`).join(''):'<tr><td colspan="7" style="text-align:center;padding:20px">موردی ثبت نشده است.</td></tr>';};
72
73 // فاکتور فروش: حذف در کنار ویرایش/چاپ
66 -window.deleteInvoice=function(id){const source=getMyInvoices().find(x=>x.id===id);if(typeof jeGuardSourceMutation==='function'){try{jeGuardSourceMutation(source,'فاکتور فروش');}catch(e){alert(e.message);return;}}if(typeof getMyPayments==='function'&&getMyPayments().some(p=>p.invoiceType==='sale'&&p.invoiceId===id)){alert('برای این فاکتور دریافت ثبت شده است؛ برای حفظ سابقه مالی ابتدا تخصیص دریافت را اصلاح کنید.');return;}if(!requireWrite()||!confirm('این فاکتور حذف شود؟'))return;datastore.invoices=datastore.invoices.filter(x=>!(x.id===id&&x.ownerUserId===currentUser.id));saveDatastore();refreshAllSurfaces();};
74 +window.deleteInvoice=function(id){const source=getMyInvoices().find(x=>x.id===id);if(typeof jeGuardSourceDeletion==='function'){try{jeGuardSourceDeletion(source,'فاکتور فروش');}catch(e){alert(e.message);return;}}if(typeof getMyPayments==='function'&&getMyPayments().some(p=>p.invoiceType==='sale'&&p.invoiceId===id)){alert('برای این فاکتور دریافت ثبت شده است؛ برای حفظ سابقه مالی ابتدا تخصیص دریافت را اصلاح کنید.');return;}if(!requireWrite()||!confirm('این فاکتور حذف شود؟'))return;datastore.invoices=datastore.invoices.filter(x=>!(x.id===id&&x.ownerUserId===currentUser.id));saveDatastore();refreshAllSurfaces();};
75 const ri=window.renderInvoices;window.renderInvoices=function(){ri();document.querySelectorAll('#invoice-archive-table-body tr').forEach(tr=>{const edit=tr.querySelector('button[onclick^="editInvoice"]');if(!edit)return;const m=(edit.getAttribute('onclick')||'').match(/editInvoice\('([^']+)'\)/);if(!m)return;const cell=tr.lastElementChild;if(cell&&!cell.querySelector('.delete-invoice')){const b=document.createElement('button');b.className='btn btn-danger btn-inline delete-invoice';b.style.cssText='padding:4px 8px;font-size:12px;min-height:30px';b.textContent='حذف';b.onclick=()=>deleteInvoice(m[1]);cell.appendChild(b);}});};
76 try{if(currentUser)refreshAllSurfaces();}catch(e){console.error('crud init',e);}
77 })();
\ No newline at end of file
js/payments.js
+5 -5
@@ -37,10 +37,10 @@ function refreshPaymentInvoices(){
37 const el=document.getElementById('pay-invoice');if(!el)return;
38 const dir=document.getElementById('pay-direction')?.value||'inbound';
39 const cid=document.getElementById('pay-contact')?.value||'';
40 - let rows=[];
40 + let rows=[];const editing=getMyPayments().find(p=>p.id===editingPaymentId);const retained=(i,type)=>editing&&editing.invoiceType===type&&editing.invoiceId===i.id&&editing.direction===dir;
41 const companies=getMyCompanies(),active=getMySettings().default_company_id||companies[0]?.id||'',legacyOk=companies.length===1,companyOk=i=>!active||i.companyId===active||(!i.companyId&&legacyOk);
42 - if(dir==='inbound')rows=getMyInvoices().filter(i=>companyOk(i)&&(!cid||i.contactId===cid)&&invoiceOutstanding(i)>0).map(i=>({id:i.id,type:'sale',label:`فروش ${i.number||i.invoiceNumber||i.id} — مانده ${invoiceOutstanding(i).toLocaleString('fa-IR')}`}));
43 - else rows=getMyPurchases().filter(i=>companyOk(i)&&(!cid||i.supplierId===cid)&&purchaseOutstanding(i)>0).map(i=>({id:i.id,type:'purchase',label:`خرید ${i.number||i.invoiceNo||i.id} — مانده ${purchaseOutstanding(i).toLocaleString('fa-IR')}`}));
42 + if(dir==='inbound')rows=getMyInvoices().filter(i=>companyOk(i)&&(!cid||i.contactId===cid)&&(invoiceOutstanding(i)>0||retained(i,'sale'))).map(i=>({id:i.id,type:'sale',label:`فروش ${i.number||i.invoiceNumber||i.id} — مانده ${invoiceOutstanding(i).toLocaleString('fa-IR')}`}));
43 + else rows=getMyPurchases().filter(i=>companyOk(i)&&(!cid||i.supplierId===cid)&&(purchaseOutstanding(i)>0||retained(i,'purchase'))).map(i=>({id:i.id,type:'purchase',label:`خرید ${i.number||i.invoiceNo||i.id} — مانده ${purchaseOutstanding(i).toLocaleString('fa-IR')}`}));
44 const prev=el.value;
45 el.innerHTML='<option value="">بدون تخصیص به فاکتور</option>'+rows.map(r=>`<option value="${r.type}|${escP(r.id)}">${escP(r.label)}</option>`).join('');
46 if([...el.options].some(o=>o.value===prev))el.value=prev;
@@ -66,7 +66,7 @@ function commitSavePayment(){
66 const linkedPurchase=invoiceType==='purchase'?getMyPurchases().find(i=>i.id===invoiceId):null;
67 const companies=getMyCompanies(),active=linkedSale?.companyId||linkedPurchase?.companyId||getMySettings().default_company_id||companies[0]?.id||'';
68 const payload={id:old?.id||('PAY-'+Date.now()),ownerUserId:currentUser.id,companyId:active,contactId,contactName:contact?.name||'',direction,amount,method:document.getElementById('pay-method')?.value||'bank',reference:(document.getElementById('pay-reference')?.value||'').trim(),note:(document.getElementById('pay-note')?.value||'').trim(),invoiceType,invoiceId,projectId:linkedSale?.projectId||linkedPurchase?.costCenterId||'',date:old?.date||new Date().toISOString()};
69 - if(old)Object.assign(old,payload);else{datastore.payments.push(payload);if(typeof jePostSourceRecord==='function'){try{jePostSourceRecord(direction==='outbound'?'payment':'receipt',payload);}catch(e){datastore.payments=datastore.payments.filter(x=>x.id!==payload.id);alert('دریافت/پرداخت ثبت نشد: '+e.message);return;}}}
69 + try{jeSaveOperationalRecord(direction==='outbound'?'payment':'receipt',{...old,...payload});}catch(e){alert('دریافت/پرداخت ثبت نشد: '+e.message);return;}
70 saveDatastore();resetPaymentForm();refreshAllSurfaces();renderPayments();
71 }
72 function editPayment(id){
@@ -85,7 +85,7 @@ function editPayment(id){
85 }
86 function deletePayment(id){
87 if(typeof requireWrite==='function'&&!requireWrite())return;
88 - const source=getMyPayments().find(p=>p.id===id);if(typeof jeGuardSourceMutation==='function'){try{jeGuardSourceMutation(source,'دریافت/پرداخت');}catch(e){alert(e.message);return;}}if(!confirm('این دریافت/پرداخت حذف شود؟ مانده فاکتور دوباره محاسبه می‌شود.'))return;
88 + const source=getMyPayments().find(p=>p.id===id);if(typeof jeGuardSourceDeletion==='function'){try{jeGuardSourceDeletion(source,'دریافت/پرداخت');}catch(e){alert(e.message);return;}}if(!confirm('این دریافت/پرداخت حذف شود؟ مانده فاکتور دوباره محاسبه می‌شود.'))return;
89 datastore.payments=datastore.payments.filter(p=>!(p.id===id&&p.ownerUserId===currentUser.id));
90 if(editingPaymentId===id)resetPaymentForm();
91 saveDatastore();refreshAllSurfaces();renderPayments();
js/purchases.js
+5 -5
@@ -129,12 +129,12 @@
129 const old=datastore.purchases.find(p=>p.id===editId&&p.ownerUserId===currentUser.id);
130 if(!old){alert('فاکتور خرید پیدا نشد.');return;}
131 if(typeof jeGuardSourceMutation==='function'){try{jeGuardSourceMutation(old,'فاکتور خرید');}catch(e){alert(e.message);return;}}
132 - Object.assign(old,payload);
132 + try{jeSaveOperationalRecord('purchase',{...old,...payload});}catch(e){alert('فاکتور خرید ثبت نشد: '+e.message);return;}
133 alert('فاکتور خرید اصلاح شد.');
134 }else{
135 - const record={id:'PUR_'+Date.now(),ownerUserId:currentUser.id,...payload};datastore.purchases.push(record);
136 - if(typeof jePostSourceRecord==='function'){try{jePostSourceRecord('purchase',record);}catch(e){datastore.purchases=datastore.purchases.filter(x=>x.id!==record.id);alert('فاکتور خرید ثبت نشد: '+e.message);return;}}
137 - alert('فاکتور خرید و سند حسابداری ثبت شد.');
135 + const record={id:'PUR_'+Date.now(),ownerUserId:currentUser.id,...payload};
136 + try{jeSaveOperationalRecord('purchase',record);}catch(e){alert('فاکتور خرید ثبت نشد: '+e.message);return;}
137 + alert('فاکتور خرید ثبت شد.');
138 }
139 saveDatastore();
140 purCancelEdit();
@@ -171,7 +171,7 @@
171 w.document.close();
172 };
173 window.purDelete=function(id){
174 - const source=myPurchases().find(x=>x.id===id);if(typeof jeGuardSourceMutation==='function'){try{jeGuardSourceMutation(source,'فاکتور خرید');}catch(e){alert(e.message);return;}}if(typeof getMyPayments==='function'&&getMyPayments().some(p=>p.invoiceType==='purchase'&&p.invoiceId===id)){alert('برای این فاکتور پرداخت ثبت شده است؛ برای حفظ سابقه مالی ابتدا تخصیص پرداخت را اصلاح کنید.');return;}
174 + const source=myPurchases().find(x=>x.id===id);if(typeof jeGuardSourceDeletion==='function'){try{jeGuardSourceDeletion(source,'فاکتور خرید');}catch(e){alert(e.message);return;}}if(typeof getMyPayments==='function'&&getMyPayments().some(p=>p.invoiceType==='purchase'&&p.invoiceId===id)){alert('برای این فاکتور پرداخت ثبت شده است؛ برای حفظ سابقه مالی ابتدا تخصیص پرداخت را اصلاح کنید.');return;}
175 if(!requireWrite()||!confirm('این فاکتور خرید حذف شود؟'))return;
176 datastore.purchases=datastore.purchases.filter(p=>!(p.id===id&&p.ownerUserId===currentUser.id));
177 saveDatastore();refreshAllSurfaces();
js/sync.js
+22
@@ -144,6 +144,28 @@ function safeId(raw,prefix){
144 return s;
145 }
146 function absorbRecords(imported){
147 + // Preflight the complete import before changing any collection. A generic
148 + // backup merge is not a validated accounting restore or a reversal workflow.
149 + const journalKeys=['journalVouchers','journalLines','journalLineDimensions'];
150 + const protectedMasters=['accounts','dimensionTypes','dimensionValues','accountDimensionRules','fiscalYears','postingProfiles','branches','projects'];
151 + const ownedVouchers=(datastore.journalVouchers||[]).filter(v=>v.ownerUserId===currentUser.id);
152 + const canonical=value=>{
153 + if(Array.isArray(value))return value.map(canonical);
154 + if(value&&typeof value==='object')return Object.fromEntries(Object.keys(value).filter(k=>k!=='ownerUserId').sort().map(k=>[k,canonical(value[k])]));
155 + return value;
156 + };
157 + Object.keys(imported).forEach(key=>{
158 + if(!Array.isArray(imported[key])||!Array.isArray(datastore[key]))return;
159 + imported[key].forEach(raw=>{
160 + if(!raw||typeof raw!=='object')return;
161 + const candidate=neutralize(raw),id=safeId(candidate.id,key.slice(0,3));candidate.id=id;
162 + const old=datastore[key].find(x=>x.id===id&&x.ownerUserId===currentUser.id);
163 + if(old&&JSON.stringify(canonical(old))===JSON.stringify(canonical(candidate)))return;
164 + if(journalKeys.includes(key))throw new Error('ورود یا بازنویسی دفتر حسابداری از مسیر عمومی پشتیبان مجاز نیست؛ بازیابی کنترل‌شده لازم است.');
165 + if(protectedMasters.includes(key)&&ownedVouchers.some(v=>['posted','reversed'].includes(v.status)&&(v.companyId===old?.companyId||v.companyId===candidate.companyId)))throw new Error('اطلاعات پایه دارای سابقه حسابداری از فایل پشتیبان بازنویسی نمی‌شود.');
166 + if(old&&['invoices','purchases','payments','expenses','cheques'].includes(key)&&ownedVouchers.some(v=>v.sourceId===old.id||v.id===old.journalVoucherId))throw new Error('رکورد دارای سابقه حسابداری از فایل پشتیبان بازنویسی نمی‌شود.');
167 + });
168 + });
169 const uid=currentUser.id;let count=0;
170 ['companies','contacts','products','invoices','purchases','cheques','expenses','payments','fiscalYears','accounts','dimensionTypes','dimensionValues','accountDimensionRules','branches','projects','projectLinks','postingProfiles','journalVouchers','journalLines','journalLineDimensions'].forEach(key=>{
171 if(!Array.isArray(imported[key]))return;
scripts/phase3-check.mjs
+2 -2
@@ -4,6 +4,6 @@ const need=(src,x,label)=>{for(const n of x)if(!src.includes(n))throw new Error(
4 need(e,['jeActiveSourceVoucher','jeGuardSourceMutation','jePostSourceRecord','jeValidateLines','jeValidateDimensions','sourceVersion','jeReverse','reversalVoucherId','jeDeleteDraft','jeTrialBalance','journalLineDimensions','paymentMethod===\'credit\'','jeVatPayableAccount'],'engine');
5 need(u,['view-journal','jeSaveManual','jePostUi','jeReverseUi','je-trial'],'ui');
6 for(const x of ['postingProfiles','journalVouchers','journalLines','journalLineDimensions']){if(!c.includes("'"+x+"'")||!s.includes(x)||!b.includes(x))throw new Error('persistence missing '+x)}
7 -need(i,['journal-engine.js?v=20260928-phase3-final','journal-ui.js?v=20260928-phase3-final'],'index');
7 +need(i,['journal-engine.js?v=20260928-phase3-recovery-v2','journal-ui.js?v=20260928-phase3-recovery-v2'],'index');
8 if(e.includes('datastore.journalVouchers=datastore.journalVouchers.filter')&&!e.includes("v.status!=='draft'"))throw new Error('posted voucher destructive delete guard missing');
9 -console.log('Phase 3 double-entry invariants passed.');
9 +console.log('Phase 3 wiring checks passed (behavioral tests run separately).');
scripts/phase3-engine.test.mjs new
+184
@@ -0,0 +1,184 @@
1 +import test from 'node:test';
2 +import assert from 'node:assert/strict';
3 +import {journalFixture, sale} from './test-helpers/journal-fixture.mjs';
4 +
5 +const copy = value => JSON.parse(JSON.stringify(value));
6 +function manual(app, overrides = {}) {
7 + const cash = app.state.accounts.find(a=>a.code==='1101').id;
8 + const revenue = app.state.accounts.find(a=>a.code==='4101').id;
9 + return {date:'1405/07/06',lines:[{accountId:cash,debit:100,credit:0},{accountId:revenue,debit:0,credit:100}],...overrides};
10 +}
11 +
12 +test('posted original and reversal cancel account balances, retaining both movements',()=>{
13 + const a=journalFixture(), v=a.context.jeCreateDraft(manual(a));a.context.jePost(v.id);a.context.jeReverse(v.id,'1405/07/06','correction');
14 + const rows=a.context.jeTrialBalance();
15 + assert.deepEqual(copy(rows.map(r=>[r.debit,r.credit,r.balance])),[[100,100,0],[100,100,0]]);
16 + assert.equal(a.context.jeLedgerRows().length,4);
17 +});
18 +
19 +test('Gregorian payment date posts in its Jalali fiscal year without opening journal UI',()=>{
20 + const a=journalFixture(); const v=a.context.jeAutoPost('receipt',sale({id:'receipt-a',amount:30,date:'2026-09-28T10:00:00.000Z'}));
21 + assert.equal(v.date,'1405/07/06');assert.equal(v.status,'posted');assert.equal(v.totalDebit,30);
22 +});
23 +
24 +test('failed duplicate source posting leaves no orphan draft or lines',()=>{
25 + const a=journalFixture();a.context.jeAutoPost('sale',sale());const before=copy(a.state);
26 + assert.throws(()=>a.context.jeAutoPost('sale',sale()));assert.deepEqual(copy(a.state),before);
27 +});
28 +
29 +test('duplicate voucher numbers in the same fiscal year are rejected',()=>{
30 + const a=journalFixture();a.context.jeCreateDraft(manual(a,{number:'17'}));
31 + assert.throws(()=>a.context.jeCreateDraft(manual(a,{number:'17'})));
32 +});
33 +
34 +test('posting revalidates a draft date against its fiscal year',()=>{
35 + const a=journalFixture(),v=a.context.jeCreateDraft(manual(a));v.date='1404/07/06';
36 + assert.throws(()=>a.context.jePost(v.id));assert.equal(v.status,'draft');
37 +});
38 +
39 +for(const value of [NaN,Infinity,-0.1])test(`invalid opposite-side amount ${String(value)} cannot be silently coerced to zero`,()=>{
40 + const a=journalFixture(), input=manual(a);input.lines[0].credit=value;
41 + assert.throws(()=>a.context.jeCreateDraft(input));assert.equal(a.state.journalVouchers.length,0);
42 +});
43 +
44 +test('duplicate assignments for a dimension are rejected instead of last-value-wins',()=>{
45 + const a=journalFixture(), input=manual(a), d=a.state.dimensionTypes.find(x=>x.sourceEntity==='branch');
46 + a.state.branches.push({id:'branch-a',ownerUserId:'user-a',companyId:'company-a',name:'Branch',active:true});
47 + input.lines[0].dimensions=[{dimensionTypeId:d.id,dimensionValueId:'invalid'},{dimensionTypeId:d.id,dimensionValueId:'branch-a'}];
48 + assert.throws(()=>a.context.jeCreateDraft(input));
49 +});
50 +
51 +test('unscoped posting accounts are not shared across companies',()=>{
52 + const a=journalFixture(), input=manual(a);delete a.state.accounts.find(x=>x.id===input.lines[0].accountId).companyId;
53 + assert.throws(()=>a.context.jeCreateDraft(input));
54 +});
55 +
56 +test('source company cannot silently post into the currently selected company',()=>{
57 + const a=journalFixture();assert.throws(()=>a.context.jeAutoPost('sale',sale({companyId:'company-b'})));
58 + assert.equal(a.state.journalVouchers.length,0);
59 +});
60 +
61 +test('pre-invoice is saved without a revenue journal',()=>{
62 + const a=journalFixture(), record=a.context.jeSaveOperationalRecord('sale',sale({kind:'pre_invoice'}));
63 + assert.equal(a.state.invoices.length,1);assert.equal(a.state.journalVouchers.length,0);assert.notEqual(record.accountingStatus,'posted');
64 +});
65 +
66 +test('legacy invoicing remains usable before accounting setup',()=>{
67 + const a=journalFixture({template:false});const record=a.context.jeSaveOperationalRecord('sale',sale());
68 + assert.equal(a.state.invoices.length,1);assert.equal(record.accountingStatus,'not_configured');assert.equal(a.state.journalVouchers.length,0);
69 +});
70 +
71 +test('partial accounting setup fails closed and preserves existing sources',()=>{
72 + const a=journalFixture();a.state.accounts=a.state.accounts.filter(x=>x.code!=='4101'&&x.code!=='4107');const before=copy(a.state);
73 + assert.throws(()=>a.context.jeSaveOperationalRecord('sale',sale()));assert.deepEqual(copy(a.state),before);
74 +});
75 +
76 +test('source reversal and correction produce new version and correct net balances',()=>{
77 + const a=journalFixture();const original=a.context.jeSaveOperationalRecord('sale',sale({grandTotal:100,vat:0}));
78 + a.context.jeReverse(original.journalVoucherId,'1405/07/06','wrong amount');
79 + const corrected=a.context.jeSaveOperationalRecord('sale',{...original,grandTotal:150});
80 + assert.equal(corrected.accountingVersion,2);assert.equal(a.state.invoices.length,1);assert.equal(a.state.journalVouchers.length,3);
81 + const ar=a.context.jeTrialBalance().find(r=>r.code==='1102');assert.equal(ar.balance,150);
82 +});
83 +
84 +test('a failed correction leaves old source and journal untouched',()=>{
85 + const a=journalFixture(), source=a.context.jeSaveOperationalRecord('sale',sale());a.context.jeReverse(source.journalVoucherId,'1405/07/06','correction');
86 + const before=copy(a.state);assert.throws(()=>a.context.jeSaveOperationalRecord('sale',{...source,date:'1404/01/01',grandTotal:200}));
87 + assert.deepEqual(copy(a.state),before);
88 +});
89 +
90 +test('source lock survives missing client-side voucher pointer',()=>{
91 + const a=journalFixture(),source=sale();a.context.jePostSourceRecord('sale',source);delete source.journalVoucherId;
92 + assert.throws(()=>a.context.jeGuardSourceMutation(source));
93 +});
94 +
95 +test('reversed journal history protects source from destructive deletion',()=>{
96 + const a=journalFixture(),source=sale();a.context.jePostSourceRecord('sale',source);a.context.jeReverse(source.journalVoucherId,'1405/07/06','correction');
97 + assert.throws(()=>a.context.jeGuardSourceDeletion(source));
98 +});
99 +
100 +test('cheque settlement is rejected before cash is recognized',()=>{
101 + const a=journalFixture();a.context.jeEnsureDefaultProfiles();const before=copy(a.state);
102 + assert.throws(()=>a.context.jeAutoPost('receipt',sale({amount:100,method:'cheque'})));
103 + assert.deepEqual(copy(a.state),before);
104 +});
105 +
106 +test('non-cash sales use configured posting profile accounts',()=>{
107 + const a=journalFixture();a.context.jeEnsureDefaultProfiles();
108 + const profile=a.state.postingProfiles.find(p=>p.kind==='sale'),custom=a.state.accounts.find(x=>x.code==='4107');profile.creditAccountId=custom.id;
109 + const v=a.context.jeAutoPost('sale',sale({grandTotal:100,vat:0}));
110 + assert.equal(a.state.journalLines.find(l=>l.voucherId===v.id&&l.credit===100).accountId,custom.id);
111 +});
112 +
113 +test('dimension rule of a posted account cannot be overwritten in place',()=>{
114 + const a=journalFixture();a.context.jeAutoPost('sale',sale());
115 + const rule=a.state.accountDimensionRules.find(r=>r.applicability==='required');
116 + for(const [id,value] of Object.entries({'af-rule-account':rule.accountId,'af-rule-dimension':rule.dimensionTypeId,'af-rule-app':'unavailable'}))a.elements.set(id,{value});
117 + a.context.afSaveRule();assert.equal(rule.applicability,'required');assert.ok(a.alerts.length);
118 +});
119 +
120 +test('backup import cannot overwrite a posted voucher or its lines',()=>{
121 + const a=journalFixture(),v=a.context.jeCreateDraft(manual(a));a.context.jePost(v.id);const before=copy(a.state);
122 + const line=a.state.journalLines[0];assert.throws(()=>a.context.absorbRecords({journalVouchers:[{...v,status:'draft'}],journalLines:[{...line,debit:999}]}));
123 + assert.deepEqual(copy(a.state),before);
124 +});
125 +
126 +test('backup import cannot replace an operational source locked by a journal',()=>{
127 + const a=journalFixture(),v=a.context.jeSaveOperationalRecord('sale',sale());const before=copy(a.state);
128 + assert.throws(()=>a.context.absorbRecords({invoices:[{...v,grandTotal:999}]}));assert.deepEqual(copy(a.state),before);
129 +});
130 +
131 +test('unbalanced and locked-year postings are rejected before any mutation',()=>{
132 + const a=journalFixture(),input=manual(a);input.lines[1].credit=90;assert.throws(()=>a.context.jeCreateDraft(input));
133 + a.state.fiscalYears[0].status='locked';assert.throws(()=>a.context.jeCreateDraft(manual(a)));assert.equal(a.state.journalVouchers.length,0);
134 +});
135 +
136 +test('switching active company does not unlock a previously posted source',()=>{
137 + const a=journalFixture(),source=a.context.jeSaveOperationalRecord('sale',sale());
138 + a.state.companies.push({id:'company-b',ownerUserId:'user-a'});a.run("getMySettings().default_company_id='company-b'");
139 + assert.throws(()=>a.context.jeGuardSourceMutation(source));assert.throws(()=>a.context.jeGuardSourceDeletion(source));
140 +});
141 +
142 +test('a reversal cannot itself be reversed and unlock a double-counted correction',()=>{
143 + const a=journalFixture(),source=a.context.jeSaveOperationalRecord('sale',sale({grandTotal:100,vat:0}));
144 + const reversal=a.context.jeReverse(source.journalVoucherId,'1405/07/06','correction');const before=copy(a.state);
145 + assert.throws(()=>a.context.jeReverse(reversal.id,'1405/07/06','undo correction'));
146 + assert.deepEqual(copy(a.state),before);
147 +});
148 +
149 +for(const date of ['2026-02-31','1405/12/30','1405/07/31'])test(`invalid calendar date ${date} is rejected without rollover`,()=>{
150 + const a=journalFixture();assert.throws(()=>a.context.jeDate(date));
151 +});
152 +
153 +test('valid leap day and localized short Jalali dates normalize correctly',()=>{
154 + const a=journalFixture();assert.equal(a.context.jeDate('۱۳۹۹/۱۲/۳۰'),'1399/12/30');assert.equal(a.context.jeDate('۱۴۰۵/۷/۶'),'1405/07/06');
155 +});
156 +
157 +test('an unchanged backup can be re-imported without replacing journal history',()=>{
158 + const a=journalFixture();a.context.jeSaveOperationalRecord('sale',sale());const before=copy(a.state);
159 + a.context.absorbRecords(copy(a.state));assert.deepEqual(copy(a.state),before);
160 +});
161 +
162 +test('journal import preflight rejects the whole file before applying unrelated records',()=>{
163 + const a=journalFixture();const before=copy(a.state);
164 + assert.throws(()=>a.context.absorbRecords({products:[{id:'new-product',name:'Must not persist'}],journalVouchers:[{id:'unvalidated',status:'posted'}]}));
165 + assert.deepEqual(copy(a.state),before);
166 +});
167 +
168 +test('read-only user cannot save sources or journals',()=>{
169 + const a=journalFixture();a.context.writable=false;const before=copy(a.state);
170 + assert.throws(()=>a.context.jeSaveOperationalRecord('sale',sale()));assert.throws(()=>a.context.jeCreateDraft(manual(a)));
171 + assert.deepEqual(copy(a.state),before);
172 +});
173 +
174 +for(const [kind,source,want] of [
175 + ['sale',sale({paymentMethod:'cash',grandTotal:100,vat:0}),[['1101',100,0],['4101',0,100]]],
176 + ['purchase',sale({paymentMethod:'credit',supplierId:'party-a',grandTotal:100,vat:0}),[['2101',0,100],['5101',100,0]]],
177 + ['receipt',sale({amount:30,method:'bank'}),[['1101',30,0],['1102',0,30]]],
178 + ['payment',sale({amount:40,method:'bank'}),[['1101',0,40],['2101',40,0]]],
179 + ['expense',sale({amount:50}),[['1101',0,50],['6103',50,0]]],
180 + ['income',sale({amount:60}),[['1101',60,0],['4201',0,60]]],
181 +])test(`${kind} integration recognizes independently checked account movements`,()=>{
182 + const a=journalFixture();a.context.jeSaveOperationalRecord(kind,source);
183 + assert.deepEqual(copy(a.context.jeTrialBalance().map(r=>[r.code,r.debit,r.credit])),want);
184 +});
scripts/phase3-ui.test.mjs new
+50
@@ -0,0 +1,50 @@
1 +import {test} from 'node:test';
2 +import assert from 'node:assert/strict';
3 +import vm from 'node:vm';
4 +import fs from 'node:fs';
5 +function fixture(file){
6 + const elements=new Map(),calls=[],alerts=[];
7 + const element=id=>{if(!elements.has(id))elements.set(id,{value:'',style:{},options:[],selectedIndex:0,innerHTML:'',textContent:'',className:''});return elements.get(id)};
8 + const ds={payments:[],expenses:[],cheques:[],invoices:[],purchases:[]};
9 + const c={console,Date,datastore:ds,currentUser:{id:'u'},document:{getElementById:element,querySelectorAll:()=>[],querySelector:()=>null,addEventListener:()=>{}},requireWrite:()=>true,getMyCompanies:()=>[{id:'c'}],getMySettings:()=>({default_company_id:'c'}),getMyContacts:()=>[{id:'person',name:'Person',projects:[]}],getMyPayments:()=>ds.payments,getMyExpenses:()=>ds.expenses,getMyInvoices:()=>ds.invoices,getMyPurchases:()=>ds.purchases,getMyCheques:()=>ds.cheques,getMyProducts:()=>[],getJalaliNumeric:()=> '1405/07/06',saveDatastore:()=>{},refreshAllSurfaces:()=>{},renderProducts:()=>{},renderInvoices:()=>{},switchView:()=>{},parseFormattedNumber:Number,esc:String,alert:m=>alerts.push(m),confirm:()=>true,jeGuardSourceMutation:()=>{},jeGuardSourceDeletion:()=>{throw Error('history protected')},jeSaveOperationalRecord:(kind,record)=>{calls.push({kind,record});throw Error('test rejection')}};
10 + c.window=c;vm.createContext(c);vm.runInContext(fs.readFileSync(new URL('../js/'+file,import.meta.url),'utf8'),c);
11 + return {c,ds,element,calls,alerts};
12 +}
13 +for(const edited of [false,true])test(`payment ${edited?'edit':'create'} delegates atomically and retains form on failure`,()=>{
14 + const {c,ds,element,calls,alerts}=fixture('payments.js');
15 + if(edited){ds.payments.push({id:'old',ownerUserId:'u',contactId:'person',amount:10,direction:'inbound',method:'bank'});c.editPayment('old')}
16 + element('pay-contact').value='person';element('pay-direction').value='inbound';element('pay-amount').value='25';element('pay-method').value='bank';
17 + c.commitSavePayment();assert.equal(calls.length,1);assert.equal(calls[0].record.amount,25);assert.equal(ds.payments.length,edited?1:0);if(edited)assert.equal(ds.payments[0].amount,10);assert.equal(element('pay-amount').value,'25');assert.match(alerts.at(-1),/test rejection/);
18 +});
19 +for(const edited of [false,true])test(`expense ${edited?'edit':'create'} delegates atomically and retains form on failure`,()=>{
20 + const {c,ds,element,calls}=fixture('operations.js');
21 + if(edited){ds.expenses.push({id:'old',ownerUserId:'u',contactId:'person',amount:10,kind:'expense'});c.editExpense('old')}
22 + element('trx-contact-select').value='person';element('trx-kind-input').value='expense';element('trx-amount-input').value='25';
23 + c.commitSaveExpense();assert.equal(calls.length,1);assert.equal(ds.expenses.length,edited?1:0);if(edited)assert.equal(ds.expenses[0].amount,10);assert.equal(element('trx-amount-input').value,'25');
24 +});
25 +test('payment deletion protects reversed journal history',()=>{const {c,ds}=fixture('payments.js');ds.payments.push({id:'old',ownerUserId:'u'});c.deletePayment('old');assert.equal(ds.payments.length,1)});
26 +test('journal uses routed pane and clears successful manual submission',()=>{
27 + const {c,element}=fixture('journal-ui.js');let section; c.document.getElementById=id=>id==='view-journal'?null:element(id);c.document.createElement=()=>({});c.document.querySelector=()=>({appendChild:s=>{section=s},insertBefore:s=>{section=s}});c.ensureJournalView();assert.equal(section.className,'view-pane');
28 + c.jeCollectRows=()=>[];c.jeCreateDraft=()=>({number:'1'});c.renderJournal=()=>{};element('je-lines').innerHTML='previous rows';element('je-desc').value='previous';c.jeSaveManual();assert.equal(element('je-lines').innerHTML,'');assert.equal(element('je-desc').value,'');
29 +});
30 +for(const edited of [false,true])test(`invoice ${edited?'edit':'create'} delegates without mutating source on rejection`,()=>{
31 + const {c,ds,element,calls}=fixture('invoices.js');c.getCurrencyLabel=()=> 'ریال';c.recomputeTotals=()=>({grandTotal:25,subtotal:25});
32 + const row={querySelector:sel=>sel==='.row-product-select'?{value:'prod',options:[{text:'Product'}],selectedIndex:0}:{value:sel==='.row-quantity'?'1':'25'}};c.document.querySelectorAll=()=>[row];
33 + element('invoice-company-id').value='c';element('invoice-number').value='new';element('invoice-kind').value='non_formal';
34 + if(edited){ds.invoices.push({id:'old',ownerUserId:'u',grandTotal:10});element('edit-invoice-id').value='old'}
35 + c.commitSaveInvoice();assert.equal(calls.length,1);assert.equal(calls[0].record.grandTotal,25);assert.equal(ds.invoices.length,edited?1:0);if(edited)assert.equal(ds.invoices[0].grandTotal,10);
36 +});
37 +for(const edited of [false,true])test(`purchase ${edited?'edit':'create'} delegates without mutating source on rejection`,()=>{
38 + const {c,ds,element,calls}=fixture('purchases.js');c.purRecalc=()=>({sub:25,disc:0,vat:0,grand:25});
39 + const row={querySelector:sel=>sel==='.pur-prod'?{value:'prod',options:[{text:'Product'}],selectedIndex:0}:{value:sel==='.pur-qty'?'1':'25'}};c.document.querySelectorAll=()=>[row];
40 + element('pur-supplier').value='person';element('pur-supplier').options=[{text:'Person'}];element('pur-number').value='new';if(edited){ds.purchases.push({id:'old',ownerUserId:'u',grandTotal:10});element('pur-edit-id').value='old'}
41 + c.purSave();assert.equal(calls.length,1);assert.equal(calls[0].record.grandTotal,25);assert.equal(ds.purchases.length,edited?1:0);if(edited)assert.equal(ds.purchases[0].grandTotal,10);
42 +});
43 +for(const [file,collection,method] of [['operations.js','expenses','deleteExpense'],['operations.js','invoices','deleteInvoice'],['purchases.js','purchases','purDelete'],['operations.js','cheques','deleteCheque']])test(`${collection} deletion preserves linked journal history`,()=>{const {c,ds}=fixture(file);ds[collection].push({id:'old',ownerUserId:'u'});c[method]('old');assert.equal(ds[collection].length,1)});
44 +test('journal resets stale account rows when active company changes',()=>{
45 + const {c,element}=fixture('journal-ui.js');c.afCompanyId=()=> 'new-company';c.jeEnsureDefaultProfiles=()=>{};c.getMyJournalVouchers=()=>[];c.jeTrialBalance=()=>[];let added=0;c.jeAddRow=()=>added++;
46 + element('je-lines').dataset={scope:'u|old-company'};element('je-lines').innerHTML='old account rows';element('je-desc').value='old description';c.renderJournal();assert.equal(element('je-lines').dataset.scope,'u|new-company');assert.equal(element('je-lines').innerHTML,'');assert.equal(element('je-desc').value,'');assert.equal(added,2);
47 +});
48 +test('fully settled invoice stays available while editing its receipt',()=>{
49 + const {c,ds,element}=fixture('payments.js');ds.invoices.push({id:'inv',companyId:'c',contactId:'person',grandTotal:10,paymentMethod:'credit'});ds.payments.push({id:'old',ownerUserId:'u',contactId:'person',amount:10,direction:'inbound',method:'bank',invoiceType:'sale',invoiceId:'inv'});c.editPayment('old');assert.match(element('pay-invoice').innerHTML,/sale\|inv/);
50 +});
scripts/quality-check.mjs
+6 -6
@@ -62,17 +62,17 @@ for(const cssNeedle of ['--shell-rail','--shell-panel','.module-tab.active','.mo
62 if(!index.includes(cssNeedle))throw new Error('Phase 1 responsive shell CSS missing '+cssNeedle);
63
64 for(const coll of ['fiscalYears','accounts','dimensionTypes','dimensionValues','accountDimensionRules','branches','projects','projectLinks'])if(!all['core.js'].includes("'"+coll+"'"))throw new Error('Phase 2 collection missing '+coll);
65 -if(!index.includes('data-module="accounting"')||!index.includes('accounting-foundation.js?v=20260928-phase3-final'))throw new Error('Phase 2 accounting shell integration missing');
65 +if(!index.includes('data-module="accounting"')||!index.includes('accounting-foundation.js?v=20260928-phase3-recovery-v2'))throw new Error('Phase 2 accounting shell integration missing');
66
67 for(const coll of ['postingProfiles','journalVouchers','journalLines','journalLineDimensions'])if(!all['core.js'].includes("'"+coll+"'")||!all['sync.js'].includes(coll))throw new Error('Phase 3 collection missing '+coll);
68 for(const needle of ['jeValidateLines','jeValidateDimensions','jeCreateDraft','jePost','jeReverse','jeDeleteDraft','jeTrialBalance','sourceVersion'])if(!all['journal-engine.js']?.includes(needle))throw new Error('Phase 3 journal invariant missing '+needle);
69 -if(!index.includes('journal-engine.js?v=20260928-phase3-final')||!index.includes('journal-ui.js?v=20260928-phase3-final'))throw new Error('Phase 3 journal scripts missing');
69 +if(!index.includes('journal-engine.js?v=20260928-phase3-recovery-v2')||!index.includes('journal-ui.js?v=20260928-phase3-recovery-v2'))throw new Error('Phase 3 journal scripts missing');
70
71 for(const needle of ['jeActiveSourceVoucher','jeGuardSourceMutation','jePostSourceRecord',"v.status==='posted'"])if(!all['journal-engine.js']?.includes(needle))throw new Error('Phase 3 source/ledger safety missing '+needle);
72 for(const [file,needles] of Object.entries({
73 - 'invoices.js':['jeGuardSourceMutation','jePostSourceRecord'],
74 - 'purchases.js':['jeGuardSourceMutation','jePostSourceRecord'],
75 - 'payments.js':['jeGuardSourceMutation','jePostSourceRecord'],
76 - 'operations.js':['jeGuardSourceMutation','jePostSourceRecord'],
73 + 'invoices.js':['jeGuardSourceMutation','jeSaveOperationalRecord'],
74 + 'purchases.js':['jeGuardSourceMutation','jeSaveOperationalRecord','jeGuardSourceDeletion'],
75 + 'payments.js':['jeGuardSourceMutation','jeSaveOperationalRecord','jeGuardSourceDeletion'],
76 + 'operations.js':['jeGuardSourceMutation','jeSaveOperationalRecord','jeGuardSourceDeletion'],
77 'accounting-foundation.js':["journalLines||[]","سابقه دفتر"]
78 }))for(const needle of needles)if(!all[file]?.includes(needle))throw new Error('Phase 3 operational integration missing '+file+' '+needle);
scripts/test-helpers/journal-fixture.mjs new
+33
@@ -0,0 +1,33 @@
1 +import fs from 'node:fs';
2 +import vm from 'node:vm';
3 +
4 +// Execute the application modules, replacing only browser/network scheduling.
5 +export function journalFixture({template = true} = {}) {
6 + const alerts = [];
7 + const elements = new Map();
8 + const context = vm.createContext({
9 + console, Intl, Date, Math, JSON, Map, Set,
10 + currentUser: {id: 'user-a'}, writable: true,
11 + canWrite() { return context.writable; },
12 + requireWrite() { return context.writable; },
13 + setTimeout() { return 1; }, clearTimeout() {},
14 + alert(message) { alerts.push(message); }, confirm() { return true; },
15 + getJalaliNumeric() { return '1405/07/06'; },
16 + toEnDigits(value) { return String(value).replace(/[۰-۹]/g, d => '۰۱۲۳۴۵۶۷۸۹'.indexOf(d)).replace(/[٠-٩]/g, d => '٠١٢٣٤٥٦٧٨٩'.indexOf(d)); },
17 + document: {addEventListener() {}, getElementById(id) { return elements.get(id) || null; }},
18 + window: {addEventListener() {}}, renderAccountingFoundation() {}, refreshAllSurfaces() {},
19 + });
20 + const run = code => vm.runInContext(code, context);
21 + for (const path of ['js/sync.js', 'js/accounting-foundation.js', 'js/journal-engine.js']) {
22 + vm.runInContext(fs.readFileSync(path, 'utf8'), context, {filename: path});
23 + }
24 + run(`datastore.companies.push({id:'company-a',ownerUserId:'user-a'});
25 + datastore.contacts.push({id:'party-a',ownerUserId:'user-a',name:'Party'});
26 + getMySettings().default_company_id='company-a'; afSeed();`);
27 + if (template) run("afApplyTemplate('company-a','trading')");
28 + return {context, run, alerts, elements, get state() { return run('datastore'); }};
29 +}
30 +
31 +export function sale(overrides = {}) {
32 + return {id:'sale-a',ownerUserId:'user-a',companyId:'company-a',date:'1405/07/06',kind:'formal',paymentMethod:'credit',contactId:'party-a',grandTotal:110,vat:10,...overrides};
33 +}