سامانه صدور فاکتور و حسابداری
Mirrored from https://github.com/davoodmehraban89/Factor-easy.git
Synced Dec 3, 22:00 UTC
fix: reconcile unknown upsert outcomes before bounded exact CAS replay
davoodmehraban89 committed
Nov 24, 2026 at 11:25 UTC
9adb2f5801dcd167453ee0d7c432963c29319f95
7 files changed
+113
-13
PROJECT_STATE.md
+5
@@ -700,3 +700,8 @@ Next action: run and inspect Quality on the latest PR212 head. If any browser te
700
### 2026-11-24 — FIN-B02 — bounded reconciliation decision before implementation
701
- Parent PR252 exact 3fd33525ad83408e55a78842c7a8663d9a51b436; Security/WP2 PASS, Quality/WP1 in progress. PR251 99fb2d4 exact WP1/WP2/Security PASS; Quality 45349424243 failed browser with 258 passed/2 failed: operational settings mock bypasses initial pull and mutates datastore before read; invoice transient recovery no longer retries. Keep both acceptance contracts; fix fixture by seeding mock server and real pull; never disable hydration guard. Remove artificial settings-array deletion before read (would be a legitimate dirty-state conflict).
702
- Scope: same CAS batch, no new intent/rebase; only ambiguous network failure on upsert-only batch. Scoped read-back of record IDs/version/content, classify entire batch against exact preimage or exact intended postimage; if all unchanged allow one bounded replay of identical request; if all match desired postimage record state equivalence (not proof of actor/audit/transaction receipt); otherwise pause with no mutation/retry. No automatic recovery of deletes or permission/conflict errors. Preserve newer local edits and tenant/snapshot guards. Tests for precommit, lost ACK, divergent and partial state, tenant change, delete and read failure; retain browser transient recovery. No SQL/Production/merge. B02 still candidate, not accepted. Deliberate resolution UX for divergent state remains separate.
703
+
704
+
705
+### 2026-11-24 — FIN-B02 candidate checkpoint
706
+- B02 branch stacked on PR252, original A01 browser regressions traced. Implemented bounded organization-scoped upsert CAS recovery: exact immutable request, complete target preimage/postimage checks, no rebase, one replay only when all preimages unchanged, state-equivalent readback when all postimages/version match, no automatic delete recovery, divergence/read error/stale context remains paused. Read-back is not an actor/audit receipt. Newer edits remain pending for subsequent normal CAS. No database changes.
707
+- Existing operational settings test now hydrates through real pullAll from seeded synthetic server, no dirty-state bypass; original persistence/audit/permission assertions retained. Existing transient invoice browser test uses realistic SDK transport error, preserves automatic exact recovery expectation. Added focused Node tests of no duplicate writes, lost ACK, divergent/partial/failed read, wrong tenant, delete, retry bound, newer edit and stale tenant. Exact candidate CI pending; no local test execution claimed. Explicit resolution of divergent and deletion cases remains open. Next inspect A01/B01/B02 CI, preserve previous REDs and plan #229 after dependency gate.
docs/EXECUTION_STATUS.md
+4
@@ -197,3 +197,7 @@
197
- Base PR251 99fb2d4; staged identity/read + atomic local publication and pending-state block. No DB change. Exact candidate CI and review pending; forced membership revocation remains authoritative. B02 recovery unresolved. A01/B01 not accepted.
198
199
- PR252 candidate 7f20ad8 initially did not trigger WP2. Path coverage expanded to organization-rbac/sync/pending-sync behavioral test, with membership stale-response and real purge tests; check new exact-head CI.
200
+
201
+
202
+### 2026-11-24 — FIN-B02 (candidate)
203
+- PR251 browser 258 passed/2 failed; fix synthetic operational settings hydration and bounded transient CAS recovery on stacked B02, no schema changes. Exact-head tests pending. No blind retry on divergent or delete outcome; deliberate resolution still open.
index.html
+1
-1
@@ -937,7 +937,7 @@ body{background:#f6f9fc}
937
<script src="js/password-recovery.js?v=20261026-recovery-cancel-v2"></script>
938
<script src="js/core.js?v=20261110-account-read-v3"></script>
939
<script src="js/admin.js?v=20261028-central-password-reset-v1"></script>
940
-<script src="js/sync.js?v=20261124-pending-context-v1"></script>
940
+<script src="js/sync.js?v=20261124-cas-recovery-v1"></script>
941
<script src="js/ui.js?v=20261031-workspace-recovery-v1"></script>
942
<script src="js/invoices.js?v=20261117-source-autopost-v1"></script>
943
<script src="js/print.js?v=20261012-clean-invoice-print-v1"></script>
js/sync.js
+59
-3
@@ -111,6 +111,61 @@ function computeDiff(){
111
return {up,del};
112
}
113
function scheduleSync(ms){clearTimeout(syncTimer);syncTimer=setTimeout(runSync,ms);}
114
+// Generic CAS recovery is deliberately limited to upserts in a verified
115
+// organization. Deletions/financial conflicts require separate reconciliation.
116
+function finoraSyncTransportUnknown(error){
117
+ const code=String(error?.code||''),message=String(error?.message||error||'');
118
+ return (!code||code==='FETCH_ERROR')&&/failed to fetch|networkerror|network request failed|load failed|fetch failed|connection reset|timed?\s*out/i.test(message);
119
+}
120
+function finoraCanonicalJson(value){
121
+ if(value===null||typeof value!=='object')return JSON.stringify(value);
122
+ if(Array.isArray(value))return '['+value.map(finoraCanonicalJson).join(',')+']';
123
+ return '{'+Object.keys(value).sort().map(k=>JSON.stringify(k)+':'+finoraCanonicalJson(value[k])).join(',')+'}';
124
+}
125
+function finoraComparableRecord(data,id){
126
+ if(!data||typeof data!=='object'||Array.isArray(data))throw finoraSyncIssue('FINORA_RECOVERY_ROW_INVALID');
127
+ return finoraCanonicalJson(stripOwner({...data,id}));
128
+}
129
+async function finoraReadRecoveryRow(context,request,stillCurrent){
130
+ const controller=new AbortController(),timer=setTimeout(()=>controller.abort(),10000);
131
+ try{
132
+ let query=sb.from('records').select('collection,id,data,version,organization_id').eq('organization_id',context.org).eq('collection',request.collection).eq('id',request.id).range(0,1);
133
+ if(typeof query.abortSignal==='function')query=query.abortSignal(controller.signal);
134
+ const {data,error}=await finoraAbortableRead(query,controller.signal);
135
+ if(controller.signal.aborted||!stillCurrent()||error||!Array.isArray(data))throw finoraSyncIssue('FINORA_RECOVERY_READ_FAILED');
136
+ const matches=data.filter(r=>r.collection===request.collection&&r.id===request.id);
137
+ if(matches.length>1||matches.some(r=>r.organization_id!=null&&r.organization_id!==context.org))throw finoraSyncIssue('FINORA_RECOVERY_ROW_INVALID');
138
+ if(!matches.length)return null;
139
+ const row=matches[0];
140
+ if(!Number.isSafeInteger(row.version)||row.version<1)throw finoraSyncIssue('FINORA_RECOVERY_ROW_INVALID');
141
+ return row;
142
+ }finally{clearTimeout(timer);}
143
+}
144
+async function finoraSendVersionedBatch(args,up,context,snapshotSerial){
145
+ const stillCurrent=()=>finoraSyncContextMatches(context)&&snapshotSerial===finoraSnapshotSerial&&finoraHydratedTenant===finoraTenantKey(context);
146
+ const send=async()=>{try{return await sb.rpc('finora_sync_records_v2',JSON.parse(JSON.stringify(args)));}catch(error){return {error};}};
147
+ const result=await send();
148
+ if(!result?.error||!finoraSyncTransportUnknown(result.error)||!stillCurrent()||!context.org||args.p_deletes.length||!up.length)return result;
149
+ try{
150
+ // Keep the immutable request, original CAS revisions and base payloads.
151
+ // Read-back may establish state equivalence, never an audit/actor receipt.
152
+ let unchanged=true,applied=true;
153
+ for(let i=0;i<up.length;i++){
154
+ if(!stillCurrent())throw finoraSyncIssue('FINORA_SYNC_CONTEXT_CHANGED');
155
+ const r=up[i],request=args.p_upserts[i],row=await finoraReadRecoveryRow(context,request,stillCurrent);
156
+ const version=row?.version??0,actual=row?finoraComparableRecord(row.data,request.id):null;
157
+ const before=syncSnap.get(r.key);
158
+ const beforeComparable=before===undefined?null:finoraComparableRecord(JSON.parse(before),request.id);
159
+ const desired=finoraComparableRecord(request.data,request.id);
160
+ unchanged=unchanged&&version===request.expected_version&&actual===beforeComparable;
161
+ applied=applied&&version===request.expected_version+1&&actual===desired;
162
+ }
163
+ if(!stillCurrent())throw finoraSyncIssue('FINORA_SYNC_CONTEXT_CHANGED');
164
+ if(applied)return {data:{upserts:args.p_upserts.map(r=>({collection:r.collection,id:r.id,version:r.expected_version+1})),deletes:[]},error:null};
165
+ if(unchanged)return await send(); // One exact CAS replay, never a new revision/ID.
166
+ return {error:finoraSyncIssue('FINORA_RECOVERY_DIVERGENT')};
167
+ }catch(error){return {error};}
168
+}
169
async function runSync(){
170
if(!currentUser)return;
171
if(finoraSyncIsPaused()){syncPending=true;setSyncBadge('conflict');return;}
@@ -131,11 +186,12 @@ async function runSync(){
186
if(!Number.isSafeInteger(version)||version<1)throw new Error('FINORA_DELETE_VERSION_MISSING: '+k);
187
return {collection:k.slice(0,j),id:k.slice(j+1),expected_version:version};
188
});
134
- const {data,error}=await sb.rpc('finora_sync_records_v2',{
135
- p_upserts:up.map(r=>({collection:r.coll,id:r.id,data:r.payload,expected_version:r.expectedVersion})),
189
+ const args={
190
+ p_upserts:up.map(r=>({collection:r.coll,id:r.id,data:JSON.parse(r.s),expected_version:r.expectedVersion})),
191
p_deletes:deletes,
192
p_organization_id:context.org
138
- });
193
+ };
194
+ const {data,error}=await finoraSendVersionedBatch(args,up,context,snapshotSerial);
195
if(!finoraSyncContextMatches(context)||snapshotSerial!==finoraSnapshotSerial)throw finoraSyncIssue('FINORA_SYNC_CONTEXT_CHANGED');
196
if(error)throw error;
197
if(!data||!Array.isArray(data.upserts)||!Array.isArray(data.deletes))throw finoraSyncIssue('FINORA_SYNC_ACK_INVALID');
scripts/dom-smoke.spec.js
+11
-7
@@ -163,6 +163,14 @@ test('isolated print document honors CSS paper size in Chromium PDF',async({page
163
// Synthetic transport only: real operational settings UI, sync and reload path.
164
test('operational settings persist warehouse, currency and costing with an accurate audit record',async({page})=>{
165
const rows=new Map(),errors=[];let writes=0;
166
+ for(const [collection,id,data] of [
167
+ ['companies','QA_OPS_CO',{name:'Operational Settings Fixture'}],
168
+ ['settings','main',{default_company_id:'QA_OPS_CO',defaultWarehouseId:'QA_WH_A',baseCurrencyCode:'IRR',inventoryCostMethod:'weighted_average'}],
169
+ ['warehouses','QA_WH_A',{companyId:'QA_OPS_CO',name:'Warehouse A',active:true}],
170
+ ['warehouses','QA_WH_B',{companyId:'QA_OPS_CO',name:'Warehouse B',active:true}],
171
+ ['currencies','QA_IRR',{companyId:'QA_OPS_CO',code:'IRR',title:'ریال',active:true,base:true}],
172
+ ['currencies','QA_USD',{companyId:'QA_OPS_CO',code:'USD',title:'دلار',active:true,base:false}]
173
+ ])rows.set(collection+'|'+id,{collection,id,data,version:1,organization_id:'QA_ORG'});
174
page.on('pageerror',error=>{errors.push(error.message);console.info('OPS_SETTINGS_PAGEERROR: '+error.message)});
175
await page.route('https://*.supabase.co/**',async route=>{
176
const request=route.request(),path=new URL(request.url()).pathname;
@@ -190,14 +198,10 @@ test('operational settings persist warehouse, currency and costing with an accur
198
});
199
await page.goto(process.env.FINORA_TEST_BASE_URL||'http://127.0.0.1:4173/index.html',{waitUntil:'domcontentloaded'});
200
await page.waitForFunction(()=>window.FinoraStartupStatus?.extensionsReady===true&&window.FinoraStartupStatus?.failedExtensionCount===0&&window.FinoraStartupStatus?.authChecked===true);await page.evaluate(()=>Promise.all([window.FinoraAppAssetsReady,window.FinoraOrganizationContextReady]));
193
- await page.evaluate(()=>{
201
+ await page.evaluate(async()=>{
202
window.alert=()=>{};window.confirm=()=>false;
203
currentUser={id:'QA_OPS_SETTINGS',organizationId:'QA_ORG',role:'admin',modules:['full_suite'],subscription:{type:'lifetime',status:'active',endDate:'2099-01-01'}};
196
- const fresh={};COLLS.forEach(key=>fresh[key]=[]);datastore=fresh;syncSnap.clear();syncVersionSnap.clear();
197
- datastore.companies=[{id:'QA_OPS_CO',ownerUserId:currentUser.id,name:'Operational Settings Fixture'}];
198
- datastore.settings=[{id:'main',ownerUserId:currentUser.id,default_company_id:'QA_OPS_CO',defaultWarehouseId:'QA_WH_A',baseCurrencyCode:'IRR',inventoryCostMethod:'weighted_average'}];
199
- datastore.warehouses=[{id:'QA_WH_A',ownerUserId:currentUser.id,companyId:'QA_OPS_CO',name:'Warehouse A',active:true},{id:'QA_WH_B',ownerUserId:currentUser.id,companyId:'QA_OPS_CO',name:'Warehouse B',active:true}];
200
- datastore.currencies=[{id:'QA_IRR',ownerUserId:currentUser.id,companyId:'QA_OPS_CO',code:'IRR',title:'ریال',active:true,base:true},{id:'QA_USD',ownerUserId:currentUser.id,companyId:'QA_OPS_CO',code:'USD',title:'دلار',active:true,base:false}];
204
+ await pullAll();
205
document.getElementById('auth-screen').style.display='none';
206
document.querySelectorAll('.view-pane').forEach(el=>el.classList.toggle('active',el.id==='view-data-center'));
207
p5RenderDataCenter();
@@ -218,7 +222,7 @@ test('operational settings persist warehouse, currency and costing with an accur
222
const audits=[...rows.values()].filter(row=>row.collection==='phase5Audit');
223
expect(audits).toHaveLength(1);
224
expect(audits[0].data).toMatchObject({action:'update',entity:'companyOpsSettings',entityId:'QA_OPS_CO',before:{defaultWarehouseId:'QA_WH_A',baseCurrencyCode:'IRR',inventoryCostMethod:'weighted_average'},after:selected});
221
- await page.evaluate(async()=>{datastore.settings=[];await pullAll();p5RenderDataCenter()});
225
+ await page.evaluate(async()=>{await pullAll();p5RenderDataCenter()});
226
await expect(page.locator('#p5-set-default-wh')).toHaveValue('QA_WH_B');
227
await expect(page.locator('#p5-set-base-cur')).toHaveValue('USD');
228
await expect(page.locator('#p5-set-cost-method')).toHaveValue('weighted_average');
scripts/pending-sync-preservation.test.mjs
+32
-1
@@ -15,7 +15,7 @@ function row(name='server-before',version=7){return {collection:'contacts',id:'C
15
async function harness(organization=true){
16
const requests=[],timers=new Map(),badge={style:{}},alerts=[];let seq=0,read=async()=>({data:[row()],error:null});
17
const c={currentUser:{id:'U1',organizationId:organization?'ORG_A':null,organizations:[{organization:{id:'ORG_A'}},{organization:{id:'ORG_B'}}]},
18
- COLLS:['contacts','settings'],ID_RE:/^[\w-]+$/,console:{warn(){},error(){},log(){}},
18
+ COLLS:['contacts','settings'],ID_RE:/^[\w-]+$/,AbortController,console:{warn(){},error(){},log(){}},
19
setTimeout:(fn,ms)=>{timers.set(++seq,{fn,ms});return seq;},clearTimeout:id=>timers.delete(id),
20
window:{addEventListener(){}},document:{addEventListener(){},getElementById:()=>badge},
21
finoraAbortableRead:async q=>q,finoraOrganizationRead:async q=>q,alert:x=>alerts.push(x),
@@ -160,3 +160,34 @@ test('current membership revocation still purges pending memory and signs out',a
160
h.setRead(async()=>({data:[],error:null}));assert.equal(await h.c.window.revalidateFinoraMembership({sensitive:true}),false);
161
assert.equal(h.c.currentUser,null);assert.equal(h.evaluate('datastore.contacts.length'),0);assert.equal(h.evaluate('syncSnap.size'),0);assert.equal(h.evaluate('syncVersionSnap.size'),0);assert.equal(h.evaluate('syncPending'),false);assert.equal(h.c.signOutCalls,1);assert.deepEqual(h.c.lockCalls,[false]);
162
});
163
+
164
+const networkFailure=()=>({error:{code:'',message:'TypeError: Failed to fetch'}});
165
+test('unknown precommit upsert failure reads original revision and retries exact request once',async()=>{
166
+ const h=await harness();h.evaluate("datastore.contacts[0].name='new';syncPending=true");const real=h.c.sb.rpc;let first=true;
167
+ h.c.sb.rpc=async(name,args)=>{if(first){first=false;h.requests.push({name,args});return networkFailure();}return real(name,args);};
168
+ await h.c.runSync();assert.equal(h.requests.length,2);assert.deepEqual(h.requests[0],h.requests[1]);assert.equal(h.state().pending,false);assert.equal(h.state().versions[0][1],8);
169
+});
170
+test('lost ACK with exact committed postimage reconciles without sending the write again',async()=>{
171
+ const h=await harness();h.evaluate("datastore.contacts[0].name='new';syncPending=true");
172
+ h.c.sb.rpc=async(name,args)=>{h.requests.push({name,args});h.setRead(async()=>({data:[row('new',8)],error:null}));return networkFailure();};
173
+ await h.c.runSync();assert.equal(h.requests.length,1);assert.equal(h.state().pending,false);assert.equal(h.state().versions[0][1],8);assert.equal(h.state().row.name,'new');
174
+});
175
+for(const mode of ['divergent','partial','read-error','wrong-tenant','delete','second-network'])test('unknown ACK recovery fails closed for '+mode,async()=>{
176
+ const h=await harness();h.evaluate("datastore.contacts[0].name='new';syncPending=true");
177
+ if(mode==='partial')h.evaluate("datastore.settings.push({id:'main',ownerUserId:'U1',theme:'new'})");
178
+ if(mode==='delete')h.evaluate("datastore.contacts=[]");
179
+ const before=h.state();
180
+ h.c.sb.rpc=async(name,args)=>{h.requests.push({name,args});if(mode==='divergent')h.setRead(async()=>({data:[row('other',8)],error:null}));if(mode==='partial')h.setRead(async()=>({data:[row('new',8)],error:null}));if(mode==='read-error')h.setRead(async()=>({data:null,error:{message:'failed'}}));if(mode==='wrong-tenant')h.setRead(async()=>({data:[{...row('new',8),organization_id:'ORG_B'}],error:null}));return networkFailure();};
181
+ await h.c.runSync();assert.equal(h.requests.length,mode==='second-network'?2:1);assert.deepEqual(h.state(),before);assert.equal(h.evaluate('finoraSyncIsPaused()'),true);
182
+});
183
+test('new edits during recovery are not included in the replayed request',async()=>{
184
+ const h=await harness(),d=deferred();h.evaluate("datastore.contacts[0].name='sent';syncPending=true");const real=h.c.sb.rpc;let first=true;
185
+ h.c.sb.rpc=async(name,args)=>{if(first){first=false;h.requests.push({name,args});h.setRead(()=>d.promise);return networkFailure();}return real(name,args);};
186
+ const work=h.c.runSync();await tick();h.evaluate("datastore.contacts[0].name='newer'");d.resolve({data:[row()],error:null});await work;
187
+ assert.equal(h.requests.length,3);assert.deepEqual(h.requests[0],h.requests[1]);assert.equal(h.requests[2].args.p_upserts[0].expected_version,8);assert.equal(h.requests[2].args.p_upserts[0].data.name,'newer');assert.equal(h.state().versions[0][1],9);
188
+});
189
+test('tenant change during read-back cannot publish or replay the old request',async()=>{
190
+ const h=await harness(),d=deferred();h.evaluate("datastore.contacts[0].name='old';syncPending=true");h.c.sb.rpc=async(name,args)=>{h.requests.push({name,args});h.setRead(()=>d.promise);return networkFailure();};
191
+ const work=h.c.runSync();await tick();h.evaluate("finoraInvalidateSyncContext();currentUser={...currentUser,organizationId:'ORG_B'}");h.setRead(async()=>({data:[row('B',3)],error:null}));await h.c.pullAll();d.resolve({data:[row('old',8)],error:null});await work;
192
+ assert.equal(h.requests.length,1);assert.equal(h.state().row.name,'B');assert.equal(h.state().versions[0][1],3);assert.equal(h.state().pending,false);
193
+});
scripts/phase0-invoice-persistence.spec.js
+1
-1
@@ -19,7 +19,7 @@ async function installHarness(page,server){
19
await page.exposeFunction('qaF0Read',async()=>[...server.records.values()].map(row=>({...copy(row),version:Number(row.version)||1})));
20
await page.exposeFunction('qaF0Write',async args=>{
21
server.rpcCount++;
22
- if(server.failNext){server.failNext=false;server.failCount++;return {error:{message:'Network unavailable — isolated QA failure',code:'QA_NETWORK'}};}
22
+ if(server.failNext){server.failNext=false;server.failCount++;return {error:{message:'TypeError: Failed to fetch',code:''}};}
23
if(args.p_organization_id!=='QA_ORG')return {error:{message:'Unexpected organization scope',code:'QA_ORG_SCOPE'}};
24
const upserts=[];
25
for(const row of args.p_upserts||[]){