1
+// Factor-easyPro V2 — read-only control totals and discrepancy diagnostics.
2
+// Pure function: never repairs or mutates financial, settlement or stock records.
3
+import { qtyUnits } from './RetailFinanceCore.mjs';
4
+
5
+const safeMoney = value => Number.isSafeInteger(value) && value >= 0;
6
+const keyOf = (w,p) => JSON.stringify([w,p]);
7
+const safeAdd = (a,b) => {
8
+ const value = a+b;
9
+ if (!Number.isSafeInteger(value)) throw Error('سرریز محاسبات مغایرتگیری');
10
+ return value;
11
+};
12
+
13
+export function reconcileFinancialData({
14
+ accounts = [], journals = [], journalLines = [], invoices = [],
15
+ settlements = [], transactions = [], inventoryBalances = [],
16
+ stockMovements = [], integrated = false
17
+} = {}) {
18
+ const issues = [];
19
+ const report = (code, message, reference = '', severity = 'error', expected = null, actual = null) => {
20
+ issues.push({ code, severity, reference: String(reference || ''), message, expected, actual });
21
+ };
22
+ const chart = new Map(accounts.map(a => [a.id, a]));
23
+ const posted = journals.filter(j => j.status === 'posted');
24
+ const byJournal = new Map(journals.map(j => [j.id, j]));
25
+ const journalLinesById = new Map();
26
+ for (const line of journalLines) {
27
+ const journal = byJournal.get(line.journalId);
28
+ if (!journal) {
29
+ report('ORPHAN_JOURNAL_LINE', 'سطر سند بدون سند اصلی', line.id);
30
+ continue;
31
+ }
32
+ if (!journalLinesById.has(line.journalId)) journalLinesById.set(line.journalId, []);
33
+ journalLinesById.get(line.journalId).push(line);
34
+ if (!chart.has(line.accountId)) report('UNKNOWN_ACCOUNT', 'سطر سند به حساب ناموجود اشاره دارد', line.journalId);
35
+ }
36
+ for (const journal of posted) {
37
+ const lines = journalLinesById.get(journal.id) || [];
38
+ if (!lines.length) {
39
+ report('EMPTY_JOURNAL', 'سند قطعی بدون سطر حسابداری', journal.id);
40
+ continue;
41
+ }
42
+ let debit = 0, credit = 0, valid = true;
43
+ for (const line of lines) {
44
+ if (!safeMoney(line.debit) || !safeMoney(line.credit) || (line.debit && line.credit)) {
45
+ report('INVALID_JOURNAL_LINE', 'بدهکار یا بستانکار سطر سند نامعتبر است', journal.id);
46
+ valid = false; break;
47
+ }
48
+ debit = safeAdd(debit, line.debit);
49
+ credit = safeAdd(credit, line.credit);
50
+ }
51
+ if (!valid) continue;
52
+ if (debit !== credit) report('JOURNAL_UNBALANCED', 'مجموع بدهکار و بستانکار سند برابر نیست', journal.id, 'error', debit, credit);
53
+ if (journal.debit !== debit || journal.credit !== credit) {
54
+ report('JOURNAL_TOTAL_MISMATCH', 'جمع ثبتشده روی سند با ردیفهای آن یکسان نیست',
55
+ journal.id, 'error', debit, journal.debit);
56
+ }
57
+ }
58
+
59
+ const allTransactions = new Map(transactions.filter(t => t.recordType === 'transaction').map(t => [t.id,t]));
60
+ const invoiceById = new Map(invoices.map(i => [i.id,i]));
61
+ const settlementsByInvoice = new Map();
62
+ for (const row of settlements) {
63
+ if (!invoiceById.has(row.invoiceId)) report('ORPHAN_SETTLEMENT', 'تسویه به فاکتور ناموجود متصل است', row.id);
64
+ if (!allTransactions.has(row.transactionId)) report('MISSING_SETTLEMENT_TRANSACTION', 'تراکنش مربوط به تسویه یافت نشد', row.id);
65
+ if (!safeMoney(row.amount) || row.amount === 0) report('INVALID_SETTLEMENT_AMOUNT', 'مبلغ تسویه نامعتبر است', row.id);
66
+ if (!settlementsByInvoice.has(row.invoiceId)) settlementsByInvoice.set(row.invoiceId, []);
67
+ settlementsByInvoice.get(row.invoiceId).push(row);
68
+ }
69
+ let checkedInvoices = 0;
70
+ for (const inv of invoices) {
71
+ if (inv.isPreInvoice || !inv.financePosted) continue;
72
+ checkedInvoices++;
73
+ const source = byJournal.get(inv.journalId);
74
+ if (!source || source.status !== 'posted' || source.sourceType !== 'invoice' || source.sourceId !== inv.id) {
75
+ report('INVOICE_JOURNAL_MISSING', 'فاکتور قطعی سند مالی معتبر ندارد', inv.number || inv.id);
76
+ }
77
+ if (!safeMoney(inv.grandTotal) || !safeMoney(inv.paidAmount) || !safeMoney(inv.remaining)) {
78
+ report('INVALID_INVOICE_TOTAL', 'مبلغ یا مانده فاکتور نامعتبر است', inv.number || inv.id);
79
+ continue;
80
+ }
81
+ const applied = (settlementsByInvoice.get(inv.id) || []).reduce((s,x) =>
82
+ safeMoney(x.amount) ? safeAdd(s,x.amount) : s, 0);
83
+ if (inv.paidAmount !== applied) {
84
+ report('INVOICE_SETTLEMENT_MISMATCH', 'جمع تسویهها با پرداختشده فاکتور برابر نیست',
85
+ inv.number || inv.id, 'error', inv.paidAmount, applied);
86
+ }
87
+ if (safeAdd(inv.paidAmount,inv.remaining) !== inv.grandTotal) {
88
+ report('INVOICE_BALANCE_MISMATCH', 'مبلغ پرداختشده و مانده با مبلغ کل فاکتور تطبیق ندارد',
89
+ inv.number || inv.id, 'error', inv.grandTotal, inv.paidAmount + inv.remaining);
90
+ }
91
+ }
92
+
93
+ let inventoryBook = 0, inventoryLedger = 0;
94
+ let stockUnits = 0;
95
+ if (integrated) {
96
+ const inventoryAccountIds = new Set(accounts.filter(a => a.code === '103').map(a => a.id));
97
+ if (!inventoryAccountIds.size) report('INVENTORY_ACCOUNT_MISSING', 'حساب موجودی کالا (۱۰۳) در کدینگ وجود ندارد');
98
+ for (const line of journalLines) {
99
+ if (!inventoryAccountIds.has(line.accountId)) continue;
100
+ if (byJournal.get(line.journalId)?.status !== 'posted') continue;
101
+ if (safeMoney(line.debit) && safeMoney(line.credit)) {
102
+ inventoryLedger = safeAdd(inventoryLedger,line.debit-line.credit);
103
+ }
104
+ }
105
+ const byMovement = new Map();
106
+ for (const move of stockMovements) {
107
+ if (!['in','out'].includes(move.type)) {
108
+ report('INVALID_STOCK_MOVEMENT', 'نوع گردش موجودی نامعتبر است', move.id);
109
+ continue;
110
+ }
111
+ let units;
112
+ try { units = qtyUnits(move.qty); }
113
+ catch { report('INVALID_STOCK_QUANTITY', 'مقدار گردش انبار نامعتبر است', move.id); continue; }
114
+ const key = keyOf(move.warehouseId,move.productId);
115
+ const sign = move.type === 'in' ? 1 : -1;
116
+ byMovement.set(key,safeAdd(byMovement.get(key) || 0,sign*units));
117
+ }
118
+ const byBalance = new Map();
119
+ for (const b of inventoryBalances) {
120
+ const key=keyOf(b.warehouseId,b.productId);
121
+ if (byBalance.has(key)) report('DUPLICATE_STOCK_BALANCE', 'مانده تکراری برای کالا و انبار', b.id);
122
+ byBalance.set(key,b);
123
+ if (!safeMoney(b.quantityUnits) || !safeMoney(b.value)) {
124
+ report('INVALID_STOCK_BALANCE', 'مانده مقدار یا ارزش انبار نامعتبر است', b.id);
125
+ continue;
126
+ }
127
+ stockUnits = safeAdd(stockUnits,b.quantityUnits);
128
+ inventoryBook = safeAdd(inventoryBook,b.value);
129
+ if (b.quantityUnits !== (byMovement.get(key) || 0)) {
130
+ report('STOCK_QUANTITY_MISMATCH', 'مقدار مانده انبار با جمع گردش کالا یکسان نیست',
131
+ b.id, 'error', b.quantityUnits, byMovement.get(key) || 0);
132
+ }
133
+ }
134
+ for (const [key,units] of byMovement) {
135
+ if (units !== 0 && !byBalance.has(key)) {
136
+ report('MISSING_STOCK_BALANCE', 'گردش کالا بدون رکورد مانده انبار', key);
137
+ }
138
+ }
139
+ if (inventoryLedger !== inventoryBook) {
140
+ report('INVENTORY_LEDGER_MISMATCH', 'ارزش انبار با مانده حساب کل موجودی کالا برابر نیست',
141
+ '103', 'error', inventoryBook, inventoryLedger);
142
+ }
143
+ }
144
+ return {
145
+ integrated, checkedAt: new Date().toISOString(),
146
+ counts: { journals: posted.length, invoices: checkedInvoices, settlements: settlements.length,
147
+ inventoryBalances: inventoryBalances.length, issues: issues.length },
148
+ totals: { inventoryBook, inventoryLedger, stockUnits },
149
+ issues
150
+ };
151
+}