@davoodmehraban89 / Factor-easy / commits / 46fe0c7
Fork 0

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

Add Phase 5 complementary ERP domain slices [skip ci]

davoodmehraban89 committed Sep 29, 2026 at 20:45 UTC 46fe0c74e853137c817250112200ae2334fe3363
5 files changed +202
docs/PHASE_5_VERIFICATION.md new
+21
@@ -0,0 +1,21 @@
1 +# Phase 5 — Complementary ERP & Integrations
2 +
3 +Scope implemented as vertical slices:
4 +- warehouse master, immutable posted stock movements, transfers, stock count adjustments and derived purchase/sale movements
5 +- weighted-average inventory valuation
6 +- fixed-asset register and straight-line periodic depreciation with balanced journal posting
7 +- currency master, dated exchange rates and deterministic conversion rule
8 +- cost-center master prepared as an entity-backed accounting dimension
9 +- full v5 backup payload plus non-destructive restore validation/preview and import audit batches
10 +- integration connection metadata and durable outbox; browser stores no integration secrets
11 +- Phase 5 audit collection and production guards/indexes
12 +
13 +Accounting boundaries:
14 +- posted journal remains accounting truth
15 +- posted stock/count/depreciation records are immutable at the database boundary
16 +- stock transfers do not create value-changing journal entries
17 +- depreciation posts debit 6201 / credit 1502 after required accounts are created
18 +- purchase/sale quantities feed operational stock only for the configured default warehouse; explicit warehouse selection on source documents is a future enhancement
19 +- external webhook delivery is intentionally server-side architecture only; browser outbox export is available, but live third-party delivery is NOT VERIFIED
20 +
21 +Verification requires syntax/static checks, Phase 5 behavioral scenarios, real-DOM smoke, Supabase migration/RLS/advisors, and final-head CI.
js/phase5-domain.js new
+31
@@ -0,0 +1,31 @@
1 +/* Phase 5 pure domain rules — deterministic and DOM-free */
2 +(function(root){
3 +'use strict';
4 +const num=v=>Number(v)||0;
5 +function stockFromEvents(events){return (events||[]).reduce((q,e)=>q+num(e.delta),0)}
6 +function weightedAverage(openingQty,openingUnitCost,receipts){
7 + let qty=Math.max(0,num(openingQty)),value=qty*Math.max(0,num(openingUnitCost));
8 + for(const r of receipts||[]){const q=Math.max(0,num(r.qty)),c=Math.max(0,num(r.unitCost));qty+=q;value+=q*c}
9 + return qty>0?value/qty:0;
10 +}
11 +function monthlyDepreciation(cost,salvage,usefulMonths){
12 + cost=Math.max(0,num(cost));salvage=Math.max(0,num(salvage));usefulMonths=Math.max(1,Math.trunc(num(usefulMonths)||1));
13 + if(salvage>cost)throw new Error('salvage exceeds cost');
14 + return (cost-salvage)/usefulMonths;
15 +}
16 +function convert(amount,rate){rate=num(rate);if(rate<=0)throw new Error('invalid exchange rate');return num(amount)*rate}
17 +function validateMovement(m){
18 + if(!m||!['opening','adjustment_in','adjustment_out','transfer'].includes(m.kind))throw new Error('invalid movement kind');
19 + if(!m.productId||!m.warehouseId||num(m.qty)<=0)throw new Error('invalid movement');
20 + if(m.kind==='transfer'&&(!m.toWarehouseId||m.toWarehouseId===m.warehouseId))throw new Error('invalid transfer');
21 + return true;
22 +}
23 +function validateRestore(payload,allowed){
24 + if(!payload||typeof payload!=='object'||Array.isArray(payload))throw new Error('invalid backup');
25 + const keys=Object.keys(payload).filter(k=>!['user','exportedAt','formatVersion','checksum'].includes(k));
26 + const bad=keys.filter(k=>!allowed.includes(k)||!Array.isArray(payload[k]));
27 + if(bad.length)throw new Error('unsupported backup collections: '+bad.join(','));
28 + return true;
29 +}
30 +root.P5Domain={num,stockFromEvents,weightedAverage,monthlyDepreciation,convert,validateMovement,validateRestore};
31 +})(typeof window!=='undefined'?window:globalThis);
js/phase5-enterprise.js new
+109
@@ -0,0 +1,109 @@
1 +/* Phase 5 — complementary ERP: inventory, assets, FX, analytics, import/backup and integration outbox */
2 +const P5_LABELS={opening:'افتتاحیه',adjustment_in:'تعدیل افزایشی',adjustment_out:'تعدیل کاهشی',transfer:'انتقال'};
3 +function p5Owned(k){const cid=afCompanyId();return(datastore[k]||[]).filter(x=>x.ownerUserId===currentUser?.id&&(!x.companyId||x.companyId===cid))}
4 +function getMyWarehouses(){return p5Owned('warehouses')} function getMyStockMovements(){return p5Owned('stockMovements')}
5 +function getMyInventoryCounts(){return p5Owned('inventoryCounts')} function getMyFixedAssets(){return p5Owned('fixedAssets')}
6 +function getMyAssetDepreciations(){return p5Owned('assetDepreciations')} function getMyCurrencies(){return p5Owned('currencies')}
7 +function getMyExchangeRates(){return p5Owned('exchangeRates')} function getMyCostCenters(){return p5Owned('costCenters')}
8 +function getMyImportBatches(){return p5Owned('importBatches')} function getMyIntegrationConnections(){return p5Owned('integrationConnections')}
9 +function getMyIntegrationOutbox(){return p5Owned('integrationOutbox')} function getMyPhase5Audit(){return p5Owned('phase5Audit')}
10 +function p5Id(p){return p+'_'+Date.now().toString(36)+'_'+Math.random().toString(36).slice(2,7)}
11 +function p5Audit(action,entity,entityId,before,after){if(!currentUser)return;datastore.phase5Audit.push({id:p5Id('P5A'),ownerUserId:currentUser.id,companyId:afCompanyId(),action,entity,entityId,before:before||null,after:after||null,at:new Date().toISOString()})}
12 +function p5Need(){if(!requireWrite())return'';const c=afCompanyId();if(!c)alert('ابتدا شرکت فعال را انتخاب کنید.');return c}
13 +function p5EnsureSeed(){
14 + if(!currentUser||!afCompanyId())return;let ch=false,cid=afCompanyId();
15 + if(!getMyWarehouses().length){datastore.warehouses.push({id:p5Id('WH'),ownerUserId:currentUser.id,companyId:cid,code:'MAIN',name:'انبار اصلی',active:true,createdAt:new Date().toISOString()});ch=true}
16 + if(!getMyCurrencies().some(x=>x.code==='IRR')){datastore.currencies.push({id:p5Id('CUR'),ownerUserId:currentUser.id,companyId:cid,code:'IRR',title:'ریال ایران',symbol:'ریال',decimals:0,base:true,active:true});ch=true}
17 + const s=getMySettings();if(!s.baseCurrencyCode){s.baseCurrencyCode='IRR';ch=true}if(!s.inventoryCostMethod){s.inventoryCostMethod='weighted_average';ch=true}
18 + if(ch)saveDatastore();
19 +}
20 +function p5DefaultWarehouse(){p5EnsureSeed();return getMyWarehouses().find(x=>x.id===getMySettings().defaultWarehouseId)||getMyWarehouses().find(x=>x.active!==false)||null}
21 +function p5OperationalEvents(productId,warehouseId){
22 + const wh=p5DefaultWarehouse();if(!wh||warehouseId!==wh.id)return[];
23 + const out=[];
24 + getMyPurchases().forEach(d=>(d.items||[]).forEach(i=>{if((i.prodId||i.productId)===productId)out.push({delta:Number(i.qty??i.quantity)||0,qty:Number(i.qty??i.quantity)||0,unitCost:Number(i.price??i.unitPrice)||0,date:d.date||'',source:'purchase',sourceId:d.id})}));
25 + getMyInvoices().forEach(d=>(d.items||[]).forEach(i=>{if((i.prodId||i.productId)===productId)out.push({delta:-(Number(i.qty??i.quantity)||0),qty:Number(i.qty??i.quantity)||0,unitCost:0,date:d.date||'',source:'sale',sourceId:d.id})}));
26 + return out;
27 +}
28 +function p5ManualEvents(productId,warehouseId){
29 + const out=[];getMyStockMovements().filter(m=>m.status==='posted'&&m.productId===productId).forEach(m=>{
30 + const q=Number(m.qty)||0;if(m.kind==='transfer'){if(m.warehouseId===warehouseId)out.push({delta:-q,...m});if(m.toWarehouseId===warehouseId)out.push({delta:q,...m});}
31 + else if(m.warehouseId===warehouseId)out.push({delta:m.kind==='adjustment_out'?-q:q,...m});
32 + });return out;
33 +}
34 +function p5Stock(productId,warehouseId){return P5Domain.stockFromEvents([...p5OperationalEvents(productId,warehouseId),...p5ManualEvents(productId,warehouseId)])}
35 +function p5AverageCost(productId){
36 + const p=getMyProducts().find(x=>x.id===productId);if(!p)return 0;const wh=p5DefaultWarehouse();if(!wh)return Number(p.buy_price)||0;
37 + const opening=getMyStockMovements().filter(m=>m.status==='posted'&&m.productId===productId&&m.warehouseId===wh.id&&m.kind==='opening');
38 + const oq=opening.reduce((s,m)=>s+(Number(m.qty)||0),0),oc=oq?opening.reduce((s,m)=>s+(Number(m.qty)||0)*(Number(m.unitCost)||0),0)/oq:(Number(p.buy_price)||0);
39 + const receipts=[];getMyPurchases().forEach(d=>(d.items||[]).forEach(i=>{if((i.prodId||i.productId)===productId)receipts.push({qty:Number(i.qty??i.quantity)||0,unitCost:Number(i.price??i.unitPrice)||0})}));
40 + getMyStockMovements().filter(m=>m.status==='posted'&&m.productId===productId&&m.kind==='adjustment_in').forEach(m=>receipts.push({qty:m.qty,unitCost:m.unitCost}));
41 + return P5Domain.weightedAverage(oq,oc,receipts);
42 +}
43 +function p5InventorySnapshot(){p5EnsureSeed();return getMyProducts().filter(p=>p.type!=='service').flatMap(p=>getMyWarehouses().filter(w=>w.active!==false).map(w=>({product:p,warehouse:w,qty:p5Stock(p.id,w.id),avgCost:p5AverageCost(p.id)})))}
44 +function p5SaveWarehouse(){
45 + const cid=p5Need();if(!cid)return;const code=document.getElementById('p5-wh-code').value.trim().toUpperCase(),name=document.getElementById('p5-wh-name').value.trim();if(!code||!name)return alert('کد و نام انبار الزامی است.');if(getMyWarehouses().some(x=>x.code===code))return alert('کد انبار تکراری است.');
46 + const r={id:p5Id('WH'),ownerUserId:currentUser.id,companyId:cid,code,name,active:true,createdAt:new Date().toISOString()};datastore.warehouses.push(r);p5Audit('create','warehouse',r.id,null,r);saveDatastore();p5RenderInventory();
47 +}
48 +function p5PostMovement(){
49 + const cid=p5Need();if(!cid)return;const m={id:p5Id('SM'),ownerUserId:currentUser.id,companyId:cid,kind:document.getElementById('p5-mv-kind').value,productId:document.getElementById('p5-mv-product').value,warehouseId:document.getElementById('p5-mv-from').value,toWarehouseId:document.getElementById('p5-mv-to').value,qty:Number(toEnDigits(document.getElementById('p5-mv-qty').value))||0,unitCost:Number(toEnDigits(document.getElementById('p5-mv-cost').value))||0,date:document.getElementById('p5-mv-date').value||getJalaliNumeric(),reference:document.getElementById('p5-mv-ref').value.trim(),status:'posted',postedAt:new Date().toISOString()};
50 + try{P5Domain.validateMovement(m);if(['adjustment_out','transfer'].includes(m.kind)&&p5Stock(m.productId,m.warehouseId)<m.qty)throw new Error('موجودی انبار برای خروج کافی نیست.');}catch(e){return alert(e.message)}
51 + datastore.stockMovements.push(m);p5Audit('post','stockMovement',m.id,null,m);saveDatastore();p5RenderInventory();
52 +}
53 +function p5SaveCount(){
54 + const cid=p5Need();if(!cid)return;const productId=document.getElementById('p5-count-product').value,warehouseId=document.getElementById('p5-count-wh').value,physicalQty=Number(toEnDigits(document.getElementById('p5-count-qty').value));if(!productId||!warehouseId||!Number.isFinite(physicalQty)||physicalQty<0)return alert('اطلاعات شمارش معتبر نیست.');
55 + const systemQty=p5Stock(productId,warehouseId),diff=physicalQty-systemQty,r={id:p5Id('IC'),ownerUserId:currentUser.id,companyId:cid,productId,warehouseId,date:getJalaliNumeric(),systemQty,physicalQty,difference:diff,status:'posted',postedAt:new Date().toISOString()};datastore.inventoryCounts.push(r);
56 + if(diff){datastore.stockMovements.push({id:p5Id('SM'),ownerUserId:currentUser.id,companyId:cid,kind:diff>0?'adjustment_in':'adjustment_out',productId,warehouseId,toWarehouseId:'',qty:Math.abs(diff),unitCost:p5AverageCost(productId),date:r.date,reference:'انبارگردانی '+r.id,status:'posted',sourceType:'inventory_count',sourceId:r.id,postedAt:r.postedAt})}
57 + p5Audit('post','inventoryCount',r.id,null,r);saveDatastore();p5RenderInventory();
58 +}
59 +function p5EnsureAssetAccounts(){
60 + const cid=afCompanyId();if(!cid)return;const specs=[['15','دارایی‌های ثابت','subsidiary','debit','1'],['1501','دارایی ثابت مشهود','detail','debit','15'],['1502','استهلاک انباشته دارایی ثابت','detail','credit','15'],['62','هزینه استهلاک','subsidiary','debit','6'],['6201','هزینه استهلاک دارایی ثابت','detail','debit','62']];const byCode=Object.fromEntries(getMyAccounts().map(a=>[a.code,a]));let ch=false;
61 + specs.forEach(([code,title,level,normalBalance,parentCode])=>{if(byCode[code])return;const parent=byCode[parentCode];if(!parent)return;const a={id:afId('ACC'),ownerUserId:currentUser.id,companyId:cid,code,title,level,parentId:parent.id,normalBalance,postingAllowed:level==='detail',active:true,template:'phase5'};datastore.accounts.push(a);byCode[code]=a;ch=true});if(ch)saveDatastore();
62 +}
63 +function p5SaveAsset(){
64 + const cid=p5Need();if(!cid)return;const code=document.getElementById('p5-asset-code').value.trim(),name=document.getElementById('p5-asset-name').value.trim(),cost=Number(toEnDigits(document.getElementById('p5-asset-cost').value))||0,salvage=Number(toEnDigits(document.getElementById('p5-asset-salvage').value))||0,usefulMonths=Number(toEnDigits(document.getElementById('p5-asset-months').value))||0,acquisitionDate=document.getElementById('p5-asset-date').value||getJalaliNumeric();if(!code||!name||cost<=0||usefulMonths<=0||salvage>cost)return alert('اطلاعات دارایی معتبر نیست.');if(getMyFixedAssets().some(x=>x.code===code))return alert('کد دارایی تکراری است.');
65 + const a={id:p5Id('FA'),ownerUserId:currentUser.id,companyId:cid,code,name,cost,salvage,usefulMonths,acquisitionDate,status:'active',createdAt:new Date().toISOString()};datastore.fixedAssets.push(a);p5Audit('create','fixedAsset',a.id,null,a);p5EnsureAssetAccounts();saveDatastore();p5RenderAssets();
66 +}
67 +function p5RunDepreciation(assetId){
68 + const cid=p5Need(),a=getMyFixedAssets().find(x=>x.id===assetId);if(!cid||!a||a.status!=='active')return;const period=prompt('دوره استهلاک (مثلاً 1405/07):',String(getJalaliNumeric()).slice(0,7));if(!period)return;if(getMyAssetDepreciations().some(x=>x.assetId===assetId&&x.period===period&&x.status==='posted'))return alert('استهلاک این دوره قبلاً ثبت شده است.');
69 + const monthly=P5Domain.monthlyDepreciation(a.cost,a.salvage,a.usefulMonths),posted=getMyAssetDepreciations().filter(x=>x.assetId===assetId&&x.status==='posted').reduce((s,x)=>s+(Number(x.amount)||0),0),amount=Math.max(0,Math.min(monthly,a.cost-a.salvage-posted));if(amount<=0)return alert('دارایی به سقف استهلاک رسیده است.');
70 + p5EnsureAssetAccounts();const dep=jeAccountByCode('6201'),acc=jeAccountByCode('1502');if(!dep||!acc)return alert('حساب‌های استهلاک در کدینگ قابل ایجاد نیستند.');
71 + const r={id:p5Id('DEP'),ownerUserId:currentUser.id,companyId:cid,assetId,period,amount,status:'draft',createdAt:new Date().toISOString()};datastore.assetDepreciations.push(r);
72 + try{const v=jeCreateDraft({date:period+'/29',description:'استهلاک '+a.name+' — '+period,sourceType:'asset_depreciation',sourceId:r.id,lines:[{accountId:dep.id,debit:amount,credit:0,description:'هزینه استهلاک',dimensions:[]},{accountId:acc.id,debit:0,credit:amount,description:'استهلاک انباشته',dimensions:[]}]});jePost(v.id);r.status='posted';r.journalVoucherId=v.id;r.postedAt=new Date().toISOString();p5Audit('post','assetDepreciation',r.id,null,r);saveDatastore();p5RenderAssets()}catch(e){datastore.assetDepreciations=datastore.assetDepreciations.filter(x=>x.id!==r.id);saveDatastore();alert(e.message)}
73 +}
74 +function p5SaveCurrency(){
75 + const cid=p5Need();if(!cid)return;const code=document.getElementById('p5-cur-code').value.trim().toUpperCase(),title=document.getElementById('p5-cur-title').value.trim(),symbol=document.getElementById('p5-cur-symbol').value.trim();if(!/^[A-Z]{3}$/.test(code)||!title)return alert('کد سه‌حرفی و عنوان ارز الزامی است.');if(getMyCurrencies().some(x=>x.code===code))return alert('این ارز قبلاً تعریف شده است.');const r={id:p5Id('CUR'),ownerUserId:currentUser.id,companyId:cid,code,title,symbol:symbol||code,decimals:2,base:false,active:true};datastore.currencies.push(r);p5Audit('create','currency',r.id,null,r);saveDatastore();p5RenderCurrency();
76 +}
77 +function p5SaveRate(){
78 + const cid=p5Need();if(!cid)return;const currencyCode=document.getElementById('p5-rate-cur').value,date=document.getElementById('p5-rate-date').value||getJalaliNumeric(),rate=Number(toEnDigits(document.getElementById('p5-rate-value').value))||0;if(!currencyCode||currencyCode==='IRR'||rate<=0)return alert('ارز و نرخ معتبر انتخاب کنید.');const old=getMyExchangeRates().find(x=>x.currencyCode===currencyCode&&x.date===date);if(old)return alert('برای این ارز و تاریخ نرخ ثبت شده است.');const r={id:p5Id('FX'),ownerUserId:currentUser.id,companyId:cid,currencyCode,date,rate,baseCurrencyCode:getMySettings().baseCurrencyCode||'IRR',createdAt:new Date().toISOString()};datastore.exchangeRates.push(r);p5Audit('create','exchangeRate',r.id,null,r);saveDatastore();p5RenderCurrency();
79 +}
80 +function p5Rate(code,date){if(code===(getMySettings().baseCurrencyCode||'IRR'))return 1;const rows=getMyExchangeRates().filter(x=>x.currencyCode===code&&(!date||x.date<=date)).sort((a,b)=>String(b.date).localeCompare(String(a.date)));return Number(rows[0]?.rate)||0}
81 +function p5SaveCostCenter(){
82 + const cid=p5Need();if(!cid)return;const code=document.getElementById('p5-cc-code').value.trim(),name=document.getElementById('p5-cc-name').value.trim();if(!code||!name)return alert('کد و عنوان مرکز هزینه الزامی است.');if(getMyCostCenters().some(x=>x.code===code))return alert('کد تکراری است.');const r={id:p5Id('CC'),ownerUserId:currentUser.id,companyId:cid,code,name,active:true};datastore.costCenters.push(r);p5Audit('create','costCenter',r.id,null,r);saveDatastore();p5RenderDataCenter();
83 +}
84 +function p5BackupPayload(){const o={formatVersion:5,user:currentUser?.username,exportedAt:new Date().toISOString()};COLLS.forEach(k=>o[k]=(datastore[k]||[]).filter(x=>x.ownerUserId===currentUser?.id).map(x=>{const y={...x};delete y.ownerUserId;return y}));return o}
85 +function p5ExportBackup(){const blob=new Blob([JSON.stringify(p5BackupPayload(),null,2)],{type:'application/json'}),a=document.createElement('a');a.href=URL.createObjectURL(blob);a.download='finora-full-backup-'+Date.now()+'.json';a.click();setTimeout(()=>URL.revokeObjectURL(a.href),500)}
86 +function p5PreviewRestore(event){
87 + const file=event.target.files[0];if(!file)return;const r=new FileReader();r.onload=()=>{try{const p=JSON.parse(r.result);P5Domain.validateRestore(p,COLLS);const counts=COLLS.filter(k=>Array.isArray(p[k])&&p[k].length).map(k=>k+': '+p[k].length);document.getElementById('p5-import-preview').textContent='پیش‌نمایش معتبر — '+counts.join(' | ');datastore.importBatches.push({id:p5Id('IMP'),ownerUserId:currentUser.id,companyId:afCompanyId(),fileName:file.name,mode:'preview',counts:Object.fromEntries(COLLS.map(k=>[k,(p[k]||[]).length])),status:'validated',createdAt:new Date().toISOString()});saveDatastore()}catch(e){document.getElementById('p5-import-preview').textContent='نامعتبر: '+e.message}};r.readAsText(file)
88 +}
89 +function p5SaveIntegration(){
90 + const cid=p5Need();if(!cid)return;const name=document.getElementById('p5-int-name').value.trim(),kind=document.getElementById('p5-int-kind').value,endpoint=document.getElementById('p5-int-endpoint').value.trim();if(!name)return alert('نام اتصال الزامی است.');if(endpoint&&!/^https:\/\//i.test(endpoint))return alert('نشانی اتصال باید HTTPS باشد.');const r={id:p5Id('INT'),ownerUserId:currentUser.id,companyId:cid,name,kind,endpoint,active:true,secretStored:false,createdAt:new Date().toISOString()};datastore.integrationConnections.push(r);p5Audit('create','integrationConnection',r.id,null,r);saveDatastore();p5RenderIntegrations();
91 +}
92 +function p5QueueEvent(connectionId,eventType){
93 + const cid=p5Need(),c=getMyIntegrationConnections().find(x=>x.id===connectionId);if(!cid||!c)return;const r={id:p5Id('OUT'),ownerUserId:currentUser.id,companyId:cid,connectionId,eventType,payload:{companyId:cid,generatedAt:new Date().toISOString()},status:'pending',attempts:0,createdAt:new Date().toISOString()};datastore.integrationOutbox.push(r);p5Audit('queue','integrationOutbox',r.id,null,r);saveDatastore();p5RenderIntegrations();
94 +}
95 +function p5ExportOutbox(id){const r=getMyIntegrationOutbox().find(x=>x.id===id);if(!r)return;const b=new Blob([JSON.stringify(r,null,2)],{type:'application/json'}),a=document.createElement('a');a.href=URL.createObjectURL(b);a.download='finora-outbox-'+id+'.json';a.click();setTimeout(()=>URL.revokeObjectURL(a.href),500)}
96 +function p5Options(rows,label='name'){return rows.map(x=>'<option value="'+esc(x.id)+'">'+esc(x.code?x.code+' — ':'')+esc(x[label]||x.title||'')+'</option>').join('')}
97 +function p5RenderInventory(){
98 + const root=document.getElementById('p5-inventory-root');if(!root)return;p5EnsureSeed();const wh=getMyWarehouses().filter(x=>x.active!==false),goods=getMyProducts().filter(x=>x.type!=='service'),snap=p5InventorySnapshot();
99 + root.innerHTML='<div class="grid-kpi"><div class="kpi-unit"><div><div class="kpi-lbl">انبار فعال</div><div class="kpi-val">'+wh.length.toLocaleString('fa-IR')+'</div></div></div><div class="kpi-unit"><div><div class="kpi-lbl">ارزش تقریبی موجودی</div><div class="kpi-val">'+Math.round(snap.reduce((s,x)=>s+x.qty*x.avgCost,0)).toLocaleString('fa-IR')+'</div></div></div></div>'+
100 + '<div class="card"><h3>تعریف انبار</h3><div class="form-row"><div class="form-group"><label>کد</label><input id="p5-wh-code" class="form-control"></div><div class="form-group"><label>نام</label><input id="p5-wh-name" class="form-control"></div></div><button class="btn btn-success" onclick="p5SaveWarehouse()">ثبت انبار</button></div>'+
101 + '<div class="card"><h3>گردش انبار</h3><div class="form-row"><div class="form-group"><label>نوع</label><select id="p5-mv-kind" class="form-control"><option value="opening">افتتاحیه</option><option value="adjustment_in">تعدیل افزایشی</option><option value="adjustment_out">تعدیل کاهشی</option><option value="transfer">انتقال</option></select></div><div class="form-group"><label>کالا</label><select id="p5-mv-product" class="form-control">'+p5Options(goods)+'</select></div><div class="form-group"><label>از انبار</label><select id="p5-mv-from" class="form-control">'+p5Options(wh)+'</select></div><div class="form-group"><label>به انبار (انتقال)</label><select id="p5-mv-to" class="form-control"><option value="">—</option>'+p5Options(wh)+'</select></div><div class="form-group"><label>مقدار</label><input id="p5-mv-qty" class="form-control"></div><div class="form-group"><label>بهای واحد</label><input id="p5-mv-cost" class="form-control"></div><div class="form-group"><label>تاریخ</label><input id="p5-mv-date" class="form-control" value="'+esc(getJalaliNumeric())+'"></div><div class="form-group"><label>مرجع</label><input id="p5-mv-ref" class="form-control"></div></div><button class="btn btn-primary" onclick="p5PostMovement()">ثبت قطعی گردش</button></div>'+
102 + '<div class="card"><h3>انبارگردانی</h3><div class="form-row"><div class="form-group"><label>کالا</label><select id="p5-count-product" class="form-control">'+p5Options(goods)+'</select></div><div class="form-group"><label>انبار</label><select id="p5-count-wh" class="form-control">'+p5Options(wh)+'</select></div><div class="form-group"><label>موجودی شمارش‌شده</label><input id="p5-count-qty" class="form-control"></div></div><button class="btn btn-secondary" onclick="p5SaveCount()">ثبت شمارش و تعدیل</button></div>'+
103 + '<div class="card"><h3>موجودی و بهای میانگین موزون</h3><div class="table-responsive"><table><thead><tr><th>کالا</th><th>انبار</th><th>موجودی</th><th>میانگین بها</th><th>ارزش</th></tr></thead><tbody>'+snap.map(x=>'<tr><td>'+esc(x.product.name)+'</td><td>'+esc(x.warehouse.name)+'</td><td>'+x.qty.toLocaleString('fa-IR')+'</td><td>'+Math.round(x.avgCost).toLocaleString('fa-IR')+'</td><td>'+Math.round(x.qty*x.avgCost).toLocaleString('fa-IR')+'</td></tr>').join('')+'</tbody></table></div></div>';
104 +}
105 +function p5RenderAssets(){const root=document.getElementById('p5-assets-root');if(!root)return;const rows=getMyFixedAssets();root.innerHTML='<div class="card"><h3>ثبت دارایی ثابت</h3><div class="form-row"><div class="form-group"><label>کد</label><input id="p5-asset-code" class="form-control"></div><div class="form-group"><label>عنوان</label><input id="p5-asset-name" class="form-control"></div><div class="form-group"><label>بهای تمام‌شده</label><input id="p5-asset-cost" class="form-control"></div><div class="form-group"><label>ارزش اسقاط</label><input id="p5-asset-salvage" class="form-control" value="0"></div><div class="form-group"><label>عمر مفید (ماه)</label><input id="p5-asset-months" class="form-control" value="60"></div><div class="form-group"><label>تاریخ تحصیل</label><input id="p5-asset-date" class="form-control" value="'+esc(getJalaliNumeric())+'"></div></div><button class="btn btn-success" onclick="p5SaveAsset()">ثبت دارایی</button></div><div class="card"><h3>دفتر دارایی‌ها</h3><div class="table-responsive"><table><thead><tr><th>کد</th><th>دارایی</th><th>بها</th><th>استهلاک ثبت‌شده</th><th>ارزش دفتری</th><th>عملیات</th></tr></thead><tbody>'+rows.map(a=>{const d=getMyAssetDepreciations().filter(x=>x.assetId===a.id&&x.status==='posted').reduce((s,x)=>s+(Number(x.amount)||0),0);return '<tr><td>'+esc(a.code)+'</td><td>'+esc(a.name)+'</td><td>'+Number(a.cost).toLocaleString('fa-IR')+'</td><td>'+Math.round(d).toLocaleString('fa-IR')+'</td><td>'+Math.round(a.cost-d).toLocaleString('fa-IR')+'</td><td><button class="btn btn-secondary btn-inline" onclick="p5RunDepreciation(\''+a.id+'\')">ثبت استهلاک دوره</button></td></tr>'}).join('')+'</tbody></table></div></div>'}
106 +function p5RenderCurrency(){const root=document.getElementById('p5-currency-root');if(!root)return;p5EnsureSeed();const cs=getMyCurrencies(),rates=getMyExchangeRates().slice().sort((a,b)=>String(b.date).localeCompare(String(a.date)));root.innerHTML='<div class="card"><h3>ارزها</h3><div class="form-row"><div class="form-group"><label>کد ISO</label><input id="p5-cur-code" class="form-control" placeholder="USD"></div><div class="form-group"><label>عنوان</label><input id="p5-cur-title" class="form-control"></div><div class="form-group"><label>نماد</label><input id="p5-cur-symbol" class="form-control"></div></div><button class="btn btn-success" onclick="p5SaveCurrency()">ثبت ارز</button></div><div class="card"><h3>نرخ تبدیل به ارز پایه</h3><div class="form-row"><div class="form-group"><label>ارز</label><select id="p5-rate-cur" class="form-control">'+cs.filter(x=>!x.base).map(x=>'<option value="'+esc(x.code)+'">'+esc(x.code+' — '+x.title)+'</option>').join('')+'</select></div><div class="form-group"><label>تاریخ</label><input id="p5-rate-date" class="form-control" value="'+esc(getJalaliNumeric())+'"></div><div class="form-group"><label>نرخ</label><input id="p5-rate-value" class="form-control"></div></div><button class="btn btn-primary" onclick="p5SaveRate()">ثبت نرخ</button><div class="table-responsive" style="margin-top:14px"><table><thead><tr><th>ارز</th><th>تاریخ</th><th>نرخ</th></tr></thead><tbody>'+rates.map(x=>'<tr><td>'+esc(x.currencyCode)+'</td><td>'+esc(x.date)+'</td><td>'+Number(x.rate).toLocaleString('fa-IR')+'</td></tr>').join('')+'</tbody></table></div></div>'}
107 +function p5RenderDataCenter(){const root=document.getElementById('p5-data-root');if(!root)return;const cc=getMyCostCenters();root.innerHTML='<div class="card"><h3>مراکز هزینه و تحلیل</h3><div class="form-row"><div class="form-group"><label>کد</label><input id="p5-cc-code" class="form-control"></div><div class="form-group"><label>عنوان</label><input id="p5-cc-name" class="form-control"></div></div><button class="btn btn-success" onclick="p5SaveCostCenter()">ثبت مرکز هزینه</button><div class="table-responsive" style="margin-top:14px"><table><thead><tr><th>کد</th><th>عنوان</th><th>وضعیت</th></tr></thead><tbody>'+cc.map(x=>'<tr><td>'+esc(x.code)+'</td><td>'+esc(x.name)+'</td><td>فعال</td></tr>').join('')+'</tbody></table></div></div><div class="card"><h3>مرکز ورود و پشتیبان</h3><p style="color:var(--text-muted);margin:8px 0 14px">پشتیبان کامل نسخه ۵ همه مجموعه‌های مالی و عملیاتی را پوشش می‌دهد. بازگردانی ابتدا فقط اعتبارسنجی و پیش‌نمایش می‌شود.</p><div style="display:flex;gap:8px;flex-wrap:wrap"><button class="btn btn-secondary" onclick="p5ExportBackup()">دانلود پشتیبان کامل</button><label class="btn btn-secondary">اعتبارسنجی فایل پشتیبان<input type="file" accept=".json" style="display:none" onchange="p5PreviewRestore(event)"></label></div><div id="p5-import-preview" style="margin-top:12px;font-size:12px;color:var(--text-muted)"></div></div>'}
108 +function p5RenderIntegrations(){const root=document.getElementById('p5-integrations-root');if(!root)return;const cs=getMyIntegrationConnections(),out=getMyIntegrationOutbox().slice(-20).reverse();root.innerHTML='<div class="card"><h3>اتصالات و API</h3><p style="font-size:12px;color:var(--text-muted);margin-bottom:12px">در مرورگر هیچ Secret ذخیره نمی‌شود. اتصال‌ها متادیتا هستند و رویدادها از الگوی Outbox قابل تحویل به سرویس امن سمت سرور پیروی می‌کنند.</p><div class="form-row"><div class="form-group"><label>نام</label><input id="p5-int-name" class="form-control"></div><div class="form-group"><label>نوع</label><select id="p5-int-kind" class="form-control"><option value="webhook">Webhook</option><option value="tax">سامانه مالیاتی</option><option value="bank">بانک/پرداخت</option><option value="custom">سفارشی</option></select></div><div class="form-group"><label>Endpoint HTTPS</label><input id="p5-int-endpoint" class="form-control" dir="ltr"></div></div><button class="btn btn-success" onclick="p5SaveIntegration()">ثبت اتصال</button><div class="table-responsive" style="margin-top:14px"><table><thead><tr><th>نام</th><th>نوع</th><th>Endpoint</th><th>صف</th></tr></thead><tbody>'+cs.map(x=>'<tr><td>'+esc(x.name)+'</td><td>'+esc(x.kind)+'</td><td dir="ltr">'+esc(x.endpoint||'—')+'</td><td><button class="btn btn-secondary btn-inline" onclick="p5QueueEvent(\''+x.id+'\',\'manual.test\')">رویداد آزمایشی</button></td></tr>').join('')+'</tbody></table></div></div><div class="card"><h3>Integration Outbox</h3><div class="table-responsive"><table><thead><tr><th>رویداد</th><th>وضعیت</th><th>زمان</th><th>خروجی</th></tr></thead><tbody>'+out.map(x=>'<tr><td>'+esc(x.eventType)+'</td><td>'+esc(x.status)+'</td><td>'+esc(x.createdAt)+'</td><td><button class="btn btn-secondary btn-inline" onclick="p5ExportOutbox(\''+x.id+'\')">JSON</button></td></tr>').join('')+'</tbody></table></div></div>'}
109 +function p5Render(viewId){p5EnsureSeed();if(viewId==='view-inventory')p5RenderInventory();else if(viewId==='view-assets')p5RenderAssets();else if(viewId==='view-currency')p5RenderCurrency();else if(viewId==='view-data-center')p5RenderDataCenter();else if(viewId==='view-integrations')p5RenderIntegrations()}
scripts/phase5-behavior-check.mjs new
+13
@@ -0,0 +1,13 @@
1 +import fs from 'node:fs';import vm from 'node:vm';
2 +const src=fs.readFileSync('js/phase5-domain.js','utf8');const ctx={window:{}};vm.createContext(ctx);vm.runInContext(src,ctx);const D=ctx.window.P5Domain;
3 +const eq=(a,b,m)=>{if(Math.abs(a-b)>1e-9)throw new Error(m+': '+a+' != '+b)};
4 +eq(D.stockFromEvents([{delta:10},{delta:-3},{delta:2}]),9,'stock event balance');
5 +eq(D.weightedAverage(10,100,[{qty:10,unitCost:200}]),150,'weighted average');
6 +eq(D.monthlyDepreciation(1200,0,12),100,'straight-line depreciation');
7 +eq(D.monthlyDepreciation(1200,120,12),90,'salvage depreciation');
8 +eq(D.convert(10,600000),6000000,'fx conversion');
9 +D.validateMovement({kind:'transfer',productId:'P1',warehouseId:'W1',toWarehouseId:'W2',qty:1});
10 +let rejected=false;try{D.validateMovement({kind:'transfer',productId:'P1',warehouseId:'W1',toWarehouseId:'W1',qty:1})}catch{rejected=true}if(!rejected)throw new Error('same-warehouse transfer accepted');
11 +D.validateRestore({formatVersion:5,warehouses:[]},['warehouses']);rejected=false;try{D.validateRestore({evil:[]},['warehouses'])}catch{rejected=true}if(!rejected)throw new Error('unknown restore collection accepted');
12 +const app=fs.readFileSync('js/phase5-enterprise.js','utf8');for(const x of ['p5PostMovement','p5SaveCount','p5RunDepreciation','p5SaveRate','p5SaveCostCenter','p5PreviewRestore','p5QueueEvent','status:\'posted\''])if(!app.includes(x))throw new Error('Phase5 application invariant missing '+x);
13 +console.log('Phase 5 behavioral/domain scenarios passed.');
supabase/migrations/20260929123000_phase5_complementary_erp_collections.sql new
+28
@@ -0,0 +1,28 @@
1 +alter table public.records drop constraint if exists records_collection_check;
2 +alter table public.records add constraint records_collection_check check (collection = any (array[
3 +'companies','contacts','products','invoices','cheques','expenses','settings','purchases','payments',
4 +'fiscalYears','accounts','dimensionTypes','dimensionValues','accountDimensionRules','branches','projects','projectLinks',
5 +'postingProfiles','journalVouchers','journalLines','journalLineDimensions',
6 +'contracts','contractAmendments','contractParties','contractDeductions','guarantees','guaranteeEvents','contractStatements','phase4Audit',
7 +'warehouses','stockMovements','inventoryCounts','fixedAssets','assetDepreciations','currencies','exchangeRates','costCenters',
8 +'importBatches','integrationConnections','integrationOutbox','phase5Audit'
9 +]::text[]));
10 +
11 +create or replace function public.finora_guard_phase5_posted_records()
12 +returns trigger language plpgsql security invoker set search_path=public as $$
13 +begin
14 + if old.collection not in ('stockMovements','inventoryCounts','assetDepreciations') or coalesce(old.data->>'status','') <> 'posted' then
15 + return case when tg_op='DELETE' then old else new end;
16 + end if;
17 + if tg_op='UPDATE' and new.data=old.data then return new; end if;
18 + raise exception 'posted Phase 5 operational record is immutable';
19 +end $$;
20 +drop trigger if exists trg_finora_guard_phase5_posted_records on public.records;
21 +create trigger trg_finora_guard_phase5_posted_records before update or delete on public.records
22 +for each row execute function public.finora_guard_phase5_posted_records();
23 +
24 +create unique index if not exists ux_finora_warehouse_code on public.records(owner_id,(data->>'companyId'),upper(data->>'code')) where collection='warehouses';
25 +create unique index if not exists ux_finora_asset_code on public.records(owner_id,(data->>'companyId'),upper(data->>'code')) where collection='fixedAssets';
26 +create unique index if not exists ux_finora_currency_code on public.records(owner_id,(data->>'companyId'),upper(data->>'code')) where collection='currencies';
27 +create unique index if not exists ux_finora_exchange_rate_day on public.records(owner_id,(data->>'companyId'),(data->>'currencyCode'),(data->>'date')) where collection='exchangeRates';
28 +create unique index if not exists ux_finora_asset_depreciation_period on public.records(owner_id,(data->>'companyId'),(data->>'assetId'),(data->>'period')) where collection='assetDepreciations' and data->>'status'='posted';