سامانه صدور فاکتور و حسابداری
Mirrored from https://github.com/davoodmehraban89/Factor-easy.git
Synced Dec 3, 17:00 UTC
feat: complete accounting core P0 journal slice
* docs: start accounting core P0 slice * feat: complete accounting core P0 journal slice * docs: record accounting P0 PR evidence
davoodmehraban89 committed
Oct 7, 2026 at 01:51 UTC
b88f0f35902cc99ebd09c9fffcd5700ce759ac69
11 files changed
+134
-28
.github/workflows/quality.yml
+3
-1
@@ -32,6 +32,8 @@ jobs:
32
run: node scripts/phase3-check.mjs
33
- name: Phase 3 behavioral accounting scenarios
34
run: node scripts/phase3-behavior-check.mjs
35
+ - name: Accounting P0 dimensions and journal invariants
36
+ run: node scripts/accounting-p0-check.mjs
37
- name: Phase 4 accounting invariants
38
run: node scripts/phase4-behavior-check.mjs
39
- name: Phase 5 complementary ERP invariants
@@ -99,7 +101,7 @@ jobs:
101
- name: Real DOM smoke
102
run: |
103
python3 -m http.server 4173 >/tmp/finora-http.log 2>&1 &
102
- npx playwright test scripts/dom-smoke.spec.js scripts/platform-office.spec.js scripts/enterprise-license.spec.js scripts/enterprise-role.spec.js scripts/enterprise-invitation.spec.js scripts/enterprise-org-ux.spec.js scripts/identity-wave5a.spec.js scripts/identity-wave5b.spec.js scripts/identity-wave5c.spec.js scripts/branding-login.spec.js scripts/shell-scroll-ownership.spec.js scripts/office-slice-c1.spec.js scripts/office-slice-c2.spec.js scripts/office-slice-c3.spec.js scripts/office-slice-c4.spec.js scripts/office-slice-c5.spec.js scripts/office-slice-c6.spec.js scripts/office-slice-c7.spec.js scripts/office-slice-c8.spec.js scripts/office-slice-c8-runtime.spec.js scripts/request-workflow-d2.spec.js scripts/request-workflow-d3b.spec.js scripts/request-workflow-d3c.spec.js scripts/request-workflow-d4a.spec.js scripts/taxpayer-print.spec.js scripts/chart-completeness.spec.js scripts/pages-artifact.spec.js --reporter=line --workers=1
104
+ npx playwright test scripts/dom-smoke.spec.js scripts/platform-office.spec.js scripts/enterprise-license.spec.js scripts/enterprise-role.spec.js scripts/enterprise-invitation.spec.js scripts/enterprise-org-ux.spec.js scripts/identity-wave5a.spec.js scripts/identity-wave5b.spec.js scripts/identity-wave5c.spec.js scripts/branding-login.spec.js scripts/shell-scroll-ownership.spec.js scripts/office-slice-c1.spec.js scripts/office-slice-c2.spec.js scripts/office-slice-c3.spec.js scripts/office-slice-c4.spec.js scripts/office-slice-c5.spec.js scripts/office-slice-c6.spec.js scripts/office-slice-c7.spec.js scripts/office-slice-c8.spec.js scripts/office-slice-c8-runtime.spec.js scripts/request-workflow-d2.spec.js scripts/request-workflow-d3b.spec.js scripts/request-workflow-d3c.spec.js scripts/request-workflow-d4a.spec.js scripts/taxpayer-print.spec.js scripts/chart-completeness.spec.js scripts/accounting-p0-journal.spec.js scripts/pages-artifact.spec.js --reporter=line --workers=1
105
106
identity-wave5a-database:
107
runs-on: ubuntu-latest
PROJECT_STATE.md
+1
@@ -17,6 +17,7 @@ The latest user message is the sole source of new instructions. Read AGENTS.md t
17
## Current change ledger
18
| Date | Request / decision | Status | Evidence / next action |
19
|---|---|---|---|
20
+| 2026-10-07 | Owner directed autonomous continuation to finish the remaining Finora development backlog, starting with the agreed P0 accounting core: extensible analytical/floating dimensions, journal UX, context-driven posting rules and end-to-end accounting integration, then continue through remaining verified blockers without routine pauses. | **PR VERIFIED / MERGE PENDING** | P0 adds independent COST_CENTER analytics, role-driven dimension compatibility without rewriting posted history, strict per-fiscal-year journal numbers, voucher type/reference, generic dimension-to-legacy compatibility fields, independent project vs cost-center posting, copy-to-draft, account search, row copy, and live debit/credit/difference totals. Implementation head `de2c58a52cb36bfe54eeb3c90985cd6c94cae812`; PR #52 Quality `37539607474` SUCCESS including Accounting P0 invariant step and Real DOM smoke, Security `37539607498` SUCCESS. Local quality + phases 2-6 + Golden PASS. No schema/RLS/auth/role/destructive production data change. Next: merge after this evidence-state commit rechecks green, then verify main release/deploy exact SHA. |
21
| 2026-10-07 | Owner authorized implementation to completion of the researched commerce/accounting redesign: one invoice workspace in Commerce, context-driven reusable floating counterparties, purchase parity (quick supplier + Excel template), and selected-company factory reset that preserves the company. | **COMPLETED / MERGED / RELEASE VERIFIED** | Merged to `main` as `5ae9117c776a33a3cc39775c68ad0c10e13b9c44`. Push Quality run `37529032595` = success; Security `37529032630` = success; Release gate `37529230156` = success; exact gated Pages deployment `37529272934` = success and deployed the same SHA to `http://factoreasy.ir/`. Live HTML loads `js/commercial-rnd.js?v=20261007-commerce-r1`; live bundle contains factory-reset guard, quick supplier, and Excel-template code. PR Real-DOM/accounting gates were green. No production reset and no schema/RLS/auth/role mutation. |
22
| 2026-10-04 | Continue the recorded chart and taxpayer-reference correction after interrupted sessions. | **MERGED / CONTROLLED DOM + ACCOUNTING VERIFIED / GATED PAGES DEPLOYED** | 62 additive chart rows across all eight templates, including non-current assets and contra accounts; explicit preview/apply for compatible existing templates preserves old accounts and posted history. Actual supplied tax logo and reference-aligned totals/settlement layout; image-ready printing. Local chart invariants and 3 chart DOM tests passed; 2 print DOM tests plus single-page landscape PDF passed; accounting phases 2–6 and Golden passed. Full local DOM: 52/53 passed, Pages artifact failed on external ERR_CERT_AUTHORITY_INVALID; no gate weakened. PR #47 implementation SHA `db9e7f2375e914bfa9e78932e63222af68c4c9d3`: Quality `37170173739` and Security `37170173740` passed; inspected static job `111341365938` confirms 53/53 real-DOM tests, chart invariants, phases 2–6 and Golden passed, including Pages artifact. All three disposable DB jobs passed. Production recheck on 2026-10-04: 79 migrations, latest `20261003033540`; public RLS 18/18, private 3/10. See docs/CHART_OF_ACCOUNTS_RESEARCH_2026-10-03.md and docs/CHART_TAXPAYER_VERIFICATION_2026-10-03.md. No schema/RLS/auth/role or production record mutation. |
23
| 2026-10-03 | Owner requested continuation of unfinished work, deep Iranian chart-of-accounts research/completion (especially missing non-current assets), and exact taxpayer invoice layout matching the first supplied reference with the supplied official logo. | **REQUEST RECORDED / IMPLEMENTATION NOT VERIFIED** | PR #46 merged as `3085dce9d8f457e61aca6676f872737418116e7a`; Quality `37094979694`, Security `37094979835`; inspected job `111122956074`: 49 DOM tests and accounting gates passed. Live Supabase has 79 migrations including `20261003033540`; public RLS 18/18, private 3/10. Existing print exactness claim is superseded by owner-reported/reference-visible differences. Preserve historical account IDs/codes/postings; no schema/RLS/auth/role changes authorized by this request. |
index.html
+3
-3
@@ -904,11 +904,11 @@ body{background:#f6f9fc}
904
<style id="phase2-accounting-style">
905
.af-head{display:flex;justify-content:space-between;align-items:flex-start;gap:12px;margin-bottom:16px}.af-head h1{font-size:20px;color:#0f172a}.af-head p,.af-hint{font-size:12px;color:#64748b;margin-top:5px}.af-grid{display:grid;grid-template-columns:1fr 1fr;gap:14px}.af-space,.af-list{margin-top:14px}.af-chip{display:inline-flex;align-items:center;gap:6px;background:#eef7f8;color:#0b6874;border:1px solid #cce9ec;border-radius:999px;padding:6px 10px;margin:3px;font-size:11px}.af-chip button{border:0;background:transparent;color:#b91c1c;cursor:pointer;font-size:15px}.af-master-row{display:flex;align-items:center;justify-content:space-between;gap:10px;padding:10px;border-bottom:1px solid #edf1f5}.af-master-row:last-child{border-bottom:0}.af-master-row small{display:block;color:#64748b;margin-top:3px}.af-empty{text-align:center;padding:18px;color:#64748b}@media(max-width:820px){.af-grid{grid-template-columns:1fr}}
906
</style>
907
-<script src="js/accounting-foundation.js?v=20261003-chart-v4"></script>
908
-<script src="js/journal-engine.js?v=20260928-phase3-final"></script>
907
+<script src="js/accounting-foundation.js?v=20261007-p0-r1"></script>
908
+<script src="js/journal-engine.js?v=20261007-p0-r1"></script>
909
<script src="js/accounting-foundation-ui.js?v=20261003-chart-v4"></script>
910
<script src="js/accounting-foundation-render.js?v=20260928-phase2-v1"></script>
911
-<script src="js/journal-ui.js?v=20260928-phase3-final"></script>
911
+<script src="js/journal-ui.js?v=20261007-p0-r1"></script>
912
<script src="js/drilldown.js?v=20260928-drill-v10"></script>
913
<script src="js/phase4-contracting.js?v=20260929-phase4-v1"></script>
914
<script src="js/phase5-domain.js?v=20260929-phase5-v1"></script>
js/accounting-foundation.js
+11
-4
@@ -108,7 +108,7 @@ function afEnsureIranComplianceTemplateV3(){
108
company.accountingTemplate.complianceVersion=3;company.accountingTemplate.complianceMigratedAt=new Date().toISOString();if(changed)saveDatastore();else saveDatastore();
109
}
110
function afSeed(){
111
- if(!currentUser||!afCompanyId())return;afEnsureFloatingSlotCompatibility();afEnsureContractingPhase4Accounts();afEnsureIranComplianceTemplateV3();let ch=false,cid=afCompanyId();
111
+ if(!currentUser||!afCompanyId())return;afEnsureFloatingSlotCompatibility();afEnsureAccountingP0Compatibility();afEnsureContractingPhase4Accounts();afEnsureIranComplianceTemplateV3();let ch=false,cid=afCompanyId();
112
if(!getMyFiscalYears().length){const y=toEnDigits(String(getJalaliNumeric()).split('/')[0]);datastore.fiscalYears.push({id:afId('FY'),ownerUserId:currentUser.id,companyId:cid,title:'سال مالی '+y,startDate:y+'/01/01',endDate:y+'/12/29',status:'open',createdAt:new Date().toISOString()});ch=true}
113
if(ch)saveDatastore();
114
}
@@ -124,8 +124,14 @@ function afCreateDimension(cid,code,title,sourceEntity,maxDepth=1,slot=0){
124
}
125
function afEnsureFloatingSlotCompatibility(){
126
if(!currentUser||!afCompanyId())return false;const cid=afCompanyId(),company=getMyCompanies().find(x=>x.id===cid);if(!company)return false;let changed=false;
127
- const defs=[['BRANCH','شعبه','branch',1],['COUNTERPARTY','طرف حساب','contact',2],['PROJECT','پروژه','project',3],['CONTRACT','قرارداد / پیمان','contract',4]];
128
- defs.forEach(([code,title,source,slot])=>{let d=getMyDimensionTypes().find(x=>x.code===code);if(!d){d=afCreateDimension(cid,code,title,source,1,slot);changed=true}else if(Number(d.slot||0)!==slot){d.slot=slot;changed=true}});
127
+ const defs=[['BRANCH','شعبه','branch',1],['COUNTERPARTY','طرف حساب','contact',2],['PROJECT','پروژه','project',3],['CONTRACT','قرارداد / پیمان','contract',4],['COST_CENTER','مرکز هزینه','costCenter',0]];
128
+ defs.forEach(([code,title,source,slot])=>{let d=getMyDimensionTypes().find(x=>x.code===code);if(!d){d=afCreateDimension(cid,code,title,source,1,slot);changed=true}else if(slot&&Number(d.slot||0)!==slot){d.slot=slot;changed=true}});
129
+ if(changed)saveDatastore();return changed;
130
+}
131
+function afEnsureAccountingP0Compatibility(){
132
+ if(!currentUser||!afCompanyId())return false;const cid=afCompanyId(),dims=Object.fromEntries(getMyDimensionTypes().map(d=>[d.code,d])),used=id=>(datastore.journalLines||[]).some(l=>l.ownerUserId===currentUser.id&&(!l.companyId||l.companyId===cid)&&l.accountId===id);let changed=false;
133
+ const ensure=(a,d,app)=>{if(!a||!d)return;const existing=getMyAccountDimensionRules().find(r=>r.accountId===a.id&&r.dimensionTypeId===d.id);if(existing)return;const legacyRequired=app==='required'&&used(a.id);datastore.accountDimensionRules.push({id:afId('ADR'),ownerUserId:currentUser.id,companyId:cid,accountId:a.id,dimensionTypeId:d.id,applicability:legacyRequired?'optional':app,allowedValuesMode:'all',active:true,compatibilityMode:legacyRequired?'legacy-history-preserved':'recommended-p0'});changed=true};
134
+ getMyAccounts().filter(a=>a.active!==false&&a.postingAllowed).forEach(a=>{const role=a.systemRole||'';if(['receivable_control','payable_control'].includes(role))ensure(a,dims.COUNTERPARTY,'required');if(['cash_default','receivable_control','payable_control','revenue_default','purchase_default','expense_default','other_income_default'].includes(role))ensure(a,dims.BRANCH,'optional');if(['revenue_default','purchase_default','expense_default','other_income_default'].includes(role))ensure(a,dims.PROJECT,'optional');if(['purchase_default','expense_default'].includes(role))ensure(a,dims.COST_CENTER,'optional')});
135
if(changed)saveDatastore();return changed;
136
}
137
function afApplyTemplate(companyId,type){
@@ -139,12 +145,13 @@ function afApplyTemplate(companyId,type){
145
const party=afCreateDimension(companyId,'COUNTERPARTY','طرف حساب','contact',1,2);
146
const project=afCreateDimension(companyId,'PROJECT','پروژه','project',1,3);
147
const contract=afCreateDimension(companyId,'CONTRACT','قرارداد / پیمان','contract',1,4);
148
+ afCreateDimension(companyId,'COST_CENTER','مرکز هزینه','costCenter',1,0);
149
const cost=afCreateDimension(companyId,'COST_ELEMENT','عناصر هزینه','manual',3);
150
const addRule=(code,d,app)=>{const a=byCode[code];if(a&&!datastore.accountDimensionRules.some(x=>x.accountId===a.id&&x.dimensionTypeId===d.id))datastore.accountDimensionRules.push({id:afId('ADR'),ownerUserId:currentUser.id,companyId,accountId:a.id,dimensionTypeId:d.id,applicability:app,allowedValuesMode:'all',active:true})};
151
['1102','2101'].forEach(c=>addRule(c,party,'required'));['1101','4101','5101','6101','6102','6103'].forEach(c=>addRule(c,branch,'optional'));
152
if(type==='contracting'){['4301','5301','5302','1105','1106','1107','2104','2105','6109'].forEach(c=>{addRule(c,project,'required');addRule(c,contract,'required')})}
153
if(['service','manufacturing','contracting','professional'].includes(type)){['6101','6102','6103','5101'].forEach(c=>addRule(c,cost,'optional'))}
147
- company.activityType=type;company.accountingTemplate={type,appliedAt:new Date().toISOString(),version:3,chartVersion:4,complianceVersion:3,jurisdiction:'IR'};saveDatastore();if(typeof jeEnsureDefaultProfiles==='function')jeEnsureDefaultProfiles();return true;
154
+ company.activityType=type;company.accountingTemplate={type,appliedAt:new Date().toISOString(),version:3,chartVersion:4,complianceVersion:3,jurisdiction:'IR'};saveDatastore();afEnsureAccountingP0Compatibility();if(typeof jeEnsureDefaultProfiles==='function')jeEnsureDefaultProfiles();return true;
155
}finally{getMySettings().default_company_id=previous;saveDatastore()}
156
}
157
function afImportCell(row,names){for(const n of names){if(Object.prototype.hasOwnProperty.call(row,n)&&String(row[n]??'').trim()!=='')return String(row[n]).trim()}return ''}
js/journal-engine.js
+11
-6
@@ -42,11 +42,13 @@ function jeValidateLines(lines){
42
return {debit:dr,credit:cr};
43
}
44
function jeNextNumber(fiscalYearId){const nums=getMyJournalVouchers().filter(v=>v.fiscalYearId===fiscalYearId).map(v=>Number(v.number)||0);return String(Math.max(0,...nums)+1)}
45
+function jeVoucherNumberTaken(fiscalYearId,number,ignoreId=''){const n=String(number||'').trim();return !!n&&getMyJournalVouchers().some(v=>v.id!==ignoreId&&v.fiscalYearId===fiscalYearId&&String(v.number||'').trim()===n)}
46
+function jeDimensionValueBySource(assignments,sourceEntity){for(const d of assignments||[]){const t=getMyDimensionTypes().find(x=>x.id===d.dimensionTypeId);if(t?.sourceEntity===sourceEntity)return d.dimensionValueId||''}return''}
47
function jeCreateDraft(input){
46
- if(!requireWrite())throw new Error('write denied');const cid=afCompanyId(),fy=jeFiscalForDate(input.date);if(!cid||!fy)throw new Error('سال مالی متناظر با تاریخ سند پیدا نشد.');if(fy.status==='locked')throw new Error('سال مالی قفل است.');
47
- const sourceType=input.sourceType||'manual',sourceId=input.sourceId||'',sourceVersion=Number(input.sourceVersion||1);if(sourceId&&getMyJournalVouchers().some(x=>['posted','reversed'].includes(x.status)&&x.sourceType===sourceType&&x.sourceId===sourceId&&Number(x.sourceVersion||1)===sourceVersion))throw new Error('برای این رویداد منبع قبلاً سند قطعی ثبت شده است.');
48
- const totals=jeValidateLines(input.lines),id=afId('JV'),voucher={id,ownerUserId:currentUser.id,companyId:cid,fiscalYearId:fy.id,number:input.number||jeNextNumber(fy.id),date:input.date||getJalaliNumeric(),description:String(input.description||''),status:'draft',sourceType,sourceId,sourceVersion,totalDebit:totals.debit,totalCredit:totals.credit,createdAt:new Date().toISOString(),createdBy:currentUser.id};
49
- datastore.journalVouchers.push(voucher);input.lines.forEach((l,n)=>{const lineId=afId('JL');datastore.journalLines.push({id:lineId,ownerUserId:currentUser.id,companyId:cid,voucherId:id,lineNo:n+1,accountId:l.accountId,debit:jeNum(l.debit),credit:jeNum(l.credit),description:String(l.description||''),counterpartyId:l.counterpartyId||'',projectId:l.projectId||''});(l.dimensions||[]).forEach(d=>datastore.journalLineDimensions.push({id:afId('JLD'),ownerUserId:currentUser.id,companyId:cid,voucherId:id,journalLineId:lineId,dimensionTypeId:d.dimensionTypeId,dimensionValueId:d.dimensionValueId}))});saveDatastore();return voucher;
48
+ if(!requireWrite())throw new Error('write denied');const cid=afCompanyId(),date=input.date||getJalaliNumeric(),fy=jeFiscalForDate(date);if(!cid||!fy)throw new Error('سال مالی متناظر با تاریخ سند پیدا نشد.');if(fy.status==='locked')throw new Error('سال مالی قفل است.');
49
+ const sourceType=input.sourceType||'manual',sourceId=input.sourceId||'',sourceVersion=Number(input.sourceVersion||1),number=String(input.number||jeNextNumber(fy.id)).trim();if(!number)throw new Error('شماره سند الزامی است.');if(jeVoucherNumberTaken(fy.id,number))throw new Error('شماره سند در این سال مالی تکراری است.');if(sourceId&&getMyJournalVouchers().some(x=>['posted','reversed'].includes(x.status)&&x.sourceType===sourceType&&x.sourceId===sourceId&&Number(x.sourceVersion||1)===sourceVersion))throw new Error('برای این رویداد منبع قبلاً سند قطعی ثبت شده است.');
50
+ const totals=jeValidateLines(input.lines),id=afId('JV'),voucher={id,ownerUserId:currentUser.id,companyId:cid,fiscalYearId:fy.id,number,date,description:String(input.description||''),reference:String(input.reference||''),voucherType:String(input.voucherType||'manual'),status:'draft',sourceType,sourceId,sourceVersion,totalDebit:totals.debit,totalCredit:totals.credit,createdAt:new Date().toISOString(),createdBy:currentUser.id};
51
+ datastore.journalVouchers.push(voucher);input.lines.forEach((l,n)=>{const lineId=afId('JL'),dims=l.dimensions||[],counterpartyId=l.counterpartyId||jeDimensionValueBySource(dims,'contact'),projectId=l.projectId||jeDimensionValueBySource(dims,'project');datastore.journalLines.push({id:lineId,ownerUserId:currentUser.id,companyId:cid,voucherId:id,lineNo:n+1,accountId:l.accountId,debit:jeNum(l.debit),credit:jeNum(l.credit),description:String(l.description||''),counterpartyId,projectId});dims.forEach(d=>datastore.journalLineDimensions.push({id:afId('JLD'),ownerUserId:currentUser.id,companyId:cid,voucherId:id,journalLineId:lineId,dimensionTypeId:d.dimensionTypeId,dimensionValueId:d.dimensionValueId}))});saveDatastore();return voucher;
52
}
53
function jePost(voucherId){
54
if(!requireWrite())throw new Error('write denied');const v=getMyJournalVouchers().find(x=>x.id===voucherId);if(!v||v.status!=='draft')throw new Error('فقط سند پیشنویس قابل قطعیسازی است.');const fy=getMyFiscalYears().find(x=>x.id===v.fiscalYearId);if(!fy||fy.status==='locked')throw new Error('سال مالی قفل است.');
@@ -57,7 +59,10 @@ function jePost(voucherId){
59
function jeReverse(voucherId,date,reason){
60
if(!requireWrite())throw new Error('write denied');const v=getMyJournalVouchers().find(x=>x.id===voucherId);if(!v||v.status!=='posted')throw new Error('فقط سند قطعی قابل برگشت است.');if(v.reversalVoucherId)throw new Error('این سند قبلاً برگشت شده است.');
61
const lines=getMyJournalLines().filter(x=>x.voucherId===v.id).map(l=>({accountId:l.accountId,debit:l.credit,credit:l.debit,description:'برگشت: '+(l.description||v.description||''),dimensions:getMyJournalLineDimensions().filter(d=>d.journalLineId===l.id).map(d=>({dimensionTypeId:d.dimensionTypeId,dimensionValueId:d.dimensionValueId}))}));
60
- const rv=jeCreateDraft({date:date||getJalaliNumeric(),description:'برگشت سند '+v.number+(reason?' — '+reason:''),sourceType:'reversal',sourceId:v.id,lines});jePost(rv.id);v.status='reversed';v.reversalVoucherId=rv.id;v.reversedAt=new Date().toISOString();saveDatastore();return rv;
62
+ const rv=jeCreateDraft({date:date||getJalaliNumeric(),description:'برگشت سند '+v.number+(reason?' — '+reason:''),reference:v.reference||'',voucherType:'reversal',sourceType:'reversal',sourceId:v.id,lines});jePost(rv.id);v.status='reversed';v.reversalVoucherId=rv.id;v.reversedAt=new Date().toISOString();saveDatastore();return rv;
63
+}
64
+function jeCopyVoucherToDraft(voucherId,date){
65
+ if(!requireWrite())throw new Error('write denied');const v=getMyJournalVouchers().find(x=>x.id===voucherId);if(!v)throw new Error('سند پیدا نشد.');const lines=getMyJournalLines().filter(x=>x.voucherId===v.id).sort((a,b)=>(a.lineNo||0)-(b.lineNo||0)).map(l=>({accountId:l.accountId,debit:l.debit,credit:l.credit,description:l.description||'',dimensions:getMyJournalLineDimensions().filter(d=>d.journalLineId===l.id).map(d=>({dimensionTypeId:d.dimensionTypeId,dimensionValueId:d.dimensionValueId}))}));return jeCreateDraft({date:date||getJalaliNumeric(),description:'کپی سند '+v.number+(v.description?' — '+v.description:''),reference:v.reference||('سند '+v.number),voucherType:'copy',sourceType:'manual',sourceId:'',lines});
66
}
67
function jeDeleteDraft(voucherId){if(!requireWrite())return false;const v=getMyJournalVouchers().find(x=>x.id===voucherId);if(!v||v.status!=='draft')throw new Error('سند قطعی/برگشتی حذفپذیر نیست.');const ids=getMyJournalLines().filter(x=>x.voucherId===voucherId).map(x=>x.id);datastore.journalLineDimensions=datastore.journalLineDimensions.filter(x=>!ids.includes(x.journalLineId));datastore.journalLines=datastore.journalLines.filter(x=>x.voucherId!==voucherId);datastore.journalVouchers=datastore.journalVouchers.filter(x=>x.id!==voucherId);saveDatastore();return true}
68
function jeLedgerRows(){return getMyJournalLines().flatMap(l=>{const v=getMyJournalVouchers().find(x=>x.id===l.voucherId);return v&&['posted','reversed'].includes(v.status)?[{...l,voucher:v,account:jePostingAccount(l.accountId)}]:[]})}
@@ -73,7 +78,7 @@ function jeEnsureDefaultProfiles(){
78
}
79
function jeAutoPost(kind,source){
80
jeEnsureDefaultProfiles();const amount=jeNum(source.amount??source.grandTotal);if(amount<=0)throw new Error('مبلغ سند منبع معتبر نیست.');
76
- const ctx={contactId:source.contactId||source.supplierId||'',projectId:source.projectId||source.costCenterId||'',branchId:source.branchId||'',contractId:source.contractId||'',costCenterId:source.costCenterId||''},dims=a=>jeDimensionAssignmentsForContext(a,ctx);
81
+ const ctx={contactId:source.contactId||source.supplierId||'',projectId:source.projectId||'',branchId:source.branchId||'',contractId:source.contractId||'',costCenterId:source.costCenterId||''},dims=a=>jeDimensionAssignmentsForContext(a,ctx);
82
let lines=[],title='';
83
if(kind==='sale'){
84
const cash=jeCashAccount(),ar=jeReceivableAccount(),rev=jeRevenueAccount(),vat=jeVatPayableAccount(),gross=jeNum(source.grandTotal),tax=jeNum(source.vat),net=Math.max(0,gross-tax),debit=source.paymentMethod==='credit'?ar:cash;if(!debit||!rev)throw new Error('حسابهای فروش/دریافتنی/نقد در کدینگ تکمیل نیست.');
js/journal-ui.js
+23
-10
@@ -1,23 +1,36 @@
1
-/* Phase 3 — journal UI */
1
+/* Phase 3 / P0 — journal UI */
2
function ensureJournalView(){
3
- if(document.getElementById('view-journal'))return;const s=document.createElement('section');s.id='view-journal';s.className='view-pane';s.innerHTML=`<div class="af-head"><div><h1>اسناد حسابداری</h1><p>ثبت دوبل، قطعیسازی و برگشت اسناد</p></div></div>
4
- <div class="card" data-finora-task="new"><h3>ثبت سند حسابداری</h3><div class="form-row"><div class="form-group"><label>تاریخ</label><input id="je-date" class="form-control"></div><div class="form-group"><label>شرح</label><input id="je-desc" class="form-control"></div></div><div id="je-lines"></div><div style="display:flex;gap:8px;flex-wrap:wrap"><button class="btn btn-secondary" onclick="jeAddRow()">+ آرتیکل</button><button class="btn btn-success" onclick="jeSaveManual()">ثبت پیشنویس</button></div></div>
5
- <div class="card" data-finora-task="register"><h3>فهرست اسناد حسابداری</h3><div class="table-responsive"><table><thead><tr><th>شماره</th><th>تاریخ</th><th>شرح</th><th>وضعیت</th><th>بدهکار</th><th>بستانکار</th><th>عملیات</th></tr></thead><tbody id="je-vouchers"></tbody></table></div></div>
3
+ if(document.getElementById('view-journal'))return;const s=document.createElement('section');s.id='view-journal';s.className='view-pane';s.innerHTML=`<div class="af-head"><div><h1>اسناد حسابداری</h1><p>ثبت دوبل، ابعاد تحلیلی، قطعیسازی و برگشت اسناد</p></div></div>
4
+ <div class="card" data-finora-task="new"><h3>ثبت سند حسابداری</h3><div class="form-row"><div class="form-group"><label>شماره سند</label><input id="je-number" class="form-control" placeholder="خودکار"></div><div class="form-group"><label>تاریخ</label><input id="je-date" class="form-control"></div><div class="form-group"><label>نوع سند</label><select id="je-voucher-type" class="form-control"><option value="manual">عادی</option><option value="adjustment">اصلاحی</option><option value="opening">افتتاحیه</option><option value="closing">اختتامیه</option></select></div><div class="form-group"><label>مرجع</label><input id="je-reference" class="form-control" placeholder="شماره فاکتور/قرارداد/نامه"></div></div>
5
+ <div class="form-row"><div class="form-group" style="flex:1"><label>شرح سند</label><input id="je-desc" class="form-control"></div></div><div id="je-lines"></div>
6
+ <div id="je-totals" class="af-hint" style="margin:10px 0;font-weight:700"></div><div style="display:flex;gap:8px;flex-wrap:wrap"><button class="btn btn-secondary" onclick="jeAddRow()">+ آرتیکل</button><button class="btn btn-success" onclick="jeSaveManual()">ثبت پیشنویس</button></div></div>
7
+ <div class="card" data-finora-task="register"><h3>فهرست اسناد حسابداری</h3><div class="table-responsive"><table><thead><tr><th>شماره</th><th>تاریخ</th><th>نوع</th><th>مرجع</th><th>شرح</th><th>وضعیت</th><th>بدهکار</th><th>بستانکار</th><th>منبع</th><th>عملیات</th></tr></thead><tbody id="je-vouchers"></tbody></table></div></div>
8
<div class="card" data-finora-task="trial"><h3>تراز آزمایشی</h3><div class="table-responsive"><table><thead><tr><th>کد</th><th>حساب</th><th>بدهکار</th><th>بستانکار</th><th>مانده</th></tr></thead><tbody id="je-trial"></tbody></table></div></div>`;const main=document.querySelector('.main-surface'),p=document.getElementById('printable-invoice');p?main.insertBefore(s,p):main.appendChild(s);
9
}
8
-function jeAddRow(){
9
- const box=document.getElementById('je-lines');if(!box)return;const row=document.createElement('div');row.className='form-row je-line';row.innerHTML='<div class="form-group"><label>حساب</label><select class="form-control je-account" onchange="jeRenderDims(this.closest(\'.je-line\'))"><option value="">انتخاب حساب</option>'+getMyAccounts().filter(x=>x.postingAllowed&&x.active!==false).map(x=>'<option value="'+x.id+'">'+esc(x.code)+' — '+esc(x.title)+'</option>').join('')+'</select></div><div class="form-group"><label>بدهکار</label><input class="form-control je-debit" inputmode="decimal"></div><div class="form-group"><label>بستانکار</label><input class="form-control je-credit" inputmode="decimal"></div><div class="form-group"><label>شرح</label><input class="form-control je-line-desc"></div><button class="btn btn-danger btn-inline" onclick="this.closest(\'.je-line\').remove()">×</button><div class="je-dims" style="width:100%"></div>';box.appendChild(row);
10
+function jeAccountOptions(){return getMyAccounts().filter(x=>x.postingAllowed&&x.active!==false).map(x=>'<option value="'+x.id+'">'+esc(x.code)+' — '+esc(x.title)+'</option>').join('')}
11
+function jeAddRow(seed={}){
12
+ const box=document.getElementById('je-lines');if(!box)return;const row=document.createElement('div');row.className='form-row je-line';row.innerHTML='<div class="form-group"><label>جستجوی حساب</label><input class="form-control je-account-search" placeholder="کد یا نام حساب" oninput="jeFilterAccounts(this)"><select class="form-control je-account" onchange="jeRenderDims(this.closest(\'.je-line\'))"><option value="">انتخاب حساب</option>'+jeAccountOptions()+'</select></div><div class="form-group"><label>بدهکار</label><input class="form-control je-debit" inputmode="decimal" oninput="jeUpdateTotals()"></div><div class="form-group"><label>بستانکار</label><input class="form-control je-credit" inputmode="decimal" oninput="jeUpdateTotals()"></div><div class="form-group"><label>شرح</label><input class="form-control je-line-desc"></div><div style="display:flex;gap:4px;align-items:end"><button type="button" class="btn btn-secondary btn-inline" title="کپی ردیف" onclick="jeCopyRow(this)">⧉</button><button type="button" class="btn btn-danger btn-inline" title="حذف ردیف" onclick="jeRemoveRow(this)">×</button></div><div class="je-dims" style="width:100%"></div>';box.appendChild(row);
13
+ row.querySelector('.je-account').value=seed.accountId||'';row.querySelector('.je-debit').value=seed.debit||'';row.querySelector('.je-credit').value=seed.credit||'';row.querySelector('.je-line-desc').value=seed.description||'';jeRenderDims(row);(seed.dimensions||[]).forEach(d=>{const el=row.querySelector('.je-dim[data-type="'+d.dimensionTypeId+'"]');if(el)el.value=d.dimensionValueId||''});jeUpdateTotals();return row;
14
}
15
+function jeFilterAccounts(input){const q=String(input.value||'').trim().toLowerCase(),sel=input.closest('.je-line')?.querySelector('.je-account');if(!sel)return;[...sel.options].forEach((o,i)=>{if(i===0){o.hidden=false;return}o.hidden=!!q&&!o.text.toLowerCase().includes(q)})}
16
function jeRenderDims(row){
17
const aid=row.querySelector('.je-account').value,box=row.querySelector('.je-dims'),rules=jeRulesForAccount(aid).filter(x=>x.applicability!=='unavailable');box.innerHTML=rules.map(r=>{const t=getMyDimensionTypes().find(x=>x.id===r.dimensionTypeId),vals=t?afResolvedValues(t).filter(v=>v.postable!==false):[];return t?'<label style="display:inline-block;margin:5px 8px">'+esc(t.title)+(r.applicability==='required'?' *':'')+' <select class="form-control je-dim" data-type="'+t.id+'" style="min-width:180px"><option value="">— انتخاب —</option>'+vals.map(v=>'<option value="'+v.id+'">'+esc(v.title||v.name)+'</option>').join('')+'</select></label>':''}).join('');
18
}
19
function jeCollectRows(){return[...document.querySelectorAll('#je-lines .je-line')].map(r=>({accountId:r.querySelector('.je-account').value,debit:parseFormattedNumber(r.querySelector('.je-debit').value),credit:parseFormattedNumber(r.querySelector('.je-credit').value),description:r.querySelector('.je-line-desc').value,dimensions:[...r.querySelectorAll('.je-dim')].filter(x=>x.value).map(x=>({dimensionTypeId:x.dataset.type,dimensionValueId:x.value}))}))}
15
-function jeSaveManual(){try{const v=jeCreateDraft({date:document.getElementById('je-date').value||getJalaliNumeric(),description:document.getElementById('je-desc').value,lines:jeCollectRows()});alert('پیشنویس سند '+v.number+' ثبت شد.');renderJournal()}catch(e){alert(e.message)}}
16
-function jePostUi(id){try{jePost(id);renderJournal()}catch(e){alert(e.message)}} function jeReverseUi(id){const why=prompt('علت برگشت سند:','اصلاح ثبت');if(why===null)return;try{jeReverse(id,getJalaliNumeric(),why);renderJournal()}catch(e){alert(e.message)}}
20
+function jeUpdateTotals(){const rows=jeCollectRows(),d=rows.reduce((s,x)=>s+(Number(x.debit)||0),0),c=rows.reduce((s,x)=>s+(Number(x.credit)||0),0),diff=d-c,box=document.getElementById('je-totals');if(box)box.textContent='جمع بدهکار: '+d.toLocaleString('fa-IR')+' | جمع بستانکار: '+c.toLocaleString('fa-IR')+' | اختلاف: '+Math.abs(diff).toLocaleString('fa-IR')+(d>0&&Math.abs(diff)<0.0001?' ✓ تراز':'')}
21
+function jeRemoveRow(btn){const rows=document.querySelectorAll('#je-lines .je-line');if(rows.length<=2)return alert('سند باید حداقل دو آرتیکل داشته باشد.');btn.closest('.je-line').remove();jeUpdateTotals()}
22
+function jeCopyRow(btn){const row=btn.closest('.je-line'),seed={accountId:row.querySelector('.je-account').value,debit:row.querySelector('.je-debit').value,credit:row.querySelector('.je-credit').value,description:row.querySelector('.je-line-desc').value,dimensions:[...row.querySelectorAll('.je-dim')].filter(x=>x.value).map(x=>({dimensionTypeId:x.dataset.type,dimensionValueId:x.value}))};jeAddRow(seed)}
23
+function jeClearManualForm(){['je-number','je-reference','je-desc'].forEach(id=>{const e=document.getElementById(id);if(e)e.value=''});const box=document.getElementById('je-lines');if(box)box.innerHTML='';jeAddRow();jeAddRow();jeUpdateTotals()}
24
+function jeSaveManual(){try{const v=jeCreateDraft({number:document.getElementById('je-number').value,date:document.getElementById('je-date').value||getJalaliNumeric(),voucherType:document.getElementById('je-voucher-type').value,reference:document.getElementById('je-reference').value,description:document.getElementById('je-desc').value,lines:jeCollectRows()});alert('پیشنویس سند '+v.number+' ثبت شد.');jeClearManualForm();renderJournal()}catch(e){alert(e.message)}}
25
+function jePostUi(id){try{jePost(id);renderJournal()}catch(e){alert(e.message)}}
26
+function jeReverseUi(id){const why=prompt('علت برگشت سند:','اصلاح ثبت');if(why===null)return;try{jeReverse(id,getJalaliNumeric(),why);renderJournal()}catch(e){alert(e.message)}}
27
+function jeCopyVoucherUi(id){try{const v=jeCopyVoucherToDraft(id,getJalaliNumeric());alert('کپی سند به پیشنویس '+v.number+' ایجاد شد.');renderJournal()}catch(e){alert(e.message)}}
28
function jeDeleteUi(id){if(!confirm('پیشنویس حذف شود؟'))return;try{jeDeleteDraft(id);renderJournal()}catch(e){alert(e.message)}}
29
+function jeStatusLabel(v){return v==='draft'?'پیشنویس':v==='posted'?'قطعی':v==='reversed'?'برگشتشده':v}
30
+function jeTypeLabel(v){return({manual:'عادی',adjustment:'اصلاحی',opening:'افتتاحیه',closing:'اختتامیه',copy:'کپی',reversal:'برگشت'})[v]||v||'عادی'}
31
function renderJournal(){
19
- ensureJournalView();if(!currentUser)return;jeEnsureDefaultProfiles();const body=document.getElementById('je-vouchers'),vs=getMyJournalVouchers().slice().sort((a,b)=>String(b.createdAt).localeCompare(String(a.createdAt)));if(body)body.innerHTML=vs.length?vs.map(v=>'<tr><td>'+esc(v.number)+'</td><td>'+esc(v.date)+'</td><td>'+esc(v.description)+'</td><td>'+esc(v.status)+'</td><td>'+Number(v.totalDebit).toLocaleString('fa-IR')+'</td><td>'+Number(v.totalCredit).toLocaleString('fa-IR')+'</td><td>'+(v.status==='draft'?'<button class="btn btn-success btn-inline" onclick="jePostUi(\''+v.id+'\')">قطعی</button> <button class="btn btn-danger btn-inline" onclick="jeDeleteUi(\''+v.id+'\')">حذف</button>':v.status==='posted'?'<button class="btn btn-secondary btn-inline" onclick="jeReverseUi(\''+v.id+'\')">برگشت</button>':'—')+'</td></tr>').join(''):'<tr><td colspan="7" class="af-empty">سندی ثبت نشده است.</td></tr>';
32
+ ensureJournalView();if(!currentUser)return;if(typeof afEnsureAccountingP0Compatibility==='function')afEnsureAccountingP0Compatibility();jeEnsureDefaultProfiles();const body=document.getElementById('je-vouchers'),vs=getMyJournalVouchers().slice().sort((a,b)=>String(b.createdAt).localeCompare(String(a.createdAt)));if(body)body.innerHTML=vs.length?vs.map(v=>'<tr><td>'+esc(v.number)+'</td><td>'+esc(v.date)+'</td><td>'+esc(jeTypeLabel(v.voucherType))+'</td><td>'+esc(v.reference||'—')+'</td><td>'+esc(v.description)+'</td><td>'+esc(jeStatusLabel(v.status))+'</td><td>'+Number(v.totalDebit).toLocaleString('fa-IR')+'</td><td>'+Number(v.totalCredit).toLocaleString('fa-IR')+'</td><td>'+esc(v.sourceType||'manual')+'</td><td>'+(v.status==='draft'?'<button class="btn btn-success btn-inline" onclick="jePostUi(\''+v.id+'\')">قطعی</button> <button class="btn btn-danger btn-inline" onclick="jeDeleteUi(\''+v.id+'\')">حذف</button> ':v.status==='posted'?'<button class="btn btn-secondary btn-inline" onclick="jeReverseUi(\''+v.id+'\')">برگشت</button> ':'')+'<button class="btn btn-secondary btn-inline" onclick="jeCopyVoucherUi(\''+v.id+'\')">کپی</button></td></tr>').join(''):'<tr><td colspan="10" class="af-empty">سندی ثبت نشده است.</td></tr>';
33
const tb=document.getElementById('je-trial'),rows=jeTrialBalance();if(tb)tb.innerHTML=rows.length?rows.map(x=>'<tr><td>'+esc(x.code)+'</td><td>'+esc(x.title)+'</td><td>'+x.debit.toLocaleString('fa-IR')+'</td><td>'+x.credit.toLocaleString('fa-IR')+'</td><td>'+x.balance.toLocaleString('fa-IR')+'</td></tr>').join(''):'<tr><td colspan="5" class="af-empty">گردشی وجود ندارد.</td></tr>';
21
- const d=document.getElementById('je-date');if(d&&!d.value)d.value=getJalaliNumeric();if(!document.querySelector('#je-lines .je-line')){jeAddRow();jeAddRow()}
34
+ const d=document.getElementById('je-date');if(d&&!d.value)d.value=getJalaliNumeric();if(!document.querySelector('#je-lines .je-line')){jeAddRow();jeAddRow()}jeUpdateTotals();
35
}
36
document.addEventListener('DOMContentLoaded',ensureJournalView);
scripts/accounting-p0-check.mjs
new
+17
@@ -0,0 +1,17 @@
1
+import fs from 'node:fs';
2
+const foundation=fs.readFileSync('js/accounting-foundation.js','utf8');
3
+const engine=fs.readFileSync('js/journal-engine.js','utf8');
4
+const ui=fs.readFileSync('js/journal-ui.js','utf8');
5
+function ok(v,m){if(!v)throw new Error(m)}
6
+ok(foundation.includes("['COST_CENTER','مرکز هزینه','costCenter',0]"),'P0 must seed an independent cost-center analytic dimension.');
7
+ok(foundation.includes('function afEnsureAccountingP0Compatibility()'),'P0 compatibility upgrader is missing.');
8
+ok(foundation.includes("['receivable_control','payable_control'].includes(role)"),'Receivable/payable roles must drive counterparty rules.');
9
+ok(foundation.includes("compatibilityMode:legacyRequired?'legacy-history-preserved':'recommended-p0'"),'Legacy posted history must not be retroactively broken by new required rules.');
10
+ok(engine.includes("projectId:source.projectId||'',branchId"),'Project context must not fall back to cost center.');
11
+ok(engine.includes('function jeVoucherNumberTaken'),'Journal number uniqueness guard is missing.');
12
+ok(engine.includes('function jeCopyVoucherToDraft'),'Journal copy-to-draft workflow is missing.');
13
+ok(engine.includes("jeDimensionValueBySource(dims,'contact')")&&engine.includes("jeDimensionValueBySource(dims,'project')"),'Generic analytic dimensions must maintain compatibility fields.');
14
+ok(ui.includes('id="je-number"')&&ui.includes('id="je-reference"')&&ui.includes('id="je-voucher-type"'),'Journal header must expose number, type, and reference.');
15
+ok(ui.includes('id="je-totals"')&&ui.includes('function jeUpdateTotals()'),'Journal must show live debit/credit/difference totals.');
16
+ok(ui.includes('function jeFilterAccounts')&&ui.includes('function jeCopyRow'),'Journal must support account search and row copy.');
17
+console.log('Accounting P0 invariants passed.');
scripts/accounting-p0-journal.spec.js
new
+58
@@ -0,0 +1,58 @@
1
+const {test,expect}=require('@playwright/test');
2
+const path=require('node:path');
3
+async function boot(page){
4
+ await page.setContent('<main class="main-surface"></main>');
5
+ await page.addScriptTag({content:`var currentUser={id:'U1'},datastore={journalVouchers:[],journalLines:[],journalLineDimensions:[]};
6
+ function esc(v){return String(v??'').replace(/[&<>"']/g,c=>({'&':'&','<':'<','>':'>','"':'"',"'":'''}[c]))}
7
+ function parseFormattedNumber(v){return Number(String(v||'').replace(/,/g,''))||0}
8
+ function getJalaliNumeric(){return '1405/07/15'}
9
+ function getMyAccounts(){return [{id:'A1',code:'1102',title:'حسابهای دریافتنی',postingAllowed:true,active:true},{id:'A2',code:'4101',title:'فروش',postingAllowed:true,active:true}]}
10
+ function getMyDimensionTypes(){return [{id:'D1',title:'طرف حساب',sourceEntity:'contact',active:true}]}
11
+ function afResolvedValues(){return [{id:'C1',title:'مشتری نمونه',postable:true}]}
12
+ function jeRulesForAccount(id){return id==='A1'?[{dimensionTypeId:'D1',applicability:'required'}]:[]}
13
+ function afEnsureAccountingP0Compatibility(){}
14
+ function jeEnsureDefaultProfiles(){}
15
+ function getMyJournalVouchers(){return datastore.journalVouchers}
16
+ function jeTrialBalance(){return []}
17
+ function jeCreateDraft(input){window.lastDraft=input;return {number:input.number||'1'}}
18
+ function jePost(){}
19
+ function jeReverse(){}
20
+ function jeCopyVoucherToDraft(){return {number:'2'}}
21
+ function jeDeleteDraft(){}
22
+ `});
23
+ await page.addScriptTag({path:path.resolve('js/journal-ui.js')});
24
+ await page.evaluate(()=>renderJournal());
25
+}
26
+test('journal P0 renders header controls, live balance and dynamic dimensions',async({page})=>{
27
+ await boot(page);
28
+ await expect(page.locator('#je-number')).toBeVisible();
29
+ await expect(page.locator('#je-reference')).toBeVisible();
30
+ await expect(page.locator('#je-voucher-type')).toBeVisible();
31
+ await expect(page.locator('#je-lines .je-line')).toHaveCount(2);
32
+ const first=page.locator('#je-lines .je-line').first();
33
+ await first.locator('.je-account').selectOption('A1');
34
+ await expect(first.locator('.je-dim[data-type="D1"]')).toBeVisible();
35
+ await first.locator('.je-dim[data-type="D1"]').selectOption('C1');
36
+ await first.locator('.je-debit').fill('1000');
37
+ const second=page.locator('#je-lines .je-line').nth(1);
38
+ await second.locator('.je-account').selectOption('A2');
39
+ await second.locator('.je-credit').fill('1000');
40
+ await expect(page.locator('#je-totals')).toContainText('✓ تراز');
41
+ await first.locator('.je-account-search').fill('دریافتنی');
42
+ expect(await first.locator('.je-account option[value="A2"]').evaluate(o=>o.hidden)).toBe(true);
43
+});
44
+test('journal row copy preserves account, amount and analytic selection',async({page})=>{
45
+ await boot(page);
46
+ const first=page.locator('#je-lines .je-line').first();
47
+ await first.locator('.je-account').selectOption('A1');
48
+ await first.locator('.je-dim[data-type="D1"]').selectOption('C1');
49
+ await first.locator('.je-debit').fill('1250');
50
+ await first.locator('.je-line-desc').fill('شرح ردیف');
51
+ await first.getByTitle('کپی ردیف').click();
52
+ await expect(page.locator('#je-lines .je-line')).toHaveCount(3);
53
+ const copied=page.locator('#je-lines .je-line').nth(2);
54
+ await expect(copied.locator('.je-account')).toHaveValue('A1');
55
+ await expect(copied.locator('.je-debit')).toHaveValue('1250');
56
+ await expect(copied.locator('.je-line-desc')).toHaveValue('شرح ردیف');
57
+ await expect(copied.locator('.je-dim[data-type="D1"]')).toHaveValue('C1');
58
+});
scripts/phase3-behavior-check.mjs
+4
-1
@@ -24,6 +24,8 @@ rules.push({accountId:'rev',dimensionTypeId:'D_PARTY',applicability:'unavailable
24
let forbiddenDim=false;try{ctx.jeCreateDraft({date:'1405/07/07',description:'forbidden dim',sourceType:'manual',sourceId:'BAD4',lines:[{accountId:'cash',debit:100,credit:0,dimensions:[]},{accountId:'rev',debit:0,credit:100,dimensions:[{dimensionTypeId:'D_PARTY',dimensionValueId:'CUST1'}]}]})}catch(_){forbiddenDim=true}assert(forbiddenDim,'unavailable analytic dimension must be rejected');
25
let duplicateDim=false;try{ctx.jeCreateDraft({date:'1405/07/07',description:'duplicate dim',sourceType:'manual',sourceId:'BAD5',lines:[{accountId:'ar',debit:100,credit:0,dimensions:[{dimensionTypeId:'D_PARTY',dimensionValueId:'CUST1'},{dimensionTypeId:'D_PARTY',dimensionValueId:'CUST1'}]},{accountId:'rev',debit:0,credit:100,dimensions:[]}]})}catch(_){duplicateDim=true}assert(duplicateDim,'duplicate analytic assignment must be rejected');
26
rules.push({accountId:'cash',dimensionTypeId:'D_PARTY',applicability:'optional',active:true});assert(ctx.jeValidateDimensions('cash',[])===true,'optional analytic dimension must allow omission');
27
+dimensions.push({id:'D_PROJECT',sourceEntity:'project',active:true},{id:'D_CC',sourceEntity:'costCenter',active:true});dimensionValues.push({id:'PR1',dimensionTypeId:'D_PROJECT',postable:true},{id:'CC1',dimensionTypeId:'D_CC',postable:true});rules.push({accountId:'buyTrading',dimensionTypeId:'D_PROJECT',applicability:'optional',active:true},{accountId:'buyTrading',dimensionTypeId:'D_CC',applicability:'optional',active:true});
28
+const numbered=ctx.jeCreateDraft({number:'77',date:'1405/07/07',description:'numbered',lines:[{accountId:'cash',debit:10,credit:0,dimensions:[]},{accountId:'rev',debit:0,credit:10,dimensions:[]}]});assert(numbered.number==='77','explicit journal number was not retained');let duplicateNumber=false;try{ctx.jeCreateDraft({number:'77',date:'1405/07/07',description:'duplicate number',lines:[{accountId:'cash',debit:10,credit:0,dimensions:[]},{accountId:'rev',debit:0,credit:10,dimensions:[]}]})}catch(_){duplicateNumber=true}assert(duplicateNumber,'duplicate journal number in fiscal year must fail');
29
let unknownDim=false;try{ctx.jeValidateDimensions('cash',[{dimensionTypeId:'UNKNOWN',dimensionValueId:'CUST1'}])}catch(_){unknownDim=true}assert(unknownDim,'undefined analytic dimension must be rejected');
30
const receipt={id:'PAY1',date:'1405/07/07',amount:125000,contactId:'CUST1'};
31
const v=ctx.jePostSourceRecord('receipt',receipt);
@@ -37,8 +39,9 @@ assert(v.status==='reversed'&&rv.status==='posted','reversal lifecycle failed');
39
let mutationBlocked=false;try{ctx.jeGuardSourceMutation(receipt,'receipt')}catch(_){mutationBlocked=true}assert(mutationBlocked,'reversed source mutation must fail');
40
let repostBlocked=false;try{ctx.jePostSourceRecord('receipt',receipt)}catch(_){repostBlocked=true}assert(repostBlocked,'reversed source repost must fail');
41
assert(ctx.jeTrialBalance().every(x=>Math.abs(x.balance)<0.0001),'reversal must net original ledger to zero');
42
+const copied=ctx.jeCopyVoucherToDraft(v.id,'1405/07/09');assert(copied.status==='draft'&&copied.sourceType==='manual'&&!copied.sourceId&&copied.voucherType==='copy','voucher copy must create an independent manual draft');const copiedDims=datastore.journalLineDimensions.filter(x=>x.voucherId===copied.id);assert(copiedDims.some(x=>x.dimensionTypeId==='D_PARTY'&&x.dimensionValueId==='CUST1'),'voucher copy must preserve analytic dimensions');assert(datastore.journalLines.filter(x=>x.voucherId===copied.id).some(x=>x.counterpartyId==='CUST1'),'generic counterparty dimension must populate compatibility field');
43
const saleTrading=ctx.jePostSourceRecord('sale',{id:'SALE_TRADING',date:'1405/07/07',grandTotal:100,vat:0,paymentMethod:'cash'});assert(datastore.journalLines.some(x=>x.voucherId===saleTrading.id&&x.accountId==='revTrading'&&x.credit===100),'trading sale did not use activity-specific revenue account');
41
-const purchaseTrading=ctx.jePostSourceRecord('purchase',{id:'PUR_TRADING',date:'1405/07/07',grandTotal:80,vat:0,paymentMethod:'cash'});assert(datastore.journalLines.some(x=>x.voucherId===purchaseTrading.id&&x.accountId==='buyTrading'&&x.debit===80),'trading purchase did not use activity-specific purchase account');
44
+const purchaseTrading=ctx.jePostSourceRecord('purchase',{id:'PUR_TRADING',date:'1405/07/07',grandTotal:80,vat:0,paymentMethod:'cash',projectId:'PR1',costCenterId:'CC1'});assert(datastore.journalLines.some(x=>x.voucherId===purchaseTrading.id&&x.accountId==='buyTrading'&&x.debit===80),'trading purchase did not use activity-specific purchase account');const purchaseDims=datastore.journalLineDimensions.filter(x=>x.voucherId===purchaseTrading.id);assert(purchaseDims.some(x=>x.dimensionTypeId==='D_PROJECT'&&x.dimensionValueId==='PR1'),'purchase project dimension was not posted independently');assert(purchaseDims.some(x=>x.dimensionTypeId==='D_CC'&&x.dimensionValueId==='CC1'),'purchase cost-center dimension was not posted independently');assert(!purchaseDims.some(x=>x.dimensionTypeId==='D_PROJECT'&&x.dimensionValueId==='CC1'),'cost center must never be substituted as project');
45
const ev=ctx.jePostSourceRecord('expense',{id:'EXP_OK',date:'1405/07/08',amount:700});assert(ev.status==='posted','expense source must post');const iv=ctx.jePostSourceRecord('income',{id:'INC_OK',date:'1405/07/08',amount:900});assert(iv.status==='posted','income source must post');
46
fiscal[0].status='locked';let locked=false;try{ctx.jePostSourceRecord('expense',{id:'EXP1',date:'1405/07/09',amount:1000})}catch(_){locked=true}assert(locked,'locked fiscal year must reject posting');
47
console.log('Phase 3 behavioral accounting scenarios passed.');
scripts/phase3-check.mjs
+1
-1
@@ -5,7 +5,7 @@ const need=(src,x,label)=>{for(const n of x)if(!src.includes(n))throw new Error(
5
need(e,['jeSourceVoucher','jeActiveSourceVoucher','jeSourceLocked','jeGuardSourceMutation','jePostSourceRecord','jeValidateLines','jeValidateDimensions','sourceVersion','jeReverse','reversalVoucherId','jeDeleteDraft','jeTrialBalance','journalLineDimensions','paymentMethod===\'credit\'','jeVatPayableAccount',"jeAccountByCode('1108')",'jeTemplateType',"trading:'4107'","service:'4106'","jeTemplateType()==='trading'?'5102'"],'engine');
6
need(u,['view-journal','jeSaveManual','jePostUi','jeReverseUi','je-trial'],'ui');
7
for(const x of ['postingProfiles','journalVouchers','journalLines','journalLineDimensions']){if(!c.includes("'"+x+"'")||!s.includes(x)||!b.includes(x))throw new Error('persistence missing '+x)}
8
-need(i,['journal-engine.js?v=20260928-phase3-final','journal-ui.js?v=20260928-phase3-final'],'index');
8
+need(i,['journal-engine.js?v=20261007-p0-r1','journal-ui.js?v=20261007-p0-r1'],'index');
9
need(s,["sb.rpc('finora_sync_records'",'p_upserts','p_deletes'],'atomic sync');
10
need(pay,["date:old?.date||getJalaliNumeric()"],'payment fiscal date');
11
need(inv,['invoiceCreatesAccountingEntry',"kind==='formal'||kind==='non_formal'"],'invoice posting semantics');
scripts/quality-check.mjs
+2
-2
@@ -63,11 +63,11 @@ for(const cssNeedle of ['--shell-rail','--shell-panel','.module-tab.active','.mo
63
if(!index.includes(cssNeedle))throw new Error('Phase 1 responsive shell CSS missing '+cssNeedle);
64
65
for(const coll of ['fiscalYears','accounts','dimensionTypes','dimensionValues','accountDimensionRules','branches','projects','projectLinks'])if(!all['core.js'].includes("'"+coll+"'"))throw new Error('Phase 2 collection missing '+coll);
66
-if(!index.includes('data-module="accounting"')||!index.includes('accounting-foundation.js?v=20261003-chart-v4'))throw new Error('Phase 2 accounting shell integration missing');
66
+if(!index.includes('data-module="accounting"')||!index.includes('accounting-foundation.js?v=20261007-p0-r1'))throw new Error('Phase 2 accounting shell integration missing');
67
68
for(const coll of ['postingProfiles','journalVouchers','journalLines','journalLineDimensions'])if(!all['core.js'].includes("'"+coll+"'")||!all['sync.js'].includes(coll))throw new Error('Phase 3 collection missing '+coll);
69
for(const needle of ['jeValidateLines','jeValidateDimensions','jeCreateDraft','jePost','jeReverse','jeDeleteDraft','jeTrialBalance','sourceVersion'])if(!all['journal-engine.js']?.includes(needle))throw new Error('Phase 3 journal invariant missing '+needle);
70
-if(!index.includes('journal-engine.js?v=20260928-phase3-final')||!index.includes('journal-ui.js?v=20260928-phase3-final'))throw new Error('Phase 3 journal scripts missing');
70
+if(!index.includes('journal-engine.js?v=20261007-p0-r1')||!index.includes('journal-ui.js?v=20261007-p0-r1'))throw new Error('Phase 3 journal scripts missing');
71
72
for(const needle of ['jeActiveSourceVoucher','jeSourceLocked','jeGuardSourceMutation','jePostSourceRecord',"['posted','reversed'].includes"])if(!all['journal-engine.js']?.includes(needle))throw new Error('Phase 3 source/ledger safety missing '+needle);
73
for(const [file,needles] of Object.entries({