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

feat(stage3.2): add safe sale source CAS sync, deterministic server post and targeted replay recovery

davoodmehraban89 committed Oct 23, 2026 at 03:23 UTC f6b1dd69eddf75c7d743ec9eda1cb9b3bc89ee36
1 file changed +92
js/invoices.js
+92
@@ -377,6 +377,98 @@ function invoiceDocumentStatusLabel(inv){
377 function invoiceMayEdit(inv){
378 return !!inv&&invoiceDocumentStatus(inv)==='draft'||!!inv&&invoiceDocumentStatus(inv)==='operational';
379 }
380 +// Stage 3.2: guarded, opt-in FINORA sale source posting.
381 +// No browser-created posted lines/numbers and no mutation of posted source.
382 +const finoraSaleServerInFlight=new Map();
383 +function finoraStage3SaleV1Valid(source){
384 + if(source?.currencyCode!=='IRR'||(getMySettings().currency_mode||'rial')!=='rial')
385 + throw new Error('این قرارداد فقط واحد ریال را می‌پذیرد؛ تبدیل ارز یا تومان تصویب نشده است.');
386 + if(source.accountingVersion!==1||!['formal','non_formal'].includes(source.kind)||
387 + !['credit','cash'].includes(source.paymentMethod)||
388 + !['none','with_vat'].includes(source.vatMode))
389 + throw new Error('قرارداد مالی فروش نسخه ۱ برای این پیش‌نویس معتبر نیست.');
390 + for(const k of ['subtotal','discount','discountInput','vat','vatRate','grandTotal']){
391 + if(!Number.isSafeInteger(source[k])||source[k]<0)
392 + throw new Error('مبلغ یا نرخ سند مالی باید عدد صحیح معتبر باشد.');
393 + }
394 + if(!Array.isArray(source.items)||source.items.length===0||
395 + source.items.some(x=>!Number.isSafeInteger(x.qty)||x.qty<=0||
396 + !Number.isSafeInteger(x.price)||x.price<0||
397 + !Number.isSafeInteger(x.lineTotal)||x.lineTotal!==x.qty*x.price))
398 + throw new Error('مقدار یا قیمت ردیف فروش با قرارداد مالی ریالی سازگار نیست.');
399 +}
400 +async function finoraStage3SyncSourceOnly(source){
401 + const key='invoices|'+source.id;
402 + const payload=stripOwner(source),snapshot=JSON.stringify(payload);
403 + let deadline=Date.now()+8000;
404 + while(syncRunning&&Date.now()<deadline)
405 + await new Promise(resolve=>setTimeout(resolve,100));
406 + if(syncRunning)throw new Error('همگام‌سازی دیگری در جریان است؛ ابتدا وضعیت را بررسی کنید.');
407 + if(syncSnap.get(key)===snapshot)return;
408 + const expected=versionSnap.get(key)||0;
409 + if(!Number.isSafeInteger(expected)||expected<0)
410 + throw new Error('نسخه معتبر پیش‌نویس فروش مشخص نیست.');
411 + const {data,error}=await sb.rpc('finora_sync_records_v2',{
412 + p_upserts:[{collection:'invoices',id:source.id,data:payload,expected_version:expected}],
413 + p_deletes:[]
414 + });
415 + if(error)throw new Error('ثبت پیش‌نویس روی سرور تأیید نشد: '+error.message);
416 + const ack=(data?.upserts||[]).find(x=>x.collection==='invoices'&&x.id===source.id);
417 + if(!Number.isSafeInteger(Number(ack?.version))||Number(ack.version)<1)
418 + throw new Error('نسخه نهایی پیش‌نویس از سرور دریافت نشد.');
419 + syncSnap.set(key,snapshot);versionSnap.set(key,Number(ack.version));
420 +}
421 +async function finoraStage3FinalizeSaleServer(source){
422 + if(finoraSaleServerInFlight.has(source.id))return finoraSaleServerInFlight.get(source.id);
423 + const job=(async()=>{
424 + if(typeof navigator!=='undefined'&&navigator.onLine===false)
425 + throw new Error('قطعی‌سازی سروری نیازمند اتصال اینترنت است؛ پیش‌نویس محفوظ است.');
426 + finoraStage3SaleV1Valid(source);
427 + const fy=jeFiscalForDate(source.date);
428 + if(!fy||fy.status==='locked'||fy.companyId&&fy.companyId!==source.companyId)
429 + throw new Error('سال مالی باز و هم‌شرکت برای این فاکتور موجود نیست.');
430 + // Existing unsaved nonfinancial work is NOT flushed or discarded here.
431 + await finoraStage3SyncSourceOnly(source);
432 + const voucherId='JVS_'+source.id;
433 + const params={p_organization_id:finoraManualOrg(),
434 + p_voucher_id:voucherId,p_source_collection:'invoices',p_source_id:source.id,
435 + p_header:{companyId:source.companyId,fiscalYearId:fy.id,
436 + date:source.date,sourceType:'sale',sourceId:source.id,
437 + sourceVersion:String(source.accountingVersion)},p_lines:null};
438 + let timer,result;
439 + try{
440 + const out=await Promise.race([
441 + sb.rpc('finora_journal_autopost',params),
442 + new Promise((_,reject)=>{
443 + timer=setTimeout(()=>reject(new Error('FINORA_STAGE3_POST_TIMEOUT')),12000);
444 + })
445 + ]);
446 + if(out.error)throw new Error(out.error.message||'سرور ثبت فروش را رد کرد.');
447 + result=out.data;
448 + }catch(e){
449 + // Unknown acknowledgement: same deterministic voucher ID, targeted read
450 + // only. Never create a second financial voucher or globally pullAll().
451 + try{
452 + const known=await finoraManualReload(voucherId);
453 + if(known?.status==='posted'){
454 + refreshAllSurfaces();return known.id;
455 + }
456 + }catch(readError){console.warn('Stage3 targeted source recovery failed',readError);}
457 + throw new Error('وضعیت قطعی‌سازی فروش نامشخص است؛ پیش از تلاش دوباره فقط سند متناظر را بررسی کنید: '+e.message);
458 + }finally{if(timer)clearTimeout(timer);}
459 + const posted=result?.voucher;
460 + if(posted?.status!=='posted'||!posted.id||!Number.isSafeInteger(Number(result.contractVersion)))
461 + throw new Error('سرور پاسخ قطعی و نسخه قرارداد مالی را تأیید نکرد.');
462 + const local=await finoraManualReload(posted.id);
463 + if(local?.status!=='posted'||local.sourceId!==source.id||
464 + local.sourceType!=='sale'||local.companyId!==source.companyId)
465 + throw new Error('تطبیق سند قطعی فروش با منبع تأیید نشد.');
466 + refreshAllSurfaces();return posted.id;
467 + })().finally(()=>finoraSaleServerInFlight.delete(source.id));
468 + finoraSaleServerInFlight.set(source.id,job);
469 + return job;
470 +}
471 +
472 async function finalizeInvoiceDocument(invoiceId){
473 if(!requireWrite()||!currentUser)throw new Error('مجوز قطعی‌سازی ندارید.');
474 const inv=getMyInvoices().find(i=>i.id===invoiceId);