سامانه صدور فاکتور و حسابداری
Mirrored from https://github.com/davoodmehraban89/Factor-easy.git
Synced Dec 4, 08:00 UTC
fix: guard purchase corrections before local ledger mutation
JVK committed
Nov 3, 2026 at 11:10 UTC
7f9c08534888d0631464125044a77f843f883ee3
11 files changed
+187
-2
.github/workflows/quality.yml
+2
@@ -22,6 +22,8 @@ jobs:
22
run: node scripts/migration-manifest-check.mjs
23
- name: Migration manifest mutation tests
24
run: node scripts/migration-manifest-test.mjs
25
+ - name: Purchase correction server-mode guards
26
+ run: node scripts/wp1-purchase-correction-guard-test.mjs
27
- name: JavaScript syntax
28
run: node scripts/syntax-check.mjs
29
- name: Generated Pages public regression (standalone suite)
PROJECT_STATE.md
+5
@@ -246,3 +246,8 @@ Owner requests layer-by-layer click/functional testing of all controls and compa
246
- Persisted SQL/tests restored; prior /tmp logs and running1000event jobs were lost, so no completion inferred. Rerun uses durable /workspace/wp1-evidence-nov3. Source unchanged; main4416794 reverified. CorrectiveSQL generated by CLI20261102141933 remains unvalidated until whole-run evidence. No production mutation or clientactivation.
247
- Nov2 read-only aggregate legacyaudit:11postedvouchers;0unbalanced/invalid-amount/less-than2lines/duplicate-number groups/orphanlines. Limited audit only, not fullscope/currency/periodproof; docs/wp1/LEGACY_SHADOW_COUNTS.json.
248
- VerifiedNov3 scopedservercheckpoint: directD1/D2/dimensionREDonbaseline; stagedchainfailedclosed/wrongcompany/wrongyear/currency; corrected14negativecasesPASS, shadow/admin/WHENPASS, oldENFORCE→newAUDITidentitymove andnullamountsPASS. Actualtwo-sessionracePASS (duplicatecreateidempotent, numbers1/2, concurrentreversalonlyonewinner). Corrective-onlyUP/DOWN/UPPASS retainscounter17/history. Logs docs/wp1/evidence. Full1000run interrupted beforecompletion again; NOT VERIFIED. NoUI/clientactivation, noProductionmigration. EntireWP1 remainsINCOMPLETE pendingfullsuite/CI, all11prerequisiteDOWN, capability-safeclientandpurchasecorrection, sourcecoverage andG1package. Currentcandidate manifests94files including12unappliedWP1files; historical24/24drift unchanged.
249
+
250
+### 2026-11-03 — Owner approves completing subsequent phases
251
+- Owner explicitly approves continuation and asks to complete the phases. This supersedes the earlier WP0+WP1-only session scope; continue sequential package acceptance and maintain factual goal/in-progress/remaining docs. G1–G5 concrete owner gates remain; this is not approval to install an unreviewed Production migration. PR195head4b00e5b is still draft: Security/3DB success, full Quality and WP1proof running at this checkpoint. Proceed with remaining WP1 before declaring any later package complete.
252
+- PR195 initialhead4b00e5b allrequiredCI SUCCESS: Quality41586514247,Security41586514251,WP1proof41586514303. WP1job05:53:25–06:07:08UTC completedbaselineRED,fullSQLsuite(includingseeded1000 andactualconcurrency)andcorrectionUP/DOWN/UP. Artifactdownload unavailable fromprovider; job/stepcompletion verifiedviaGitHubAPI; do notinventrawCIlogcounts. This supersedes interruptedlocal1000status for exact4b00e5b only.
253
+- NewpurchaseguardRED→GREEN: enforce/network/malformedmode/accountswitchreject beforelocalreversal/save/sync; onlyconfirmedmissingRPC oroff/auditretainlegacycorrection. Browser28/28PASS incl3newnegativecases; generatedPages3/3PASS. Guard is safe refusal, NOT completedserverpurchasecorrection. Firstbrowserattemptfailedbecausefixtureorgwasaddedbeforeorganizationbootstrap; correctedfixturesetsorgafterready, noappAuthchange/assertionrelaxation. Newsourcechange notyetremoteCIverified.
docs/ROADMAP_CURRENT.md
new
+24
@@ -0,0 +1,24 @@
1
+# نقشه راه جاری فینورا — ۲۰۲۶/۱۱/۰۳
2
+
3
+مرجع نیازمندی: [پرامپت مالک REV2](owner-prompts/FINORA_HARDENING_MASTER_2026-11-02_REV2.txt). دستور جدید مالک «فازها را تکمیل کن» ادامه همه بستهها را پس از گیت هر مرحله مجاز کرده است. شمارههای WP زیر با نقشههای قدیمی فاز۰/Phase1A/Stage1–3 یکی نیستند؛ [تطبیق تاریخچه](CURRENT_WORK_REGISTER_2026-10-30.md) محفوظ است.
4
+
5
+| بسته | هدف | وضعیت واقعی | معیار پایان / شاهد |
6
+|---|---|---|---|
7
+| WP0 | خط مبنا، فهرست شاخهها، drift و بازتولید نقص | گزارش و بازتولید تحویل؛ PR194 هنوز ادغام نشده | [PR194](https://github.com/davoodmehraban89/Factor-easy/pull/194)، Quality41416988716/Security41416988731 موفق؛ [گزارش](wp0/BASELINE_REPORT_FA.md). F150 سایت عمومی همچنان باز |
8
+| WP1 | هسته مالی سمت سرور | در حال انجام؛ پیشنویس PR195 | [وضعیت دقیق](wp1/STATUS_FA.md): تمام آزمونها،۱۰۰۰رویداد،همزمانی،DOWN/UP کامل،کلاینت و خرید،shadow و بسته G1؛ نصب عملیاتی نشده |
9
+| WP2 | امنیت،CSP،دسترسی و ورود | آغاز نشده؛ برخی کنترلهای قبلی موجودند | inline صفر،منفی دوکاربره و RPC،Edge/Auth/OTP،advisor و مرورگر؛ مسئله106 باز |
10
+| WP3 | ساختار کد | آغاز نشده | format مستقل بدون تغییر رفتار،ESLint،wrapper ratchet تا صفر،ARCHITECTURE |
11
+| WP4 | محصول قابل فروش و وضعیتهای صادقانه | آغاز نشده | هسته فروش مشخص،پیشرفتهها beta و مجوزدار،وضعیت ذخیره/قطعی روشن |
12
+| WP5 | پذیرش واقعی محیط غیرعملیاتی | آغاز نشده | E2E با Auth/DB واقعی تست،دو کاربر همزمان،کارایی/RTL/چاپ و چکلیست G4 |
13
+| WP6 | صحت ایران/مالیات | آغاز نشده | جلالی/ریال/VAT تاریخدار؛ آداپتور مستند مؤدیان بدون ادعای ارسال واقعی |
14
+| WP7 | بکاپ و بازیابی | ابزار قبلی موجود؛ اجرای واقعی تأیید نشده | G3 از محیط امن،pg_dump→age،restore مستقل و تطبیق شمارش/دفتر |
15
+| WP8 | انتشار کنترلشده | مجاز به نصب نشده | اثبات WP1/WP2،بکاپ،بسته G1،shadow سپس enforce منبعبهمنبع |
16
+| WP9 | تداوم و مستندات | این جدول جاری است؛ پاکسازی کامل انجام نشده | آرشیو بدون حذف تاریخچه،PROJECT_STATE زیر۱۵KB،README دقیق،تصمیم مستند PRهای قدیمی |
17
+
18
+## کار جاری
19
+
20
+۱. نتیجه آزمون کامل WP1 در CI مستقل از قطع محیط، سپس رفع هر شکست بدون تضعیف تست.
21
+۲. حفاظت خرید زیر ENFORCE پیش از تغییر محلی؛ اتصال امن sync/RPC با تشخیص قابلیت و خطای صادقانه.
22
+۳. تکمیل rollback پیشنیازها، گردش کامل خرید و پوشش منبعبهمنبع. [بسته انتشار هنوز آماده نیست](wp1/ROLLOUT_HOLD.md).
23
+
24
+تست synthetic یا SQL fixture معادل تأیید ورود روی اینترنت مالک، JWT/PostgREST واقعی،چاپگر یا داده واقعی نیست. هیچ درصد تکمیل ساختگی گزارش نمیشود. G1 نصب migration،G2 تنظیمات داشبورد،G3 راز بکاپ،G4 داده تست Production وG5 هزینه همچنان فقط پس از آمادهشدن نتیجه قابل بررسی به مالک ارجاع میشوند.
docs/wp1/STATUS_FA.md
+7
-1
@@ -12,9 +12,15 @@
12
13
باقیمانده: تستهای منفی یافتههای بالا و رفع آنها؛ اثبات همزمانی و۱۰۰۰رویداد؛ DOWN برای تمام تغییرات و UP/DOWN/UP؛ feature probe و fallback صحیح کلاینت؛ مسیر اصلاح/ابطال/ذخیره خرید زیر ENFORCE؛ پوشش منبعبهمنبع و برچسب صادقانه پوشش؛ گزارش shadow؛ بسته rollout/backup/rollback برای G1؛ CI تازه. آزمون واقعی JWT/PostgREST و Production پذیرش نشدهاند.
14
15
-هیچ نصب یا تأییدی از مالک اکنون لازم نیست. G1 فقط پس از آمادهشدن بسته قابل بازبینی و اثبات کامل درخواست میشود. WP2 به بعد در این نوبت آغاز نمیشوند.
15
+هیچ نصب یا تأییدی از مالک اکنون لازم نیست. G1 فقط پس از آمادهشدن بسته قابل بازبینی و اثبات کامل درخواست میشود. مالک در ۲۰۲۶/۱۱/۰۳ ادامه فازهای بعد را تأیید کرده؛ آغاز آنها تابع گیت مرحله قبل است. [نقشه راه جاری](../ROADMAP_CURRENT.md).
16
17
## checkpoint 2026-11-03
18
پس از راهاندازی مجدد محیط، آزمونهای هدفمند دوباره اجرا شدند:۱۴ حالت منفی posting و قرارداد shadow/defaultaudit/adminsetter/WHEN موفق. آزمون کامل۱۰۰۰رویداد هنوز نتیجه نهایی ندارد؛ اجرای قطعشده قبلی قبولی محسوب نمیشود.۱۲فایل candidate جدید باعث۹۴فایل migration شده؛۲۴production-only و۳۶repo-only شامل۱۲candidate نصبنشده است، نه۱۲اختلاف تازه Production.
19
20
آزمون همزمان واقعیِ دو اتصال نیز موفق شد: ساخت تکراری یک سند ایجاد کرد، دو قطعیسازی شمارههای۱و۲ گرفتند، و از دو برگشت همزمان فقط یکی مجاز شد. آزمون انتقال هویت سند و مقدار null و چرخه اصلاحی UP/DOWN/UP مجدداً موفقاند؛ شواهد در پوشههای concurrency-final،scope-final،correction-final ثبت شدهاند. اجرای۱۰۰۰رویداد دوباره پیش از نتیجه نهایی قطع شد؛ قبولی آن ثبت نمیشود. شاخه بهصورت پیشنویس منتشر میشود تا CI مستقل از قطع محیط ادامه دهد؛ قابل ادغام یا نصب نیست.
21
+
22
+## نتیجه تازه CI
23
+
24
+روی کامیت `4b00e5b`، [Quality41586514247](https://github.com/davoodmehraban89/Factor-easy/actions/runs/41586514247)،[Security41586514251](https://github.com/davoodmehraban89/Factor-easy/actions/runs/41586514251) و [WP1 proof41586514303](https://github.com/davoodmehraban89/Factor-easy/actions/runs/41586514303) موفق شدند. فرمان کامل SQL شامل آزمون۱۰۰۰رویداد و همزمانی پایان یافت؛ این شاهد جایگزین اجرای محلی قطعشده است. دریافت artifact از provider ممکن نشد؛ نتیجه job/step در GitHub API تأیید شد، نه شمارش ساختگی لاگ.
25
+
26
+محافظ جدید خرید قبل از تغییر محلی، حالت سرور را بررسی میکند: ENFORCE یا خطای شبکه/حالت نامعتبر/تعویض حساب، اصلاح و ابطال را بدون تغییر رد میکند. نبود صریح RPC یا off/audit مسیر قبلی را حفظ میکند.۲۸تست مرورگر و۳تست محافظ در Pages موفق؛ اجرای نهایی CI این تغییر جداست. این حفاظت معادل تکمیل عملیات اصلاح خرید روی سرور نیست.
docs/wp1/evidence/purchase-guard/browser-pages.log
new
+15
@@ -0,0 +1,15 @@
1
+
2
+Running 3 tests using 1 worker
3
+
4
+[1A[2K(node:55394) Warning: The 'NO_COLOR' env is ignored due to the 'FORCE_COLOR' env being set.
5
+(Use `node --trace-warnings ...` to show where the warning was created)
6
+
7
+
8
+[1A[2K(node:55394) Warning: The 'NO_COLOR' env is ignored due to the 'FORCE_COLOR' env being set.
9
+(Use `node --trace-warnings ...` to show where the warning was created)
10
+
11
+
12
+[1A[2K[1/3] scripts/accounting-document-workflow.spec.js:647:52 › WP1 ENFORCE purchase return rejects before local or server mutation
13
+[1A[2K[2/3] scripts/accounting-document-workflow.spec.js:647:52 › WP1 ENFORCE purchase cancel rejects before local or server mutation
14
+[1A[2K[3/3] scripts/accounting-document-workflow.spec.js:647:52 › WP1 ENFORCE purchase seamless rejects before local or server mutation
15
+[1A[2K 3 passed (5.4s)
docs/wp1/evidence/purchase-guard/browser-source.log
new
+44
@@ -0,0 +1,44 @@
1
+
2
+Running 28 tests using 1 worker
3
+
4
+[1A[2K(node:50434) Warning: The 'NO_COLOR' env is ignored due to the 'FORCE_COLOR' env being set.
5
+(Use `node --trace-warnings ...` to show where the warning was created)
6
+
7
+
8
+[1A[2K(node:50434) Warning: The 'NO_COLOR' env is ignored due to the 'FORCE_COLOR' env being set.
9
+(Use `node --trace-warnings ...` to show where the warning was created)
10
+
11
+
12
+[1A[2K[1/28] scripts/accounting-document-workflow.spec.js:89:1 › invoice and purchase registers isolate companies selected in Settings; no ALL fallback or cross-company edit
13
+[1A[2K[2/28] scripts/accounting-document-workflow.spec.js:155:1 › formal invoice remains editable draft across server reload; explicit posting creates exactly one balanced voucher
14
+[1A[2K[3/28] scripts/accounting-document-workflow.spec.js:211:1 › posted sale can be returned to an editable corrective draft; original voucher stays immutable and balances
15
+[1A[2K[4/28] scripts/accounting-document-workflow.spec.js:263:1 › pilot manual journal correction permits draft edits, balanced repost and auditable cancellation
16
+[1A[2K[5/28] scripts/accounting-document-workflow.spec.js:296:1 › pilot cancellation preserves posted invoice record while only unposted drafts can be deleted
17
+[1A[2K[6/28] scripts/accounting-document-workflow.spec.js:334:1 › pilot purchase: posted to corrective draft to edited balanced repost via document manager
18
+[1A[2K[7/28] scripts/accounting-document-workflow.spec.js:388:1 › pilot purchase denies paid/consumed source; cancels unallocated posting without erasing old voucher
19
+[1A[2K[8/28] scripts/accounting-document-workflow.spec.js:415:1 › seamless sale correction: opening and cancelling leaves ledger unchanged; saving retains visible identity, printing and audit
20
+[1A[2K[9/28] scripts/accounting-document-workflow.spec.js:459:1 › seamless purchase correction: same visible number, no write on opening, save and print corrected purchase
21
+[1A[2K[10/28] scripts/accounting-document-workflow.spec.js:506:1 › treasury amendment in the same form preserves one record and same reference without on-open ledger writes
22
+[1A[2K[11/28] scripts/accounting-document-workflow.spec.js:561:1 › treasury correction excludes cheque, linked settlements and locked periods; cancellation retains immutable history
23
+[1A[2K[12/28] scripts/accounting-document-workflow.spec.js:600:1 › treasury amend rejection on lost RPC keeps protected original on server and no partial correction payload
24
+[1A[2K[13/28] scripts/accounting-document-workflow.spec.js:617:1 › cannot finalize draft if fiscal posting chart has no required account; draft remains intact
25
+[1A[2K[14/28] scripts/accounting-document-workflow.spec.js:629:1 › F2 validates formal invoice then saves a draft without posting any financial journal
26
+[1A[2K[15/28] scripts/accounting-document-workflow.spec.js:647:52 › WP1 ENFORCE purchase return rejects before local or server mutation
27
+[1A[2K[16/28] scripts/accounting-document-workflow.spec.js:647:52 › WP1 ENFORCE purchase cancel rejects before local or server mutation
28
+[1A[2K[17/28] scripts/accounting-document-workflow.spec.js:647:52 › WP1 ENFORCE purchase seamless rejects before local or server mutation
29
+[1A[2K[18/28] scripts/commerce-route-types.spec.js:21:1 › commerce menu routes offer only matching document families and retain unsaved sale fields
30
+[1A[2K[19/28] scripts/commerce-route-types.spec.js:35:1 › sales document selector reflects restored defaults and existing kind changes
31
+[1A[2K[20/28] scripts/pages-artifact.spec.js:10:1 › hardened Pages artifact loads without script/CSP console errors
32
+[1A[2Kscripts/pages-artifact.spec.js:10:1 › hardened Pages artifact loads without script/CSP console errors
33
+Pages artifact built: 133 static + 270 runtime inline handlers externalized; diag.html intentionally excluded.
34
+
35
+
36
+[1A[2K[21/28] scripts/pages-artifact.spec.js:30:1 › Production CSP login and connectivity actions work while later ERP JS is still downloading
37
+[1A[2K[22/28] scripts/pages-artifact.spec.js:59:1 › Slow final CSP dispatcher keeps login usable without loading legacy ERP scripts
38
+[1A[2K[23/28] scripts/pages-artifact.spec.js:122:1 › Built Pages uses exactly one SHA-pinned local bundle for all 14 ERP extensions
39
+[1A[2K[24/28] scripts/pages-artifact.spec.js:145:1 › A blocked production bundle fails closed and never exposes a partial financial workspace
40
+[1A[2K[25/28] scripts/pages-artifact.spec.js:166:1 › Built Pages loads exactly three ordered core groups instead of 38 blocking requests
41
+[1A[2K[26/28] scripts/pages-artifact.spec.js:189:1 › A blocked required core Pages group prevents opening partial financial workspace
42
+[1A[2K[27/28] scripts/pages-artifact.spec.js:210:1 › Published Pages CSP event bindings open Commerce and the top-bar sales invoice menu
43
+[1A[2K[28/28] scripts/pages-artifact.spec.js:253:1 › Published Pages invoice product and buyer filters stay scoped and do not persist draft edits
44
+[1A[2K 28 passed (1.0m)
docs/wp1/evidence/purchase-guard/red.log
new
+15
@@ -0,0 +1,15 @@
1
+node:internal/modules/run_main:107
2
+ triggerUncaughtException(
3
+ ^
4
+
5
+AssertionError [ERR_ASSERTION]: Missing expected rejection: enforce must reject
6
+ at async file:///workspace/Factor-easy-wp1/scripts/wp1-purchase-correction-guard-test.mjs:17:35 {
7
+ generatedMessage: false,
8
+ code: 'ERR_ASSERTION',
9
+ actual: undefined,
10
+ expected: undefined,
11
+ operator: 'rejects',
12
+ diff: 'simple'
13
+}
14
+
15
+Node.js v24.19.0
index.html
+1
-1
@@ -947,7 +947,7 @@ body{background:#f6f9fc}
947
948
<script src="js/projects.js?v=20260928-projects-v7"></script>
949
<script src="js/invoice-excel-import.js"></script>
950
-<script src="js/purchases.js?v=20261011-persian-print-v1"></script>
950
+<script src="js/purchases.js?v=20261103-server-correction-guard-v1"></script>
951
<script src="js/commercial-rnd.js?v=20261031-workspace-recovery-v1"></script>
952
<script src="js/operations.js?v=20260928-phase3-final"></script>
953
<script src="js/payments.js?v=20260928-phase3-final"></script>
js/purchases.js
+23
@@ -141,7 +141,29 @@
141
}
142
return number;
143
}
144
+ // Never mutate the local ledger while the server owns posting/reversal.
145
+ // Missing capability is the sole legacy fallback; transport errors fail closed.
146
+ async function purchaseRequireLegacyCorrection(){
147
+ const userId=currentUser?.id,org=currentUser?.organizationId,company=afCompanyId();
148
+ if(!userId||!org)throw new Error('سازمان فعال مشخص نیست؛ اطلاعات حساب را دوباره بارگذاری کنید.');
149
+ let timer,result;
150
+ try{
151
+ result=await Promise.race([
152
+ sb.rpc('finora_journal_get_guard_mode',{p_organization_id:org}),
153
+ new Promise((_,reject)=>{timer=setTimeout(()=>reject(new Error('timeout')),20000);})
154
+ ]);
155
+ }catch(_){throw new Error('وضعیت کنترل سروری دریافت نشد؛ تغییری در سند انجام نشد. دوباره تلاش کنید.');}
156
+ finally{clearTimeout(timer);}
157
+ if(currentUser?.id!==userId||currentUser?.organizationId!==org||afCompanyId()!==company)
158
+ throw new Error('حساب یا شرکت فعال تغییر کرده است؛ سند را دوباره باز کنید.');
159
+ const missing=result?.error&&['PGRST202','42883'].includes(result.error.code);
160
+ if(!missing&&(result?.error||!['off','audit','enforce'].includes(result?.data)))
161
+ throw new Error('وضعیت کنترل سروری تأیید نشد؛ تغییری در سند انجام نشد.');
162
+ if(!missing&&result.data==='enforce')
163
+ throw new Error('اصلاح و ابطال خرید در حالت کنترل سروری هنوز آماده نیست؛ هیچ تغییری ثبت نشد.');
164
+ }
165
window.returnPostedPurchaseAsDraft=async function(id,reason){
166
+ await purchaseRequireLegacyCorrection();
167
const {purchase:p,voucher:v}=purchasePilotEligibility(id),why=String(reason||'').trim();
168
if(!why)throw new Error('دلیل اصلاح خرید الزامی است.');
169
const number=purchasePilotNumber(p),now=new Date().toISOString(),newId=afId('PUR');
@@ -156,6 +178,7 @@
178
return draft.id;
179
};
180
window.cancelPostedPurchasePilot=async function(id,reason){
181
+ await purchaseRequireLegacyCorrection();
182
const {voucher:v}=purchasePilotEligibility(id),why=String(reason||'').trim();
183
if(!why)throw new Error('دلیل ابطال الزامی است.');
184
const reversal=jeReverse(v.id,getJalaliNumeric(),'ابطال خرید پایلوت: '+why);
scripts/accounting-document-workflow.spec.js
+27
@@ -55,10 +55,12 @@ async function authenticatedMockBrowser(page){
55
})
56
});
57
sb.rpc=async(name,args)=>{
58
+ if(name==='finora_journal_get_guard_mode')return {data:null,error:{code:'PGRST202'}};
59
if(name!=='finora_sync_records')throw Error('Unexpected RPC '+name);
60
return await window.qaF0Write(args);
61
};
62
await enterApp({id:'FINORA_F0_FIXTURE_ONLY'});
63
+ currentUser.organizationId='QA_ORG';
64
document.querySelectorAll('.modal-backdrop.active').forEach(x=>x.classList.remove('active'));
65
switchView('view-invoices');
66
});
@@ -641,3 +643,28 @@ test('F2 validates formal invoice then saves a draft without posting any financi
643
expect(remoteInvoices(server)).toHaveLength(1);
644
expect([...server.records.values()].filter(x=>x.collection==='journalVouchers')).toHaveLength(0);
645
});
646
+
647
+for(const action of ['return','cancel','seamless'])test('WP1 ENFORCE purchase '+action+' rejects before local or server mutation',async({page})=>{
648
+ const server=fakeServer();await installHarness(page,server);await authenticatedMockBrowser(page);
649
+ const id=await createPostedPurchase(page,server,'ENFORCE-'+action,2);
650
+ const before=copy([...server.records.values()]);
651
+ const localBefore=await page.evaluate(()=>JSON.stringify(datastore));
652
+ await page.evaluate(()=>{
653
+ const original=sb.rpc;sb.rpc=async(name,args)=>name==='finora_journal_get_guard_mode'?{data:'enforce',error:null}:original(name,args);
654
+ window.__wp1Writes=0;const save=saveDatastore;saveDatastore=function(){window.__wp1Writes++;return save.apply(this,arguments);};
655
+ window.__wp1Reversals=0;const reverse=jeReverse;jeReverse=function(){window.__wp1Reversals++;return reverse.apply(this,arguments);};
656
+ });
657
+ if(action==='seamless'){
658
+ await page.evaluate(x=>beginPurchaseAmendment(x),id);
659
+ await page.locator('#pur-items-body .pur-qty').first().fill('3');
660
+ await page.locator('#pur-items-body .pur-qty').first().dispatchEvent('input');
661
+ await page.locator('#pur-save-btn').click();
662
+ await expect.poll(()=>page.evaluate(()=>window.__f0Alerts.some(x=>x.includes('کنترل سروری هنوز آماده نیست')))).toBe(true);
663
+ }else{
664
+ const error=await page.evaluate(async({id,action})=>{try{await window[action==='return'?'returnPostedPurchaseAsDraft':'cancelPostedPurchasePilot'](id,'fixture');return null;}catch(e){return e.message;}},{id,action});
665
+ expect(error).toContain('کنترل سروری هنوز آماده نیست');
666
+ }
667
+ expect(await page.evaluate(()=>({writes:window.__wp1Writes,reversals:window.__wp1Reversals}))).toEqual({writes:0,reversals:0});
668
+ expect(await page.evaluate(()=>JSON.stringify(datastore))).toBe(localBefore);
669
+ expect([...server.records.values()]).toEqual(before);
670
+});
scripts/wp1-purchase-correction-guard-test.mjs
new
+24
@@ -0,0 +1,24 @@
1
+import fs from 'node:fs';
2
+import vm from 'node:vm';
3
+import assert from 'node:assert/strict';
4
+function fixture(reply){
5
+ const p={id:'P',ownerUserId:'U',companyId:'C',number:'1',items:[{prodId:'PRODUCT',qty:1}],accountingStatus:'posted'};
6
+ const v={id:'V',sourceType:'purchase',sourceId:'P',status:'posted',fiscalYearId:'Y'};
7
+ const counts={reverse:0,save:0,sync:0};
8
+ const c={console,Date,Math,Number,String,Array,Set,Promise,setTimeout,clearTimeout,COLLS:[],currentUser:{id:'U',organizationId:'O'},
9
+ document:{getElementById:id=>id==='view-purchases'?{}:null,addEventListener(){}},datastore:{purchases:[p]},
10
+ requireWrite:()=>true,afCompanyId:()=> 'C',afId:()=> 'NEW',getJalaliNumeric:()=> '1405/07/24',
11
+ getMyFiscalYears:()=>[{id:'Y',status:'open'}],jeFiscalForDate:()=>({id:'Y',status:'open'}),getMyPayments:()=>[],getMyProducts:()=>[{id:'PRODUCT'}],productMovement:()=>({available:5}),jeSourceVoucher:()=>v,
12
+ jeReverse:()=>{counts.reverse++;return {id:'REV'};},saveDatastore:()=>counts.save++,invoicePilotAwaitSync:async()=>counts.sync++,refreshAllSurfaces(){},sb:{rpc:async()=> typeof reply==='function'?reply(c):reply}};
13
+ c.window=c;vm.createContext(c);vm.runInContext(fs.readFileSync('js/purchases.js','utf8'),c);return {c,counts};
14
+}
15
+for(const action of ['returnPostedPurchaseAsDraft','cancelPostedPurchasePilot']){
16
+ for(const [name,reply] of [['enforce',{data:'enforce',error:null}],['network',{error:{code:'NETWORK',message:'private detail'}}],['unknown',{data:null,error:null}],['changed',c=>{c.currentUser={id:'OTHER',organizationId:'OTHER'};return {data:'off',error:null};}]]){
17
+ const {c,counts}=fixture(reply);await assert.rejects(c[action]('P','fixture reason'),undefined,name+' must reject');
18
+ assert.deepEqual(counts,{reverse:0,save:0,sync:0},name+' must not touch local/remote ledger');assert.equal(c.datastore.purchases.length,1);
19
+ }
20
+ for(const reply of [{data:'off',error:null},{data:'audit',error:null},{data:null,error:{code:'PGRST202'}}]){
21
+ const {c,counts}=fixture(reply);await c[action]('P','fixture reason');assert.equal(counts.reverse,1);assert.equal(counts.sync,1);
22
+ }
23
+}
24
+console.log('PASS purchase correction/cancel guards: enforce, transport, malformed mode, changed identity reject before mutation; off/audit/missing RPC retain legacy path.');