@davoodmehraban89 / Factor-easy-2 Mirror · read-only / commits / 7f20ad8
Fork 0

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

Mirrored from https://github.com/davoodmehraban89/Factor-easy.git

Synced Dec 3, 22:00 UTC

fix: prevent voluntary tenant switches from discarding pending edits

davoodmehraban89 committed Nov 24, 2026 at 11:14 UTC 7f20ad848785da04a051bbaf3ce993444c6aa3fc
5 files changed +118 -24
PROJECT_STATE.md
+5
@@ -688,3 +688,8 @@ Next action: run and inspect Quality on the latest PR212 head. If any browser te
688 - Owner continues FIN-INTEGRATION-A01. Base PR251 99fb2d47d24f8066262b8b43dba0c8ad0082c848; exact WP2 45349424265 and Security 45349424198 SUCCESS, Quality 45349424243 passed static steps and browser stage pending, WP1 45349424333 in progress. A01 not accepted. Use stacked disposable candidate `fix/finora-b01-safe-org-switch-20261124` so A01 CI can finish without cancellation.
689 - Source-proven B01 gap: switchFinoraOrganization invalidates context before auth/read, changes selected organization before success, then pullAll overwrites previous dirty graph. Stage target identity and data separately; reject voluntary switch if paused/dirty/in-flight or if old state changes during async reads; only publish verified target snapshot after all checks. Reject stale membership read from old tenant. Preserve forced membership revocation purge and stale-ACK tests. No change to server/RLS or historical records.
690 - Acceptance: targeted Node VM positive clean switch, pending/paused/running rejection, edit during identity and data reads, rejected read, wrong target, and forced round-trip stale ACK; verify browser/static/full exact SHA CI. Recovery from ambiguous writes remains separate B02. No production work, no merge.
691 +
692 +
693 +### 2026-11-24 — FIN-B01 — candidate implementation checkpoint (not accepted)
694 +- Stage target membership and snapshot without changing active identity, local selection or graph; prohibit switching with dirty/pending/paused/in-flight state and recheck context/fingerprint after every await; publish target and snapshots only together. Stale membership reply ignored. Rejected/failed switch restores selector, no automatic destructive recovery. Forced revocation still purges memory. Source-backed tests now distinguish voluntary blocked switch from forced A→B→A stale ACK.
695 +- Files: js/organization-rbac.js, js/bootstrap.js, scripts/pending-sync-preservation.test.mjs, cache assertion if present; docs. Targeted tests cover clean switch, four dirty/inflight states, edits during awaits, read/identity failure, concurrent switch and retained stale completion. Exact-head CI not yet observed; not accepted. No SQL or Production. B02 deliberate recovery from paused/ambiguous writes is open, separate; next inspect all A01/B01 gates and then B02. No new implementation of same engine.
docs/EXECUTION_STATUS.md
+4
@@ -191,3 +191,7 @@
191 - PR251, baseline PR234 bc4f2a8, transfer 40226be, source PR250 1366724. PR234 four CI gates successful; PR250 Quality failed old auto-reload conflict expectation. PR249 Quality/WP2 failed; its PR219 migrations are excluded.
192 - Work: transplant pending-edit protections and targeted tests, keep PR234 QA, reconcile Phase5 conflict assertion to preserve all data/CAS and inhibit unsafe retry. Deliberate conflict recovery and pending tenant switch remain unaccepted. No hosted DB or release.
193 - Acceptance: exact-head Quality/WP1/WP2/Security + independent review. Next check CI logs and open recovery path; C/D not accepted. Issues 229/245/246/248/238/223 remain open.
194 +
195 +
196 +### 2026-11-24 — FIN-B01 safe organization switching (candidate)
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.
js/bootstrap.js
+1 -1
@@ -3,7 +3,7 @@
3 // browsers may download in parallel but preserve script execution/dependencies.
4 // Auth starts only once all extensions have finished loading or failed.
5 const FINORA_EXTENSION_SCRIPTS=[
6 - "js/organization-rbac.js?v=20261124-pending-context-v1",
6 + "js/organization-rbac.js?v=20261124-safe-org-switch-v2",
7 "js/organization-invitations.js?v=20261110-organization-read-v2",
8 "js/organization-enterprise-ux.js?v=20261110-organization-read-v2",
9 "js/platform-modules.js?v=20261031-workspace-recovery-v1",
js/organization-rbac.js
+62 -19
@@ -9,7 +9,7 @@ async function finoraOrganizationRead(query,signal,stage='ORG_ACCESS'){
9 if(signal?.aborted)throw new Error('FINORA_LOGIN_READ_TIMEOUT');
10 return result;
11 }
12 -async function loadOrganizationContext(user,{signal}={}){
12 +async function loadOrganizationContext(user,{signal,organizationId}={}){
13 const {data:members,error:memberError}=await finoraOrganizationRead(sb.from('organization_members').select('id,organization_id,unit_id,position_title,status,is_owner').eq('user_id',user.id).eq('status','active'),signal,'ORG_MEMBERSHIP');
14 if(memberError)throw memberError;
15 const orgIds=(members||[]).map(x=>x.organization_id);
@@ -33,7 +33,7 @@ async function loadOrganizationContext(user,{signal}={}){
33 return {membership:m,organization:(orgs||[]).find(o=>o.id===m.organization_id),license:(licenses||[]).find(l=>l.organization_id===m.organization_id),permissions:directPermissions.concat(rolePermissions),directPermissions,rolePermissions,roles:(roles||[]).filter(r=>assignedRoleIds.has(r.id))};
34 }).filter(x=>x.organization&&x.license);
35 const saved=localStorage.getItem('finora_active_org_'+user.id);
36 - const selected=contexts.find(x=>x.organization.id===saved)||contexts.find(x=>x.membership.is_owner)||contexts[0];
36 + const selected=organizationId?contexts.find(x=>x.organization.id===organizationId):contexts.find(x=>x.organization.id===saved)||contexts.find(x=>x.membership.is_owner)||contexts[0];
37 if(!selected)throw new Error('FINORA_ORGANIZATION_CONTEXT_UNAVAILABLE');
38 const lic=selected.license,sub={type:lic.plan,startDate:lic.starts_at,endDate:lic.ends_at,status:lic.status};
39 user.organizations=contexts;
@@ -82,9 +82,10 @@ window.revalidateFinoraMembership=async function(options){
82 if(!currentUser?.id||!currentUser?.organizationId)return false;
83 if(finoraMembershipRevalidationBusy)return false;
84 finoraMembershipRevalidationBusy=true;
85 - const uid=currentUser.id,orgId=currentUser.organizationId;
85 + const context=finoraSyncContext(),uid=context.uid,orgId=context.org;
86 try{
87 const {data,error}=await sb.from('organization_members').select('id,organization_id,status').eq('user_id',uid).eq('status','active');
88 + if(!finoraSyncContextMatches(context))return false;
89 if(error){if(sensitive)return false;throw error}
90 const active=data||[];
91 if(active.some(m=>m.organization_id===orgId))return true;
@@ -105,10 +106,8 @@ window.hasFinoraCapability=function(moduleKey,capability='read'){
106 return (currentUser.modulePermissions||[]).some(p=>(p.module_key===moduleKey||p.module_key==='full_suite')&&Array.isArray(p.capabilities)&&p.capabilities.includes(capability));
107 };
108 const legacyPullAll=pullAll;
108 -pullAll=async function(options={}){
109 - const signal=options?.signal;
110 - if(!currentUser?.organizationId)return legacyPullAll(options);
111 - const capture=finoraCaptureRead(),uid=capture.context.uid,orgId=capture.context.org,fresh={};COLLS.forEach(k=>fresh[k]=[]);
109 +async function finoraReadOrganizationSnapshot(orgId,uid,signal){
110 + const fresh={};COLLS.forEach(k=>fresh[k]=[]);
111 const snap=new Map(),snapVersions=new Map(),page=1000;let from=0;
112 for(;;){
113 const request=sb.from('records').select('collection,id,data,owner_id,organization_id,version').eq('organization_id',orgId).order('collection').order('id').range(from,from+page-1);
@@ -117,28 +116,72 @@ pullAll=async function(options={}){
116 (data||[]).forEach(r=>{if(!fresh[r.collection])return;const obj=(r.data&&typeof r.data==='object'&&!Array.isArray(r.data))?r.data:{};obj.id=r.id;obj._serverVersion=Number(r.version);if(!Number.isSafeInteger(obj._serverVersion)||obj._serverVersion<1)throw new Error('FINORA_SERVER_VERSION_MISSING: '+r.collection+'|'+r.id);const key=r.collection+'|'+r.id;snap.set(key,JSON.stringify(stripOwner(obj)));snapVersions.set(key,obj._serverVersion);obj.ownerUserId=uid;fresh[r.collection].push(obj)});
117 if(!data||data.length<page)break;from+=page;
118 }
120 - // Never apply an aborted/stale company snapshot to the active tenant.
119 + if(signal?.aborted)throw new Error('FINORA_LOGIN_READ_TIMEOUT');
120 + return {fresh,snap,snapVersions};
121 +}
122 +function finoraPublishOrganizationSnapshot(snapshot,context){
123 + datastore=snapshot.fresh;syncSnap.clear();snapshot.snap.forEach((v,k)=>syncSnap.set(k,v));syncVersionSnap.clear();snapshot.snapVersions.forEach((v,k)=>syncVersionSnap.set(k,v));
124 + finoraReadPublished(context);
125 +}
126 +pullAll=async function(options={}){
127 + const signal=options?.signal;
128 + if(!currentUser?.organizationId)return legacyPullAll(options);
129 + const capture=finoraCaptureRead(),uid=capture.context.uid,orgId=capture.context.org;
130 + const snapshot=await finoraReadOrganizationSnapshot(orgId,uid,signal);
131 if(signal?.aborted)throw new Error('FINORA_LOGIN_READ_TIMEOUT');
132 if(currentUser?.id!==uid||currentUser.organizationId!==orgId)throw new Error('FINORA_ORGANIZATION_CONTEXT_CHANGED');
133 finoraAssertRead(capture);
124 - datastore=fresh;syncSnap.clear();snap.forEach((v,k)=>syncSnap.set(k,v));syncVersionSnap.clear();snapVersions.forEach((v,k)=>syncVersionSnap.set(k,v));
125 - finoraReadPublished(capture.context);
134 + finoraPublishOrganizationSnapshot(snapshot,capture.context);
135 };
136 +let finoraOrganizationSwitchBusy=false;
137 // Keep the version-aware, atomic runSync implementation from js/sync.js.
138 // The former organization override called legacy finora_sync_records without expected_version,
139 // bypassing optimistic concurrency and allowing stale writes.
130 -window.switchFinoraOrganization=async function(orgId){
131 - if(!currentUser?.organizations?.some(x=>x.organization.id===orgId))return false;
132 - finoraInvalidateSyncContext();
133 - localStorage.setItem('finora_active_org_'+currentUser.id,orgId);
134 - const {data}=await sb.auth.getUser();if(!data?.user)return false;
135 - currentUser=await fetchCurrentUser(data.user);await pullAll();
136 - if(typeof jeRpcRefreshEffectiveStatuses==='function')await jeRpcRefreshEffectiveStatuses();
137 - refreshAllSurfaces();if(typeof showModuleLauncher==='function')showModuleLauncher(true);return true;
140 +window.switchFinoraOrganization=async function(orgId,selector){
141 + const resetSelection=()=>{if(selector)selector.value=currentUser?.organizationId||'';};
142 + if(!currentUser?.organizations?.some(x=>x.organization.id===orgId)||finoraOrganizationSwitchBusy){resetSelection();return false;}
143 + if(currentUser.organizationId===orgId){resetSelection();return true;}
144 + const context=finoraSyncContext();
145 + const isClean=()=>finoraSyncContextMatches(context)&&finoraHydratedTenant===finoraTenantKey(context)&&!syncRunning&&!syncPending&&!finoraSyncIsPaused()&&!finoraSyncHasChanges();
146 + const blocked=()=>{alert('تغییر سازمان انجام نشد؛ ابتدا وضعیت ذخیرهٔ تغییرات سازمان فعلی را مشخص کنید.');return false;};
147 + if(!isClean()){resetSelection();return blocked();}
148 + const fingerprint=finoraSyncStateFingerprint();
149 + finoraOrganizationSwitchBusy=true;
150 + if(selector)selector.disabled=true;
151 + try{
152 + const {data,error}=await sb.auth.getUser();
153 + if(!isClean()||fingerprint!==finoraSyncStateFingerprint())return blocked();
154 + if(error||data?.user?.id!==context.uid)return false;
155 + // Stage both identity and snapshot without publishing a new tenant or
156 + // overwriting the previous tenant's local state while any read is pending.
157 + const target=await fetchCurrentUser(data.user,{organizationId:orgId});
158 + if(!isClean()||fingerprint!==finoraSyncStateFingerprint())return blocked();
159 + if(target?.id!==context.uid||target.organizationId!==orgId)return false;
160 + const snapshot=await finoraReadOrganizationSnapshot(orgId,context.uid);
161 + if(!isClean()||fingerprint!==finoraSyncStateFingerprint())return blocked();
162 + localStorage.setItem('finora_active_org_'+context.uid,orgId);
163 + clearTimeout(syncTimer);syncTimer=null;syncAgain=false;
164 + finoraInvalidateSyncContext();
165 + currentUser=target;
166 + finoraPublishOrganizationSnapshot(snapshot,finoraSyncContext());
167 + // The transition itself has committed locally. A rendering failure must
168 + // not claim the old tenant is still active or undo the verified snapshot.
169 + try{
170 + if(typeof jeRpcRefreshEffectiveStatuses==='function')await jeRpcRefreshEffectiveStatuses();
171 + refreshAllSurfaces();if(typeof showModuleLauncher==='function')showModuleLauncher(true);
172 + }catch(e){console.error('organization surface refresh failed',e);alert('سازمان تغییر کرد، اما بازخوانی نما کامل نشد.');}
173 + return true;
174 + }catch(e){
175 + console.error('organization switch failed',e);alert('تغییر سازمان انجام نشد؛ اطلاعات سازمان فعلی محفوظ است.');return false;
176 + }finally{
177 + finoraOrganizationSwitchBusy=false;
178 + if(selector)selector.disabled=false;
179 + resetSelection();
180 + }
181 };
182 window.finoraOrganizationSwitcherHtml=function(){
183 const xs=currentUser?.organizations||[];if(xs.length<2)return '';
141 - return '<div class="form-group" style="margin-top:12px"><label>سازمان فعال</label><select class="form-control" onchange="switchFinoraOrganization(this.value)">'+xs.map(x=>'<option value="'+esc(x.organization.id)+'" '+(x.organization.id===currentUser.organizationId?'selected':'')+'>'+esc(x.organization.name)+'</option>').join('')+'</select></div>';
184 + return '<div class="form-group" style="margin-top:12px"><label>سازمان فعال</label><select class="form-control" onchange="switchFinoraOrganization(this.value,this)">'+xs.map(x=>'<option value="'+esc(x.organization.id)+'" '+(x.organization.id===currentUser.organizationId?'selected':'')+'>'+esc(x.organization.name)+'</option>').join('')+'</select></div>';
185 };
186 window.finoraCanConfigureModule=function(moduleKey){return !!currentUser&&(currentUser.isOrganizationOwner||hasFinoraCapability(moduleKey,'configure'))};
187 window.finoraCanManageOrganization=function(){return !!currentUser&&(currentUser.isOrganizationOwner||hasFinoraCapability('core','configure'))};
scripts/pending-sync-preservation.test.mjs
+46 -4
@@ -18,7 +18,7 @@ async function harness(organization=true){
18 window:{addEventListener(){}},document:{addEventListener(){},getElementById:()=>badge},
19 finoraAbortableRead:async q=>q,finoraOrganizationRead:async q=>q,alert:x=>alerts.push(x),
20 canWrite:()=>true,requireWrite:()=>true,refreshAllSurfaces(){},
21 - localStorage:{setItem(_k,v){c.selectedOrg=v;}},fetchCurrentUser:async()=>({...c.currentUser,organizationId:c.selectedOrg}),
21 + localStorage:{setItem(_k,v){c.selectedOrg=v;}},fetchCurrentUser:async(_u,options)=>({...c.currentUser,organizationId:options?.organizationId||c.selectedOrg}),
22 sb:{auth:{getUser:async()=>({data:{user:{id:'U1'}}})},from:()=>({select(){return this},eq(){return this},order(){return this},range(){return this},then(a,b){return read().then(a,b)}}),
23 rpc:async(name,args)=>{requests.push({name,args});return {data:{upserts:args.p_upserts.map(r=>({collection:r.collection,id:r.id,version:r.expected_version+1})),deletes:args.p_deletes.map(({collection,id})=>({collection,id}))},error:null};}}
24 };
@@ -54,13 +54,55 @@ test('same-user old-tenant ACK cannot overwrite newly hydrated tenant',async()=>
54 d.resolve({data:{upserts:[{collection:'contacts',id:'C1',version:8}],deletes:[]},error:null});await write;
55 assert.equal(h.state().row.name,'B-value');assert.equal(h.state().row._serverVersion,3);assert.equal(h.state().versions[0][1],3);assert.match(h.state().snap[0][1],/B-value/);
56 });
57 -test('actual organization A-to-B-to-A switch invalidates an old completion',async()=>{
57 +test('forced organization A-to-B-to-A context transition invalidates an old completion',async()=>{
58 const h=await harness(),d=deferred();h.evaluate("datastore.contacts[0].name='A-edit';syncPending=true");h.c.sb.rpc=async()=>d.promise;const write=h.c.runSync();await tick();
59 - h.setRead(async()=>({data:[row('B',3)],error:null}));await h.c.window.switchFinoraOrganization('ORG_B');
60 - h.setRead(async()=>({data:[row('A-new',10)],error:null}));await h.c.window.switchFinoraOrganization('ORG_A');
59 + // Voluntary switch now refuses pending work. Simulate forced identity replacement
60 + // independently to retain the epoch/late-ACK regression from PR250.
61 + h.evaluate("finoraInvalidateSyncContext();currentUser={...currentUser,organizationId:'ORG_B'}");h.setRead(async()=>({data:[row('B',3)],error:null}));await h.c.pullAll();
62 + h.evaluate("finoraInvalidateSyncContext();currentUser={...currentUser,organizationId:'ORG_A'}");h.setRead(async()=>({data:[row('A-new',10)],error:null}));await h.c.pullAll();
63 d.resolve({data:{upserts:[{collection:'contacts',id:'C1',version:8}],deletes:[]},error:null});await write;
64 assert.equal(h.state().row.name,'A-new');assert.equal(h.state().row._serverVersion,10);
65 });
66 +test('voluntary clean organization switch stages and publishes identity and snapshot together',async()=>{
67 + const h=await harness(),d=deferred(),selector={value:'ORG_B'};
68 + h.setRead(()=>d.promise);const change=h.c.window.switchFinoraOrganization('ORG_B',selector);await tick();
69 + assert.equal(h.c.currentUser.organizationId,'ORG_A');assert.equal(h.state().row.name,'server-before');assert.equal(h.c.selectedOrg,undefined);assert.equal(selector.disabled,true);
70 + d.resolve({data:[row('B-new',3)],error:null});assert.equal(await change,true);
71 + assert.equal(h.c.currentUser.organizationId,'ORG_B');assert.equal(h.state().row.name,'B-new');assert.equal(h.state().versions[0][1],3);assert.equal(h.c.selectedOrg,'ORG_B');assert.equal(selector.value,'ORG_B');assert.equal(selector.disabled,false);
72 +});
73 +for(const mode of ['dirty','pending','paused','running'])test('voluntary switch blocks '+mode+' state without auth or read',async()=>{
74 + const h=await harness(),selector={value:'ORG_B'};let authCalls=0,reads=0;
75 + h.c.sb.auth.getUser=async()=>{authCalls++;return {data:{user:{id:'U1'}}}};
76 + h.setRead(async()=>{reads++;return {data:[row('B',3)],error:null}});
77 + if(mode==='dirty')h.evaluate("datastore.contacts[0].name='A-dirty'");
78 + if(mode==='pending')h.evaluate("syncPending=true");
79 + if(mode==='paused')await h.c.handleSyncError({code:'40001'});
80 + if(mode==='running')h.evaluate("syncRunning=true");
81 + const before=h.state();
82 + assert.equal(await h.c.window.switchFinoraOrganization('ORG_B',selector),false);
83 + assert.deepEqual(h.state(),before);assert.equal(h.c.currentUser.organizationId,'ORG_A');assert.equal(h.c.selectedOrg,undefined);assert.equal(selector.value,'ORG_A');assert.equal(authCalls,0);assert.equal(reads,0);
84 +});
85 +for(const stage of ['identity','snapshot'])test('voluntary switch preserves edits made during '+stage+' await',async()=>{
86 + const h=await harness(),d=deferred();
87 + if(stage==='identity')h.c.fetchCurrentUser=()=>d.promise;else h.setRead(()=>d.promise);
88 + const change=h.c.window.switchFinoraOrganization('ORG_B');await tick();
89 + h.evaluate("datastore.contacts[0].name='A-new-edit';syncPending=true");
90 + if(stage==='identity')d.resolve({...h.c.currentUser,organizationId:'ORG_B'});else d.resolve({data:[row('B',3)],error:null});
91 + assert.equal(await change,false);assert.equal(h.c.currentUser.organizationId,'ORG_A');assert.equal(h.state().row.name,'A-new-edit');assert.equal(h.state().pending,true);assert.equal(h.state().versions[0][1],7);assert.equal(h.c.selectedOrg,undefined);
92 +});
93 +test('failed target read and wrong target identity never publish or invalidate the current context',async()=>{
94 + const h=await harness(),before=h.state(),epoch=h.evaluate('finoraSyncEpoch');
95 + h.setRead(async()=>({data:null,error:{message:'read failed'}}));
96 + assert.equal(await h.c.window.switchFinoraOrganization('ORG_B'),false);assert.deepEqual(h.state(),before);assert.equal(h.evaluate('finoraSyncEpoch'),epoch);assert.equal(h.c.selectedOrg,undefined);
97 + h.c.fetchCurrentUser=async()=>({...h.c.currentUser,organizationId:'ORG_A'});
98 + assert.equal(await h.c.window.switchFinoraOrganization('ORG_B'),false);assert.deepEqual(h.state(),before);assert.equal(h.c.currentUser.organizationId,'ORG_A');
99 +});
100 +test('concurrent voluntary switch does not publish a second target',async()=>{
101 + const h=await harness(),d=deferred();h.setRead(()=>d.promise);
102 + const first=h.c.window.switchFinoraOrganization('ORG_B');await tick();
103 + assert.equal(await h.c.window.switchFinoraOrganization('ORG_A'),false);
104 + d.resolve({data:[row('B',3)],error:null});assert.equal(await first,true);assert.equal(h.c.currentUser.organizationId,'ORG_B');
105 +});
106 test('40001 preserves dirty data and pauses automatic retries',async()=>{
107 const h=await harness();h.evaluate("datastore.contacts[0].name='pending-conflict';syncPending=true");
108 h.c.sb.rpc=async(name,args)=>{h.requests.push({name,args});return {data:null,error:{code:'40001',message:'FINORA_VERSION_CONFLICT'}};};