سامانه صدور فاکتور و حسابداری
test: real Chromium invoice draft edit, explicit post, balanced voucher idempotency and posting failure
davoodmehraban89 committed
Oct 11, 2026 at 20:46 UTC
a5e899e791fa0e13671f91795b0f1496e48362c3
1 file changed
+132
scripts/accounting-document-workflow.spec.js
new
+132
@@ -0,0 +1,132 @@
1
+const {test,expect}=require('@playwright/test');
2
+
3
+const BASE=process.env.FINORA_TEST_BASE_URL||'http://127.0.0.1:4173/index.html';
4
+const USER='FINORA_F0_FIXTURE_ONLY';
5
+const copy=value=>JSON.parse(JSON.stringify(value));
6
+function fakeServer(){
7
+ const records=new Map();
8
+ for(const [collection,id,data] of [
9
+ ['companies','QA_CO',{name:'شرکت آزمون ایزوله',entityType:'legal'}],
10
+ ['contacts','QA_CONTACT',{name:'خریدار آزمایشی'}],
11
+ ['products','QA_PROD',{name:'بلوک سیمانی',code:'BLK-001',unit:'عدد',sale_price:1500}],
12
+ ['settings','main',{invoice_kind:'formal',vat_mode:'none',vat_rate:10,default_company_id:'QA_CO',currency_mode:'rial'}],
13
+ ['fiscalYears','FY_QA',{name:'۱۴۰۵',startDate:'1405/01/01',endDate:'1405/12/29',status:'open'}],
14
+ ['accounts','A_CASH',{code:'1101',title:'صندوق',systemRole:'cash_default',postingAllowed:true,active:true}],
15
+ ['accounts','A_AR',{code:'1102',title:'دریافتنی',systemRole:'receivable_control',postingAllowed:true,active:true}],
16
+ ['accounts','A_REV',{code:'4101',title:'درآمد فروش',systemRole:'revenue_default',postingAllowed:true,active:true}],
17
+ ['accounts','A_VAT',{code:'2102',title:'مالیات',systemRole:'vat_payable',postingAllowed:true,active:true}],
18
+ ])records.set(collection+'|'+id,{collection,id,data:copy(data)});
19
+ return {records,failNext:false,failCount:0,rpcCount:0};
20
+}
21
+function remoteInvoices(server){return [...server.records.values()].filter(r=>r.collection==='invoices').map(r=>copy(r.data));}
22
+
23
+async function installHarness(page,server){
24
+ await page.exposeFunction('qaF0Read',async()=>[...server.records.values()].map(copy));
25
+ await page.exposeFunction('qaF0Write',async args=>{
26
+ server.rpcCount++;
27
+ if(server.failNext){server.failNext=false;server.failCount++;return {error:{message:'Network unavailable — isolated QA failure',code:'QA_NETWORK'}};}
28
+ for(const row of args.p_upserts||[])server.records.set(row.collection+'|'+row.id,{collection:row.collection,id:row.id,data:copy(row.data)});
29
+ for(const row of args.p_deletes||[])server.records.delete(row.collection+'|'+row.id);
30
+ return {error:null};
31
+ });
32
+ await page.route(/https:\/\/[^/]*supabase\.co\//,route=>route.abort());
33
+}
34
+async function authenticatedMockBrowser(page){
35
+ await page.goto(BASE,{waitUntil:'domcontentloaded'});
36
+ await page.waitForFunction(()=>typeof enterApp==='function'&&typeof commitSaveInvoice==='function'&&typeof pullAll==='function');
37
+ await page.evaluate(async()=>{
38
+ window.__FINORA_PRINT_TEST_MODE=true;
39
+ window.__f0Alerts=[];
40
+ window.alert=m=>window.__f0Alerts.push(String(m));
41
+ window.confirm=()=>false;
42
+ fetchCurrentUser=async()=>({id:'FINORA_F0_FIXTURE_ONLY',username:'qa-only',email:'qa@example.invalid',fullName:'QA F0',role:'admin',maxCompanies:2,subscription:{type:'lifetime',status:'active',endDate:'2099-12-31'}});
43
+ maybeMigrateLegacyData=()=>{};
44
+ sb.from=collection=>({
45
+ select:()=>({
46
+ order(){return this;},
47
+ async range(from,to){const rows=(await window.qaF0Read()).filter(r=>r.collection).sort((a,b)=>a.collection.localeCompare(b.collection)||a.id.localeCompare(b.id));return {data:rows.slice(from,to+1),error:null};}
48
+ })
49
+ });
50
+ sb.rpc=async(name,args)=>{
51
+ if(name!=='finora_sync_records')throw Error('Unexpected RPC '+name);
52
+ return await window.qaF0Write(args);
53
+ };
54
+ await enterApp({id:'FINORA_F0_FIXTURE_ONLY'});
55
+ switchView('view-invoices');
56
+ });
57
+ await expect(page.locator('#auth-screen')).toBeHidden();
58
+ await expect(page.locator('#invoice-company-id option[value="QA_CO"]')).toHaveCount(1);
59
+ await expect(page.locator('#invoice-items-table-body .row-product-select').first().locator('option[value="QA_PROD"]')).toHaveCount(1);
60
+}
61
+async function fillInvoice(page,number,qty){
62
+ // The native invoice-kind/contact selectors are hidden by the unified commercial combobox.
63
+ // Drive their real DOM change handlers, not Playwright visibility on replaced native selects.
64
+ await page.evaluate(()=>{
65
+ for(const [id,value] of [['invoice-kind','formal'],['invoice-company-id','QA_CO'],['invoice-contact-id','QA_CONTACT']]){
66
+ const el=document.getElementById(id);el.value=value;el.dispatchEvent(new Event('change',{bubbles:true}));
67
+ }
68
+ });
69
+ await page.locator('#invoice-number').fill(number);
70
+ await page.locator('#invoice-date-input').fill('۱۴۰۵/۰۷/۱۹');
71
+ await page.evaluate(()=>{
72
+ const el=document.querySelector('#invoice-items-table-body .row-product-select');
73
+ el.value='QA_PROD';el.dispatchEvent(new Event('change',{bubbles:true}));
74
+ });
75
+ await page.locator('#invoice-items-table-body .row-quantity').first().fill(String(qty));
76
+ await page.locator('#invoice-items-table-body .row-quantity').first().dispatchEvent('input');
77
+}
78
+
79
+test('formal invoice remains editable draft across server reload; explicit posting creates exactly one balanced voucher',async({page})=>{
80
+ const server=fakeServer();await installHarness(page,server);await authenticatedMockBrowser(page);
81
+ await fillInvoice(page,'FIN-DRAFT-001',2);
82
+ await page.evaluate(()=>commitSaveInvoice());
83
+ await expect.poll(()=>remoteInvoices(server).length,{timeout:13000}).toBe(1);
84
+ expect(remoteInvoices(server)[0].accountingStatus).toBe('draft');
85
+ expect([...server.records.values()].filter(x=>x.collection==='journalVouchers')).toHaveLength(0);
86
+ const id=remoteInvoices(server)[0].id;
87
+ await page.reload({waitUntil:'domcontentloaded'});await authenticatedMockBrowser(page);
88
+ await page.evaluate(x=>editInvoice(x),id);
89
+ await expect(page.locator('#edit-invoice-id')).toHaveValue(id);
90
+ await page.locator('#invoice-items-table-body .row-quantity').first().fill('3');
91
+ await page.locator('#invoice-items-table-body .row-quantity').first().dispatchEvent('input');
92
+ await page.evaluate(()=>commitSaveInvoice());
93
+ await expect.poll(()=>remoteInvoices(server)[0]?.grandTotal,{timeout:13000}).toBe(4500);
94
+ await page.evaluate(()=>navigateShell('accounting','view-journal','documents'));
95
+ await expect(page.locator('#finora-document-management-body')).toContainText('FIN-DRAFT-001');
96
+ await expect(page.locator('#finora-document-management-body')).toContainText('پیشنویس');
97
+ await page.locator('#finora-document-management-body [data-doc-action="post"]').click();
98
+ // Show a confirmation requiring explicit intent; no automatic posting on Save.
99
+ await expect.poll(()=>remoteInvoices(server)[0].accountingStatus,{timeout:3000}).toBe('draft');
100
+ await page.evaluate(()=>{window.confirm=()=>true});
101
+ await page.locator('#finora-document-management-body [data-doc-action="post"]').click();
102
+ await expect.poll(()=>remoteInvoices(server)[0]?.accountingStatus,{timeout:13000}).toBe('posted');
103
+ const posted=remoteInvoices(server)[0];
104
+ const vouchers=[...server.records.values()].filter(x=>x.collection==='journalVouchers');
105
+ const lines=[...server.records.values()].filter(x=>x.collection==='journalLines');
106
+ expect(vouchers).toHaveLength(1);
107
+ expect(vouchers[0].data.status).toBe('posted');
108
+ expect(lines.length).toBeGreaterThanOrEqual(2);
109
+ expect(lines.reduce((t,x)=>t+Number(x.data.debit||0),0)).toBe(4500);
110
+ expect(lines.reduce((t,x)=>t+Number(x.data.credit||0),0)).toBe(4500);
111
+ expect(posted.journalVoucherId).toBe(vouchers[0].id);
112
+ // Repeat post must be idempotent, and posted source cannot be edited or overwritten.
113
+ await page.evaluate(x=>finalizeInvoiceDocument(x),id);
114
+ expect([...server.records.values()].filter(x=>x.collection==='journalVouchers')).toHaveLength(1);
115
+ await page.evaluate(x=>editInvoice(x),id);
116
+ await expect(page.locator('#edit-invoice-id')).toHaveValue('');
117
+ await page.reload({waitUntil:'domcontentloaded'});await authenticatedMockBrowser(page);
118
+ const saved=await page.evaluate(x=>getMyInvoices().find(i=>i.id===x),id);
119
+ expect(saved.documentStatus).toBe('posted');
120
+ expect(saved.grandTotal).toBe(4500);
121
+ expect(saved.documentVersion).toBe(2);
122
+});
123
+test('cannot finalize draft if fiscal posting chart has no required account; draft remains intact',async({page})=>{
124
+ const server=fakeServer();server.records.delete('accounts|A_REV');await installHarness(page,server);await authenticatedMockBrowser(page);
125
+ await fillInvoice(page,'FIN-NO-REVENUE-ACCOUNT',2);await page.evaluate(()=>commitSaveInvoice());
126
+ await expect.poll(()=>remoteInvoices(server).length,{timeout:13000}).toBe(1);
127
+ const id=remoteInvoices(server)[0].id;
128
+ const result=await page.evaluate(x=>{try{finalizeInvoiceDocument(x);return 'unexpected success'}catch(e){return String(e.message)}},id);
129
+ expect(result).toMatch(/حساب|کدینگ/);
130
+ expect(remoteInvoices(server)[0].accountingStatus).toBe('draft');
131
+ expect([...server.records.values()].filter(x=>x.collection==='journalVouchers')).toHaveLength(0);
132
+});