فینورا پرو - سامانه جامع حسابداری و صدور فاکتور

Release Factor-easyPro 2.0.0: integrated accounting, inventory and Windows delivery

Davood Mehraban committed Oct 10, 2026 at 23:58 UTC d0a211789990e6e7f0b9361d862fd147f13dc414
71 files changed +4009 -282
.gitignore
+13
@@ -141,3 +141,16 @@ dist
141 vite.config.js.timestamp-*
142 vite.config.ts.timestamp-*
143 .vite/
144 +
145 +# Factor-easyPro build, test and user-data isolation
146 +src-tauri/target/
147 +release-delivery/
148 +*.fbackup
149 +*.bak
150 +*.sqlite
151 +*.sqlite3
152 +*.db
153 +*.db-wal
154 +*.db-shm
155 +*.user-data/
156 +*.log
README.md
+46 -2
@@ -1,2 +1,46 @@
1 -# Factor-easyPro
2 -فینورا پرو - سامانه جامع حسابداری و صدور فاکتور
1 +# Factor-easyPro 2.0.0
2 +
3 +نرم‌افزار فاکتور، خزانه، انبار و حسابداری دوبل فارسی برای ویندوز ۶۴بیتی؛ مبتنی بر Tauri 2، Vite و IndexedDB، با امکان کار آفلاین.
4 +
5 +## دریافت و نصب
6 +نصب‌کننده ویندوز در **GitHub Releases** قرار دارد:
7 +https://github.com/davoodmehraban89/Factor-easyPro/releases
8 +
9 +فایل `Factor-easyPro_2.0.0_x64-setup.exe` را دریافت و اجرا کنید. نسخه منتشرشده با پایگاه داده خالی توزیع می‌شود؛ هیچ داده واقعی یا نمونه مشتری داخل فایل نصب نیست. فایل نصب در این انتشار امضای کد تجاری ندارد، بنابراین هش SHA-256 آن را با بخش Release مقایسه کنید.
10 +
11 +## شروع به کار
12 +1. برنامه را باز و رمز مدیر را تعیین کنید. رمز اولیه عمومی وجود ندارد.
13 +2. از منوی **حسابداری**، دوره مالی شمسی مربوط به سال جاری را تعریف کنید.
14 +3. در «کدینگ حساب‌ها»، **ایجاد کدینگ پیشنهادی** را انتخاب کنید.
15 +4. در زبانه «عملیات یکپارچه و انبار»، ثبت یکپارچه را برای شرکت خالی فعال کنید؛ انبار و صندوق اولیه با مانده صفر ایجاد می‌شوند.
16 +5. کالا و طرف‌حساب بسازید؛ ابتدا فاکتور خرید برای ورود موجودی و سپس فروش، تسویه، گزارش و انبارگردانی را اجرا کنید.
17 +
18 +**توجه:** فعال‌سازی یکپارچه برای شرکتی که از قبل فاکتور/انبار/خزانه و مانده افتتاحیه دارد، به‌طور خودکار انجام نمی‌شود تا داده‌های تاریخی مغایر نشوند. برای نصب پاک، اطلاعات برنامه قدیمی را فقط پس از اطمینان از عدم نیاز حذف کنید.
19 +
20 +## ماژول‌ها
21 +- صدور فاکتور فروش و خرید، پیش‌فاکتور، مرجوعی با اتصال به فاکتور اصلی و شماره‌گذاری قابل تنظیم.
22 +- جستجوی کالا و طرف‌حساب، موجودی به تفکیک انبار، ارزش‌گذاری میانگین موزون و انبارگردانی.
23 +- دریافت و پرداخت، تسویه جزئی، حساب‌های صندوق و بانک، چک، هزینه و درآمد.
24 +- کدینگ چندسطحی، دوره مالی، سند دستی، دفتر کل، تراز آزمایشی، سود و زیان و ترازنامه.
25 +- پشتیبان رمزگذاری‌شده با AES-GCM و قابلیت بازیابی در محدوده شرکت فعال.
26 +- مدیریت کاربران و مجوزها. صدور اسناد دستی و تغییر ساختار حسابداری فقط برای مدیر مجاز است.
27 +
28 +## راهنمای توسعه
29 +```bash
30 +npm ci
31 +npm test
32 +npm run build
33 +npm exec tauri build
34 +```
35 +
36 +سیستم توسعه Windows به Node.js و Rust / ابزارهای Tauri نیاز دارد. تست‌ها از `fake-indexeddb` استفاده می‌کنند و اطلاعات واقعی کاربر را تغییر نمی‌دهند.
37 +
38 +## ملاحظات
39 +- مبالغ حسابداری به ریال صحیح و مقادیر کالا تا سه رقم اعشار نگهداری می‌شوند.
40 +- مرورگر/IndexedDB برای یک سیستم آفلاین محلی طراحی شده است؛ این نسخه سرور چندکاربره هم‌زمان نیست.
41 +- چاپ رسمی به معنی تایید حقوقی مالیاتی یا ارسال خودکار به سامانه مودیان نیست. قوانین مالیاتی را با حسابدار بررسی کنید.
42 +- لایسنس/نسخه آزمایشی فعلی سقف استفاده دارد؛ شرایط آن در خود نرم‌افزار نمایش داده می‌شود.
43 +- اطلاعات IndexedDB در حالت عادی رمزگذاری سراسری نیست؛ امنیت سیستم‌عامل، حساب ویندوز و نسخه پشتیبان ضروری است.
44 +- نصب‌کننده امضای دیجیتال تجاری ندارد و باید از صفحه اصلی Release دریافت شود.
45 +
46 +مستندات پروژه: `V2_THREE_PHASE_PLAN.md` و `V2_PHASE2_DELIVERY.md`.
RELEASE_NOTES_FA.md new
+37
@@ -0,0 +1,37 @@
1 +# Factor-easyPro 2.0.0 — یادداشت انتشار
2 +
3 +## امکانات نسخه ۲
4 +نرم‌افزار فارسی حسابداری و فاکتور برای Windows 64-bit با قابلیت کار آفلاین، راه‌اندازی اولیه از پایگاه داده خالی، ورود رمزدار و امکان تعریف چند شرکت.
5 +
6 +- فاکتور فروش/خرید، پیش‌فاکتور، مرجوعی متصل به فاکتور اولیه، شماره‌گذاری و چاپ A4/A5/حرارتی.
7 +- دفتر کل دوبل: کدینگ حساب‌ها، دوره مالی، سند دستی، قطعی‌سازی و جلوگیری از حذف مستقیم سند قطعی.
8 +- اتصال اتمی گردش فاکتور، ردیف‌ها، موجودی انبار، تسویه و سند حسابداری.
9 +- موجودی چندانباره، میانگین موزون بهای کالا، جلوگیری از منفی‌شدن موجودی، انبارگردانی و سند تعدیل.
10 +- تسویه جزئی، صندوق و بانک با معین مستقل، دریافت/پرداخت و چک؛ تراز آزمایشی و صورت‌های مالی.
11 +- نسخه پشتیبان رمزگذاری‌شده با گذرواژه، بازیابی تحت شرکت و کنترل مجوز مدیر.
12 +- نمایش قابل خواندن خطاها بر روی پنجره‌های فرم، جستجوی کالا و مشتری بر اساس نام/کد.
13 +
14 +## آزمون و تحویل
15 +- ۶۳ آزمون خودکار در آخرین اجرای کامل: همگی موفق.
16 +- صحت ارتقای ساختار داده، تراز حسابداری، مرجوعی‌های جزئی، تسویه، پشتیبان‌گیری و هم‌زمانی ثبت آزموده شد.
17 +- ساخت Windows NSIS x64 و آزمون اجرایی نسخه نصب‌شده/مجزا پیش از انتشار بررسی می‌شود.
18 +- هیچ پایگاه داده کاربر یا اطلاعات آزمایشی در نصب‌کننده بسته‌بندی نشده است.
19 +
20 +## نصب و اجرای نخست
21 +۱) فایل `Factor-easyPro_2.0.0_x64-setup.exe` را دریافت کنید.
22 +۲) در اولین اجرا رمز مدیر تعیین کنید.
23 +۳) حسابداری ← دوره‌های مالی: سال مالی را ایجاد کنید.
24 +۴) کدینگ حساب‌ها: کدینگ پیشنهادی را ایجاد کنید.
25 +۵) عملیات یکپارچه و انبار: فعال‌سازی برای شرکت بدون گردش قبلی؛ صندوق و انبار پایه ایجاد می‌شود.
26 +۶) کالاها و اشخاص را تعریف کنید و گردش خرید/فروش را ثبت کنید.
27 +
28 +## محدودیت‌های صریح
29 +- سیستم تک‌دستگاهی و آفلاین است؛ سرور هم‌زمان چندکاربره محسوب نمی‌شود.
30 +- تبدیل خودکار مانده‌ها و فاکتورهای تاریخی در محیط یکپارچه پشتیبانی نمی‌شود؛ این نصب از پایگاه داده خالی آغاز می‌شود.
31 +- «فاکتور رسمی» چاپی معادل اتصال به سامانه مؤدیان یا گواهی انطباق مالیاتی نیست.
32 +- رفع مغایرت اسناد قطعی از طریق رویدادهای مرجوعی و ثبت اصلاحی انجام می‌شود؛ همه مسیرهای اصلاحی فرم اختصاصی ندارند.
33 +- مجوز فعلی نسخه آزمایشی محدودیت زمان/تعداد صدور دارد (پیش‌فرض: ۱۵ روز یا ۲۰ فاکتور) و ادامه کار به مجوز نیاز دارد.
34 +- داده‌های اصلی IndexedDB رمزگذاری عمومی ندارند؛ ایمن‌سازی ویندوز و پشتیبان رمزدار ضروری است.
35 +- این نسخه امضای دیجیتال کد ندارد؛ پس از دانلود هش SHA-256 منتشرشده در Release را کنترل کنید.
36 +
37 +**منبع دانلود رسمی:** https://github.com/davoodmehraban89/Factor-easyPro/releases/tag/v2.0.0
V2_PHASE1_DELIVERY.md new
+45
@@ -0,0 +1,45 @@
1 +# Factor-easyPro V2 — Phase 1 delivery record
2 +Date: 2026-10-10
3 +Checkpoint: v2.0.0-alpha.1 accounting foundation (NOT a V2 production release)
4 +Plan: V2_THREE_PHASE_PLAN.md
5 +
6 +## Actual code delivered
7 +- src/core/AccountingCore.mjs: hierarchy, type classification, Persian date including leap-year check, fiscal period validation, debit/credit safe-integer arithmetic, period/date/company checks, reversible journal lines, source identity.
8 +- src/core/AccountingService.js: transaction-safe account creation and opt-in chart seeding; create/list/close fiscal periods; manual draft creation, editing, finalization, discarding; balanced posted journals, exactly-once source enforcement, immutable reversal and trial balance.
9 +- src/core/StorageService.js: existing v5 schema, atomic transaction and new accounting stores retained; v4->v5 migration test.
10 +- src/core/DataScope.js: four accounting tables explicitly scoped by company.
11 +- src/core/CompanyBackupService.js: atomic company backup import, accounting foreign key checks, duplicate/cross-company checks and rollback.
12 +- src/controllers/SettingsController.js: backup export includes V2 stores; a store read failure cannot be misrepresented as a complete backup; restore delegates to the atomic service.
13 +- src/views/SettingsView.js: correct encrypted .fbackup file picker and precise restore wording.
14 +- src/views/AccountingView.js: dedicated isolated route for chart, periods, draft/posted journals, reversal and trial balance, without changing legacy invoices.
15 +- src/main.js and index.html: route/menu for phase-one accounting module.
16 +- src/package.json: ESM boundary for direct source testing, root package.json: npm test and npm run test:phase1; fake-indexeddb as test-only dependency.
17 +
18 +## Acceptance evidence
19 +- Unit and isolated fake-IndexedDB integration tests cover chart, company boundary, closed periods, unbalanced drafts, durable posting, source deduplication, reversal, deactivation after posting, transaction rollback, backup import/export, migration from legacy DB v4 and licensing.
20 +- Automated suite: 33/33 passed (last run 2026-10-10); includes protection against adding a child to an account with posted movements.
21 +- Production frontend: npm run build succeeded.
22 +- Headless Chrome on isolated test profile: created fiscal period, seeded chart, issued a 2-line balanced manual journal through UI, displayed trial balance; no error toast. This profile is NOT the user's production data.
23 +- The packaged Tauri Windows app was launched in an isolated WebView2 temporary profile (not the user's production profile); CDP UI smoke passed: accounting route, new fiscal period, chart seed (13), two-line 12,000-rial journal, posted status and trial balance. Test app closed after verification.
24 +- A Tauri NSIS Windows x64 installer was generated successfully: src-tauri/target/release/bundle/nsis/Factor-easyPro_2.0.0-alpha.1_x64-setup.exe (2,252,940 bytes, 2026-10-10 13:02:33 local time).
25 +- Installer SHA256: B2059AF02BF5395B74DB059ADBAB39120C43131EAF6305E37C26FD8B575132B5.
26 +- The installer is **not code signed** (Authenticode Status=NotSigned). NSIS installation itself was not run on the user's working PC, to avoid replacing their existing installation; production install/upgrade rehearsals remain Phase 3.
27 +- No production database was wiped, no installed version replaced, and no prior changes were reset.
28 +- The v2.0.0-alpha.1 installer is a local Phase-1 checkpoint; it has NOT been published as a stable release or uploaded to GitHub.
29 +
30 +## Not done in Phase 1 (intentionally assigned later)
31 +- Existing invoice/purchase/treasury actions do NOT automatically post to the new accounting ledger.
32 +- Weighted-average stock valuation, stocktake, returns and invoice correction journal integration are for Phase 2.
33 +- Full legal/financial validation of accounting treatment and tax compliance remains necessary.
34 +- Financial statements and detailed ledger reports are Phase 3; trial balance here covers Phase-1 posted journal data only.
35 +- Installer release labeled stable V2 must wait for Phase 3 acceptance.
36 +
37 +## Important operating instructions
38 +1. Before manipulating any real financial records, take an encrypted backup from the existing Settings page and verify restore on a disposable profile.
39 +2. Accounting > periods: add a fiscal year, optionally seed the sample account chart, enter manual journal with balanced integer amounts in rial.
40 +3. Posted journals are immutable; correction is by reversal. A period with drafts cannot be closed.
41 +4. Existing invoices are still managed by legacy data flows until Phase-2 unified posting; do not interpret this Phase-1 trial balance as complete historic books.
42 +5. Do not remove existing code/unfinished modifications from the repository. There were numerous preexisting uncommitted changes before this phase.
43 +
44 +## Follow-on dependency contract
45 +Phase 2 must consume AccountingService and Financial Period rather than writing directly to journal stores. It must establish a transaction encompassing invoice, stock, settlement and journal posting, and provide mappings and multi-company tests.
V2_PHASE2_DELIVERY.md new
+33
@@ -0,0 +1,33 @@
1 +# Factor-easyPro — گزارش تحویل فاز دوم
2 +تاریخ: 2026-10-10
3 +نسخه: 2.0.0-alpha.2 (پیش‌نمایش آزمایشی؛ **نه نسخه نهایی یا پایدار**)
4 +مرجع: V2_THREE_PHASE_PLAN.md
5 +
6 +## قابلیت‌های پیاده‌سازی‌شده
7 +- صدور فاکتورهای خرید، فروش، مرجوعی فروش و مرجوعی خرید با سند حسابداری دوبل در یک تراکنش اتمی IndexedDB.
8 +- ثبت مالیات ورودی و خروجی، تخفیف، بهای تمام‌شده و مانده طرف حساب با اتصال به دوره مالی باز.
9 +- ثبت دریافت/پرداخت، پرداخت جزئی و تسویه‌های متعدد به یک فاکتور؛ انتقال بین بانک‌ها/صندوق‌ها و ثبت درآمد/هزینه.
10 +- ثبت چک‌های پرداختنی/دریافتنی و برخی تغییر وضعیت‌های آن‌ها در دفاتر مالی.
11 +- موجودی به تفکیک کالا، شرکت و انبار؛ بهای میانگین موزون با مقدار تا سه رقم اعشار و ریال صحیح.
12 +- جلوگیری از موجودی منفی و ثبت تکراری فاکتور/سند؛ کنترل شماره تکراری حتی در ثبت هم‌زمان.
13 +- انبارگردانی با شمارش واقعی، توقف گردش انبار حین شمارش و صدور سند تعدیل متوازن.
14 +- انتقال کالا بین انبارها، حفاظت از حذف کالا و اشخاص دارای گردش، ممنوعیت ثبت دستی خارج از دفتر یکپارچه.
15 +- ارتقای پایگاه داده از نسخه ۵ به ۶ با حفظ داده‌های قبلی و ورود/خروج پشتیبان شرکت.
16 +- افزودن تب عملیات یکپارچه در محیط حسابداری و اتصال فرم فعلی فاکتور، خزانه، هزینه و چک به موتور مالی.
17 +
18 +## شواهد پذیرش
19 +- آخرین اجرای کامل آزمون‌ها: **۵۹ از ۵۹ موفق** در ۱۰ اکتبر ۲۰۲۶.
20 +- آزمون تراکنش اتمی خرید ← فروش ← بهای تمام‌شده ← پرداخت جزئی ← دریافت باقیمانده؛ تراز بدهکار و بستانکار برابر.
21 +- آزمون هم‌زمانی ثبت یک سند و برخورد شماره فاکتور، برگشت کالا در چند مرحله با حفظ تمام ریال‌های بهای تاریخی، عملیات انبارگردانی و حساب‌های شرکت‌های جداگانه.
22 +- آزمون بازیابی پشتیبان پس از ثبت مالی و ردکردن داده مرجع نامعتبر بدون ثبت ناقص.
23 +- آزمون عملی در Chromium با نمایه مجزا: ایجاد دوره و کدینگ، فعال‌سازی شرکت آزمایشی، انبار، خرید و فروش از فرم واقعی با جستجوی کالا/مشتری و پرداخت جزئی.
24 +- ساخت Vite موفق. ساخت مجدد نصب‌کننده Windows NSIS نسخه alpha.2 در فرایند کنترل نهایی؛ وضعیت، زمان و هش آن باید جداگانه تأیید شوند.
25 +
26 +## محدودیت‌ها و خطرهای شناخته‌شده
27 +- سیستم یکپارچه فقط پس از فعال‌سازی صریح برای **شرکت بدون گردش قدیمی** فعال می‌شود؛ مهاجرت خودکار گردش قبلی یا مانده افتتاحیه انجام نمی‌شود.
28 +- برای کار با داده عملیاتی واقعی باید مهاجرت، مانده افتتاحیه، گزارش‌های کنترلی و بازیابی را روی نسخه آزمایشی تمرین کرد.
29 +- برگشت فروش/خرید از مسیر اسناد مرجوعی انجام می‌شود؛ فرآیند اصلاح جامع همه انواع اسناد مالی، نقش‌ها و ردپای حسابرسی در فاز سوم نیاز به تکمیل/تأیید دارد.
30 +- پرداخت چندمرحله‌ای از راه ثبت چند دریافت/پرداخت قابل انجام است؛ فرم واحد برای پرداخت چندروش هم‌زمان هنوز پذیرش مستقل نشده است.
31 +- تطبیق انبار و حسابداری در تست‌ها اثبات شده، اما آزمون بار، نصب روی دستگاه مشتری، چاپ‌های چندصفحه‌ای، انطباق حقوقی/مالیاتی و اعتبارسنجی کامل داده واقعی جزو پذیرش فاز سوم‌اند.
32 +- از جایگزینی نسخه نصب‌شده یا تغییر اطلاعات حسابداری واقعی بدون نسخه پشتیبان و تأیید کاربر خودداری شود.
33 +- نصب‌کننده alpha.2 امضای دیجیتال نهایی ندارد و برای انتشار عمومی نهایی تأیید نشده است.
V2_RELEASE_ACCEPTANCE.md new
+28
@@ -0,0 +1,28 @@
1 +# Factor-easyPro V2 — کنترل و پذیرش انتشار 2.0.0
2 +تاریخ اجرا: 2026-10-10
3 +
4 +## مسیر انتشار
5 +مخزن: https://github.com/davoodmehraban89/Factor-easyPro
6 +نسخه: 2.0.0 / tag: v2.0.0
7 +محصول: Windows x64 NSIS installer، Tauri 2
8 +
9 +## نتیجه آزمون واقعی
10 +- ۶۳/۶۳ آزمون خودکار Node (ریال صحیح، ثبت دوبل، داده چندشرکتی، migration، concurrency، rollback، خرید/فروش، قیمت میانگین، مرجوعی، انبارگردانی، بکاپ).
11 +- `npm run build`: موفق.
12 +- `npm exec tauri build`: موفق؛ برنامه app.exe و NSIS installer تولید شد.
13 +- اجرای app.exe از نسخه release با `WEBVIEW2_USER_DATA_FOLDER` مجزا: موفق؛ رمز مدیر در اولین اجرا تعیین شد.
14 +- رابط واقعی: ایجاد دوره، کدینگ پیشنهادی، فعال‌سازی یکپارچه، ایجاد انبار، خرید ۱۰۰۰ ریال، فروش ۶۰۰ ریال، پرداخت جزئی ۲۰۰ ریال و مانده ۴۰۰ ریال: موفق.
15 +- رابط گزارش‌های مالی: درآمد ۶۰۰، بهای تمام‌شده ۳۰۰، سود ۳۰۰ و اختلاف ترازنامه صفر: موفق.
16 +- قالب چاپ رسمی: نمایش عنوان «صورتحساب فروش کالا و خدمات» در وسط، شماره/تاریخ در چپ با چیدمان منظم و بدون کادر سربرگ: تأیید بررسی HTML.
17 +- داده آزمایشی هرگز همراه فایل نصب بسته‌بندی نشده است؛ پروفایل محلی پیشین برنامه با درخواست کاربر حذف شد.
18 +- مسیرهای ثبت دستی حرکت کالا، ویرایش سند قطعی و بازیابی بدون مجوز مدیر بررسی و در سطح سرویس محدود شدند.
19 +
20 +## محدودیت آزمون
21 +- آزمون نصب‌کننده با نصب واقعی روی ویندوز مشتری انجام نشد تا رجیستری و برنامه دیگر موجود دست‌کاری نشود؛ خود برنامه خروجی مستقیم تست شد.
22 +- پرینت واقعی با چاپگر، نمایش چندصفحه‌ای روی همه چاپگرها و قانون‌پذیری مالیاتی مستقلاً تأیید نشده‌اند.
23 +- نصب‌کننده بدون گواهی امضای کد است؛ برای تأیید فایل هش SHA-256 در Release ارائه می‌شود.
24 +- سطح دسترسی محلی در IndexedDB جایگزین رمزگذاری تمام داده و کنترل امنیتی سیستم‌عامل نیست.
25 +- سامانه مؤدیان و عملیات سرور شبکه‌ای خارج از محدوده این نسخه دسکتاپ هستند.
26 +
27 +## نتیجه
28 +آزمون‌های خودکار و سناریوهای اصلی روی نسخه release موفق‌اند. تولید و انتشار قابل دانلود همراه هش کنترل می‌شود. این متن گواهی مالیاتی، ممیزی امنیتی ثالث یا تضمین عملکرد روی همه نسخه‌های ویندوز نیست.
V2_THREE_PHASE_PLAN.md new
+48
@@ -0,0 +1,48 @@
1 +# Factor-easyPro V2 — Three-phase implementation contract
2 +Date: 2026-10-10 | Status: VERSION 2.0.0 RELEASE VALIDATED (63/63 tests, Windows build and isolated native-app UI smoke); GitHub publishing follows | Language: Persian product
3 +Release candidate: 2.0.0; automated 63/63 tests passed; Windows WebView2 isolated acceptance passed. See V2_RELEASE_ACCEPTANCE.md for verified scope and limitations.
4 +
5 +## Product definition
6 +Keep the existing Tauri/Vite/IndexedDB desktop program and preexisting user data. Build an affordable offline-first Iranian retail accounting application. Public Holoo features serve only as a functional benchmark; do not copy proprietary source, protected account charts or UI assets. Maintain backward compatibility and avoid unrequested rewrites.
7 +
8 +## Phase 1 — Accounting foundation and data integrity
9 +**Owner:** Accounting architecture and implementation. **Reviewer:** independent quality/data-integrity verification.
10 +- Accounting hierarchy: group, general, subsidiary, detail with parent/type/company validation.
11 +- Optional idempotent seed chart, explicitly NOT a proprietary Holoo chart.
12 +- Fiscal periods: open/closed, overlap detection, Jalali validation, admin-only close.
13 +- Manual journals: draft (editable/discardable), posted balanced entries, posting source deduplication, ledger lines, reversal without destructive edits.
14 +- Atomic IndexedDB multi-store financial transactions, company-scoped access, trial balance for posted journals.
15 +- Real isolated UI route for phase-one accounting operations (no changes to existing invoice posting).
16 +- Company-scoped encrypted backup export / atomic restore of Phase-1 records, reject foreign company collisions, test v4->v5 IndexedDB migration.
17 +- Evidence: unit/integration tests, Chromium smoke test on disposable profile, production Vite build, Windows bundling validation.
18 +**Exit:** all Phase-1 acceptance tests pass, no destructive changes to user records, limitations documented.
19 +**Explicit exclusion:** No automatic posting from existing invoices/treasury until a unified Phase-2 transaction is implemented.
20 +
21 +## Phase 2 — Complete integrated retail and financial flows
22 +**Owner:** transactional backend/inventory lead. **Reviewer:** accounting and regression lead.
23 +- Create event-to-ledger posting rules for sales, purchases, returns, expenses, receipts and payments, including tax/discount treatment.
24 +- Associate account/detail mappings and financial period with each operation. Enforce exactly-once posting per event and revision; use reversal for corrections.
25 +- Atomic item rows, stock movements, inventory valuation, receivable/payable ledgers and financial journal posting.
26 +- Stock valuation using defined weighted-average policy; quantity precision distinct from integer IRR amounts; no silent negative stock.
27 +- Stocktake count sessions, base snapshot, discrepancy review/approval, adjustment movements and balanced journal.
28 +- Transactional cash/bank/cheque flows, partial settlement and multi-method payments.
29 +- Keep existing forms working and improve keyboard, barcode and cashier workflows only where necessary.
30 +- High-risk tests: partial failure rollback, duplicate event, returns, cross-company access, concurrent posting, finance/stock reconciliation.
31 +**Exit:** from purchase to sale to settlement, all stock and financial totals reconcile against known sample scenarios.
32 +
33 +## Phase 3 — V2 final release and acceptance
34 +**Owner:** delivery/operations lead. **Reviewer:** independent quality/security lead.
35 +- Accounting reports: journal/daybook, general/subsidiary ledger, trial balance, balance sheet and P&L, drilldown and exports.
36 +- Role enforcement at service layer, operational audit trail and company isolation.
37 +- Comprehensive print/layout QA (Arabic/Persian fonts, multipage documents), UI accessibility and relevant regression fixes.
38 +- Full upgrade and restore rehearsals from 1.1.x with checksums/reconciliation, no data loss.
39 +- Independent end-to-end validation on disposable and restored fixtures; security hardening, performance checks.
40 +- Build final Windows x64 installer (version 2.0.0), verify installer/hash and publish GitHub Release download link after acceptance.
41 +**Exit:** a Windows installer of the complete V2 product, docs and verified release link, not an unfinished prototype.
42 +
43 +## Rules of engagement
44 +- Never reset an uncommitted working tree or mutate actual user's accounting data for tests.
45 +- Work only on authorized local source, avoid publishing partial V2 as stable.
46 +- Keep development changes in the live source tree and update this plan/delivery notes after each phase.
47 +- If an acceptance requirement cannot be demonstrated, mark it pending (not complete).
48 +- User's next instruction "مرحله بعدی" advances exactly one phase.
index.html
+5 -4
@@ -4,7 +4,7 @@
4 <meta charset="UTF-8" />
5 <meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover" />
6 <meta name="theme-color" content="#0d9488" />
7 - <title>فینورا پرو | سامانه حسابداری و صدور فاکتور</title>
7 + <title>Factor-easyPro | سامانه حسابداری و صدور فاکتور</title>
8
9 <link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/rastikerdar/vazirmatn@v33.003/misc/Farsi-Digits/Vazirmatn-FD-font-face.css" />
10 <link rel="stylesheet" href="/src/styles/main.css" />
@@ -14,7 +14,7 @@
14 <body>
15 <div id="app" class="app">
16 <div id="splash">
17 - <div class="splash-logo">فینورا پرو</div>
17 + <div class="splash-logo">Factor-easyPro</div>
18 <div class="splash-spinner"></div>
19 </div>
20
@@ -22,8 +22,8 @@
22 <div class="sidebar-brand">
23 <div class="brand-logo">فینورا</div>
24 <div class="brand-text hide-on-collapse">
25 - <h1>فینورا پرو</h1>
26 - <small>نسخه ۰.۱.۰</small>
25 + <h1>Factor-easyPro</h1>
26 + <small>نسخه ۲.۰.۰</small>
27 </div>
28 </div>
29
@@ -36,6 +36,7 @@
36 <li><a data-page="cheques"><span class="icon">💳</span><span class="label">چک‌ها</span></a></li>
37 <li><a data-page="expenses"><span class="icon">💰</span><span class="label">هزینه و درآمد</span></a></li>
38 <li><a data-page="reports"><span class="icon">📈</span><span class="label">گزارش سود و زیان</span></a></li>
39 + <li><a data-page="accounting"><span class="icon">📒</span><span class="label">حسابداری (فاز ۱)</span></a></li>
40 <li><a data-page="settings"><span class="icon">⚙️</span><span class="label">تنظیمات</span></a></li>
41 </ul>
42
package-lock.json
+19 -8
@@ -1,20 +1,21 @@
1 {
2 "name": "factor-easypro",
3 - "version": "1.0.0",
3 + "version": "2.0.0",
4 "lockfileVersion": 3,
5 "requires": true,
6 "packages": {
7 "": {
8 "name": "factor-easypro",
9 - "version": "1.0.0",
9 + "version": "2.0.0",
10 "license": "ISC",
11 "dependencies": {
12 - "@tauri-apps/plugin-dialog": "^2.7.3",
13 - "@tauri-apps/plugin-fs": "^2.5.2",
14 - "@tauri-apps/plugin-opener": "^2.5.5"
12 + "@tauri-apps/plugin-dialog": "2.7.3",
13 + "@tauri-apps/plugin-fs": "2.5.2",
14 + "@tauri-apps/plugin-opener": "2.5.5"
15 },
16 "devDependencies": {
17 "@tauri-apps/cli": "^2.11.4",
18 + "fake-indexeddb": "^6.2.5",
19 "vite": "^8.3.0"
20 }
21 },
@@ -587,6 +588,16 @@
588 "node": ">=8"
589 }
590 },
591 + "node_modules/fake-indexeddb": {
592 + "version": "6.2.5",
593 + "resolved": "https://registry.npmjs.org/fake-indexeddb/-/fake-indexeddb-6.2.5.tgz",
594 + "integrity": "sha512-CGnyrvbhPlWYMngksqrSSUT1BAVP49dZocrHuK0SvtR0D5TMs5wP0o3j7jexDJW01KSadjBp1M/71o/KR3nD1w==",
595 + "dev": true,
596 + "license": "Apache-2.0",
597 + "engines": {
598 + "node": ">=18"
599 + }
600 + },
601 "node_modules/fdir": {
602 "version": "6.5.0",
603 "resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz",
@@ -996,9 +1007,9 @@
1007 }
1008 },
1009 "node_modules/source-map-js": {
999 - "version": "1.2.1",
1000 - "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.1.tgz",
1001 - "integrity": "sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==",
1010 + "version": "1.2.2",
1011 + "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.2.tgz",
1012 + "integrity": "sha512-KGj/8Y43x35aZVDtt+J4mK1hoLGHULMYfSkODJNQjNDC3oW1PqPoxMwo0pLUsWM/UEGzON/NxeHywEfNXNP3Vw==",
1013 "dev": true,
1014 "license": "BSD-3-Clause",
1015 "engines": {
package.json
+8 -5
@@ -1,12 +1,14 @@
1 {
2 "name": "factor-easypro",
3 - "version": "1.0.0",
3 + "version": "2.0.0",
4 "description": "فینورا پرو - سامانه جامع حسابداری و صدور فاکتور",
5 "main": "index.js",
6 "scripts": {
7 "dev": "vite",
8 "build": "vite build",
9 - "preview": "vite preview"
9 + "preview": "vite preview",
10 + "test": "node --test tests/*.test.mjs",
11 + "test:phase1": "node --test tests/accounting-core.test.mjs tests/accounting-migration.test.mjs tests/accounting-phase1.test.mjs"
12 },
13 "repository": {
14 "type": "git",
@@ -22,11 +24,12 @@
24 "homepage": "https://github.com/davoodmehraban89/Factor-easyPro#readme",
25 "devDependencies": {
26 "@tauri-apps/cli": "^2.11.4",
27 + "fake-indexeddb": "^6.2.5",
28 "vite": "^8.3.0"
29 },
30 "dependencies": {
28 - "@tauri-apps/plugin-dialog": "^2.7.3",
29 - "@tauri-apps/plugin-fs": "^2.5.2",
30 - "@tauri-apps/plugin-opener": "^2.5.5"
31 + "@tauri-apps/plugin-dialog": "2.7.3",
32 + "@tauri-apps/plugin-fs": "2.5.2",
33 + "@tauri-apps/plugin-opener": "2.5.5"
34 }
35 }
src-tauri/Cargo.lock
+1 -1
@@ -66,7 +66,7 @@ checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470"
66
67 [[package]]
68 name = "app"
69 -version = "0.1.0"
69 +version = "2.0.0"
70 dependencies = [
71 "log",
72 "serde",
src-tauri/Cargo.toml
+1 -1
@@ -1,6 +1,6 @@
1 [package]
2 name = "app"
3 -version = "0.1.0"
3 +version = "2.0.0"
4 description = "A Tauri App"
5 authors = ["you"]
6 license = ""
src-tauri/src/lib.rs
+20 -8
@@ -1,9 +1,21 @@
1 +#[cfg(windows)]
2 +#[repr(C)] struct DataBlob { cb_data:u32, pb_data:*mut u8 }
3 +#[cfg(windows)]
4 +#[link(name="Crypt32")] extern "system" { fn CryptProtectData(p:*const DataBlob,d:*const u16,e:*const DataBlob,r:*mut core::ffi::c_void,prompt:*mut core::ffi::c_void,flags:u32,out:*mut DataBlob)->i32; fn CryptUnprotectData(p:*const DataBlob,d:*mut *mut u16,e:*const DataBlob,r:*mut core::ffi::c_void,prompt:*mut core::ffi::c_void,flags:u32,out:*mut DataBlob)->i32; }
5 +#[cfg(windows)]
6 +#[link(name="Kernel32")] extern "system" { fn LocalFree(p:*mut core::ffi::c_void)->*mut core::ffi::c_void; }
7 +fn hex_encode(v:&[u8])->String{v.iter().map(|b|format!("{:02x}",b)).collect()}
8 +fn hex_decode(s:&str)->Result<Vec<u8>,String>{if s.len()%2!=0{return Err("invalid protected data".into())} (0..s.len()).step_by(2).map(|i|u8::from_str_radix(&s[i..i+2],16).map_err(|e|e.to_string())).collect()}
9 +#[tauri::command]
10 +fn protect_local_state(value:String)->Result<String,String>{
11 + #[cfg(windows)] unsafe{let bytes=value.into_bytes();let input=DataBlob{cb_data:bytes.len() as u32,pb_data:bytes.as_ptr() as *mut u8};let mut out=DataBlob{cb_data:0,pb_data:core::ptr::null_mut()};if CryptProtectData(&input,core::ptr::null(),core::ptr::null(),core::ptr::null_mut(),core::ptr::null_mut(),1,&mut out)==0{return Err("DPAPI protect failed".into())}let data=core::slice::from_raw_parts(out.pb_data,out.cb_data as usize);let result=hex_encode(data);LocalFree(out.pb_data as _);Ok(result)}
12 + #[cfg(not(windows))]{Ok(hex_encode(value.as_bytes()))}
13 +}
14 +#[tauri::command]
15 +fn unprotect_local_state(value:String)->Result<String,String>{
16 + let raw=hex_decode(&value)?;
17 + #[cfg(windows)] unsafe{let input=DataBlob{cb_data:raw.len() as u32,pb_data:raw.as_ptr() as *mut u8};let mut out=DataBlob{cb_data:0,pb_data:core::ptr::null_mut()};if CryptUnprotectData(&input,core::ptr::null_mut(),core::ptr::null(),core::ptr::null_mut(),core::ptr::null_mut(),1,&mut out)==0{return Err("DPAPI unprotect failed".into())}let data=core::slice::from_raw_parts(out.pb_data,out.cb_data as usize);let result=String::from_utf8(data.to_vec()).map_err(|e|e.to_string())?;LocalFree(out.pb_data as _);Ok(result)}
18 + #[cfg(not(windows))]{String::from_utf8(raw).map_err(|e|e.to_string())}
19 +}
20 #[cfg_attr(mobile, tauri::mobile_entry_point)]
2 -pub fn run() {
3 - tauri::Builder::default()
4 - .plugin(tauri_plugin_dialog::init())
5 - .plugin(tauri_plugin_fs::init())
6 - .plugin(tauri_plugin_opener::init())
7 - .run(tauri::generate_context!())
8 - .expect("error while running tauri application");
9 -}
\ No newline at end of file
21 +pub fn run(){tauri::Builder::default().plugin(tauri_plugin_dialog::init()).plugin(tauri_plugin_fs::init()).plugin(tauri_plugin_opener::init()).invoke_handler(tauri::generate_handler![protect_local_state,unprotect_local_state]).run(tauri::generate_context!()).expect("error while running tauri application");}
src-tauri/tauri.conf.json
+3 -3
@@ -1,7 +1,7 @@
1 {
2 "$schema": "../node_modules/@tauri-apps/cli/config.schema.json",
3 "productName": "Factor-easyPro",
4 - "version": "0.1.0",
4 + "version": "2.0.0",
5 "identifier": "com.davoodmehraban.factoreasypro",
6 "build": {
7 "frontendDist": "../dist",
@@ -12,7 +12,7 @@
12 "app": {
13 "windows": [
14 {
15 - "title": "فینورا پرو",
15 + "title": "Factor-easyPro",
16 "width": 1280,
17 "height": 800,
18 "resizable": true,
@@ -20,7 +20,7 @@
20 }
21 ],
22 "security": {
23 - "csp": null
23 + "csp": "default-src 'self'; img-src 'self' data: blob:; style-src 'self' 'unsafe-inline'; script-src 'self' 'unsafe-inline'; script-src-attr 'unsafe-inline'; connect-src 'self' ipc: http://ipc.localhost; font-src 'self' data:; object-src 'none'; base-uri 'self'; frame-ancestors 'none'"
24 }
25 },
26 "bundle": {
src/controllers/ChequeController.js
+15 -6
@@ -4,12 +4,14 @@
4
5 import { StorageService } from '../core/StorageService.js';
6 import { Auth } from '../core/Auth.js';
7 +import { DataScope } from '../core/DataScope.js';
8 +import { RetailPostingService } from '../core/RetailPostingService.js';
9
10 class ChequeControllerImpl {
11 async getAll(filter = {}) {
12 const user = Auth.current();
13 if (!user) return [];
12 - let list = await StorageService.getByOwner('cheques', user.id);
14 + let list = await DataScope.list('cheques');
15
16 if (filter.direction) list = list.filter(c => c.direction === filter.direction);
17 if (filter.status) list = list.filter(c => c.status === filter.status);
@@ -53,12 +55,15 @@ class ChequeControllerImpl {
55 refInvoiceNumber: data.refInvoiceNumber || null,
56 description: (data.description || '').trim()
57 };
56 - return await StorageService.put('cheques', cheque);
58 + const scoped = await DataScope.stamp('cheques', cheque);
59 + if (await RetailPostingService.isEnabled()) return RetailPostingService.postCheque(scoped);
60 + return await StorageService.put('cheques', scoped);
61 }
62
63 async update(id, data) {
64 const existing = await StorageService.get('cheques', id);
61 - if (!existing) throw new Error('چک یافت نشد');
65 + if (!existing || existing.companyId !== await DataScope.companyId()) throw new Error('چک در شرکت فعال یافت نشد');
66 + if (existing.financePosted) throw new Error('مشخصات چک دارای سند مالی قطعی قابل ویرایش مستقیم نیست');
67 const updated = {
68 ...existing,
69 direction: data.direction || existing.direction,
@@ -77,18 +82,22 @@ class ChequeControllerImpl {
82 refInvoiceNumber: data.refInvoiceNumber || existing.refInvoiceNumber,
83 description: (data.description || '').trim()
84 };
80 - return await StorageService.put('cheques', updated);
85 + return await StorageService.put('cheques', await DataScope.stamp('cheques', updated));
86 }
87
88 async changeStatus(id, status) {
89 const cheque = await StorageService.get('cheques', id);
85 - if (!cheque) throw new Error('چک یافت نشد');
90 + if (!cheque || cheque.companyId !== await DataScope.companyId()) throw new Error('چک در شرکت فعال یافت نشد');
91 + if (cheque.financePosted) return RetailPostingService.changeChequeStatus(id,status);
92 cheque.status = status;
93 cheque.statusChangedAt = new Date().toISOString();
88 - return await StorageService.put('cheques', cheque);
94 + return await StorageService.put('cheques', await DataScope.stamp('cheques', cheque));
95 }
96
97 async delete(id) {
98 + const cheque = await StorageService.get('cheques', id);
99 + if (!cheque || cheque.companyId !== await DataScope.companyId()) throw new Error('چک در شرکت فعال یافت نشد');
100 + if (cheque.financePosted) throw new Error('چک دارای سند مالی قطعی قابل حذف نیست');
101 return await StorageService.delete('cheques', id);
102 }
103
src/controllers/ContactController.js
+57 -13
@@ -4,12 +4,14 @@
4
5 import { StorageService } from '../core/StorageService.js';
6 import { Auth } from '../core/Auth.js';
7 +import { DataScope } from '../core/DataScope.js';
8 +import { RetailPostingService } from '../core/RetailPostingService.js';
9
10 class ContactControllerImpl {
11 async getAll(filter = {}) {
12 const user = Auth.current();
13 if (!user) return [];
12 - let list = await StorageService.getByOwner('contacts', user.id);
14 + let list = await DataScope.list('contacts');
15
16 if (filter.search) {
17 const q = String(filter.search).toLowerCase();
@@ -55,7 +57,7 @@ class ContactControllerImpl {
57 note: (data.note || '').trim(),
58 isActive: true
59 };
58 - return await StorageService.put('contacts', contact);
60 + return await StorageService.put('contacts', await DataScope.stamp('contacts', contact));
61 }
62
63 async update(id, data) {
@@ -77,22 +79,48 @@ class ContactControllerImpl {
79 tags: Array.isArray(data.tags) ? data.tags : existing.tags || [],
80 note: (data.note || '').trim()
81 };
80 - return await StorageService.put('contacts', updated);
82 + return await StorageService.put('contacts', await DataScope.stamp('contacts', updated));
83 }
84
85 async delete(id) {
84 - return await StorageService.delete('contacts', id);
86 + const contact = await StorageService.get('contacts',id);
87 + if (!contact || contact.companyId !== await DataScope.companyId()) throw new Error('شخص در شرکت فعال یافت نشد');
88 + const invoices=await DataScope.list('invoices');
89 + const cheques=await DataScope.list('cheques');
90 + const receipts=await DataScope.list('treasury');
91 + if (invoices.some(x=>x.contactId===id)||cheques.some(x=>x.contactId===id)||
92 + receipts.some(x=>x.contactId===id))
93 + throw new Error('حذف شخص دارای گردش مالی مجاز نیست؛ اطلاعات را غیرفعال کنید');
94 + return await StorageService.delete('contacts',id);
95 }
96
97 + async _financialContactRows(contactId=null) {
98 + const [accounts,entries,lines]=await Promise.all([
99 + DataScope.list('account_chart'),DataScope.list('journal_entries'),DataScope.list('journal_lines')
100 + ]);
101 + const relevant=new Set(accounts.filter(a=>['102','201'].includes(a.code)).map(a=>a.id));
102 + const posted=new Map(entries.filter(j=>j.status==='posted').map(j=>[j.id,j]));
103 + return lines.filter(l=>relevant.has(l.accountId)&&posted.has(l.journalId)&&
104 + (!contactId||l.contactId===contactId)&&!!l.contactId).map(l=>{
105 + const journal=posted.get(l.journalId);
106 + return {contactId:l.contactId,date:journal.date,refId:journal.sourceId,
107 + type:journal.sourceType,typeLabel:journal.description,refNumber:'',
108 + debit:l.debit,credit:l.credit,note:journal.description||'',dateISO:journal.postedAt||journal.date};
109 + });
110 + }
111 /**
112 * محاسبه‌ی مانده حساب
113 */
114 async getBalance(contactId) {
115 + if (await RetailPostingService.isEnabled()) {
116 + const rows=await this._financialContactRows(contactId);
117 + return rows.reduce((sum,row)=>sum+row.debit-row.credit,0);
118 + }
119 const user = Auth.current();
120 if (!user) return 0;
121
94 - const invoices = await StorageService.getByOwner('invoices', user.id);
95 - const transactions = await StorageService.getByOwner('treasury', user.id);
122 + const invoices = await DataScope.list('invoices');
123 + const transactions = await DataScope.list('treasury');
124
125 const contactInvoices = invoices.filter(i => i.contactId === contactId && !i.isPreInvoice);
126 const invoiceTotal = contactInvoices.filter(i => i.kind === 'sale').reduce((s, i) => s + (Number(i.grandTotal) || 0), 0);
@@ -109,9 +137,16 @@ class ContactControllerImpl {
137 }
138
139 async getBalanceMap(contactIds) {
140 + if (await RetailPostingService.isEnabled()) {
141 + const rows=await this._financialContactRows();
142 + const result=Object.fromEntries(contactIds.map(id=>[id,0]));
143 + for(const row of rows) if(Object.hasOwn(result,row.contactId))
144 + result[row.contactId]+=row.debit-row.credit;
145 + return result;
146 + }
147 const user = Auth.current();
113 - const invoices = await StorageService.getByOwner('invoices', user.id);
114 - const transactions = await StorageService.getByOwner('treasury', user.id);
148 + const invoices = await DataScope.list('invoices');
149 + const transactions = await DataScope.list('treasury');
150 const map = {};
151 contactIds.forEach(id => map[id] = { invoices: 0, returns: 0, receipts: 0, payments: 0 });
152
@@ -145,13 +180,22 @@ class ContactControllerImpl {
180 * تمام تراکنش‌ها (فاکتورها، برگشت‌ها، دریافت‌ها، پرداخت‌ها، چک‌ها) با مانده تجمعی
181 */
182 async getLedger(contactId) {
183 + if (await RetailPostingService.isEnabled()) {
184 + const entries=(await this._financialContactRows(contactId)).sort((a,b)=>a.date.localeCompare(b.date));
185 + let running=0,totalDebit=0,totalCredit=0;
186 + const rows=entries.map(e=>{
187 + running+=e.debit-e.credit;totalDebit+=e.debit;totalCredit+=e.credit;
188 + return {...e,balance:running};
189 + });
190 + return {rows,totalDebit,totalCredit,finalBalance:running};
191 + }
192 const user = Auth.current();
193 if (!user) return { rows: [], totalDebit: 0, totalCredit: 0, finalBalance: 0 };
194
195 const [invoices, transactions, cheques] = await Promise.all([
152 - StorageService.getByOwner('invoices', user.id),
153 - StorageService.getByOwner('treasury', user.id),
154 - StorageService.getByOwner('cheques', user.id)
196 + DataScope.list('invoices'),
197 + DataScope.list('treasury'),
198 + DataScope.list('cheques')
199 ]);
200
201 const entries = [];
@@ -311,7 +355,7 @@ class ContactControllerImpl {
355 const user = Auth.current();
356 if (!user) return { totalDebt: 0, totalCredit: 0, debtorsCount: 0, creditorsCount: 0 };
357
314 - const contacts = await StorageService.getByOwner('contacts', user.id);
358 + const contacts = await DataScope.list('contacts');
359 const ids = contacts.map(c => c.id);
360 const balanceMap = await this.getBalanceMap(ids);
361
@@ -331,7 +375,7 @@ class ContactControllerImpl {
375
376 async getAllTags() {
377 const user = Auth.current();
334 - const all = await StorageService.getByOwner('contacts', user.id);
378 + const all = await DataScope.list('contacts');
379 const set = new Set();
380 all.forEach(c => (c.tags || []).forEach(t => set.add(t)));
381 return Array.from(set).sort((a, b) => a.localeCompare(b, 'fa'));
src/controllers/ExcelController.js
+21 -20
@@ -4,6 +4,7 @@
4
5 import { StorageService } from '../core/StorageService.js';
6 import { Auth } from '../core/Auth.js';
7 +import { DataScope } from '../core/DataScope.js';
8 import { Jalali } from '../utils/Jalali.js';
9 import { ContactController } from './ContactController.js';
10 import { ProductController } from './ProductController.js';
@@ -63,20 +64,20 @@ class ExcelControllerImpl {
64 if (!user) throw new Error('کاربر یافت نشد');
65
66 const [companies, contacts, products, invoices, cheques, treasury, expenses, units, categories] = await Promise.all([
66 - StorageService.getByOwner('companies', user.id),
67 - StorageService.getByOwner('contacts', user.id),
68 - StorageService.getByOwner('products', user.id),
69 - StorageService.getByOwner('invoices', user.id),
70 - StorageService.getByOwner('cheques', user.id),
71 - StorageService.getByOwner('treasury', user.id),
72 - StorageService.getByOwner('expenses', user.id),
73 - StorageService.getByOwner('units', user.id),
74 - StorageService.getByOwner('categories', user.id)
67 + DataScope.list('companies'),
68 + DataScope.list('contacts'),
69 + DataScope.list('products'),
70 + DataScope.list('invoices'),
71 + DataScope.list('cheques'),
72 + DataScope.list('treasury'),
73 + DataScope.list('expenses'),
74 + DataScope.list('units'),
75 + DataScope.list('categories')
76 ]);
77
78 const accounts = treasury.filter(t => t.recordType === 'account');
79 const transactions = treasury.filter(t => t.recordType === 'transaction');
79 - const stockMovements = await StorageService.getByOwner('stock_movements', user.id);
80 + const stockMovements = await DataScope.list('stock_movements');
81
82 const wb = XLSX.utils.book_new();
83
@@ -301,8 +302,8 @@ class ExcelControllerImpl {
302
303 switch (section) {
304 case 'products': {
304 - const products = await StorageService.getByOwner('products', user.id);
305 - const units = await StorageService.getByOwner('units', user.id);
305 + const products = await DataScope.list('products');
306 + const units = await DataScope.list('units');
307 const stockMap = await ProductController.getStockMap(products.map(p => p.id));
308 const data = [['کد', 'نام', 'مشخصه', 'واحد', 'قیمت خرید', 'قیمت فروش', 'نقطه سفارش', 'موجودی']];
309 products.forEach(p => {
@@ -322,7 +323,7 @@ class ExcelControllerImpl {
323 }
324
325 case 'contacts': {
325 - const contacts = await StorageService.getByOwner('contacts', user.id);
326 + const contacts = await DataScope.list('contacts');
327 const balanceMap = await ContactController.getBalanceMap(contacts.map(c => c.id));
328 const data = [['نام', 'نوع', 'نقش', 'موبایل', 'تلفن', 'کد ملی/شناسه', 'کد پستی', 'نشانی', 'مانده']];
329 contacts.forEach(c => {
@@ -341,7 +342,7 @@ class ExcelControllerImpl {
342 }
343
344 case 'invoices': {
344 - const invoices = await StorageService.getByOwner('invoices', user.id);
345 + const invoices = await DataScope.list('invoices');
346 const data = [['شماره', 'تاریخ', 'نوع', 'خریدار', 'جمع', 'تخفیف', 'مالیات', 'قابل پرداخت', 'پرداخت‌شده', 'باقیمانده']];
347 invoices.forEach(inv => {
348 data.push([
@@ -362,7 +363,7 @@ class ExcelControllerImpl {
363 }
364
365 case 'cheques': {
365 - const cheques = await StorageService.getByOwner('cheques', user.id);
366 + const cheques = await DataScope.list('cheques');
367 const data = [['نوع', 'طرف حساب', 'شماره صیادی', 'بانک', 'مبلغ', 'سررسید', 'وضعیت']];
368 cheques.forEach(c => {
369 data.push([
@@ -377,7 +378,7 @@ class ExcelControllerImpl {
378 }
379
380 case 'expenses': {
380 - const expenses = await StorageService.getByOwner('expenses', user.id);
381 + const expenses = await DataScope.list('expenses');
382 const data = [['نوع', 'تاریخ', 'سرفصل', 'شرح', 'مبلغ']];
383 expenses.forEach(e => {
384 data.push([
@@ -448,7 +449,7 @@ class ExcelControllerImpl {
449 if (rows.length === 0) throw new Error('شیت کالاها خالی است');
450
451 const mode = options.mode || 'merge';
451 - const existing = await StorageService.getByOwner('products', user.id);
452 + const existing = await DataScope.list('products');
453
454 if (mode === 'replace') {
455 for (const p of existing) {
@@ -484,7 +485,7 @@ class ExcelControllerImpl {
485 isActiveBuy: true,
486 description: ''
487 };
487 - await StorageService.put('products', product);
488 + await StorageService.put('products', await DataScope.stamp('products', product));
489 added++;
490 }
491
@@ -506,7 +507,7 @@ class ExcelControllerImpl {
507 if (rows.length === 0) throw new Error('شیت اشخاص خالی است');
508
509 const mode = options.mode || 'merge';
509 - const existing = await StorageService.getByOwner('contacts', user.id);
510 + const existing = await DataScope.list('contacts');
511
512 if (mode === 'replace') {
513 for (const c of existing) {
@@ -545,7 +546,7 @@ class ExcelControllerImpl {
546 note: '',
547 isActive: true
548 };
548 - await StorageService.put('contacts', contact);
549 + await StorageService.put('contacts', await DataScope.stamp('contacts', contact));
550 added++;
551 }
552
src/controllers/ExpenseController.js
+13 -5
@@ -4,6 +4,8 @@
4
5 import { StorageService } from '../core/StorageService.js';
6 import { Auth } from '../core/Auth.js';
7 +import { DataScope } from '../core/DataScope.js';
8 +import { RetailPostingService } from '../core/RetailPostingService.js';
9 import { Jalali } from '../utils/Jalali.js';
10
11 const DEFAULT_EXPENSE_CATEGORIES = [
@@ -20,7 +22,7 @@ class ExpenseControllerImpl {
22 async getAll(filter = {}) {
23 const user = Auth.current();
24 if (!user) return [];
23 - let list = await StorageService.getByOwner('expenses', user.id);
25 + let list = await DataScope.list('expenses');
26
27 if (filter.kind) list = list.filter(e => e.kind === filter.kind);
28 if (filter.category) list = list.filter(e => e.category === filter.category);
@@ -56,12 +58,15 @@ class ExpenseControllerImpl {
58 description: (data.description || '').trim(),
59 refNumber: (data.refNumber || '').trim()
60 };
59 - return await StorageService.put('expenses', expense);
61 + const stamped = await DataScope.stamp('expenses', expense);
62 + if (await RetailPostingService.isEnabled()) return RetailPostingService.postExpense(stamped);
63 + return await StorageService.put('expenses', stamped);
64 }
65
66 async update(id, data) {
67 const existing = await StorageService.get('expenses', id);
64 - if (!existing) throw new Error('سند یافت نشد');
68 + if (!existing || existing.companyId !== await DataScope.companyId()) throw new Error('سند در شرکت فعال یافت نشد');
69 + if (existing.financePosted) throw new Error('سند قطعی مالی قابل ویرایش مستقیم نیست');
70 const updated = {
71 ...existing,
72 kind: data.kind === 'income' ? 'income' : 'expense',
@@ -72,17 +77,20 @@ class ExpenseControllerImpl {
77 description: (data.description || '').trim(),
78 refNumber: (data.refNumber || '').trim()
79 };
75 - return await StorageService.put('expenses', updated);
80 + return await StorageService.put('expenses', await DataScope.stamp('expenses', updated));
81 }
82
83 async delete(id) {
84 + const existing = await StorageService.get('expenses', id);
85 + if (!existing || existing.companyId !== await DataScope.companyId()) throw new Error('سند در شرکت فعال یافت نشد');
86 + if (existing.financePosted) throw new Error('سند مالی قطعی حذف نمی‌شود؛ اصلاح از مسیر سند برگشت انجام شود');
87 return await StorageService.delete('expenses', id);
88 }
89
90 async getCategories(kind = null) {
91 const user = Auth.current();
92 if (!user) return [];
85 - const all = await StorageService.getByOwner('expenses', user.id);
93 + const all = await DataScope.list('expenses');
94 const custom = new Set();
95 all.forEach(e => {
96 if (kind && e.kind !== kind) return;
src/controllers/InvoiceController.js
+89 -19
@@ -5,20 +5,37 @@
5 import { StorageService } from '../core/StorageService.js';
6 import { Auth } from '../core/Auth.js';
7 import { ProductController } from './ProductController.js';
8 +import { SettingsController } from './SettingsController.js';
9 +import { LicenseService } from '../core/LicenseService.js';
10 +import { DataScope } from '../core/DataScope.js';
11 +import { RetailPostingService } from '../core/RetailPostingService.js';
12
13 class InvoiceControllerImpl {
14 // شماره‌ی بعدی سریال (بر اساس نوع سند)
15 async getNextNumber(kind = 'sale') {
12 - const user = Auth.current();
13 - const all = await StorageService.getByOwner('invoices', user.id);
16 + const all = await DataScope.list('invoices');
17 const kindInvoices = all.filter(i => i.kind === kind && !i.isPreInvoice);
15 - if (kindInvoices.length === 0) return 1;
16 - const maxNum = Math.max(...kindInvoices.map(i => Number(i.number) || 0));
17 - return maxNum + 1;
18 + const maxNum = kindInvoices.length ? Math.max(...kindInvoices.map(i => Number(i.number) || 0)) : 0;
19 + const settings = await SettingsController.getInvoiceSettings();
20 + return Math.max(maxNum + 1, Number(settings.nextNumber) || 1);
21 + }
22 +
23 + async _assertUniqueNumber(number, excludeId = null) {
24 + const all = await DataScope.list('invoices');
25 + if (all.some(i => i.id !== excludeId && !i.isPreInvoice && String(i.number) === String(number))) {
26 + throw new Error('شماره فاکتور تکراری است');
27 + }
28 }
29
30 // ذخیره‌ی فاکتور (ایجاد یا ویرایش)
31 async save(data, id = null) {
32 + if (id) {
33 + const previous = await StorageService.get('invoices', id);
34 + if (!previous || previous.companyId !== await DataScope.companyId())
35 + throw new Error('فاکتور در شرکت فعال یافت نشد');
36 + if (previous.financePosted)
37 + throw new Error('فاکتور ثبت‌شده در حسابداری قطعی است؛ ویرایش مستقیم حتی به پیش‌فاکتور مجاز نیست');
38 + }
39 const user = Auth.current();
40 const items = (data.items || []).map(it => {
41 const qty = Number(it.qty) || 0;
@@ -75,6 +92,7 @@ class InvoiceControllerImpl {
92
93 const baseData = {
94 ownerUserId: user.id,
95 + companyId: await DataScope.companyId(),
96 kind: data.kind || 'sale',
97 isPreInvoice: !!data.isPreInvoice,
98 date: data.date || this._todayJalali(),
@@ -93,24 +111,62 @@ class InvoiceControllerImpl {
111 paidAmount,
112 remaining,
113 description: (data.description || '').trim(),
96 - status: remaining === 0 ? 'paid' : (paidAmount > 0 ? 'partial' : 'unpaid')
114 + status: remaining === 0 ? 'paid' : (paidAmount > 0 ? 'partial' : 'unpaid'),
115 + originalInvoiceId: data.originalInvoiceId || null,
116 + warehouseId: data.warehouseId || null
117 };
118
119 + // V2: once activated, issuance, stock movement, settlement and general ledger
120 + // must commit together. Existing posted documents are never silently rewritten.
121 + if (await RetailPostingService.isEnabled() && !baseData.isPreInvoice) {
122 + LicenseService.assertWritable();
123 + const previous = id ? await StorageService.get('invoices', id) : null;
124 + if (id && (!previous || previous.companyId !== baseData.companyId || !previous.isPreInvoice))
125 + throw new Error('فاکتور قطعی قابل ویرایش مستقیم نیست؛ اصلاح از مسیر مرجوعی یا سند معکوس انجام شود');
126 + const settings = await SettingsController.getInvoiceSettings();
127 + const minimum = await this.getNextNumber(baseData.kind);
128 + const typed = String(data.number ?? '').trim().replace(/[۰-۹]/g, c => String(c.charCodeAt(0)-1776));
129 + const number = settings.numberingMode === 'manual' && typed ? typed : String(minimum);
130 + if (!/^\d+$/.test(number) || !Number.isSafeInteger(Number(number)) || Number(number)<minimum)
131 + throw new Error('شماره فاکتور از محدوده مجاز کوچک‌تر است');
132 + const issued = await RetailPostingService.issueInvoice({ ...baseData,
133 + id: id || StorageService.uid('inv_'), clientUuid: previous?.clientUuid || this._uuid(), number });
134 + await LicenseService.recordIssuedInvoice();
135 + await SettingsController.saveInvoiceSettings({ ...settings,
136 + nextNumber: Math.max(Number(settings.nextNumber)||1, Number(number)+1) });
137 + return issued;
138 + }
139 +
140 let saved;
141 if (id) {
142 const existing = await StorageService.get('invoices', id);
143 if (!existing) throw new Error('فاکتور یافت نشد');
144 + const becomesIssued = !!existing.isPreInvoice && !baseData.isPreInvoice;
145 + if (becomesIssued) LicenseService.assertWritable();
146 saved = { ...existing, ...baseData };
104 - await StorageService.put('invoices', saved);
147 + await StorageService.put('invoices', await DataScope.stamp('invoices', saved));
148 + if (becomesIssued) await LicenseService.recordIssuedInvoice();
149 } else {
106 - const number = await this.getNextNumber(baseData.kind);
150 + if (!baseData.isPreInvoice) LicenseService.assertWritable();
151 + const settings = await SettingsController.getInvoiceSettings();
152 + const minimum = await this.getNextNumber(baseData.kind);
153 + const rawNumber = String(data.number ?? '').trim().replace(/[۰-۹]/g, ch => String(ch.charCodeAt(0) - 1776)).replace(/[٠-٩]/g, ch => String(ch.charCodeAt(0) - 1632));
154 + const number = settings.numberingMode === 'manual' ? (rawNumber || String(minimum)) : String(minimum);
155 + if (!/^\d+$/.test(number) || !Number.isSafeInteger(Number(number)) || Number(number) < minimum) {
156 + throw new Error(`شماره فاکتور باید عددی و حداقل ${minimum} باشد؛ شماره‌های قبلی مجاز نیستند`);
157 + }
158 + await this._assertUniqueNumber(number);
159 saved = {
160 id: StorageService.uid('inv_'),
161 clientUuid: this._uuid(),
162 number,
163 ...baseData
164 };
113 - await StorageService.put('invoices', saved);
165 + await StorageService.put('invoices', await DataScope.stamp('invoices', saved));
166 + if (!baseData.isPreInvoice) await LicenseService.recordIssuedInvoice();
167 + if (!baseData.isPreInvoice) {
168 + await SettingsController.saveInvoiceSettings({ ...settings, nextNumber: Math.max(Number(settings.nextNumber), Number(number) + 1) });
169 + }
170 }
171
172 // بازنویسی حرکات انبار
@@ -121,7 +177,7 @@ class InvoiceControllerImpl {
177 // ثبت حرکات انبار بر اساس نوع سند
178 async _rebuildStockMovements(invoice) {
179 const user = Auth.current();
124 - const all = await StorageService.getByOwner('stock_movements', user.id);
180 + const all = await DataScope.list('stock_movements');
181
182 // حذف حرکات قبلی این فاکتور
183 for (const m of all.filter(x => x.refId === invoice.id)) {
@@ -153,13 +209,13 @@ class InvoiceControllerImpl {
209 note: `فاکتور #${invoice.number}`,
210 date: new Date().toISOString()
211 };
156 - await StorageService.put('stock_movements', mv);
212 + await StorageService.put('stock_movements', await DataScope.stamp('stock_movements', mv));
213 }
214 }
215
216 async getAll(filter = {}) {
217 const user = Auth.current();
162 - let list = await StorageService.getByOwner('invoices', user.id);
218 + let list = await DataScope.list('invoices');
219
220 if (filter.kind) list = list.filter(i => i.kind === filter.kind);
221 if (filter.preInvoice !== undefined && filter.preInvoice !== '') {
@@ -188,8 +244,11 @@ class InvoiceControllerImpl {
244 }
245
246 async delete(id) {
247 + const record = await this.get(id);
248 + if (!record || record.companyId !== await DataScope.companyId()) throw new Error('فاکتور در شرکت فعال یافت نشد');
249 + if (record.financePosted) throw new Error('فاکتور قطعی دارای سند مالی است و قابل حذف نیست؛ از سند مرجوعی استفاده کنید');
250 const user = Auth.current();
192 - const movements = await StorageService.getByOwner('stock_movements', user.id);
251 + const movements = await DataScope.list('stock_movements');
252 for (const m of movements.filter(x => x.refId === id)) {
253 await StorageService.delete('stock_movements', m.id);
254 }
@@ -198,32 +257,43 @@ class InvoiceControllerImpl {
257
258 // تبدیل پیش‌فاکتور به فاکتور
259 async convertPreInvoice(id) {
260 + LicenseService.assertWritable();
261 const inv = await StorageService.get('invoices', id);
202 - if (!inv) throw new Error('پیش‌فاکتور یافت نشد');
262 + if (!inv || inv.companyId !== await DataScope.companyId() || !inv.isPreInvoice) throw new Error('پیش‌فاکتور در این شرکت یافت نشد');
263 + if (await RetailPostingService.isEnabled()) {
264 + const number = await this.getNextNumber(inv.kind);
265 + const issued = await RetailPostingService.issueInvoice({ ...inv, isPreInvoice: false, number });
266 + await LicenseService.recordIssuedInvoice();
267 + const settings = await SettingsController.getInvoiceSettings();
268 + await SettingsController.saveInvoiceSettings({ ...settings, nextNumber: Math.max(Number(settings.nextNumber)||1, Number(number)+1) });
269 + return issued;
270 + }
271 const number = await this.getNextNumber(inv.kind);
272 + await this._assertUniqueNumber(number, inv.id);
273 inv.isPreInvoice = false;
274 inv.number = number;
206 - await StorageService.put('invoices', inv);
275 + await StorageService.put('invoices', await DataScope.stamp('invoices', inv));
276 await this._rebuildStockMovements(inv);
277 + await LicenseService.recordIssuedInvoice();
278 return inv;
279 }
280
281 // علامت‌گذاری به‌عنوان پرداخت‌شده
282 async markPaid(id, amount = null) {
283 const inv = await StorageService.get('invoices', id);
214 - if (!inv) throw new Error('فاکتور یافت نشد');
284 + if (!inv || inv.companyId !== await DataScope.companyId()) throw new Error('فاکتور در این شرکت یافت نشد');
285 + if (inv.financePosted) throw new Error('برای تسویه فاکتور دارای سند مالی، از بخش دریافت و پرداخت استفاده کنید');
286 const pay = amount === null ? inv.grandTotal : Number(amount);
287 inv.paidAmount = (Number(inv.paidAmount) || 0) + pay;
288 inv.paidAmount = Math.min(inv.paidAmount, inv.grandTotal);
289 inv.remaining = Math.max(0, inv.grandTotal - inv.paidAmount);
290 inv.status = inv.remaining === 0 ? 'paid' : (inv.paidAmount > 0 ? 'partial' : 'unpaid');
220 - return await StorageService.put('invoices', inv);
291 + return await StorageService.put('invoices', await DataScope.stamp('invoices', inv));
292 }
293
294 // آمار برای داشبورد
295 async getStats() {
225 - const user = Auth.current();
226 - const all = await StorageService.getByOwner('invoices', user.id);
296 + const all = await DataScope.list('invoices');
297 const salesInvoices = all.filter(i => i.kind === 'sale' && !i.isPreInvoice);
298
299 const totalSales = salesInvoices.reduce((s, i) => s + (Number(i.grandTotal) || 0), 0);
src/controllers/ProductController.js
+37 -19
@@ -4,13 +4,15 @@
4
5 import { StorageService } from '../core/StorageService.js';
6 import { Auth } from '../core/Auth.js';
7 +import { DataScope } from '../core/DataScope.js';
8 +import { RetailPostingService } from '../core/RetailPostingService.js';
9
10 class ProductControllerImpl {
11 // ----- واحدها -----
12 async getUnits() {
13 const user = Auth.current();
14 if (!user) return [];
13 - const all = await StorageService.getByOwner('units', user.id);
15 + const all = await DataScope.list('units');
16 return all.sort((a, b) => (a.name || '').localeCompare(b.name || '', 'fa'));
17 }
18
@@ -22,7 +24,7 @@ class ProductControllerImpl {
24 name: (name || '').trim(),
25 symbol: (symbol || '').trim()
26 };
25 - return await StorageService.put('units', unit);
27 + return await StorageService.put('units', await DataScope.stamp('units', unit));
28 }
29
30 async deleteUnit(id) {
@@ -32,7 +34,7 @@ class ProductControllerImpl {
34 // ----- گروه‌ها -----
35 async getCategories() {
36 const user = Auth.current();
35 - const all = await StorageService.getByOwner('categories', user.id);
37 + const all = await DataScope.list('categories');
38 return all.sort((a, b) => (a.name || '').localeCompare(b.name || '', 'fa'));
39 }
40
@@ -44,7 +46,7 @@ class ProductControllerImpl {
46 parentId,
47 name: (name || '').trim()
48 };
47 - return await StorageService.put('categories', cat);
49 + return await StorageService.put('categories', await DataScope.stamp('categories', cat));
50 }
51
52 async deleteCategory(id) {
@@ -54,7 +56,7 @@ class ProductControllerImpl {
56 // ----- کالاها -----
57 async getProducts(filter = {}) {
58 const user = Auth.current();
57 - let list = await StorageService.getByOwner('products', user.id);
59 + let list = await DataScope.list('products');
60
61 if (filter.search) {
62 const q = String(filter.search).toLowerCase();
@@ -120,12 +122,18 @@ class ProductControllerImpl {
122 minStock: Number(data.minStock) || 0,
123 description: (data.description || '').trim()
124 };
123 - return await StorageService.put('products', product);
125 + return await StorageService.put('products', await DataScope.stamp('products', product));
126 }
127
128 async updateProduct(id, data) {
129 const existing = await StorageService.get('products', id);
128 - if (!existing) throw new Error('کالا یافت نشد');
130 + if (!existing || existing.companyId !== await DataScope.companyId()) throw new Error('کالا در شرکت فعال یافت نشد');
131 + if (await RetailPostingService.isEnabled() && data.trackInventory !== undefined &&
132 + (data.trackInventory !== false) !== (existing.trackInventory !== false)) {
133 + const movements = await DataScope.list('stock_movements');
134 + if (movements.some(m => m.productId === id))
135 + throw new Error('نوع کالای دارای گردش انبار را نمی‌توان به خدمت یا برعکس تغییر داد');
136 + }
137 const updated = {
138 ...existing,
139 code: (data.code || '').trim(),
@@ -142,23 +150,22 @@ class ProductControllerImpl {
150 minStock: Number(data.minStock) || 0,
151 description: (data.description || '').trim()
152 };
145 - return await StorageService.put('products', updated);
153 + return await StorageService.put('products', await DataScope.stamp('products', updated));
154 }
155
156 async deleteProduct(id) {
149 - const user = Auth.current();
150 - const movements = await StorageService.getByOwner('stock_movements', user.id);
151 - const related = movements.filter(m => m.productId === id);
152 - for (const m of related) {
153 - await StorageService.delete('stock_movements', m.id);
154 - }
157 + const product = await StorageService.get('products',id);
158 + if (!product || product.companyId !== await DataScope.companyId()) throw new Error('کالا در این شرکت پیدا نشد');
159 + const movements = await DataScope.list('stock_movements');
160 + if (movements.some(m => m.productId === id))
161 + throw new Error('کالای دارای گردش انبار قابل حذف نیست؛ کالا را غیرفعال کنید');
162 return await StorageService.delete('products', id);
163 }
164
165 // ----- موجودی -----
166 async getStock(productId) {
167 const user = Auth.current();
161 - const movements = await StorageService.getByOwner('stock_movements', user.id);
168 + const movements = await DataScope.list('stock_movements');
169 const productMoves = movements.filter(m => m.productId === productId);
170 let stock = 0;
171 productMoves.forEach(m => {
@@ -171,7 +178,7 @@ class ProductControllerImpl {
178
179 async getStockMap(productIds) {
180 const user = Auth.current();
174 - const movements = await StorageService.getByOwner('stock_movements', user.id);
181 + const movements = await DataScope.list('stock_movements');
182 const map = {};
183 productIds.forEach(id => map[id] = 0);
184 movements.forEach(m => {
@@ -184,6 +191,8 @@ class ProductControllerImpl {
191 }
192
193 async addStockMovement(productId, type, qty, refType = 'manual', refId = null, note = '') {
194 + if (await RetailPostingService.isEnabled())
195 + throw new Error('گردش دستی موجودی در شرکت یکپارچه مجاز نیست؛ از خرید، فروش، انتقال یا انبارگردانی استفاده کنید');
196 const user = Auth.current();
197 const movement = {
198 id: StorageService.uid('mv_'),
@@ -196,12 +205,12 @@ class ProductControllerImpl {
205 note,
206 date: new Date().toISOString()
207 };
199 - return await StorageService.put('stock_movements', movement);
208 + return await StorageService.put('stock_movements', await DataScope.stamp('stock_movements', movement));
209 }
210
211 async getMovements(productId) {
212 const user = Auth.current();
204 - const all = await StorageService.getByOwner('stock_movements', user.id);
213 + const all = await DataScope.list('stock_movements');
214 return all
215 .filter(m => m.productId === productId)
216 .sort((a, b) => (a.date || '').localeCompare(b.date || ''));
@@ -260,6 +269,15 @@ class ProductControllerImpl {
269 * جمع ارزش موجودی انبار (بر اساس قیمت خرید و فروش)
270 */
271 async getTotalStockValue() {
272 + if (await RetailPostingService.isEnabled()) {
273 + const products = await this.getProducts({ type: 'good' });
274 + const sellById = new Map(products.map(p => [p.id, Number(p.sellPrice) || 0]));
275 + const balances = await RetailPostingService.stockBalances();
276 + const totalBuyValue = balances.reduce((sum, b) => sum + b.value, 0);
277 + const totalSellValue = Math.round(balances.reduce((sum, b) =>
278 + sum + b.quantityUnits / 1000 * (sellById.get(b.productId) || 0), 0));
279 + return { totalBuyValue, totalSellValue, potentialProfit: totalSellValue - totalBuyValue };
280 + }
281 const products = await this.getProducts({ type: 'good' });
282 const ids = products.map(p => p.id);
283 const stockMap = await this.getStockMap(ids);
@@ -280,7 +298,7 @@ class ProductControllerImpl {
298 async getMovementSummary() {
299 const user = Auth.current();
300 if (!user) return { total: 0, in: 0, out: 0, adjust: 0 };
283 - const all = await StorageService.getByOwner('stock_movements', user.id);
301 + const all = await DataScope.list('stock_movements');
302 const summary = { total: all.length, in: 0, out: 0, adjust: 0 };
303 all.forEach(m => {
304 if (m.type === 'in') summary.in++;
src/controllers/ReportController.js
+7 -6
@@ -4,6 +4,7 @@
4
5 import { StorageService } from '../core/StorageService.js';
6 import { Auth } from '../core/Auth.js';
7 +import { DataScope } from '../core/DataScope.js';
8 import { Jalali } from '../utils/Jalali.js';
9
10 class ReportControllerImpl {
@@ -11,12 +12,12 @@ class ReportControllerImpl {
12 const user = Auth.current();
13 if (!user) throw new Error('کاربر یافت نشد');
14 const [invoices, products, expenses, contacts, cheques, treasury] = await Promise.all([
14 - StorageService.getByOwner('invoices', user.id),
15 - StorageService.getByOwner('products', user.id),
16 - StorageService.getByOwner('expenses', user.id),
17 - StorageService.getByOwner('contacts', user.id),
18 - StorageService.getByOwner('cheques', user.id),
19 - StorageService.getByOwner('treasury', user.id)
15 + DataScope.list('invoices'),
16 + DataScope.list('products'),
17 + DataScope.list('expenses'),
18 + DataScope.list('contacts'),
19 + DataScope.list('cheques'),
20 + DataScope.list('treasury')
21 ]);
22 return { invoices: invoices || [], products: products || [], expenses: expenses || [], contacts: contacts || [], cheques: cheques || [], treasury: treasury || [] };
23 }
src/controllers/SettingsController.js
+54 -53
@@ -4,8 +4,26 @@
4
5 import { StorageService, STORES } from '../core/StorageService.js';
6 import { Auth } from '../core/Auth.js';
7 +import { DataScope } from '../core/DataScope.js';
8 +import { restoreCompanyBackup, COMPANY_BACKUP_STORES } from '../core/CompanyBackupService.js';
9
10 class SettingsControllerImpl {
11 + async getInvoiceSettings() {
12 + const companyId = await DataScope.companyId();
13 + const stored = await StorageService.get('settings', `invoice_numbering_${companyId}`);
14 + return { numberingMode: stored?.numberingMode === 'manual' ? 'manual' : 'auto', nextNumber: Math.max(1, Number(stored?.nextNumber) || 1) };
15 + }
16 +
17 + async saveInvoiceSettings({ numberingMode, nextNumber }) {
18 + if (!['auto', 'manual'].includes(numberingMode) || !Number.isSafeInteger(Number(nextNumber)) || Number(nextNumber) < 1) {
19 + throw new Error('تنظیمات شماره‌گذاری نامعتبر است');
20 + }
21 + const companyId = await DataScope.companyId();
22 + const saved = { id: `invoice_numbering_${companyId}`, numberingMode, nextNumber: Number(nextNumber), companyId };
23 + await StorageService.put('settings', saved);
24 + return { numberingMode: saved.numberingMode, nextNumber: saved.nextNumber };
25 + }
26 +
27 // ============================================================
28 // بکاپ‌گیری
29 // ============================================================
@@ -14,8 +32,8 @@ class SettingsControllerImpl {
32 if (!user) throw new Error('کاربر یافت نشد');
33
34 const backup = {
17 - app: 'Finora Pro',
18 - version: '0.1.0',
35 + app: 'Factor-easyPro',
36 + version: '2.0.0',
37 exportedAt: new Date().toISOString(),
38 exportedAtJalali: this._todayJalali(),
39 user: {
@@ -26,31 +44,36 @@ class SettingsControllerImpl {
44 data: {}
45 };
46
29 - // همه‌ی جدول‌ها رو خونده و توی بکاپ می‌ذاریم
47 + // Capture one consistent read-only snapshot; exclude sensitive credentials.
48 + const companyId = await DataScope.companyId();
49 + const snapshot = await StorageService.exportAll();
50 for (const store of STORES) {
31 - try {
32 - if (store === 'settings' || store === 'logs') {
33 - backup.data[store] = await StorageService.getAll(store);
34 - } else {
35 - backup.data[store] = await StorageService.getByOwner(store, user.id);
36 - }
37 - } catch (e) {
38 - console.warn(`Backup: store "${store}" skipped:`, e.message);
39 - backup.data[store] = [];
40 - }
51 + const rows = snapshot.data[store] || [];
52 + backup.data[store] = COMPANY_BACKUP_STORES.includes(store)
53 + ? rows.filter(record => record.companyId === companyId)
54 + : rows;
55 }
56
57 return backup;
58 }
59
60 downloadBackup() {
47 - return this.exportBackup().then(backup => {
61 + return this.exportBackup().then(async backup => {
62 const json = JSON.stringify(backup, null, 2);
49 - const blob = new Blob([json], { type: 'application/json;charset=utf-8' });
63 + const password = prompt('رمز محافظت از فایل پشتیبان (حداقل ۱۲ نویسه):');
64 + if (!password || password.length < 12) throw new Error('رمز پشتیبان باید حداقل ۱۲ نویسه باشد');
65 + const salt = crypto.getRandomValues(new Uint8Array(16));
66 + const iv = crypto.getRandomValues(new Uint8Array(12));
67 + const keyMaterial = await crypto.subtle.importKey('raw', new TextEncoder().encode(password), 'PBKDF2', false, ['deriveKey']);
68 + const key = await crypto.subtle.deriveKey({ name: 'PBKDF2', salt, iterations: 600000, hash: 'SHA-256' }, keyMaterial, { name: 'AES-GCM', length: 256 }, false, ['encrypt']);
69 + const ciphertext = await crypto.subtle.encrypt({ name: 'AES-GCM', iv }, key, new TextEncoder().encode(json));
70 + const b64 = bytes => { let binary = ''; for (let i = 0; i < bytes.length; i += 8192) binary += String.fromCharCode(...bytes.subarray(i, i + 8192)); return btoa(binary); };
71 + const encrypted = JSON.stringify({ format: 'finora-encrypted-backup-v1', salt: b64(salt), iv: b64(iv), ciphertext: b64(new Uint8Array(ciphertext)) });
72 + const blob = new Blob([encrypted], { type: 'application/octet-stream' });
73 const url = URL.createObjectURL(blob);
74
75 const date = backup.exportedAtJalali.replace(/\//g, '-');
53 - const filename = `finora-backup-${date}-${Date.now()}.json`;
76 + const filename = `finora-backup-${date}-${Date.now()}.fbackup`;
77
78 const a = document.createElement('a');
79 a.href = url;
@@ -77,6 +100,7 @@ class SettingsControllerImpl {
100 // بازیابی
101 // ============================================================
102 async importBackup(fileContent, options = {}) {
103 + if(!Auth.isAdmin())throw Error('بازیابی اطلاعات فقط توسط مدیر مجاز است');
104 const user = Auth.current();
105 if (!user) throw new Error('کاربر یافت نشد');
106
@@ -87,44 +111,22 @@ class SettingsControllerImpl {
111 throw new Error('فایل بکاپ معتبر نیست (JSON نامعتبر)');
112 }
113
114 + if (backup?.format === 'finora-encrypted-backup-v1') {
115 + const password = prompt('رمز فایل پشتیبان را وارد کنید:');
116 + if (!password) throw new Error('رمز پشتیبان الزامی است');
117 + try {
118 + const fromB64 = s => Uint8Array.from(atob(s), c => c.charCodeAt(0));
119 + const material = await crypto.subtle.importKey('raw', new TextEncoder().encode(password), 'PBKDF2', false, ['deriveKey']);
120 + const key = await crypto.subtle.deriveKey({ name: 'PBKDF2', salt: fromB64(backup.salt), iterations: 600000, hash: 'SHA-256' }, material, { name: 'AES-GCM', length: 256 }, false, ['decrypt']);
121 + const clear = await crypto.subtle.decrypt({ name: 'AES-GCM', iv: fromB64(backup.iv) }, key, fromB64(backup.ciphertext));
122 + backup = JSON.parse(new TextDecoder().decode(clear));
123 + } catch (_) { throw new Error('رمز نادرست است یا فایل پشتیبان آسیب دیده است'); }
124 + }
125 if (!backup || !backup.data) {
126 throw new Error('ساختار فایل بکاپ نامعتبر است');
127 }
128
94 - const mode = options.mode || 'merge'; // merge | replace
95 - const counts = { added: 0, updated: 0, skipped: 0 };
96 -
97 - for (const store of STORES) {
98 - const items = backup.data[store];
99 - if (!Array.isArray(items) || items.length === 0) continue;
100 -
101 - // برای settings/logs مستقیم؛ بقیه با ownerUserId
102 - for (const rawItem of items) {
103 - const item = { ...rawItem };
104 -
105 - // اگه مالک اصلی فرق داره، به کاربر فعلی نسبت بده
106 - if (item.ownerUserId && item.ownerUserId !== user.id && store !== 'settings' && store !== 'logs') {
107 - item.ownerUserId = user.id;
108 - item.id = StorageService.uid(item.id?.split('_')[0] + '_' || 'item_');
109 - }
110 -
111 - if (mode === 'replace') {
112 - await StorageService.put(store, item);
113 - counts.added++;
114 - } else {
115 - // merge: اگه id از قبل هست، skip کن
116 - const existing = await StorageService.get(store, item.id);
117 - if (existing) {
118 - counts.skipped++;
119 - } else {
120 - await StorageService.put(store, item);
121 - counts.added++;
122 - }
123 - }
124 - }
125 - }
126 -
127 - return counts;
129 + return restoreCompanyBackup(backup.data, { companyId: await DataScope.companyId(), userId: user.id, mode: options.mode || 'merge' });
130 }
131
132 async readFileAsText(file) {
@@ -154,9 +156,8 @@ class SettingsControllerImpl {
156 // اطلاعات شرکت
157 // ============================================================
158 async getCompanyInfo() {
157 - const user = Auth.current();
158 - const list = await StorageService.getByOwner('companies', user.id);
159 - if (list.length > 0) return list[0];
159 + const active = globalThis.FINORA?.Company ? await globalThis.FINORA.Company.current() : null;
160 + if (active) return active;
161 return {
162 id: null,
163 name: '',
src/controllers/TreasuryController.js
+26 -11
@@ -4,6 +4,8 @@
4
5 import { StorageService } from '../core/StorageService.js';
6 import { Auth } from '../core/Auth.js';
7 +import { DataScope } from '../core/DataScope.js';
8 +import { RetailPostingService } from '../core/RetailPostingService.js';
9
10 class TreasuryControllerImpl {
11 // ============================================================
@@ -12,7 +14,7 @@ class TreasuryControllerImpl {
14 async getAccounts(filter = {}) {
15 const user = Auth.current();
16 if (!user) return [];
15 - let list = await StorageService.getByOwner('treasury', user.id);
17 + let list = await DataScope.list('treasury');
18
19 // فقط حساب‌ها (نه تراکنش‌ها) — با تفکیک recordType
20 list = list.filter(a => (a.recordType || 'account') === 'account');
@@ -62,12 +64,16 @@ class TreasuryControllerImpl {
64 const existing = await this.getAccounts();
65 if (existing.length === 0) account.isDefault = true;
66
65 - return await StorageService.put('treasury', account);
67 + const stamped=await DataScope.stamp('treasury',account);
68 + if (await RetailPostingService.isEnabled()) return RetailPostingService.createTreasuryAccount(stamped);
69 + return await StorageService.put('treasury', stamped);
70 }
71
72 async updateAccount(id, data) {
73 const existing = await StorageService.get('treasury', id);
70 - if (!existing) throw new Error('حساب یافت نشد');
74 + if (!existing || existing.companyId !== await DataScope.companyId()) throw new Error('حساب در شرکت فعال یافت نشد');
75 + if (await RetailPostingService.isEnabled() && Number(data.initialBalance||0)!==Number(existing.initialBalance||0))
76 + throw new Error('مانده افتتاحیه بانک در حالت حسابداری یکپارچه قابل تغییر مستقیم نیست');
77 const updated = {
78 ...existing,
79 type: data.type || existing.type,
@@ -82,13 +88,16 @@ class TreasuryControllerImpl {
88 color: data.color || existing.color,
89 initialBalance: Number(data.initialBalance) || 0
90 };
85 - return await StorageService.put('treasury', updated);
91 + return await StorageService.put('treasury', await DataScope.stamp('treasury', updated));
92 }
93
94 async deleteAccount(id) {
95 + const account=await StorageService.get('treasury',id);
96 + if(!account||account.companyId!==await DataScope.companyId())throw Error('حساب در شرکت فعال یافت نشد');
97 + if(account.ledgerAccountId)throw Error('حساب صندوق/بانک دارای کدینگ مالی است؛ برای حفظ سوابق فقط غیرفعال شود');
98 // چک کن تراکنشی وابسته نباشه
99 const user = Auth.current();
91 - const all = await StorageService.getByOwner('treasury', user.id);
100 + const all = await DataScope.list('treasury');
101 const related = all.filter(t => t.recordType === 'transaction' && (t.fromAccountId === id || t.toAccountId === id));
102 if (related.length > 0) {
103 throw new Error('این حساب تراکنش دارد. اول تراکنش‌ها را حذف کنید.');
@@ -98,10 +107,10 @@ class TreasuryControllerImpl {
107
108 async setDefaultAccount(id) {
109 const user = Auth.current();
101 - const all = await StorageService.getByOwner('treasury', user.id);
110 + const all = await DataScope.list('treasury');
111 for (const a of all.filter(x => x.recordType === 'account')) {
112 a.isDefault = a.id === id;
104 - await StorageService.put('treasury', a);
113 + await StorageService.put('treasury', await DataScope.stamp('treasury', a));
114 }
115 }
116
@@ -110,7 +119,7 @@ class TreasuryControllerImpl {
119 // ============================================================
120 async getAccountBalance(accountId) {
121 const user = Auth.current();
113 - const all = await StorageService.getByOwner('treasury', user.id);
122 + const all = await DataScope.list('treasury');
123 const account = all.find(a => a.id === accountId);
124 if (!account) return 0;
125
@@ -138,7 +147,7 @@ class TreasuryControllerImpl {
147
148 async getBalanceMap() {
149 const user = Auth.current();
141 - const all = await StorageService.getByOwner('treasury', user.id);
150 + const all = await DataScope.list('treasury');
151 const accounts = all.filter(a => a.recordType === 'account');
152 const transactions = all.filter(t => t.recordType === 'transaction');
153 const map = {};
@@ -171,7 +180,7 @@ class TreasuryControllerImpl {
180 async getTransactions(filter = {}) {
181 const user = Auth.current();
182 if (!user) return [];
174 - let list = await StorageService.getByOwner('treasury', user.id);
183 + let list = await DataScope.list('treasury');
184 list = list.filter(t => t.recordType === 'transaction');
185
186 if (filter.type) list = list.filter(t => t.type === filter.type);
@@ -216,10 +225,16 @@ class TreasuryControllerImpl {
225 description: (data.description || '').trim(),
226 chequeNumber: data.chequeNumber || ''
227 };
219 - return await StorageService.put('treasury', tx);
228 + if (await RetailPostingService.isEnabled()) {
229 + return RetailPostingService.postTransaction(await DataScope.stamp('treasury',tx));
230 + }
231 + return await StorageService.put('treasury', await DataScope.stamp('treasury', tx));
232 }
233
234 async deleteTransaction(id) {
235 + const existing = await StorageService.get('treasury', id);
236 + if (!existing || existing.companyId !== await DataScope.companyId()) throw new Error('تراکنش در شرکت فعال یافت نشد');
237 + if (existing.financePosted) throw new Error('تراکنش دارای سند حسابداری قابل حذف نیست؛ سند اصلاحی لازم است');
238 return await StorageService.delete('treasury', id);
239 }
240
src/core/AccountingCore.mjs new
+123
@@ -0,0 +1,123 @@
1 +// Factor-easyPro V2 / Phase 1: pure accounting domain rules.
2 +// Holoo is a functional benchmark, not a source for proprietary account codes.
3 +import { Jalali } from '../utils/Jalali.js';
4 +export const ACCOUNT_LEVELS = Object.freeze(['group', 'general', 'subsidiary', 'detail']);
5 +export const ACCOUNT_TYPES = Object.freeze(['asset', 'liability', 'equity', 'revenue', 'expense']);
6 +export const JOURNAL_STATUSES = Object.freeze(['draft', 'posted']);
7 +export const PERIOD_STATUSES = Object.freeze(['open', 'closed']);
8 +
9 +export const DEFAULT_CHART = Object.freeze([
10 + { code: '1', name: 'دارایی‌ها', type: 'asset', level: 'group' },
11 + { code: '2', name: 'بدهی‌ها', type: 'liability', level: 'group' },
12 + { code: '3', name: 'حقوق مالکانه', type: 'equity', level: 'group' },
13 + { code: '4', name: 'درآمدها', type: 'revenue', level: 'group' },
14 + { code: '5', name: 'هزینه‌ها', type: 'expense', level: 'group' },
15 + { code: '101', name: 'موجودی نقد و بانک', type: 'asset', level: 'general', parentCode: '1' },
16 + { code: '102', name: 'حساب‌های دریافتنی', type: 'asset', level: 'general', parentCode: '1' },
17 + { code: '103', name: 'موجودی کالا', type: 'asset', level: 'general', parentCode: '1' },
18 + { code: '201', name: 'حساب‌های پرداختنی', type: 'liability', level: 'general', parentCode: '2' },
19 + { code: '301', name: 'سرمایه', type: 'equity', level: 'general', parentCode: '3' },
20 + { code: '401', name: 'فروش کالا', type: 'revenue', level: 'general', parentCode: '4' },
21 + { code: '501', name: 'بهای تمام‌شده کالای فروش‌رفته', type: 'expense', level: 'general', parentCode: '5' },
22 + { code: '502', name: 'هزینه‌های عمومی', type: 'expense', level: 'general', parentCode: '5' },
23 + { code: '503', name: 'اختلاف قیمت و تعدیل انبار', type: 'expense', level: 'general', parentCode: '5' },
24 + { code: '104', name: 'مالیات خرید و اعتبار مالیاتی', type: 'asset', level: 'general', parentCode: '1' },
25 + { code: '105', name: 'اسناد دریافتنی', type: 'asset', level: 'general', parentCode: '1' },
26 + { code: '202', name: 'مالیات و عوارض فروش', type: 'liability', level: 'general', parentCode: '2' },
27 + { code: '203', name: 'اسناد پرداختنی', type: 'liability', level: 'general', parentCode: '2' },
28 + { code: '402', name: 'سایر درآمدهای عملیاتی', type: 'revenue', level: 'general', parentCode: '4' }
29 +]);
30 +
31 +export function assertJalaliDate(value) {
32 + if (typeof value !== 'string' || !/^1[34-5]\d{2}\/(0[1-9]|1[0-2])\/(0[1-9]|[12]\d|3[01])$/.test(value)) {
33 + throw new Error('تاریخ شمسی باید به صورت 1405/01/01 باشد');
34 + }
35 + const month = Number(value.slice(5, 7));
36 + const day = Number(value.slice(8, 10));
37 + if ((month >= 7 && month <= 11 && day > 30) || (month === 12 && day > 30)) {
38 + throw new Error('روز ماه شمسی نامعتبر است');
39 + }
40 + const year = Number(value.slice(0, 4));
41 + const valid = Jalali.fromDate(Jalali.toDate(year, month, day));
42 + if (valid.year !== year || valid.month !== month || valid.day !== day) {
43 + throw new Error('تاریخ شمسی یا کبیسه معتبر نیست');
44 + }
45 + return value;
46 +}
47 +
48 +export function validateFiscalPeriod(period, existing = []) {
49 + if (!period || typeof period.companyId !== 'string' || !period.companyId) throw new Error('شرکت دوره مالی مشخص نیست');
50 + assertJalaliDate(period.startDate);
51 + assertJalaliDate(period.endDate);
52 + if (period.startDate > period.endDate) throw new Error('پایان دوره قبل از آغاز دوره است');
53 + if (!PERIOD_STATUSES.includes(period.status || (period.closed ? 'closed' : 'open'))) throw new Error('وضعیت دوره مالی نامعتبر است');
54 + if (existing.some(p => p.companyId === period.companyId && p.id !== period.id && period.startDate <= p.endDate && period.endDate >= p.startDate)) {
55 + throw new Error('دوره مالی با دوره دیگری هم‌پوشانی دارد');
56 + }
57 + return true;
58 +}
59 +
60 +export function validateAccount(account, existing = []) {
61 + if (!account?.companyId || !/^\d{1,12}$/.test(String(account.code || ''))) throw new Error('کد حساب یا شرکت نامعتبر است');
62 + if (!ACCOUNT_LEVELS.includes(account.level) || !ACCOUNT_TYPES.includes(account.type)) throw new Error('سطح یا ماهیت حساب نامعتبر است');
63 + if (!String(account.name || '').trim()) throw new Error('نام حساب الزامی است');
64 + if (existing.some(a => a.companyId === account.companyId && a.code === account.code && a.id !== account.id)) {
65 + throw new Error('کد حساب در این شرکت تکراری است');
66 + }
67 + if (account.level === 'group') {
68 + if (account.parentCode) throw new Error('گروه حساب نمی‌تواند والد داشته باشد');
69 + } else {
70 + const parent = existing.find(a => a.companyId === account.companyId && a.code === account.parentCode);
71 + if (!parent || parent.active === false) throw new Error('حساب والد فعال در این شرکت یافت نشد');
72 + if (ACCOUNT_LEVELS.indexOf(parent.level) !== ACCOUNT_LEVELS.indexOf(account.level) - 1) throw new Error('رابطه سطوح حساب نامعتبر است');
73 + if (parent.type !== account.type) throw new Error('ماهیت حساب با والد سازگار نیست');
74 + }
75 + return true;
76 +}
77 +
78 +export function validateJournalLines(journal, accounts = [], { requireBalance = true, allowInactive = false, allowParent = false } = {}) {
79 + if (!journal?.companyId || !Array.isArray(journal.lines) || journal.lines.length < (requireBalance ? 2 : 1)) {
80 + throw new Error('سطرهای سند حسابداری نامعتبر است');
81 + }
82 + const totals = { debit: 0, credit: 0 };
83 + for (const line of journal.lines) {
84 + const account = accounts.find(a => a.id === line.accountId && a.companyId === journal.companyId);
85 + if (!account || (!allowInactive && account.active === false) || (!allowInactive && account.postable === false) || account.level === 'group') {
86 + throw new Error('حساب سند غیرمجاز، غیرفعال یا متعلق به شرکت دیگر است');
87 + }
88 + if (!allowParent && accounts.some(a => a.companyId === journal.companyId && a.parentCode === account.code)) {
89 + throw new Error('ثبت سند فقط روی حساب بدون زیرمجموعه مجاز است');
90 + }
91 + if (!Number.isSafeInteger(line.debit) || !Number.isSafeInteger(line.credit) ||
92 + line.debit < 0 || line.credit < 0 || (line.debit > 0) === (line.credit > 0)) {
93 + throw new Error('هر سطر فقط باید بدهکار یا بستانکار معتبر داشته باشد');
94 + }
95 + totals.debit += line.debit;
96 + totals.credit += line.credit;
97 + if (!Number.isSafeInteger(totals.debit) || !Number.isSafeInteger(totals.credit)) throw new Error('سرریز مبلغ سند');
98 + }
99 + if (requireBalance && (totals.debit === 0 || totals.debit !== totals.credit)) throw new Error('سند حسابداری تراز نیست');
100 + return totals;
101 +}
102 +
103 +export function validateJournal(journal, accounts = [], period = null, options = {}) {
104 + if (!period || period.companyId !== journal?.companyId) throw new Error('دوره مالی این شرکت معتبر نیست');
105 + if (period.closed === true || period.status === 'closed') throw new Error('دوره مالی بسته است');
106 + assertJalaliDate(journal.date);
107 + if (journal.date < period.startDate || journal.date > period.endDate) throw new Error('تاریخ سند خارج از دوره مالی است');
108 + return validateJournalLines(journal, accounts, options);
109 +}
110 +
111 +export function journalSourceKey(companyId, sourceType, sourceId, revision = 1) {
112 + if (![companyId, sourceType, sourceId].every(x => typeof x === 'string' && x.trim()) ||
113 + !Number.isSafeInteger(revision) || revision < 1) throw new Error('منشأ سند نامعتبر است');
114 + return JSON.stringify([companyId, sourceType, sourceId, revision]);
115 +}
116 +
117 +export function reversingLines(lines) {
118 + if (!Array.isArray(lines) || lines.length < 2) throw new Error('سطرهای سند اصلی موجود نیست');
119 + return lines.map(line => ({
120 + accountId: line.accountId, debit: line.credit, credit: line.debit,
121 + description: line.description || ''
122 + }));
123 +}
src/core/AccountingService.js new
+335
@@ -0,0 +1,335 @@
1 +// Factor-easyPro V2 / Phase 1: company-scoped, atomic double-entry ledger.
2 +// No automatic posting from legacy invoices until Phase 2's unified transaction.
3 +import { StorageService } from './StorageService.js';
4 +import { DataScope } from './DataScope.js';
5 +import { Auth } from './Auth.js';
6 +import { buildLedgerReports } from './LedgerReports.mjs';
7 +import {
8 + DEFAULT_CHART, assertJalaliDate, validateAccount, validateFiscalPeriod,
9 + validateJournal, validateJournalLines, journalSourceKey, reversingLines
10 +} from './AccountingCore.mjs';
11 +
12 +const requireAccountingAdmin = () => { if(!Auth.isAdmin()) throw new Error('ثبت یا ویرایش ساختار حسابداری فقط برای مدیر مجاز است'); };
13 +const RESERVED_SOURCES = new Set(['invoice','treasury','expense','cheque','cheque_status','stocktake']);
14 +const ensureManualSource = type => {
15 + if (RESERVED_SOURCES.has(type)) throw new Error('منشأ عملیاتی رزروشده فقط توسط موتور حسابداری یکپارچه ثبت می‌شود');
16 +};
17 +const uid = prefix => StorageService.uid(prefix);
18 +const actor = () => Auth.current()?.id || null;
19 +const entriesFor = (tx, companyId) => tx.getAllByIndex('journal_entries', 'companyId', companyId);
20 +const periodFor = async (tx, companyId, periodId) => {
21 + const period = await tx.get('fiscal_periods', periodId);
22 + if (!period || period.companyId !== companyId) throw new Error('دوره مالی این شرکت پیدا نشد');
23 + return period;
24 +};
25 +const ensurePeriodOpen = period => {
26 + if (period.closed || period.status === 'closed') throw new Error('دوره مالی بسته است');
27 +};
28 +const cleanLines = lines => (lines || []).map(line => ({
29 + accountId: line.accountId,
30 + debit: line.debit,
31 + credit: line.credit,
32 + description: String(line.description || '').trim()
33 +}));
34 +
35 +class AccountingServiceImpl {
36 + async financialReports(filter = {}) {
37 + const companyId = await DataScope.companyId();
38 + return StorageService.transaction(['account_chart', 'journal_entries', 'journal_lines'], async tx => {
39 + const accounts = await tx.getAllByIndex('account_chart', 'companyId', companyId);
40 + const journals = await tx.getAllByIndex('journal_entries', 'companyId', companyId);
41 + const lines = await tx.getAllByIndex('journal_lines', 'companyId', companyId);
42 + return buildLedgerReports(accounts, journals, lines, filter);
43 + }, 'readonly');
44 + }
45 + async listAccounts() {
46 + const companyId = await DataScope.companyId();
47 + return StorageService.getAllByIndex('account_chart', 'companyId', companyId);
48 + }
49 +
50 + async addAccount(data) {
51 + requireAccountingAdmin();
52 + const companyId = await DataScope.companyId();
53 + const account = {
54 + id: uid('acc_'), code: String(data.code || '').trim(),
55 + name: String(data.name || '').trim(), level: data.level, type: data.type,
56 + parentCode: data.parentCode || null, active: data.active !== false,
57 + postable: data.postable !== false, companyId, createdBy: actor()
58 + };
59 + return StorageService.transaction(['account_chart', 'journal_lines'], async tx => {
60 + const existing = await tx.getAllByIndex('account_chart', 'companyId', companyId);
61 + validateAccount(account, existing);
62 + // A posting account may not become a parent after journal lines exist.
63 + // Otherwise future postings would be rejected while historical balances remain ambiguous.
64 + if (account.parentCode) {
65 + const parent = existing.find(a => a.code === account.parentCode);
66 + const movements = await tx.getAllByIndex('journal_lines', 'companyId', companyId);
67 + if (movements.some(line => line.accountId === parent.id)) {
68 + throw new Error('حساب والد گردش مالی دارد؛ افزودن زیرحساب به آن مجاز نیست');
69 + }
70 + }
71 + await tx.put('account_chart', account);
72 + return account;
73 + });
74 + }
75 +
76 + async seedDefaultChart() {
77 + requireAccountingAdmin();
78 + const companyId = await DataScope.companyId();
79 + return StorageService.transaction('account_chart', async tx => {
80 + const existing = await tx.getAllByIndex('account_chart', 'companyId', companyId);
81 + let added = 0;
82 + for (const template of DEFAULT_CHART) {
83 + if (existing.some(a => a.code === template.code)) continue;
84 + const account = { ...template, companyId, id: uid('acc_'), active: true, createdBy: actor() };
85 + validateAccount(account, existing);
86 + await tx.put('account_chart', account);
87 + existing.push(account);
88 + added++;
89 + }
90 + return { added, total: existing.length };
91 + });
92 + }
93 +
94 + async listPeriods() {
95 + return StorageService.getAllByIndex('fiscal_periods', 'companyId', await DataScope.companyId());
96 + }
97 +
98 + async createPeriod(data) {
99 + requireAccountingAdmin();
100 + const companyId = await DataScope.companyId();
101 + const period = {
102 + id: uid('fp_'), companyId, name: String(data.name || '').trim(),
103 + startDate: data.startDate, endDate: data.endDate,
104 + status: 'open', closed: false, createdBy: actor()
105 + };
106 + if (!period.name) throw new Error('نام دوره مالی الزامی است');
107 + return StorageService.transaction('fiscal_periods', async tx => {
108 + validateFiscalPeriod(period, await tx.getAllByIndex('fiscal_periods', 'companyId', companyId));
109 + await tx.put('fiscal_periods', period);
110 + return period;
111 + });
112 + }
113 +
114 + async closePeriod(periodId) {
115 + if (!Auth.isAdmin()) throw new Error('بستن دوره مالی فقط برای مدیر مجاز است');
116 + const companyId = await DataScope.companyId();
117 + return StorageService.transaction(['fiscal_periods', 'journal_entries'], async tx => {
118 + const period = await periodFor(tx, companyId, periodId);
119 + ensurePeriodOpen(period);
120 + const journals = await entriesFor(tx, companyId);
121 + if (journals.some(j => j.periodId === periodId && j.status !== 'posted')) {
122 + throw new Error('دوره دارای اسناد پیش‌نویس است؛ ابتدا تعیین تکلیف شوند');
123 + }
124 + const closed = { ...period, status: 'closed', closed: true, closedBy: actor(), closedAt: new Date().toISOString() };
125 + await tx.put('fiscal_periods', closed);
126 + return closed;
127 + });
128 + }
129 +
130 + async listJournals({ periodId, status } = {}) {
131 + const companyId = await DataScope.companyId();
132 + const rows = await StorageService.getAllByIndex('journal_entries', 'companyId', companyId);
133 + return rows.filter(j => (!periodId || j.periodId === periodId) && (!status || j.status === status))
134 + .sort((a, b) => String(a.date).localeCompare(String(b.date)) || String(a.id).localeCompare(String(b.id)));
135 + }
136 +
137 + async getJournal(id) {
138 + const companyId = await DataScope.companyId();
139 + return StorageService.transaction(['journal_entries', 'journal_lines'], async tx => {
140 + const journal = await tx.get('journal_entries', id);
141 + if (!journal || journal.companyId !== companyId) throw new Error('سند در این شرکت یافت نشد');
142 + const lines = (await tx.getAllByIndex('journal_lines', 'journalId', id))
143 + .filter(l => l.companyId === companyId)
144 + .sort((a, b) => a.position - b.position);
145 + return { ...journal, lines };
146 + }, 'readonly');
147 + }
148 +
149 + // Drafts can be unbalanced, but must use valid accounts, dates and integer rial amounts.
150 + async saveDraftJournal(data) {
151 + requireAccountingAdmin();
152 + ensureManualSource(data.sourceType);
153 + const companyId = await DataScope.companyId();
154 + const id = uid('jn_');
155 + const lines = cleanLines(data.lines);
156 + const sourceKey = data.sourceType && data.sourceId
157 + ? journalSourceKey(companyId, data.sourceType, data.sourceId, data.revision || 1) : undefined;
158 + return StorageService.transaction(['account_chart', 'fiscal_periods', 'journal_entries', 'journal_lines'], async tx => {
159 + const period = await periodFor(tx, companyId, data.periodId);
160 + ensurePeriodOpen(period);
161 + assertJalaliDate(data.date);
162 + if (data.date < period.startDate || data.date > period.endDate) throw new Error('تاریخ سند خارج از دوره است');
163 + const accounts = await tx.getAllByIndex('account_chart', 'companyId', companyId);
164 + const totals = validateJournalLines({ ...data, lines, companyId }, accounts, { requireBalance: false });
165 + if (sourceKey) {
166 + const existing = await tx.getAllByIndex('journal_entries', 'sourceKey', sourceKey);
167 + if (existing.length) throw new Error('برای این منشأ قبلاً سند ثبت شده است');
168 + }
169 + const journal = { id, companyId, periodId: data.periodId, date: data.date,
170 + description: String(data.description || '').trim(), status: 'draft',
171 + sourceKey, sourceType: data.sourceType || null, sourceId: data.sourceId || null,
172 + revision: data.revision || 1, ...totals, createdBy: actor() };
173 + await tx.put('journal_entries', journal);
174 + for (const [position, line] of lines.entries()) {
175 + await tx.put('journal_lines', { ...line, id: uid('jl_'), companyId, journalId: id, position });
176 + }
177 + return journal;
178 + });
179 + }
180 +
181 + async updateDraftJournal(id, data, { post = false } = {}) {
182 + requireAccountingAdmin();
183 + const companyId = await DataScope.companyId();
184 + const lines = cleanLines(data.lines);
185 + return StorageService.transaction(['account_chart', 'fiscal_periods', 'journal_entries', 'journal_lines'], async tx => {
186 + const old = await tx.get('journal_entries', id);
187 + if (!old || old.companyId !== companyId || old.status !== 'draft') throw new Error('فقط پیش‌نویس این شرکت قابل ویرایش است');
188 + const period = await periodFor(tx, companyId, data.periodId);
189 + ensurePeriodOpen(period);
190 + assertJalaliDate(data.date);
191 + if (data.date < period.startDate || data.date > period.endDate) throw new Error('تاریخ سند خارج از دوره است');
192 + const accounts = await tx.getAllByIndex('account_chart', 'companyId', companyId);
193 + const totals = post
194 + ? validateJournal({ companyId, date: data.date, lines }, accounts, period)
195 + : validateJournalLines({ companyId, lines }, accounts, { requireBalance: false });
196 + const journal = {
197 + ...old, periodId: data.periodId, date: data.date,
198 + description: String(data.description || '').trim(), ...totals,
199 + status: post ? 'posted' : 'draft',
200 + ...(post ? { postedBy: actor(), postedAt: new Date().toISOString() } : {}),
201 + updatedBy: actor(), updatedAt: new Date().toISOString()
202 + };
203 + const prior = await tx.getAllByIndex('journal_lines', 'journalId', id);
204 + for (const line of prior) await tx.delete('journal_lines', line.id);
205 + await tx.put('journal_entries', journal);
206 + for (const [position, line] of lines.entries()) {
207 + await tx.put('journal_lines', { ...line, id: uid('jl_'), companyId, journalId: id, position });
208 + }
209 + return journal;
210 + });
211 + }
212 +
213 + async postJournal(data) {
214 + requireAccountingAdmin();
215 + ensureManualSource(data.sourceType);
216 + const companyId = await DataScope.companyId();
217 + const id = uid('jn_');
218 + const lines = cleanLines(data.lines);
219 + const sourceKey = data.sourceType && data.sourceId
220 + ? journalSourceKey(companyId, data.sourceType, data.sourceId, data.revision || 1) : undefined;
221 + return StorageService.transaction(['account_chart', 'fiscal_periods', 'journal_entries', 'journal_lines'], async tx => {
222 + const period = await periodFor(tx, companyId, data.periodId);
223 + const accounts = await tx.getAllByIndex('account_chart', 'companyId', companyId);
224 + const totals = validateJournal({ companyId, date: data.date, lines }, accounts, period);
225 + if (sourceKey) {
226 + const existing = await tx.getAllByIndex('journal_entries', 'sourceKey', sourceKey);
227 + if (existing.length) throw new Error('ثبت دوباره برای این منشأ مجاز نیست');
228 + }
229 + const journal = { id, companyId, periodId: data.periodId, date: data.date,
230 + description: String(data.description || '').trim(), status: 'posted',
231 + sourceKey, sourceType: data.sourceType || null, sourceId: data.sourceId || null,
232 + revision: data.revision || 1, ...totals, createdBy: actor(), postedBy: actor(),
233 + postedAt: new Date().toISOString() };
234 + await tx.put('journal_entries', journal);
235 + for (const [position, line] of lines.entries()) {
236 + await tx.put('journal_lines', { ...line, id: uid('jl_'), companyId, journalId: id, position });
237 + }
238 + return journal;
239 + });
240 + }
241 +
242 + async discardDraftJournal(id) {
243 + requireAccountingAdmin();
244 + const companyId = await DataScope.companyId();
245 + return StorageService.transaction(['journal_entries', 'journal_lines'], async tx => {
246 + const old = await tx.get('journal_entries', id);
247 + if (!old || old.companyId !== companyId || old.status !== 'draft') throw new Error('فقط پیش‌نویس این شرکت قابل حذف است');
248 + const lines = await tx.getAllByIndex('journal_lines', 'journalId', id);
249 + for (const line of lines) await tx.delete('journal_lines', line.id);
250 + await tx.delete('journal_entries', id);
251 + return true;
252 + });
253 + }
254 +
255 + async postDraftJournal(id) {
256 + requireAccountingAdmin();
257 + const companyId = await DataScope.companyId();
258 + return StorageService.transaction(['account_chart', 'fiscal_periods', 'journal_entries', 'journal_lines'], async tx => {
259 + const old = await tx.get('journal_entries', id);
260 + if (!old || old.companyId !== companyId || old.status !== 'draft') throw new Error('پیش‌نویس قابل ثبت پیدا نشد');
261 + const period = await periodFor(tx, companyId, old.periodId);
262 + const lines = (await tx.getAllByIndex('journal_lines', 'journalId', id)).filter(l => l.companyId === companyId);
263 + const accounts = await tx.getAllByIndex('account_chart', 'companyId', companyId);
264 + const totals = validateJournal({ companyId, date: old.date, lines }, accounts, period);
265 + const journal = { ...old, ...totals, status: 'posted', postedBy: actor(), postedAt: new Date().toISOString() };
266 + await tx.put('journal_entries', journal);
267 + return journal;
268 + });
269 + }
270 +
271 + async reverseJournal(originalId, { periodId, date, description = '' }) {
272 + requireAccountingAdmin();
273 + const companyId = await DataScope.companyId();
274 + return StorageService.transaction(['account_chart', 'fiscal_periods', 'journal_entries', 'journal_lines'], async tx => {
275 + const original = await tx.get('journal_entries', originalId);
276 + if (!original || original.companyId !== companyId || original.status !== 'posted' ||
277 + original.reversedById || original.reversalOfId) throw new Error('این سند قابل برگشت نیست');
278 + // Reversing commercial GL alone would leave invoice, cash and stock inconsistent.
279 + if (['invoice','treasury','expense','cheque','cheque_status','stocktake'].includes(original.sourceType))
280 + throw new Error('سند تجاری را نمی‌توان جداگانه معکوس کرد؛ اصلاح باید از سند عملیاتی منشأ انجام شود');
281 + const period = await periodFor(tx, companyId, periodId);
282 + const oldLines = (await tx.getAllByIndex('journal_lines', 'journalId', originalId))
283 + .filter(l => l.companyId === companyId)
284 + .sort((a, b) => a.position - b.position);
285 + const lines = reversingLines(oldLines);
286 + const accounts = await tx.getAllByIndex('account_chart', 'companyId', companyId);
287 + // Historical reversals remain valid even when source accounts were later deactivated or given children.
288 + const totals = validateJournal({ companyId, date, lines }, accounts, period, { allowInactive: true, allowParent: true });
289 + const key = journalSourceKey(companyId, 'journal_reversal', originalId);
290 + if ((await tx.getAllByIndex('journal_entries', 'sourceKey', key)).length) throw new Error('برگشت سند تکراری است');
291 + const id = uid('jn_');
292 + const journal = { id, companyId, periodId, date, description: String(description).trim() || `برگشت سند ${originalId}`,
293 + status: 'posted', sourceKey: key, sourceType: 'journal_reversal', sourceId: originalId,
294 + revision: 1, reversalOfId: originalId, ...totals, createdBy: actor(),
295 + postedBy: actor(), postedAt: new Date().toISOString() };
296 + await tx.put('journal_entries', journal);
297 + for (const [position, line] of lines.entries()) {
298 + await tx.put('journal_lines', { ...line, id: uid('jl_'), companyId, journalId: id, position });
299 + }
300 + await tx.put('journal_entries', { ...original, reversedById: id, reversedAt: journal.postedAt });
301 + return journal;
302 + });
303 + }
304 +
305 + async trialBalance({ periodId } = {}) {
306 + const companyId = await DataScope.companyId();
307 + return StorageService.transaction(['account_chart', 'journal_entries', 'journal_lines'], async tx => {
308 + const accounts = await tx.getAllByIndex('account_chart', 'companyId', companyId);
309 + const journals = (await entriesFor(tx, companyId))
310 + .filter(j => j.status === 'posted' && (!periodId || j.periodId === periodId));
311 + const valid = new Set(journals.map(j => j.id));
312 + const entries = new Map(accounts.map(a => [a.id, {
313 + accountId: a.id, code: a.code, name: a.name, debit: 0, credit: 0, balance: 0
314 + }]));
315 + const lines = await tx.getAllByIndex('journal_lines', 'companyId', companyId);
316 + for (const line of lines) {
317 + if (!valid.has(line.journalId)) continue;
318 + const row = entries.get(line.accountId);
319 + if (!row) throw new Error('سطر سند به حساب حذف‌شده اشاره دارد');
320 + row.debit += line.debit;
321 + row.credit += line.credit;
322 + if (!Number.isSafeInteger(row.debit) || !Number.isSafeInteger(row.credit)) throw new Error('سرریز مانده حساب');
323 + row.balance = row.debit - row.credit;
324 + }
325 + const rows = [...entries.values()].filter(r => r.debit || r.credit)
326 + .sort((a, b) => a.code.localeCompare(b.code, 'fa'));
327 + const totals = rows.reduce((sum, r) => ({ debit: sum.debit + r.debit, credit: sum.credit + r.credit }), { debit: 0, credit: 0 });
328 + if (!Number.isSafeInteger(totals.debit) || !Number.isSafeInteger(totals.credit) ||
329 + totals.debit !== totals.credit) throw new Error('گردش حساب‌ها تراز نیست');
330 + return { companyId, periodId: periodId || null, rows, totals };
331 + }, 'readonly');
332 + }
333 +}
334 +
335 +export const AccountingService = new AccountingServiceImpl();
src/core/Auth.js
+18 -7
@@ -63,15 +63,16 @@ class AuthImpl {
63
64 async init() {
65 await this._migrateLegacyPasswords();
66 + await this._migrateDefaultManagerUsername();
67
68 let users = await StorageService.getAll('users');
69 if (users.length === 0) {
70 // اولین اجرا: کاربر مدیر بدون رمز ساخته می‌شود و صفحه قفل از او رمز می‌گیرد
71 const admin = await StorageService.put('users', {
72 id: 'user_admin',
72 - username: 'admin',
73 + username: 'مدیر',
74 role: 'admin',
74 - displayName: 'مدیر سیستم',
75 + displayName: 'مدیر',
76 mustSetPassword: true,
77 createdAt: new Date().toISOString()
78 });
@@ -106,6 +107,14 @@ class AuthImpl {
107 }
108 }
109
110 + // فقط حساب مدیر پیش‌فرض قدیمی را تغییر نام می‌دهد؛ رمز، شناسه و مجوزها حفظ می‌شوند.
111 + async _migrateDefaultManagerUsername() {
112 + const users = await StorageService.getAll('users');
113 + const manager = users.find(u => u.id === 'user_admin' && u.role === 'admin' && u.username === 'admin');
114 + if (!manager || users.some(u => u.username === 'مدیر' && u.id !== manager.id)) return;
115 + await StorageService.put('users', { ...manager, username: 'مدیر', displayName: 'مدیر' });
116 + }
117 +
118 _restoreSession(users) {
119 const raw = sessionStorage.getItem(this.sessionKey);
120 if (!raw) return null;
@@ -178,8 +187,8 @@ class AuthImpl {
187 el.pass.value = '';
188 el.pass2.value = '';
189 if (next === 'setup') {
181 - el.title.textContent = 'تعیین رمز عبور';
182 - el.hint.textContent = `برای «${user.displayName || user.username}» یک رمز عبور حداقل ${MIN_PASSWORD_LENGTH} کاراکتری انتخاب کنید.`;
190 + el.title.textContent = 'تعیین رمز مدیر';
191 + el.hint.textContent = `برای حساب «مدیر» رمز عبور حداقل ${MIN_PASSWORD_LENGTH} کاراکتری انتخاب کنید.`;
192 el.user.value = user.username;
193 el.user.readOnly = true;
194 el.pass.placeholder = 'رمز عبور جدید';
@@ -188,8 +197,8 @@ class AuthImpl {
197 el.submit.textContent = 'ذخیره و ورود';
198 el.pass.focus();
199 } else {
191 - el.title.textContent = 'ورود به فینورا پرو';
192 - el.hint.textContent = 'برای ادامه وارد شوید.';
200 + el.title.textContent = 'ورود به Factor-easyPro';
201 + el.hint.textContent = 'برای ادامه وارد Factor-easyPro شوید.';
202 el.user.readOnly = false;
203 el.pass.placeholder = 'رمز عبور';
204 el.pass.autocomplete = 'current-password';
@@ -265,7 +274,7 @@ class AuthImpl {
274 const role = document.getElementById('userRole');
275 if (avatar) avatar.textContent = (u.displayName || u.username || 'م').charAt(0);
276 if (name) name.textContent = u.displayName || u.username;
268 - if (role) role.textContent = u.role === 'admin' ? 'مدیر سیستم' : 'کاربر';
277 + if (role) role.textContent = u.role === 'admin' ? 'مدیر' : 'کاربر';
278 }
279
280 current() { return this.currentUser; }
@@ -311,6 +320,8 @@ class AuthImpl {
320 throw new Error(`رمز عبور باید حداقل ${MIN_PASSWORD_LENGTH} کاراکتر باشد`);
321 }
322 const users = await StorageService.getAll('users');
323 + if (users.length >= 4) throw new Error('حداکثر ۴ کاربر (۱ مدیر و ۳ کاربر اضافی) مجاز است');
324 + if (role === 'admin' && users.some(u => u.role === 'admin')) throw new Error('فقط یک مدیر سیستم مجاز است');
325 if (users.some(u => u.username === name)) throw new Error('این نام کاربری قبلاً ثبت شده است');
326 const created = await StorageService.put('users', {
327 username: name,
src/core/CompanyBackupService.js new
+142
@@ -0,0 +1,142 @@
1 +// Factor-easyPro V2 / Phase 1: company-scoped atomic restore.
2 +// Data must never be silently cross-linked to an account or journal in another company.
3 +import { StorageService } from './StorageService.js';
4 +import { Auth } from './Auth.js';
5 +import { assertJalaliDate, validateAccount, validateFiscalPeriod, validateJournalLines, journalSourceKey } from './AccountingCore.mjs';
6 +
7 +export const COMPANY_BACKUP_STORES = Object.freeze([
8 + 'contacts', 'products', 'units', 'categories', 'treasury',
9 + 'invoices', 'invoice_items', 'stock_movements', 'transactions',
10 + 'cheques', 'expenses', 'account_chart', 'fiscal_periods',
11 + 'journal_entries', 'journal_lines', 'warehouses', 'inventory_balances',
12 + 'stocktakes', 'stocktake_lines', 'settlements', 'account_mappings'
13 +]);
14 +const V2_STORES = new Set(['account_chart', 'fiscal_periods', 'journal_entries', 'journal_lines']);
15 +const isId = id => typeof id === 'string' && id.trim().length > 0;
16 +
17 +export async function restoreCompanyBackup(data, { companyId, userId, mode = 'merge' }) {
18 + if (!Auth.isAdmin())throw Error('بازنشانی یا بازیابی اطلاعات حسابداری فقط با مدیر مجاز است');
19 + if (!companyId || !userId || !['merge', 'replace'].includes(mode)) throw new Error('گزینه‌های بازیابی نامعتبر است');
20 + if (!data || typeof data !== 'object') throw new Error('داده فایل پشتیبان نامعتبر است');
21 +
22 + for (const store of COMPANY_BACKUP_STORES) {
23 + const items = data[store];
24 + if (items === undefined) continue;
25 + if (!Array.isArray(items)) throw new Error(`جدول ${store} در فایل پشتیبان نامعتبر است`);
26 + for (const item of items) {
27 + if (!item || typeof item !== 'object' || Array.isArray(item) || !isId(item.id)) {
28 + throw new Error(`رکورد بدون شناسه معتبر در بخش ${store}`);
29 + }
30 + }
31 + }
32 +
33 + const counts = { added: 0, updated: 0, skipped: 0 };
34 + // Reads, ownership validation, foreign-key validation and writes share one IndexedDB transaction.
35 + return StorageService.transaction([...COMPANY_BACKUP_STORES, 'settings'], async tx => {
36 + for (const store of COMPANY_BACKUP_STORES) {
37 + for (const incoming of data[store] || []) {
38 + const row = { ...incoming, companyId };
39 + if (row.ownerUserId) row.ownerUserId = userId;
40 + if (store === 'journal_entries' && row.sourceType && row.sourceId) {
41 + row.sourceKey = journalSourceKey(companyId, row.sourceType, row.sourceId, row.revision || 1);
42 + }
43 + const existing = await tx.get(store, row.id);
44 + if (existing && existing.companyId !== companyId) {
45 + throw new Error(`شناسه رکورد ${store}/${row.id} متعلق به شرکت دیگر است؛ بازیابی متوقف شد`);
46 + }
47 + if (existing && mode === 'merge') {
48 + counts.skipped++;
49 + continue;
50 + }
51 + if (existing) counts.updated++;
52 + else counts.added++;
53 + await tx.putRaw(store, row);
54 + }
55 + }
56 +
57 + if (COMPANY_BACKUP_STORES.filter(s => V2_STORES.has(s)).some(s => (data[s] || []).length)) {
58 + const accounts = await tx.getAllByIndex('account_chart', 'companyId', companyId);
59 + const periods = await tx.getAllByIndex('fiscal_periods', 'companyId', companyId);
60 + const journals = await tx.getAllByIndex('journal_entries', 'companyId', companyId);
61 + const lines = await tx.getAllByIndex('journal_lines', 'companyId', companyId);
62 + for (const account of accounts) validateAccount(account, accounts);
63 + for (const period of periods) validateFiscalPeriod(period, periods);
64 + const byJournal = new Map();
65 + for (const line of lines) {
66 + if (!byJournal.has(line.journalId)) byJournal.set(line.journalId, []);
67 + byJournal.get(line.journalId).push(line);
68 + }
69 + const toCheck = new Set((data.journal_entries || []).map(x => x.id));
70 + for (const line of data.journal_lines || []) toCheck.add(line.journalId);
71 +
72 + // Recovered records must never reference missing or foreign-company accounts or periods.
73 + for (const id of toCheck) {
74 + const journal = journals.find(j => j.id === id);
75 + if (!journal) throw new Error(`سند حسابداری ${id} در بازیابی وجود ندارد`);
76 + const period = periods.find(p => p.id === journal.periodId);
77 + if (!period) throw new Error(`دوره مالی سند ${id} وجود ندارد`);
78 + assertJalaliDate(journal.date);
79 + if (journal.date < period.startDate || journal.date > period.endDate) {
80 + throw new Error(`تاریخ سند ${id} خارج از دوره است`);
81 + }
82 + validateJournalLines({
83 + companyId, lines: byJournal.get(id) || []
84 + }, accounts, {
85 + requireBalance: journal.status === 'posted',
86 + allowInactive: true,
87 + allowParent: true
88 + });
89 + }
90 + for (const line of data.journal_lines || []) {
91 + if (!accounts.some(a => a.id === line.accountId)) {
92 + throw new Error('سطر بازیابی‌شده به حساب ناموجود یا شرکت دیگر اشاره دارد');
93 + }
94 + }
95 + }
96 + if ((data.inventory_balances||[]).length || (data.stocktakes||[]).length ||
97 + (data.stocktake_lines||[]).length || (data.settlements||[]).length) {
98 + const warehouses=await tx.getAllByIndex('warehouses','companyId',companyId);
99 + const products=(await tx.getAll('products')).filter(x=>x.companyId===companyId);
100 + const inventory=await tx.getAllByIndex('inventory_balances','companyId',companyId);
101 + for(const balance of inventory){
102 + if(!warehouses.some(w=>w.id===balance.warehouseId)||
103 + !products.some(p=>p.id===balance.productId)||
104 + !Number.isSafeInteger(balance.quantityUnits)||balance.quantityUnits<0||
105 + !Number.isSafeInteger(balance.value)||balance.value<0)
106 + throw Error('موجودی انبار بازیابی‌شده نامعتبر است');
107 + }
108 + const stocktakes=await tx.getAllByIndex('stocktakes','companyId',companyId);
109 + const takeLines=await tx.getAllByIndex('stocktake_lines','companyId',companyId);
110 + for(const session of stocktakes)if(!warehouses.some(w=>w.id===session.warehouseId))
111 + throw Error('جلسه شمارش انبار نامعتبر است');
112 + for(const line of takeLines)if(!stocktakes.some(s=>s.id===line.stocktakeId)||
113 + !products.some(p=>p.id===line.productId))
114 + throw Error('برگه شمارش به جلسه یا کالای ناموجود اشاره دارد');
115 + const invoices=(await tx.getAll('invoices')).filter(x=>x.companyId===companyId);
116 + const transactions=(await tx.getAll('treasury')).filter(x=>x.companyId===companyId);
117 + const settlements=await tx.getAllByIndex('settlements','companyId',companyId);
118 + for(const row of settlements)if(!invoices.some(i=>i.id===row.invoiceId)||
119 + !transactions.some(t=>t.id===row.transactionId&&t.recordType==='transaction')||
120 + !Number.isSafeInteger(row.amount)||row.amount<=0)
121 + throw Error('تسویه بازیابی‌شده به فاکتور یا تراکنش نامعتبر اشاره دارد');
122 + }
123 + // Restore only this company's finance activation marker, never global preferences
124 + // or another company's settings.
125 + if(data.settings!==undefined && !Array.isArray(data.settings))
126 + throw Error('تنظیمات فایل پشتیبان نامعتبر است');
127 + const key='finance_v2_enabled_'+companyId;
128 + const marker=(data.settings||[]).find(x=>x&&x.id===key);
129 + if(marker?.enabled){
130 + const existing=await tx.get('settings',key);
131 + if(!existing?.enabled){
132 + const chart=await tx.getAllByIndex('account_chart','companyId',companyId);
133 + const periods=await tx.getAllByIndex('fiscal_periods','companyId',companyId);
134 + if(chart.length<19||!periods.length)
135 + throw Error('فعال‌سازی مالی بدون کدینگ و دوره مالی کامل بازیابی نمی‌شود');
136 + await tx.putRaw('settings',{id:key,companyId,enabled:true,
137 + restoredAt:new Date().toISOString(),restoredBy:userId});
138 + }
139 + }
140 + return counts;
141 + });
142 +}
src/core/CompanyService.js new
+60
@@ -0,0 +1,60 @@
1 +import { StorageService } from './StorageService.js';
2 +import { Auth } from './Auth.js';
3 +import { EventBus } from './EventBus.js';
4 +
5 +const ACTIVE_KEY = 'finora_active_company';
6 +const MAX_COMPANIES = 5;
7 +
8 +class CompanyServiceImpl {
9 + constructor(){ this.activeCompanyId = null; }
10 + async init(){
11 + const user=Auth.current();
12 + let companies=await StorageService.getAll('companies');
13 + if(!companies.length){
14 + const c=await StorageService.put('companies',{id:'company_default',ownerUserId:user.id,name:'شرکت اصلی',isDefault:true});
15 + companies=[c];
16 + }
17 + await this._migrateLegacy(companies[0].id);
18 + const allowed=this.allowedFor(user,companies);
19 + const remembered=localStorage.getItem(ACTIVE_KEY);
20 + this.activeCompanyId=allowed.some(c=>c.id===remembered)?remembered:allowed[0]?.id;
21 + if(this.activeCompanyId)localStorage.setItem(ACTIVE_KEY,this.activeCompanyId);
22 + return this.current();
23 + }
24 + allowedFor(user,companies){
25 + if(user?.role==='admin') return companies.slice(0,MAX_COMPANIES);
26 + const ids=Array.isArray(user?.companyIds)?user.companyIds:[];
27 + if (!ids.length && companies.length === 1) return companies;
28 + return companies.filter(c=>ids.includes(c.id));
29 + }
30 + async list(){ return this.allowedFor(Auth.current(),await StorageService.getAll('companies')); }
31 + async current(){ const list=await this.list(); return list.find(c=>c.id===this.activeCompanyId)||list[0]||null; }
32 + async select(id){
33 + const list=await this.list(); if(!list.some(c=>c.id===id)) throw new Error('دسترسی به این شرکت مجاز نیست');
34 + this.activeCompanyId=id; localStorage.setItem(ACTIVE_KEY,id); EventBus.emit('company:changed',id); return this.current();
35 + }
36 + async requireSelection(){
37 + const list=await this.list();
38 + if(list.length<=1){ if(list[0]) await this.select(list[0].id); return this.current(); }
39 + return new Promise(resolve=>{
40 + const root=document.createElement('div'); root.setAttribute('dir','rtl');
41 + root.style.cssText='position:fixed;inset:0;z-index:2147482999;display:flex;align-items:center;justify-content:center;background:#0f172a;font-family:inherit';
42 + root.innerHTML=`<div style="width:min(92vw,420px);background:#fff;border-radius:16px;padding:26px"><h2 style="margin:0 0 8px">انتخاب شرکت</h2><p style="color:#64748b">شرکتی را که می‌خواهید با اطلاعات آن کار کنید انتخاب کنید.</p><div id="companyChoices" style="display:grid;gap:8px"></div></div>`;
43 + const box=root.querySelector('#companyChoices');
44 + list.forEach(c=>{const b=document.createElement('button');b.type='button';b.textContent=c.name||'شرکت';b.style.cssText='padding:12px;border:1px solid #cbd5e1;border-radius:10px;background:#fff;cursor:pointer;font:inherit';b.onclick=async()=>{await this.select(c.id);root.remove();resolve(c)};box.appendChild(b)});
45 + document.body.appendChild(root);
46 + });
47 + }
48 + async create(data){
49 + if(!Auth.isAdmin()) throw new Error('فقط مدیر می‌تواند شرکت ایجاد کند');
50 + const all=await StorageService.getAll('companies'); if(all.length>=MAX_COMPANIES) throw new Error('حداکثر ۵ شرکت مجاز است');
51 + return StorageService.put('companies',{...data,id:StorageService.uid('cmp_'),ownerUserId:Auth.current().id});
52 + }
53 + async _migrateLegacy(defaultCompanyId){
54 + const marker=await StorageService.get('settings','company_scope_migration_v1'); if(marker?.done)return;
55 + const scoped=['contacts','products','units','categories','treasury','invoices','invoice_items','stock_movements','transactions','cheques','expenses'];
56 + for(const store of scoped){ const rows=await StorageService.getAll(store); for(const row of rows){ if(!row.companyId) await StorageService.put(store,{...row,companyId:defaultCompanyId}); } }
57 + await StorageService.put('settings',{id:'company_scope_migration_v1',done:true,at:new Date().toISOString()});
58 + }
59 +}
60 +export const CompanyService=new CompanyServiceImpl();
src/core/DataScope.js new
+11
@@ -0,0 +1,11 @@
1 +import { CompanyService } from './CompanyService.js';
2 +import { StorageService } from './StorageService.js';
3 +
4 +const COMPANY_SCOPED = new Set(['contacts','products','units','categories','treasury','invoices','invoice_items','stock_movements','transactions','cheques','expenses','account_chart','fiscal_periods','journal_entries','journal_lines','warehouses','inventory_balances','stocktakes','stocktake_lines','settlements','account_mappings']);
5 +
6 +class DataScopeImpl {
7 + async companyId(){ const c=await CompanyService.current(); if(!c) throw new Error('شرکت فعالی انتخاب نشده است'); return c.id; }
8 + async list(store){ return COMPANY_SCOPED.has(store) ? StorageService.getByCompany(store,await this.companyId()) : StorageService.getAll(store); }
9 + async stamp(store,obj){ if(!COMPANY_SCOPED.has(store)) return obj; return {...obj,companyId:await this.companyId()}; }
10 +}
11 +export const DataScope=new DataScopeImpl();
src/core/EntitlementVerifier.mjs new
+14
@@ -0,0 +1,14 @@
1 +const enc=new TextEncoder();
2 +function b64uToBytes(s){s=s.replace(/-/g,'+').replace(/_/g,'/');while(s.length%4)s+='=';return Uint8Array.from(atob(s),c=>c.charCodeAt(0))}
3 +function canonical(obj){if(Array.isArray(obj))return '['+obj.map(canonical).join(',')+']';if(obj&&typeof obj==='object')return '{'+Object.keys(obj).sort().map(k=>JSON.stringify(k)+':'+canonical(obj[k])).join(',')+'}';return JSON.stringify(obj)}
4 +export async function verifyEntitlement(token,publicJwk){
5 + if(!token?.payload||!token?.signature||!publicJwk)return false;
6 + try{const key=await crypto.subtle.importKey('jwk',publicJwk,{name:'ECDSA',namedCurve:'P-256'},false,['verify']);return await crypto.subtle.verify({name:'ECDSA',hash:'SHA-256'},key,b64uToBytes(token.signature),enc.encode(canonical(token.payload)))}catch{return false}
7 +}
8 +export function validateEntitlementPayload(p,installationId,now=Date.now()){
9 + if(!p||p.product!=='Factor-easyPro'||p.installationId!==installationId)return false;
10 + if(p.notBefore&&now<new Date(p.notBefore).getTime())return false;
11 + if(!p.perpetual&&p.expiresAt&&now>new Date(p.expiresAt).getTime())return false;
12 + return Number(p.maxCompanies)>=1&&Number(p.maxCompanies)<=5&&Number(p.maxUsers)>=1&&Number(p.maxUsers)<=4&&Number(p.maxDevices)>=1;
13 +}
14 +export {canonical};
src/core/LedgerReports.mjs new
+46
@@ -0,0 +1,46 @@
1 +// Posted-ledger reporting: integer rials and immutable posted journal lines.
2 +const safeAdd=(a,b)=>{const n=a+b;if(!Number.isSafeInteger(n))throw Error('سرریز مبلغ گزارش');return n};
3 +const validAmount=n=>Number.isSafeInteger(n)&&n>=0;
4 +export function buildLedgerReports(accounts,journals,lines,{periodId=null,from=null,to=null}={}){
5 + if(from&&to&&from>to)throw Error('بازه تاریخ گزارش نامعتبر است');
6 + const chart=new Map(accounts.map(a=>[a.id,a]));
7 + const allPosted=journals.filter(j=>j.status==='posted'&&(!to||j.date<=to));
8 + const selected=allPosted.filter(j=>(!periodId||j.periodId===periodId)&&(!from||j.date>=from));
9 + const selectedIds=new Set(selected.map(j=>j.id));
10 + const allIds=new Map(allPosted.map(j=>[j.id,j]));
11 + const detail=[],totals=new Map(),cumulative=new Map();
12 + for(const line of lines){
13 + const j=allIds.get(line.journalId);if(!j)continue;
14 + const a=chart.get(line.accountId);if(!a)throw Error('حساب سطر سند پیدا نشد');
15 + const debit=Number(line.debit||0),credit=Number(line.credit||0);
16 + if(!validAmount(debit)||!validAmount(credit)||debit&&credit)throw Error('مبلغ سند نامعتبر است');
17 + const add=(map)=>{const row=map.get(a.id)||{accountId:a.id,code:a.code,name:a.name,type:a.type,debit:0,credit:0,balance:0};
18 + row.debit=safeAdd(row.debit,debit);row.credit=safeAdd(row.credit,credit);
19 + row.balance=safeAdd(row.debit,-row.credit);map.set(a.id,row);};
20 + add(cumulative);
21 + if(!selectedIds.has(j.id))continue;
22 + add(totals);
23 + detail.push({journalId:j.id,date:j.date,description:j.description||'',sourceType:j.sourceType||null,accountId:a.id,code:a.code,name:a.name,debit,credit,position:line.position||0});
24 + }
25 + detail.sort((a,b)=>a.date.localeCompare(b.date)||a.journalId.localeCompare(b.journalId)||a.position-b.position);
26 + const sortRows=map=>[...map.values()].sort((a,b)=>String(a.code).localeCompare(String(b.code),'fa'));
27 + const trial=sortRows(totals),cumulativeTrial=sortRows(cumulative);
28 + const sum=(arr,key)=>arr.reduce((v,r)=>safeAdd(v,r[key]),0);
29 + const debit=sum(trial,'debit'),credit=sum(trial,'credit');
30 + if(debit!==credit||sum(cumulativeTrial,'debit')!==sum(cumulativeTrial,'credit'))throw Error('دفتر کل تراز نیست');
31 + const computePL=rows=>{const result={revenue:0,expenses:0,netProfit:0};
32 + for(const r of rows){if(r.type==='revenue')result.revenue=safeAdd(result.revenue,-r.balance);
33 + if(r.type==='expense')result.expenses=safeAdd(result.expenses,r.balance);}
34 + result.netProfit=safeAdd(result.revenue,-result.expenses);return result;};
35 + const profitLoss=computePL(trial);
36 + const cumulativeProfit=computePL(cumulativeTrial);
37 + const balanceSheet={assets:0,liabilities:0,equity:0};
38 + for(const r of cumulativeTrial){
39 + if(r.type==='asset')balanceSheet.assets=safeAdd(balanceSheet.assets,r.balance);
40 + if(r.type==='liability')balanceSheet.liabilities=safeAdd(balanceSheet.liabilities,-r.balance);
41 + if(r.type==='equity')balanceSheet.equity=safeAdd(balanceSheet.equity,-r.balance);
42 + }
43 + balanceSheet.equityWithProfit=safeAdd(balanceSheet.equity,cumulativeProfit.netProfit);
44 + balanceSheet.difference=safeAdd(safeAdd(balanceSheet.assets,-balanceSheet.liabilities),-balanceSheet.equityWithProfit);
45 + return {detail,trial,totals:{debit,credit},balanceSheet,profitLoss,postedCount:selected.length,cumulativeTrial};
46 +}
src/core/LicensePolicy.mjs new
+13
@@ -0,0 +1,13 @@
1 +export const TRIAL_DAYS=15;
2 +export const TRIAL_INVOICE_LIMIT=20;
3 +export const OFFLINE_LEASE_DAYS=30;
4 +export const WARNING_DAY=25;
5 +export function trialStatus(state,nowMs=Date.now()){
6 + const started=new Date(state?.trialStartedAt||nowMs),elapsedDays=Math.floor((nowMs-started.getTime())/86400000),invoiceCount=Number(state?.issuedInvoiceCount)||0;
7 + return{mode:'trial',elapsedDays,invoiceCount,daysRemaining:Math.max(0,TRIAL_DAYS-elapsedDays),invoicesRemaining:Math.max(0,TRIAL_INVOICE_LIMIT-invoiceCount),readOnly:elapsedDays>=TRIAL_DAYS||invoiceCount>=TRIAL_INVOICE_LIMIT,maxCompanies:5,maxUsers:4,maxDevices:1};
8 +}
9 +export function licensedStatus(license,nowMs=Date.now()){
10 + const checked=license?.lastOnlineCheckAt?new Date(license.lastOnlineCheckAt):null,ageDays=checked?(nowMs-checked.getTime())/86400000:Infinity;
11 + const expired=!license?.perpetual&&license?.expiresAt&&nowMs>new Date(license.expiresAt).getTime();
12 + return{mode:'licensed',readOnly:!!expired||ageDays>OFFLINE_LEASE_DAYS,warning:ageDays>=WARNING_DAY,maxCompanies:Math.min(5,Number(license?.maxCompanies)||1),maxUsers:Math.min(4,Number(license?.maxUsers)||1),maxDevices:Number(license?.maxDevices)||1};
13 +}
src/core/LicenseService.js new
+26
@@ -0,0 +1,26 @@
1 +import { SecureState } from './SecureState.js';
2 +import { trialStatus, licensedStatus } from './LicensePolicy.mjs';
3 +const KEY='finora_pro_entitlement_v2',LEGACY_KEY='finora_pro_entitlement_v1';
4 +class LicenseServiceImpl{
5 + constructor(){this.state=null;}
6 + async init(){
7 + let stored=await SecureState.get(KEY);
8 + if(!stored){try{stored=JSON.parse(localStorage.getItem(LEGACY_KEY)||'null')}catch(_){}}
9 + stored=stored||{}; const now=new Date();
10 + if(!stored.trialStartedAt)stored.trialStartedAt=now.toISOString();
11 + if(!Number.isFinite(stored.issuedInvoiceCount))stored.issuedInvoiceCount=0;
12 + if(!stored.installationId)stored.installationId=crypto.randomUUID();
13 + this.state=stored; await this._save(); localStorage.removeItem(LEGACY_KEY); return this.status();
14 + }
15 + async _save(){await SecureState.set(KEY,this.state);}
16 + status(){
17 + const s=this.state||{};
18 + // Never accept a locally editable `active` flag as proof of a paid entitlement.
19 + // Signed entitlement verification must succeed before licensed mode is enabled.
20 + return trialStatus(s); // Until server-issued signatures are verified at startup, remain in trial mode.
21 + }
22 + assertWritable(){if(this.status().readOnly)throw new Error('دوره استفاده یا مجوز به پایان رسیده است؛ اطلاعات فقط قابل مشاهده‌اند.');}
23 + async recordIssuedInvoice(){this.assertWritable();this.state.issuedInvoiceCount=(Number(this.state.issuedInvoiceCount)||0)+1;await this._save();return this.status();}
24 + installationId(){return this.state?.installationId||null;}
25 +}
26 +export const LicenseService=new LicenseServiceImpl();
src/core/RetailFinanceCore.mjs new
+79
@@ -0,0 +1,79 @@
1 +// Factor-easyPro V2: deterministic inventory valuation and financial validation.
2 +export const QTY_SCALE = 1000;
3 +export const LEDGER_CODES = Object.freeze({
4 + cash:'101',receivable:'102',inventory:'103',inputVat:'104',chequeIn:'105',
5 + payable:'201',outputVat:'202',chequeOut:'203',revenue:'401',
6 + otherRevenue:'402',cogs:'501',expense:'502',variance:'503'
7 +});
8 +export const INVOICE_DIRECTIONS = Object.freeze({
9 + sale:'out',non_formal:'out',purchase:'in',sale_return:'in',purchase_return:'out'
10 +});
11 +export function amount(value,label='مبلغ') {
12 + if(typeof value==='string' && !/^\d+$/.test(value.trim())) throw Error(label+' باید عدد صحیح باشد');
13 + const n=Number(value);
14 + if(!Number.isSafeInteger(n)||n<0) throw Error(label+' نامعتبر است');
15 + return n;
16 +}
17 +export function positiveAmount(v,label) {
18 + const n=amount(v,label);
19 + if(!n) throw Error('مبلغ باید مثبت باشد');
20 + return n;
21 +}
22 +export function qtyUnits(q) {
23 + const n=Number(q), scaled=n*QTY_SCALE;
24 + if(!Number.isFinite(n)||n<=0||!Number.isSafeInteger(Math.round(scaled))||
25 + Math.abs(scaled-Math.round(scaled))>1e-7) throw Error('مقدار کالا نامعتبر است');
26 + return Math.round(scaled);
27 +}
28 +export const fromQtyUnits=q=>q/QTY_SCALE;
29 +const plus=(a,b)=>{const n=a+b;if(!Number.isSafeInteger(n))throw Error('سرریز موجودی یا مبلغ');return n};
30 +export function receiveStock(current,quantity,totalCost) {
31 + const units=qtyUnits(quantity), cost=amount(totalCost,'بهای کالا');
32 + const q=current?.quantityUnits||0,v=current?.value||0;
33 + if(!Number.isSafeInteger(q)||q<0||!Number.isSafeInteger(v)||v<0)throw Error('مانده انبار نامعتبر است');
34 + return {quantityUnits:plus(q,units),value:plus(v,cost),cost};
35 +}
36 +export function issueStock(current,quantity) {
37 + const units=qtyUnits(quantity),q=current?.quantityUnits||0,v=current?.value||0;
38 + if(!Number.isSafeInteger(q)||q<units||q<=0)throw Error('موجودی کالا برای خروج کافی نیست');
39 + if(!Number.isSafeInteger(v)||v<0)throw Error('ارزش موجودی نامعتبر است');
40 + const cost=units===q?v:Number((BigInt(v)*BigInt(units)+BigInt(q)/2n)/BigInt(q));
41 + return {quantityUnits:q-units,value:v-cost,cost};
42 +}
43 +export function allocateDiscount(items,discount) {
44 + const total=items.reduce((s,i)=>plus(s,amount(i.lineTotal)),0),d=amount(discount);
45 + if(d>total)throw Error('تخفیف بیش از جمع اقلام است');
46 + if(!total)return items.map(i=>({...i,netLineTotal:0}));
47 + const bigTotal=BigInt(total),bigDiscount=BigInt(d);
48 + const values=items.map(i=>amount(i.lineTotal));
49 + const reduced=values.map(v=>Number(BigInt(v)*bigDiscount/bigTotal));
50 + const remainders=values.map((v,i)=>({i,rem:BigInt(v)*bigDiscount%bigTotal}));
51 + let remaining=d-reduced.reduce((a,b)=>a+b,0);
52 + remainders.sort((a,b)=>a.rem===b.rem?a.i-b.i:(a.rem>b.rem?-1:1));
53 + for(const r of remainders){if(!remaining)break;if(reduced[r.i]<values[r.i]){reduced[r.i]++;remaining--;}}
54 + if(remaining)throw Error('توزیع تخفیف نامعتبر است');
55 + return items.map((i,j)=>({...i,netLineTotal:values[j]-reduced[j]}));
56 +}
57 +export function postLine(accountId,debit,credit,extra={}) {
58 + const d=amount(debit),c=amount(credit);
59 + if(!d&&!c)return null;
60 + if(d&&c)throw Error('ردیف بدهکار و بستانکار همزمان مجاز نیست');
61 + return {accountId,debit:d,credit:c,...extra};
62 +}
63 +export function differenceLines(accountId,signed,extra={}) {
64 + if(!Number.isSafeInteger(signed))throw Error('اختلاف مبلغ نامعتبر است');
65 + return signed>0?postLine(accountId,signed,0,extra):signed<0?postLine(accountId,0,-signed,extra):null;
66 +}
67 +export function assertInvoiceTotals(inv) {
68 + if(!INVOICE_DIRECTIONS[inv.kind])throw Error('نوع فاکتور نامعتبر است');
69 + if(!Array.isArray(inv.items)||!inv.items.length)throw Error('فاکتور بدون قلم کالا مجاز نیست');
70 + const total=inv.items.reduce((s,i)=>{
71 + qtyUnits(i.qty);amount(i.price,'قیمت');return s+amount(i.lineTotal,'جمع ردیف');
72 + },0);
73 + if(amount(inv.subtotal)!==total)throw Error('جمع ردیف‌ها نادرست است');
74 + const disc=amount(inv.totalDiscount,'تخفیف'),vat=amount(inv.vatAmount,'مالیات');
75 + if(disc>total)throw Error('تخفیف نامعتبر است');
76 + if(amount(inv.grandTotal)!==total-disc+vat)throw Error('مبلغ کل فاکتور ناسازگار است');
77 + if(amount(inv.paidAmount)>inv.grandTotal)throw Error('مبلغ پرداخت بیش از مبلغ فاکتور است');
78 + return true;
79 +}
src/core/RetailPostingService.js new
+597
@@ -0,0 +1,597 @@
1 +// Phase 2 transactional commercial posting. Every dependent row shares one IndexedDB transaction.
2 +import { StorageService } from './StorageService.js';
3 +import { DataScope } from './DataScope.js';
4 +import { Auth } from './Auth.js';
5 +import { validateJournal, journalSourceKey, assertJalaliDate } from './AccountingCore.mjs';
6 +import { LEDGER_CODES, INVOICE_DIRECTIONS, amount, positiveAmount,
7 + qtyUnits, fromQtyUnits, receiveStock, issueStock, allocateDiscount,
8 + postLine, differenceLines, assertInvoiceTotals } from './RetailFinanceCore.mjs';
9 +
10 +export const FINANCE_STORES = Object.freeze([
11 + 'account_chart','fiscal_periods','journal_entries','journal_lines',
12 + 'invoices','invoice_items','stock_movements','products','contacts','treasury',
13 + 'warehouses','inventory_balances','stocktakes','stocktake_lines',
14 + 'settlements','expenses','cheques','settings','account_mappings'
15 +]);
16 +const uid=p=>StorageService.uid(p);
17 +const actor=()=>Auth.current()?.id||null;
18 +const activeKey=company=>'finance_v2_enabled_'+company;
19 +const balanceId=(c,w,p)=>JSON.stringify([c,w,p]);
20 +const today=()=>new Date().toISOString();
21 +const sameCompany=(record,company,label)=>{
22 + if(!record||record.companyId!==company)throw Error(label+' در شرکت فعال یافت نشد');
23 + return record;
24 +};
25 +const leg=(ctx,code)=> {
26 + const acct=ctx.accounts.find(a=>a.code===code);
27 + if(!acct||acct.active===false||acct.postable===false||acct.level==='group'||
28 + ctx.accounts.some(a=>a.parentCode===acct.code))throw Error('حساب عملیاتی '+code+' فعال یا قابل ثبت نیست');
29 + return acct.id;
30 +};
31 +
32 +class RetailPostingServiceImpl {
33 + async isEnabled() {
34 + const company=await DataScope.companyId();
35 + return !!(await StorageService.get('settings',activeKey(company)))?.enabled;
36 + }
37 + async activate() {
38 + if(!Auth.isAdmin())throw Error('فعال‌سازی فقط با مدیر سیستم مجاز است');
39 + const company=await DataScope.companyId(),user=actor();
40 + return StorageService.transaction(FINANCE_STORES,async tx=>{
41 + if((await tx.get('settings',activeKey(company)))?.enabled)return {alreadyEnabled:true};
42 + const issued=(await tx.getAll('invoices')).filter(x=>x.companyId===company&&!x.isPreInvoice);
43 + const moves=(await tx.getAll('stock_movements')).filter(x=>x.companyId===company);
44 + const money=(await tx.getAll('treasury')).filter(x=>x.companyId===company&&x.recordType==='transaction');
45 + const costs=(await tx.getAll('expenses')).filter(x=>x.companyId===company);
46 + const cheques=(await tx.getAll('cheques')).filter(x=>x.companyId===company);
47 + if(issued.length||moves.length||money.length||costs.length||cheques.length){
48 + throw Error('این شرکت گردش قبلی دارد؛ ابتدا مانده افتتاحیه و تبدیل اطلاعات در محیط کنترل‌شده تأیید شود. برای آزمون از شرکت خالی استفاده کنید');
49 + }
50 + const accounts=await tx.getAllByIndex('account_chart','companyId',company);
51 + const moneyAccounts=(await tx.getAll('treasury')).filter(a=>a.companyId===company&&a.recordType==='account');
52 + if(!moneyAccounts.length){
53 + const defaultCash={id:uid('cash_'),companyId:company,ownerUserId:user,
54 + recordType:'account',type:'cashbox',name:'صندوق اصلی',
55 + initialBalance:0,isActive:true,isDefault:true};
56 + await tx.put('treasury',defaultCash);
57 + moneyAccounts.push(defaultCash);
58 + }
59 + if(moneyAccounts.some(a=>Number(a.initialBalance||0)!==0))
60 + throw Error('مانده افتتاحیه صندوق/بانک باید ابتدا با سند افتتاحیه کنترل شود؛ فعال‌سازی متوقف شد');
61 + const periods=await tx.getAllByIndex('fiscal_periods','companyId',company);
62 + if(!periods.some(p=>!p.closed))throw Error('ابتدا یک دوره مالی باز تعریف کنید');
63 + const ctx={accounts};
64 + for(const code of Object.values(LEDGER_CODES))leg(ctx,code);
65 + const cashHeader=accounts.find(a=>a.code==='101');
66 + const oldLines=await tx.getAllByIndex('journal_lines','companyId',company);
67 + if(moneyAccounts.length && oldLines.some(l=>l.accountId===cashHeader?.id))
68 + throw Error('حساب ۱۰۱ گردش سند دستی دارد؛ قبل از ایجاد حساب‌های بانک باید انتقال و افتتاحیه آن تطبیق شود');
69 + let nextCash=1;
70 + for(const account of moneyAccounts){
71 + let code;
72 + do{code='101'+String(nextCash++).padStart(3,'0')}while(accounts.some(a=>a.code===code));
73 + const sub={id:uid('acc_'),code,name:account.name||'صندوق یا بانک',companyId:company,
74 + type:'asset',level:'subsidiary',parentCode:'101',active:true,postable:true};
75 + await tx.put('account_chart',sub);accounts.push(sub);
76 + await tx.put('treasury',{...account,ledgerAccountId:sub.id});
77 + }
78 + const warehouses=await tx.getAllByIndex('warehouses','companyId',company);
79 + if(!warehouses.length)await tx.put('warehouses',{id:uid('wh_'),companyId:company,ownerUserId:user,name:'انبار اصلی',isDefault:true,active:true});
80 + await tx.put('settings',{id:activeKey(company),companyId:company,enabled:true,createdBy:user,enabledAt:today()});
81 + return {enabled:true};
82 + });
83 + }
84 + async createTreasuryAccount(row) {
85 + const company=await DataScope.companyId();
86 + if(!Auth.isAdmin())throw Error('ایجاد صندوق/بانک فقط برای مدیر مجاز است');
87 + if(amount(row.initialBalance||0)!==0)throw Error('مانده افتتاحیه بانک باید در سند افتتاحیه ثبت شود');
88 + return StorageService.transaction(FINANCE_STORES,async tx=>{
89 + const accounts=await tx.getAllByIndex('account_chart','companyId',company);
90 + const parent=accounts.find(a=>a.code==='101'&&a.level==='general');
91 + if(!parent)throw Error('حساب ۱۰۱ موجود نیست');
92 + const history=await tx.getAllByIndex('journal_lines','companyId',company);
93 + if(history.some(l=>l.accountId===parent.id))
94 + throw Error('حساب ۱۰۱ دارای گردش مستقیم است؛ افزودن زیرحساب بانکی نیازمند اصلاح کدینگ است');
95 + let n=1,code;
96 + do{code='101'+String(n++).padStart(3,'0')}while(accounts.some(a=>a.code===code));
97 + const account={id:uid('acc_'),companyId:company,code,type:'asset',
98 + level:'subsidiary',parentCode:'101',name:row.name,active:true,postable:true};
99 + await tx.put('account_chart',account);
100 + const existing=(await tx.getAll('treasury')).filter(x=>x.companyId===company&&x.recordType==='account');
101 + const result={...row,companyId:company,recordType:'account',
102 + ledgerAccountId:account.id,isDefault:!existing.length};
103 + await tx.put('treasury',result);
104 + return result;
105 + });
106 + }
107 + async defaultWarehouse(tx,company) {
108 + const all=await tx.getAllByIndex('warehouses','companyId',company);
109 + const warehouse=all.find(x=>x.isDefault&&x.active!==false)||all.find(x=>x.active!==false);
110 + if(!warehouse)throw Error('انبار فعالی وجود ندارد');
111 + return warehouse.id;
112 + }
113 + async context(tx,company,date) {
114 + assertJalaliDate(date);
115 + const accounts=await tx.getAllByIndex('account_chart','companyId',company);
116 + const periods=await tx.getAllByIndex('fiscal_periods','companyId',company);
117 + const period=periods.find(p=>p.startDate<=date&&date<=p.endDate);
118 + if(!period||period.closed||period.status==='closed')throw Error('برای تاریخ رویداد، دوره مالی باز وجود ندارد');
119 + return {companyId:company,date,period,accounts};
120 + }
121 + async journal(tx,ctx,kind,id,lines,description,revision=1) {
122 + const filtered=lines.filter(Boolean);
123 + const totals=validateJournal({companyId:ctx.companyId,date:ctx.date,lines:filtered},ctx.accounts,ctx.period);
124 + const key=journalSourceKey(ctx.companyId,kind,id,revision);
125 + if((await tx.getAllByIndex('journal_entries','sourceKey',key)).length)throw Error('رویداد مالی قبلاً ثبت شده است');
126 + const journal={id:uid('jn_'),companyId:ctx.companyId,periodId:ctx.period.id,date:ctx.date,
127 + status:'posted',sourceKey:key,sourceType:kind,sourceId:id,revision,
128 + description,createdBy:actor(),postedBy:actor(),postedAt:today(),...totals};
129 + await tx.put('journal_entries',journal);
130 + for(const [position,line] of filtered.entries()) {
131 + await tx.put('journal_lines',{...line,id:uid('jl_'),journalId:journal.id,
132 + companyId:ctx.companyId,position});
133 + }
134 + return journal;
135 + }
136 + async stock(tx,ctx,warehouseId,item,direction,costValue,refId,refType='invoice') {
137 + if(refType!=='stocktake'){
138 + const sessions=await tx.getAllByIndex('stocktakes','warehouseId',warehouseId);
139 + if(sessions.some(s=>s.companyId===ctx.companyId&&s.status==='draft'))
140 + throw Error('انبار در حال شمارش است؛ تا بستن جلسه، ورود و خروج کالا متوقف است');
141 + }
142 + const product=sameCompany(await tx.get('products',item.productId),ctx.companyId,'کالا');
143 + if(product.trackInventory===false)return {cost:0};
144 + const id=balanceId(ctx.companyId,warehouseId,product.id);
145 + const before=await tx.get('inventory_balances',id);
146 + const next=direction==='in'?receiveStock(before,item.qty,costValue):issueStock(before,item.qty);
147 + await tx.put('inventory_balances',{id,companyId:ctx.companyId,warehouseId,productId:product.id,
148 + quantityUnits:next.quantityUnits,value:next.value});
149 + await tx.put('stock_movements',{id:uid('mv_'),companyId:ctx.companyId,ownerUserId:actor(),
150 + warehouseId,productId:product.id,type:direction,qty:item.qty,
151 + cost:next.cost,refType,refId,note:'سند '+refId,date:ctx.date});
152 + return {cost:next.cost};
153 + }
154 + async issueInvoice(invoice) {
155 + const company=await DataScope.companyId();
156 + if(!await this.isEnabled())throw Error('حسابداری یکپارچه برای این شرکت فعال نیست');
157 + assertInvoiceTotals(invoice);
158 + if(invoice.isPreInvoice)throw Error('پیش‌فاکتور نباید سند مالی تولید کند');
159 + if(!invoice.id)throw Error('شناسه یکتای فاکتور الزامی است');
160 + return StorageService.transaction(FINANCE_STORES,async tx=>{
161 + const ctx=await this.context(tx,company,invoice.date);
162 + const kinds=INVOICE_DIRECTIONS;
163 + if(!kinds[invoice.kind])throw Error('نوع فاکتور نامعتبر است');
164 + const old=await tx.get('invoices',invoice.id);
165 + if(old&&(!old.isPreInvoice||old.companyId!==company))throw Error('فاکتور قطعی از این مسیر قابل بازنویسی نیست');
166 + const existing=(await tx.getAll('invoices')).filter(i=>i.companyId===company&&!i.isPreInvoice);
167 + if(existing.some(i=>String(i.number)===String(invoice.number)))throw Error('شماره فاکتور تکراری است');
168 + if(invoice.contactId)sameCompany(await tx.get('contacts',invoice.contactId),company,'طرف حساب');
169 + if(['sale_return','purchase_return'].includes(invoice.kind)){
170 + if(!invoice.originalInvoiceId)throw Error('فاکتور مرجوعی باید به فاکتور اولیه متصل باشد');
171 + const origin=sameCompany(await tx.get('invoices',invoice.originalInvoiceId),company,'فاکتور اولیه');
172 + const validKinds=invoice.kind==='sale_return'?['sale','non_formal']:['purchase'];
173 + if(!validKinds.includes(origin.kind)||origin.isPreInvoice)
174 + throw Error('نوع فاکتور اولیه با مرجوعی سازگار نیست');
175 + if(origin.contactId!==invoice.contactId)
176 + throw Error('طرف حساب مرجوعی با فاکتور اولیه مطابقت ندارد');
177 + const otherReturns=existing.filter(x=>x.kind===invoice.kind&&x.originalInvoiceId===origin.id);
178 + const returnedRows=otherReturns.flatMap(x=>x.items||[]);
179 + const ids=new Set(invoice.items.map(x=>x.productId||x.productName));
180 + for(const id of ids){
181 + const matching=x=>(x.productId||x.productName)===id;
182 + const base=(origin.items||[]).filter(matching).reduce((sum,x)=>sum+qtyUnits(x.qty),0);
183 + const was=returnedRows.filter(matching).reduce((sum,x)=>sum+qtyUnits(x.qty),0);
184 + const requested=invoice.items.filter(matching).reduce((sum,x)=>sum+qtyUnits(x.qty),0);
185 + if(!base||was+requested>base)throw Error('تعداد مرجوعی از مقدار فاکتور اصلی بیشتر است');
186 + }
187 + }
188 + const warehouseId=invoice.warehouseId||await this.defaultWarehouse(tx,company);
189 + sameCompany(await tx.get('warehouses',warehouseId),company,'انبار');
190 + const details=allocateDiscount(invoice.items,invoice.totalDiscount);
191 + let stockCost=0,trackedNet=0,serviceNet=0;
192 + const returnAllocated = new Map();
193 + for(const item of details){
194 + if(!item.productId){serviceNet+=item.netLineTotal;continue}
195 + const product=sameCompany(await tx.get('products',item.productId),company,'کالا');
196 + if(product.trackInventory===false){serviceNet+=item.netLineTotal;continue}
197 + trackedNet+=item.netLineTotal;
198 + let inboundCost=item.netLineTotal;
199 + if(invoice.kind==='sale_return'){
200 + if(!invoice.originalInvoiceId)throw Error('مرجوعی فروش کالای انباری باید به فاکتور فروش اولیه متصل باشد');
201 + const origin=sameCompany(await tx.get('invoices',invoice.originalInvoiceId),company,'فاکتور اصلی');
202 + if(!['sale','non_formal'].includes(origin.kind)||origin.isPreInvoice)throw Error('مرجع برگشت فروش معتبر نیست');
203 + if(origin.contactId!==invoice.contactId)throw Error('طرف حساب برگشت با فروش اولیه یکسان نیست');
204 + const priorReturns=(await tx.getAll('invoices')).filter(x=>x.companyId===company &&
205 + x.kind==='sale_return'&&!x.isPreInvoice&&x.originalInvoiceId===origin.id);
206 + const alreadyReturned=priorReturns.flatMap(x=>x.items||[])
207 + .filter(x=>x.productId===item.productId).reduce((sum,x)=>sum+qtyUnits(x.qty),0);
208 + const originalLines=(await tx.getAll('stock_movements')).filter(m=>m.companyId===company&&
209 + m.refId===origin.id&&m.productId===item.productId&&m.type==='out');
210 + const originUnits=originalLines.reduce((s,m)=>s+qtyUnits(m.qty),0);
211 + const originCost=originalLines.reduce((s,m)=>s+amount(m.cost||0),0);
212 + if(!originUnits)throw Error('بهای تمام‌شده سند فروش اولیه یافت نشد');
213 + const incomingUnits=invoice.items.filter(x=>x.productId===item.productId)
214 + .reduce((sum,x)=>sum+qtyUnits(x.qty),0);
215 + if(alreadyReturned+incomingUnits>originUnits)throw Error('تعداد برگشت از مقدار فروخته‌شده بیشتر است');
216 + const priorReturnIds=new Set(priorReturns.map(x=>x.id));
217 + const priorCost=(await tx.getAll('stock_movements')).filter(m=>m.companyId===company&&
218 + priorReturnIds.has(m.refId)&&m.productId===item.productId&&m.type==='in')
219 + .reduce((sum,m)=>sum+amount(m.cost||0),0);
220 + const seen=returnAllocated.get(item.productId)||{units:0,cost:0};
221 + const rowUnits=qtyUnits(item.qty);
222 + const completes=alreadyReturned+incomingUnits===originUnits &&
223 + seen.units+rowUnits===incomingUnits;
224 + inboundCost=completes?originCost-priorCost-seen.cost:
225 + Math.round(originCost*rowUnits/originUnits);
226 + if(inboundCost<0)throw Error('بهای تمام‌شده برگشت بیش از بهای فاکتور اصلی است');
227 + returnAllocated.set(item.productId,{units:seen.units+rowUnits,cost:seen.cost+inboundCost});
228 + }
229 + const update=await this.stock(tx,ctx,warehouseId,item,kinds[invoice.kind],inboundCost,invoice.id);
230 + stockCost+=update.cost;
231 + }
232 + const net=amount(invoice.subtotal)-amount(invoice.totalDiscount);
233 + const grand=amount(invoice.grandTotal),vat=amount(invoice.vatAmount);
234 + const ref={contactId:invoice.contactId||null};
235 + const lines=[];
236 + const add=(code,debit,credit)=>{const l=postLine(leg(ctx,LEDGER_CODES[code]),debit,credit,ref);if(l)lines.push(l)};
237 + switch(invoice.kind){
238 + case 'sale': case 'non_formal':
239 + add('receivable',grand,0);add('revenue',0,net);add('outputVat',0,vat);
240 + add('cogs',stockCost,0);add('inventory',0,stockCost);break;
241 + case 'purchase':
242 + add('inventory',trackedNet,0);add('expense',serviceNet,0);
243 + add('inputVat',vat,0);add('payable',0,grand);break;
244 + case 'sale_return':
245 + add('revenue',net,0);add('outputVat',vat,0);add('receivable',0,grand);
246 + add('inventory',stockCost,0);add('cogs',0,stockCost);break;
247 + case 'purchase_return':
248 + add('payable',grand,0);add('inventory',0,stockCost);
249 + add('expense',0,serviceNet);add('inputVat',0,vat);
250 + { const variance=differenceLines(leg(ctx,LEDGER_CODES.variance),stockCost-trackedNet,ref);
251 + if(variance)lines.push(variance); }
252 + break;
253 + }
254 + const journal=await this.journal(tx,ctx,'invoice',invoice.id,lines,'فاکتور '+invoice.number);
255 + const issued={...invoice,companyId:company,ownerUserId:actor(),warehouseId,
256 + financePosted:true,journalId:journal.id,status:invoice.paidAmount?'partial':'unpaid',
257 + remaining:grand,paidAmount:0};
258 + await tx.put('invoices',issued);
259 + const previousItems=await tx.getAllByIndex('invoice_items','invoiceId',invoice.id);
260 + for(const oldItem of previousItems){
261 + if(oldItem.companyId!==company)throw Error('اقلام فاکتور متعلق به شرکت دیگری است');
262 + await tx.delete('invoice_items',oldItem.id);
263 + }
264 + for(const [position,item] of invoice.items.entries()){
265 + await tx.put('invoice_items',{...item,id:uid('ii_'),companyId:company,
266 + invoiceId:invoice.id,position});
267 + }
268 + if(invoice.paidAmount){
269 + const isIncoming=['sale','non_formal','purchase_return'].includes(invoice.kind);
270 + await this.recordCash(tx,ctx,{amount:invoice.paidAmount,
271 + contactId:invoice.contactId,invoiceId:invoice.id,method:invoice.paymentMethod,
272 + type:isIncoming?'receipt':'payment',referenceKind:invoice.kind});
273 + }
274 + return (await tx.get('invoices',invoice.id));
275 + });
276 + }
277 + async recordCash(tx,ctx,info) {
278 + const sum=positiveAmount(info.amount);
279 + if(!['receipt','payment','transfer'].includes(info.type))throw Error('نوع دریافت و پرداخت نامعتبر است');
280 + if(info.method==='cheque')throw Error('پرداخت چکی باید از گردش چک ثبت شود');
281 + const cashAccounts=(await tx.getAll('treasury')).filter(a=>a.companyId===ctx.companyId&&
282 + a.recordType==='account'&&a.isActive!==false);
283 + const chosen= info.type==='payment'?info.fromAccountId:info.toAccountId;
284 + if(chosen&&!cashAccounts.some(a=>a.id===chosen))throw Error('حساب بانکی/صندوق انتخاب‌شده متعلق به شرکت فعال نیست');
285 + const to=cashAccounts.find(a=>a.id===chosen)||cashAccounts.find(a=>a.isDefault)||cashAccounts[0];
286 + if(!to)throw Error('برای تسویه نقدی، حساب صندوق یا بانک فعال تعریف کنید');
287 + const cashLedger=to.ledgerAccountId?
288 + sameCompany(ctx.accounts.find(a=>a.id===to.ledgerAccountId),ctx.companyId,'حساب معین بانک').id:
289 + leg(ctx,LEDGER_CODES.cash);
290 + const id=info.transactionId||uid('tx_');
291 + if(await tx.get('treasury',id))throw Error('دریافت یا پرداخت تکراری است');
292 + if(info.contactId)sameCompany(await tx.get('contacts',info.contactId),ctx.companyId,'طرف حساب دریافت/پرداخت');
293 + let related=null;
294 + if(info.invoiceId) {
295 + related=sameCompany(await tx.get('invoices',info.invoiceId),ctx.companyId,'فاکتور تسویه');
296 + if(related.isPreInvoice||!related.financePosted)throw Error('این فاکتور در دفتر مالی قطعی نشده است');
297 + if(info.contactId&&related.contactId!==info.contactId)throw Error('شخص تراکنش با فاکتور متفاوت است');
298 + if(sum>related.remaining)throw Error('مبلغ تسویه بیش از مانده فاکتور است');
299 + }
300 + const isReceipt=info.type==='receipt';
301 + let otherCode=isReceipt?LEDGER_CODES.receivable:LEDGER_CODES.payable;
302 + if(related){
303 + const kind=related.kind;
304 + const expected=isReceipt?['sale','non_formal','purchase_return']:['purchase','sale_return'];
305 + if(!expected.includes(kind))throw Error('جهت دریافت/پرداخت با فاکتور مطابقت ندارد');
306 + if(kind==='purchase_return')otherCode=LEDGER_CODES.payable;
307 + if(kind==='sale_return')otherCode=LEDGER_CODES.receivable;
308 + }
309 + const side=leg(ctx,otherCode);
310 + const lines=[postLine(isReceipt?cashLedger:side,sum,0,{contactId:info.contactId||related?.contactId||null}),
311 + postLine(isReceipt?side:cashLedger,0,sum,{contactId:info.contactId||related?.contactId||null})];
312 + const journal=await this.journal(tx,ctx,'treasury',id,lines,'دریافت/پرداخت '+id);
313 + const transaction={id,companyId:ctx.companyId,ownerUserId:actor(),
314 + recordType:'transaction',type:info.type,date:ctx.date,amount:sum,
315 + fromAccountId:isReceipt?null:to.id,toAccountId:isReceipt?to.id:null,
316 + contactId:info.contactId||related?.contactId||null,refInvoiceId:related?.id||null,
317 + method:info.method||'cash',description:info.description||'',financePosted:true,journalId:journal.id};
318 + await tx.put('treasury',transaction);
319 + if(related){
320 + const paid=amount(related.paidAmount||0)+sum;
321 + await tx.put('invoices',{...related,paidAmount:paid,remaining:related.grandTotal-paid,
322 + status:paid===related.grandTotal?'paid':'partial'});
323 + await tx.put('settlements',{id:uid('set_'),companyId:ctx.companyId,
324 + invoiceId:related.id,transactionId:id,amount:sum,date:ctx.date,ownerUserId:actor()});
325 + }
326 + return transaction;
327 + }
328 + async transferCash(tx,ctx,info) {
329 + const sum=positiveAmount(info.amount),all=await tx.getAll('treasury');
330 + const from=sameCompany(all.find(a=>a.id===info.fromAccountId&&a.recordType==='account'),
331 + ctx.companyId,'حساب مبدا');
332 + const to=sameCompany(all.find(a=>a.id===info.toAccountId&&a.recordType==='account'),
333 + ctx.companyId,'حساب مقصد');
334 + if(from.id===to.id)throw Error('حساب مبدا و مقصد باید متفاوت باشند');
335 + const mapping=account=>account.ledgerAccountId?
336 + sameCompany(ctx.accounts.find(a=>a.id===account.ledgerAccountId),ctx.companyId,'سرفصل صندوق').id:
337 + leg(ctx,LEDGER_CODES.cash);
338 + const id=info.transactionId||uid('tx_');
339 + if(await tx.get('treasury',id))throw Error('تراکنش انتقال تکراری است');
340 + const journal=await this.journal(tx,ctx,'treasury',id,[
341 + postLine(mapping(to),sum,0),postLine(mapping(from),0,sum)
342 + ],'انتقال داخلی بین حساب‌ها');
343 + const row={id,companyId:ctx.companyId,ownerUserId:actor(),recordType:'transaction',
344 + type:'transfer',amount:sum,date:ctx.date,fromAccountId:from.id,toAccountId:to.id,
345 + contactId:null,method:'transfer',financePosted:true,journalId:journal.id,
346 + description:info.description||''};
347 + await tx.put('treasury',row);
348 + return row;
349 + }
350 + async postTransaction(data) {
351 + const company=await DataScope.companyId();
352 + if(!await this.isEnabled())throw Error('حسابداری یکپارچه غیرفعال است');
353 + return StorageService.transaction(FINANCE_STORES,async tx=>{
354 + const ctx=await this.context(tx,company,data.date);
355 + if(data.type==='transfer')return this.transferCash(tx,ctx,{...data,transactionId:data.id});
356 + return this.recordCash(tx,ctx,{...data,invoiceId:data.refInvoiceId,transactionId:data.id});
357 + });
358 + }
359 + async postExpense(row) {
360 + const company=await DataScope.companyId();
361 + if(!await this.isEnabled())throw Error('حسابداری یکپارچه غیرفعال است');
362 + return StorageService.transaction(FINANCE_STORES,async tx=>{
363 + const ctx=await this.context(tx,company,row.date);
364 + if(await tx.get('expenses',row.id))throw Error('سند هزینه/درآمد تکراری است');
365 + const sum=positiveAmount(row.amount);
366 + if(row.method==='cheque')throw Error('هزینه یا درآمد چکی را در بخش چک‌ها ثبت کنید');
367 + const cash=(await tx.getAll('treasury')).filter(a=>a.companyId===company&&a.recordType==='account');
368 + const selected=cash.find(a=>a.isDefault)||cash[0];
369 + if(!selected)throw Error('صندوق یا بانک برای ثبت هزینه/درآمد موجود نیست');
370 + const cashLedger=selected.ledgerAccountId?
371 + sameCompany(ctx.accounts.find(a=>a.id===selected.ledgerAccountId),company,'حساب مالی').id:
372 + leg(ctx,LEDGER_CODES.cash);
373 + const income=row.kind==='income';
374 + const other=leg(ctx,LEDGER_CODES[income?'otherRevenue':'expense']);
375 + const journal=await this.journal(tx,ctx,'expense',row.id,[
376 + postLine(income?cashLedger:other,sum,0),
377 + postLine(income?other:cashLedger,0,sum)
378 + ],row.description||row.category);
379 + const output={...row,companyId:company,financePosted:true,journalId:journal.id,
380 + treasuryAccountId:selected.id};
381 + await tx.put('expenses',output);
382 + await tx.put('treasury',{id:uid('tx_'),companyId:company,recordType:'transaction',
383 + type:income?'receipt':'payment',date:ctx.date,amount:sum,
384 + fromAccountId:income?null:selected.id,toAccountId:income?selected.id:null,
385 + contactId:null,refExpenseId:row.id,method:row.method||'cash',ownerUserId:actor(),
386 + financePosted:true,journalId:journal.id,description:row.description||row.category});
387 + return output;
388 + });
389 + }
390 + async postCheque(row) {
391 + const company=await DataScope.companyId();
392 + return StorageService.transaction(FINANCE_STORES,async tx=>{
393 + if(await tx.get('cheques',row.id))throw Error('چک تکراری است');
394 + const ctx=await this.context(tx,company,row.issueDate);
395 + positiveAmount(row.amount);
396 + if(!row.contactId)throw Error('چک باید طرف‌حساب معتبر داشته باشد');
397 + sameCompany(await tx.get('contacts',row.contactId),company,'شخص چک');
398 + const inbound=row.direction==='inbound';
399 + if(!inbound&&row.direction!=='outbound')throw Error('جهت چک نامعتبر است');
400 + if(row.status!=='pending')throw Error('چک جدید ابتدا باید در جریان ثبت شود');
401 + const sum=amount(row.amount),ref={contactId:row.contactId};
402 + const debit=leg(ctx,LEDGER_CODES[inbound?'chequeIn':'payable']);
403 + const credit=leg(ctx,LEDGER_CODES[inbound?'receivable':'chequeOut']);
404 + const journal=await this.journal(tx,ctx,'cheque',row.id,[
405 + postLine(debit,sum,0,ref),postLine(credit,0,sum,ref)
406 + ],'ثبت چک '+row.chequeNumber);
407 + const item={...row,companyId:company,status:'pending',statusVersion:1,
408 + financePosted:true,journalId:journal.id};
409 + await tx.put('cheques',item);
410 + return item;
411 + });
412 + }
413 + async changeChequeStatus(id,status,options={}) {
414 + const company=await DataScope.companyId();
415 + return StorageService.transaction(FINANCE_STORES,async tx=>{
416 + const cheque=sameCompany(await tx.get('cheques',id),company,'چک');
417 + if(!cheque.financePosted)throw Error('چک قدیمی فاقد سند مالی است؛ ابتدا تعیین تکلیف شود');
418 + if(cheque.status!=='pending')throw Error('تنها چک در جریان قابل تعیین تکلیف است');
419 + if(!['cleared','bounced','returned','spent'].includes(status))throw Error('وضعیت چک نامعتبر است');
420 + if(status==='spent'&&cheque.direction!=='inbound')throw Error('فقط چک دریافتی قابل خرج‌کرد است');
421 + const ctx=await this.context(tx,company,options.date||cheque.dueDate);
422 + const sum=amount(cheque.amount),inbound=cheque.direction==='inbound';
423 + const ref={contactId:cheque.contactId};
424 + const accounts=(await tx.getAll('treasury')).filter(a=>a.companyId===company&&a.recordType==='account');
425 + if(options.accountId&&!accounts.some(a=>a.id===options.accountId))
426 + throw Error('حساب بانکی انتخاب‌شده در شرکت فعال وجود ندارد');
427 + const bank=accounts.find(a=>a.id===options.accountId)||accounts.find(a=>a.isDefault)||accounts[0];
428 + if(status==='cleared'&&!bank)throw Error('حساب بانک یا صندوق برای وصول چک مشخص نیست');
429 + const bankLedger=status==='cleared'?(bank?.ledgerAccountId?
430 + sameCompany(ctx.accounts.find(a=>a.id===bank.ledgerAccountId),company,'حساب بانک').id:
431 + leg(ctx,LEDGER_CODES.cash)):null;
432 + const chequeAccount=leg(ctx,LEDGER_CODES[inbound?'chequeIn':'chequeOut']);
433 + let target;
434 + if(status==='cleared')target=bankLedger;
435 + else if(status==='spent')target=leg(ctx,LEDGER_CODES.payable);
436 + else target=leg(ctx,LEDGER_CODES[inbound?'receivable':'payable']);
437 + const lines=inbound?
438 + [postLine(target,sum,0,ref),postLine(chequeAccount,0,sum,ref)]:
439 + [postLine(chequeAccount,sum,0,ref),postLine(target,0,sum,ref)];
440 + const journal=await this.journal(tx,ctx,'cheque_status',id,lines,'تغییر وضعیت چک '+status,2);
441 + const updated={...cheque,status,statusVersion:2,
442 + statusJournalId:journal.id,statusChangedAt:today()};
443 + await tx.put('cheques',updated);
444 + if(status==='cleared'){
445 + if(!bank)throw Error('بانک یا صندوق چک مشخص نیست');
446 + await tx.put('treasury',{id:uid('tx_'),companyId:company,recordType:'transaction',
447 + type:inbound?'receipt':'payment',date:ctx.date,amount:sum,
448 + toAccountId:inbound?bank.id:null,fromAccountId:inbound?null:bank.id,
449 + contactId:null,refChequeId:id,method:'cheque',financePosted:true,
450 + journalId:journal.id,ownerUserId:actor(),description:'وصول چک '+id});
451 + }
452 + return updated;
453 + });
454 + }
455 + async warehouses(){
456 + const company=await DataScope.companyId();
457 + return StorageService.getAllByIndex('warehouses','companyId',company);
458 + }
459 + async addWarehouse(name) {
460 + if(!Auth.isAdmin())throw Error('ایجاد انبار فقط برای مدیر مجاز است');
461 + const company=await DataScope.companyId();
462 + const value=String(name||'').trim();
463 + if(!value)throw Error('نام انبار الزامی است');
464 + return StorageService.transaction('warehouses',async tx=>{
465 + const existing=await tx.getAllByIndex('warehouses','companyId',company);
466 + if(existing.some(w=>w.name===value))throw Error('انبار تکراری است');
467 + const warehouse={id:uid('wh_'),name:value,companyId:company,
468 + ownerUserId:actor(),active:true,isDefault:!existing.length};
469 + await tx.put('warehouses',warehouse);return warehouse;
470 + });
471 + }
472 + async stockBalances({warehouseId=null}={}) {
473 + const company=await DataScope.companyId();
474 + const rows=await StorageService.getAllByIndex('inventory_balances','companyId',company);
475 + return warehouseId?rows.filter(r=>r.warehouseId===warehouseId):rows;
476 + }
477 + async transferStock({fromWarehouseId,toWarehouseId,productId,quantity,date}) {
478 + if(fromWarehouseId===toWarehouseId)throw Error('انبار مبدا و مقصد یکسان است');
479 + const company=await DataScope.companyId(),refId=uid('tr_');
480 + return StorageService.transaction(FINANCE_STORES,async tx=>{
481 + const ctx=await this.context(tx,company,date);
482 + sameCompany(await tx.get('warehouses',fromWarehouseId),company,'انبار مبدا');
483 + sameCompany(await tx.get('warehouses',toWarehouseId),company,'انبار مقصد');
484 + const product=sameCompany(await tx.get('products',productId),company,'کالا');
485 + if(product.trackInventory===false)throw Error('خدمات امکان انتقال انبار ندارند');
486 + const original=await this.stock(tx,ctx,fromWarehouseId,{productId,qty:quantity},
487 + 'out',0,refId,'transfer');
488 + await this.stock(tx,ctx,toWarehouseId,{productId,qty:quantity},
489 + 'in',original.cost,refId,'transfer');
490 + return {id:refId,cost:original.cost,quantity};
491 + });
492 + }
493 + async newStocktake({warehouseId,date}) {
494 + const company=await DataScope.companyId();
495 + return StorageService.transaction(FINANCE_STORES,async tx=>{
496 + await this.context(tx,company,date);
497 + sameCompany(await tx.get('warehouses',warehouseId),company,'انبار شمارش');
498 + const all=await tx.getAllByIndex('stocktakes','companyId',company);
499 + if(all.some(s=>s.warehouseId===warehouseId&&s.status==='draft'))
500 + throw Error('شمارش باز دیگری برای این انبار وجود دارد');
501 + const session={id:uid('stk_'),companyId:company,warehouseId,date,
502 + status:'draft',createdBy:actor(),createdAt:today()};
503 + await tx.put('stocktakes',session);
504 + const balances=(await tx.getAllByIndex('inventory_balances','warehouseId',warehouseId))
505 + .filter(b=>b.companyId===company);
506 + for(const balance of balances){
507 + await tx.put('stocktake_lines',{id:uid('stkl_'),stocktakeId:session.id,
508 + companyId:company,productId:balance.productId,
509 + expectedUnits:balance.quantityUnits,countedUnits:null,
510 + expectedValue:balance.value});
511 + }
512 + return session;
513 + });
514 + }
515 + async countStocktake(stocktakeId,productId,quantity,unitCost=null) {
516 + if(!Auth.isAdmin())throw Error('شمارش انبار فقط توسط مدیر قابل اصلاح است');
517 + const company=await DataScope.companyId();
518 + const counted=Number(quantity)===0?0:qtyUnits(quantity);
519 + return StorageService.transaction(FINANCE_STORES,async tx=>{
520 + const session=sameCompany(await tx.get('stocktakes',stocktakeId),company,'جلسه شمارش');
521 + if(session.status!=='draft')throw Error('انبارگردانی بسته شده است');
522 + const product=sameCompany(await tx.get('products',productId),company,'کالا');
523 + if(product.trackInventory===false)throw Error('خدمات در انبارگردانی وارد نمی‌شوند');
524 + const lines=await tx.getAllByIndex('stocktake_lines','stocktakeId',stocktakeId);
525 + const old=lines.find(l=>l.companyId===company&&l.productId===productId);
526 + const balance=await tx.get('inventory_balances',balanceId(company,session.warehouseId,productId));
527 + const row=old||{id:uid('stkl_'),companyId:company,stocktakeId,productId,
528 + expectedUnits:balance?.quantityUnits||0,expectedValue:balance?.value||0};
529 + if(unitCost!==null)row.unitCost=amount(unitCost);
530 + row.countedUnits=counted;row.countedBy=actor();row.countedAt=today();
531 + await tx.put('stocktake_lines',row);return row;
532 + });
533 + }
534 + async getStocktakes() {
535 + const company=await DataScope.companyId();
536 + return StorageService.getAllByIndex('stocktakes','companyId',company);
537 + }
538 + async getStocktakeLines(stocktakeId) {
539 + const company=await DataScope.companyId();
540 + const session=sameCompany(await StorageService.get('stocktakes',stocktakeId),company,'شمارش');
541 + return (await StorageService.getAllByIndex('stocktake_lines','stocktakeId',session.id))
542 + .filter(l=>l.companyId===company);
543 + }
544 + async finalizeStocktake(stocktakeId) {
545 + if(!Auth.isAdmin())throw Error('تأیید انبارگردانی فقط توسط مدیر مجاز است');
546 + const company=await DataScope.companyId();
547 + return StorageService.transaction(FINANCE_STORES,async tx=>{
548 + const session=sameCompany(await tx.get('stocktakes',stocktakeId),company,'جلسه شمارش');
549 + if(session.status!=='draft')throw Error('این انبارگردانی قبلاً بسته شده است');
550 + const ctx=await this.context(tx,company,session.date);
551 + const lines=(await tx.getAllByIndex('stocktake_lines','stocktakeId',session.id))
552 + .filter(l=>l.companyId===company);
553 + if(!lines.length)throw Error('برگه شمارش بدون کالا است');
554 + const amounts={increase:0,decrease:0};
555 + for(const l of lines){
556 + if(l.countedUnits===null||l.countedUnits===undefined)
557 + throw Error('همه اقلام باید شمارش شوند');
558 + const id=balanceId(company,session.warehouseId,l.productId);
559 + const current=await tx.get('inventory_balances',id);
560 + const base=current?.quantityUnits||0;
561 + if(base!==l.expectedUnits|| (current?.value||0)!==l.expectedValue)
562 + throw Error('در طول شمارش موجودی تغییر کرده است؛ شمارش را تجدید کنید');
563 + const delta=l.countedUnits-l.expectedUnits;
564 + if(!delta)continue;
565 + let update;
566 + if(delta>0){
567 + const rate=l.unitCost!==undefined?amount(l.unitCost):
568 + base>0?Math.round((current.value||0)*1000/base):null;
569 + if(rate===null)throw Error('برای مازاد کالای بدون سابقه، قیمت تمام‌شده واحد را وارد کنید');
570 + update=await this.stock(tx,ctx,session.warehouseId,
571 + {productId:l.productId,qty:fromQtyUnits(delta)},'in',
572 + Math.round(rate*fromQtyUnits(delta)),session.id,'stocktake');
573 + amounts.increase+=update.cost;
574 + }else{
575 + update=await this.stock(tx,ctx,session.warehouseId,
576 + {productId:l.productId,qty:fromQtyUnits(-delta)},'out',
577 + 0,session.id,'stocktake');
578 + amounts.decrease+=update.cost;
579 + }
580 + }
581 + const net=amounts.increase-amounts.decrease;
582 + let journal=null;
583 + if(amounts.increase||amounts.decrease){
584 + journal=await this.journal(tx,ctx,'stocktake',session.id,[
585 + postLine(leg(ctx,LEDGER_CODES.inventory),amounts.increase,0),
586 + postLine(leg(ctx,LEDGER_CODES.variance),0,amounts.increase),
587 + postLine(leg(ctx,LEDGER_CODES.variance),amounts.decrease,0),
588 + postLine(leg(ctx,LEDGER_CODES.inventory),0,amounts.decrease)
589 + ],'تعدیل انبارگردانی '+session.id);
590 + }
591 + const updated={...session,status:'posted',journalId:journal?.id||null,
592 + approvedBy:actor(),approvedAt:today(),...amounts,net};
593 + await tx.put('stocktakes',updated);return updated;
594 + });
595 + }
596 +}
597 +export const RetailPostingService = new RetailPostingServiceImpl();
src/core/Router.js
+1 -1
@@ -59,7 +59,7 @@ class RouterImpl {
59 <div class="card" style="text-align:center;padding:40px">
60 <div style="font-size:40px;margin-bottom:12px">⚠️</div>
61 <h3>خطا در بارگذاری صفحه</h3>
62 - <p style="color:var(--text-muted);margin-top:8px;font-size:13px">${err.message}</p>
62 + <p style="color:var(--text-muted);margin-top:8px;font-size:13px">${String(err?.message || err).replace(/[&<>"']/g, c => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]))}</p>
63 </div>`;
64 }
65 }
src/core/SecureState.js new
+29
@@ -0,0 +1,29 @@
1 +const FALLBACK_PREFIX='finora_secure_fallback:';
2 +async function tauriInvoke(command,args){
3 + const invoke=globalThis.__TAURI_INTERNALS__?.invoke;
4 + if(typeof invoke!=='function') return null;
5 + return invoke(command,args);
6 +}
7 +export const SecureState={
8 + async get(key){
9 + const protectedValue=localStorage.getItem(FALLBACK_PREFIX+key); if(!protectedValue)return null;
10 + try{
11 + const clear=await tauriInvoke('unprotect_local_state',{value:protectedValue});
12 + return JSON.parse(clear ?? protectedValue);
13 + }catch(error){
14 + if (globalThis.__TAURI_INTERNALS__?.invoke) throw new Error('داده امن ویندوز قابل بازیابی نیست؛ از بازنشانی خودکار جلوگیری شد', { cause: error });
15 + try{return JSON.parse(protectedValue)}catch{return null}
16 + }
17 + },
18 + async set(key,value){
19 + const clear=JSON.stringify(value);
20 + try{
21 + const protectedValue=await tauriInvoke('protect_local_state',{value:clear});
22 + localStorage.setItem(FALLBACK_PREFIX+key,protectedValue ?? clear);
23 + }catch(error){
24 + if (globalThis.__TAURI_INTERNALS__?.invoke) throw new Error('ذخیره امن ویندوز ناموفق بود', { cause: error });
25 + localStorage.setItem(FALLBACK_PREFIX+key,clear)
26 + }
27 + },
28 + remove(key){ localStorage.removeItem(FALLBACK_PREFIX+key); }
29 +};
src/core/StorageService.js
+28 -6
@@ -1,10 +1,10 @@
1 // ============================================================
2 // StorageService — IndexedDB wrapper
3 -// v4: تراکنش چندجدولی، مهاجرت درست ایندکس‌ها، ورود/خروج امن داده
3 +// v5: جدول‌های حسابداری دوبل و مهاجرت سازگار با نسخه‌های قبلی
4 // ============================================================
5
6 const DB_NAME = 'finora_pro_db';
7 -const DB_VERSION = 4;
7 +const DB_VERSION = 6;
8
9 const STORES = [
10 'users', 'companies', 'contacts', 'products',
@@ -12,7 +12,10 @@ const STORES = [
12 'treasury',
13 'invoices', 'invoice_items', 'stock_movements',
14 'transactions', 'cheques', 'expenses',
15 - 'settings', 'logs'
15 + 'settings', 'logs',
16 + 'account_chart', 'fiscal_periods', 'journal_entries', 'journal_lines',
17 + 'warehouses', 'inventory_balances', 'stocktakes', 'stocktake_lines',
18 + 'settlements', 'account_mappings'
19 ];
20
21 // جدول‌هایی که ایندکس ownerUserId ندارند
@@ -22,7 +25,17 @@ const NO_OWNER_INDEX = new Set(['settings', 'logs']);
25 const INDEXES = {
26 invoices: [['date', 'date'], ['number', 'number'], ['clientUuid', 'clientUuid']],
27 stock_movements: [['productId', 'productId']],
25 - invoice_items: [['invoiceId', 'invoiceId']]
28 + invoice_items: [['invoiceId', 'invoiceId']],
29 + account_chart: [['companyId', 'companyId'], ['code', 'code']],
30 + fiscal_periods: [['companyId', 'companyId']],
31 + journal_entries: [['companyId', 'companyId'], ['sourceKey', 'sourceKey', { unique: true }]],
32 + journal_lines: [['journalId', 'journalId'], ['companyId', 'companyId']],
33 + warehouses: [['companyId', 'companyId']],
34 + inventory_balances: [['companyId', 'companyId'], ['warehouseId', 'warehouseId'], ['productId', 'productId']],
35 + stocktakes: [['companyId', 'companyId'], ['warehouseId', 'warehouseId']],
36 + stocktake_lines: [['companyId', 'companyId'], ['stocktakeId', 'stocktakeId']],
37 + settlements: [['companyId', 'companyId'], ['invoiceId', 'invoiceId'], ['transactionId', 'transactionId']],
38 + account_mappings: [['companyId', 'companyId']]
39 };
40
41 // فیلدهای مربوط به رمز عبور کاربران؛ هرگز در فایل پشتیبان نمی‌روند
@@ -142,6 +155,7 @@ class StorageServiceImpl {
155 * fetch، setTimeout یا هر چیز غیر IndexedDB باعث commit زودهنگام می‌شود.
156 */
157 async transaction(storeNames, fn, mode = 'readwrite') {
158 + if (mode === 'readwrite' && globalThis.FINORA?.License) globalThis.FINORA.License.assertWritable();
159 const db = await this.init();
160 const names = Array.isArray(storeNames) ? storeNames : [storeNames];
161
@@ -200,6 +214,12 @@ class StorageServiceImpl {
214 return r || [];
215 }
216
217 + async getByCompany(store, companyId) {
218 + if (!companyId) return [];
219 + const all = await this.getAll(store);
220 + return all.filter(row => row.companyId === companyId);
221 + }
222 +
223 async getAllByIndex(store, indexName, key) {
224 const r = await this._exec(store, 'readonly', s => s.index(indexName).getAll(key));
225 return r || [];
@@ -210,6 +230,7 @@ class StorageServiceImpl {
230 }
231
232 async put(store, obj) {
233 + if (globalThis.FINORA?.License && !['users', 'settings', 'logs'].includes(store)) globalThis.FINORA.License.assertWritable();
234 this._touch(obj);
235 await this._exec(store, 'readwrite', s => s.put(obj));
236 return obj;
@@ -224,6 +245,7 @@ class StorageServiceImpl {
245 }
246
247 async delete(store, id) {
248 + if (globalThis.FINORA?.License && !['users', 'settings', 'logs'].includes(store)) globalThis.FINORA.License.assertWritable();
249 await this._exec(store, 'readwrite', s => s.delete(id));
250 }
251
@@ -255,7 +277,7 @@ class StorageServiceImpl {
277 }
278
279 return {
258 - app: 'Finora Pro',
280 + app: 'Factor-easyPro',
281 version: DB_VERSION,
282 exportedAt: new Date().toISOString(),
283 data
@@ -271,7 +293,7 @@ class StorageServiceImpl {
293 if (!json || typeof json !== 'object' || !json.data || typeof json.data !== 'object') {
294 throw new Error('فرمت فایل نامعتبر است');
295 }
274 - if (json.app && json.app !== 'Finora Pro') {
296 + if (json.app && !['Finora Pro', 'Factor-easyPro'].includes(json.app)) {
297 throw new Error('این فایل پشتیبان فینورا پرو نیست');
298 }
299 if (typeof json.version === 'number' && json.version > DB_VERSION) {
src/core/Toast.js
+5 -1
@@ -20,6 +20,8 @@ class ToastManager {
20
21 show(message, type = 'info', title = '') {
22 const c = this._ensure();
23 + // Keep the notification host last in the body so it paints above dialogs.
24 + if (c.parentElement === document.body) document.body.appendChild(c);
25 const el = document.createElement('div');
26 el.className = `toast toast-${type}`;
27 el.innerHTML = `
@@ -31,7 +33,9 @@ class ToastManager {
33 <button class="toast-close" aria-label="بستن">×</button>`;
34 el.querySelector('.toast-close').onclick = () => el.remove();
35 c.appendChild(el);
34 - setTimeout(() => {
36 + // Errors stay visible until dismissed so users can read and report them.
37 + if (type !== 'error') setTimeout(() => {
38 + if (!el.isConnected) return;
39 el.style.animation = 'slideOut .3s ease forwards';
40 setTimeout(() => el.remove(), 300);
41 }, DURATIONS[type] || 4000);
src/main.js
+9 -2
@@ -11,6 +11,7 @@ import { ProductsView } from './views/ProductsView.js';
11 import { ExpensesView } from './views/ExpensesView.js';
12 import { DashboardView } from './views/DashboardView.js';
13 import { ReportsView } from './views/ReportsView.js';
14 +import { AccountingView } from './views/AccountingView.js';
15 import { StorageService } from './core/StorageService.js';
16 import { Theme } from './core/Theme.js';
17 import { Toast } from './core/Toast.js';
@@ -23,11 +24,13 @@ import { Formatters } from './utils/Formatters.js';
24 import { Jalali } from './utils/Jalali.js';
25 import { numberToWords } from './utils/NumberToWords.js';
26 import { NumberInput } from './utils/NumberInput.js';
27 +import { LicenseService } from './core/LicenseService.js';
28 +import { CompanyService } from './core/CompanyService.js';
29
30 const FINORA = {
28 - version: '0.1.0',
31 + version: '1.1.1',
32 Storage: StorageService,
30 - Theme, Toast, Router, Auth, EventBus, Modal, KeyboardShortcuts,
33 + Theme, Toast, Router, Auth, EventBus, Modal, KeyboardShortcuts, License: LicenseService, Company: CompanyService,
34 Utils: { Formatters, Jalali, numberToWords, NumberInput }
35 };
36 window.FINORA = FINORA;
@@ -42,6 +45,7 @@ const ROUTES = [
45 { name: 'cheques', title: 'چک‌ها', header: 'چک‌ها', view: ChequesView },
46 { name: 'expenses', title: 'هزینه و درآمد', header: 'هزینه و درآمد', view: ExpensesView },
47 { name: 'reports', title: 'گزارش سود و زیان', header: 'گزارش سود و زیان', view: ReportsView },
48 + { name: 'accounting', title: 'حسابداری', header: 'حسابداری دوبل', view: AccountingView },
49 { name: 'settings', title: 'تنظیمات', header: 'تنظیمات', view: SettingsView }
50 ];
51
@@ -143,7 +147,10 @@ async function bootstrap() {
147 NumberInput.init();
148 KeyboardShortcuts.init();
149 await StorageService.init();
150 + await LicenseService.init();
151 await Auth.init(); // تا ورود موفق (صفحه قفل) اینجا منتظر می‌ماند
152 + await CompanyService.init();
153 + await CompanyService.requireSelection();
154
155 registerRoutes();
156 Router.init('pageContent');
src/package.json new
+1
@@ -0,0 +1 @@
1 +{"type":"module"}
src/styles/main.css
+3 -3
@@ -250,10 +250,10 @@ a { color: inherit; }
250 .btn-success { background: var(--success); }
251 .btn-warning { background: var(--warning); }
252
253 -/* Toast */
253 +/* Notifications must render above invoice and other modal backdrops. */
254 .toast-container {
255 - position: fixed; top: 80px; left: 20px;
256 - z-index: 9999;
255 + position: fixed; top: 20px; left: 20px;
256 + z-index: 2147483647;
257 display: flex; flex-direction: column;
258 gap: 10px; max-width: 380px;
259 }
src/utils/InvoicePrint.js
+24 -31
@@ -5,6 +5,7 @@
5 import { InvoiceController } from '../controllers/InvoiceController.js';
6 import { ContactController } from '../controllers/ContactController.js';
7 import { StorageService } from '../core/StorageService.js';
8 +import { DataScope } from '../core/DataScope.js';
9 import { Auth } from '../core/Auth.js';
10 import { Modal } from '../core/Modal.js';
11 import { Toast } from '../core/Toast.js';
@@ -179,15 +180,15 @@ class InvoicePrintImpl {
180 const inv = await InvoiceController.get(invoiceId);
181 if (!inv) throw new Error('فاکتور یافت نشد');
182
182 - const user = Auth.current();
183 - const companies = await StorageService.getByOwner('companies', user.id);
184 - const seller = companies[0] || {
183 + const companyId = await DataScope.companyId();
184 + const seller = await StorageService.get('companies', companyId) || {
185 name: 'شرکت شما',
186 phone: '', address: '', national_id: '', economic_code: '',
187 reg_number: '', postal_code: '', footer: ''
188 };
189
190 - const contact = inv.contactId ? await StorageService.get('contacts', inv.contactId) : {};
190 + const matchedContact = inv.contactId ? await StorageService.get('contacts', inv.contactId) : null;
191 + const contact = matchedContact?.companyId === companyId ? matchedContact : {};
192
193 let balance = 0;
194 if (this.settings.showBalance !== 'none' && inv.contactId) {
@@ -245,26 +246,15 @@ class InvoicePrintImpl {
246
247 return `
248 <div class="print-doc" dir="rtl" style="direction:rtl;text-align:right;font-family:'Vazirmatn FD',Tahoma,sans-serif;color:#000;padding:6mm">
248 - <table style="width:100%;border-collapse:collapse;border:2px solid ${color};margin-bottom:4px">
249 - <tr>
250 - <td style="width:28%;border:1px solid ${color};padding:6px;font-size:11px;vertical-align:middle;text-align:center">
251 - <div style="font-weight:bold;font-size:7.5px;color:${color}">فینورا پرو</div>
252 - </td>
253 - <td style="width:44%;border:1px solid ${color};padding:8px;text-align:center;vertical-align:middle;background:#f0fdfa">
254 - <h1 style="font-size:16px;margin:0;font-weight:bold;color:${color}">${headerTitle}</h1>
255 - </td>
256 - <td style="width:28%;border:1px solid ${color};padding:6px;font-size:10.5px;vertical-align:middle">
257 - <div style="display:flex;align-items:center;line-height:1.7;gap:4px">
258 - <span style="display:inline-block;min-width:72px;text-align:left;white-space:nowrap">شماره سریال:</span>
259 - <strong style="color:#b91c1c">${Formatters.toPersianDigits(inv.number)}</strong>
260 - </div>
261 - <div style="display:flex;align-items:center;line-height:1.7;gap:4px">
262 - <span style="display:inline-block;min-width:72px;text-align:left;white-space:nowrap">تاریخ صدور:</span>
263 - <strong>${Formatters.toPersianDigits(inv.date)}</strong>
264 - </div>
265 - </td>
266 - </tr>
267 - </table>
249 + <div style="position:relative;min-height:65px;margin-bottom:8px;display:flex;align-items:flex-start;justify-content:center;padding:10px 0 6px">
250 + <h1 style="font-size:17px;margin:0;font-weight:bold;color:#111;text-align:center">${headerTitle}</h1>
251 + <div style="position:absolute;left:0;top:4px;direction:rtl;text-align:right;font-size:10.5px;line-height:2;white-space:nowrap">
252 + <div style="display:grid;grid-template-columns:86px auto;column-gap:5px;align-items:baseline">
253 + <span>شماره سریال:</span><strong>${Formatters.toPersianDigits(inv.number)}</strong>
254 + <span>تاریخ صدور:</span><strong>${Formatters.toPersianDigits(inv.date)}</strong>
255 + </div>
256 + </div>
257 + </div>
258
259 <table style="width:100%;border-collapse:collapse;border:1.5px solid ${color};font-size:10.5px;margin-bottom:4px">
260 <tr style="background:#f8fafc;font-weight:bold">
@@ -545,7 +535,7 @@ class InvoicePrintImpl {
535 ${seller.footer ? this._esc(seller.footer) : 'از خرید شما سپاسگزاریم'}
536 </div>
537 <div style="text-align:center;font-size:9px;margin-top:4px;color:#64748b">
548 - فینورا پرو
538 + Factor-easyPro
539 </div>
540 </div>
541 `;
@@ -565,7 +555,7 @@ class InvoicePrintImpl {
555
556 let pageCss = 'A4 portrait';
557 if (this.settings.template === 'thermal') {
568 - pageCss = '80mm auto';
558 + pageCss = '80mm 297mm';
559 } else {
560 const size = this.settings.paperSize === 'A5' ? 'A5' : 'A4';
561 pageCss = size + ' ' + (this.settings.orientation || 'portrait');
@@ -579,7 +569,7 @@ class InvoicePrintImpl {
569 <head>
570 <meta charset="UTF-8" />
571 <title>چاپ فاکتور</title>
582 - <link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/rastikerdar/vazirmatn@v33.003/misc/Farsi-Digits/Vazirmatn-FD-font-face.css" />
572 + <!-- Offline-first printing: use bundled/system fonts, no external network dependency. -->
573 <style>
574 @page {
575 size: ${pageCss};
@@ -597,6 +587,9 @@ class InvoicePrintImpl {
587 body { padding: 4px; }
588 table { direction: rtl; }
589 td, th { direction: rtl; }
590 + thead { display: table-header-group; }
591 + tfoot { display: table-footer-group; }
592 + tr, td, th { break-inside: avoid; page-break-inside: avoid; }
593 .print-doc { direction: rtl !important; }
594
595 @media print {
@@ -614,8 +607,8 @@ class InvoicePrintImpl {
607 `);
608 doc.close();
609
617 - // صبر می‌کنیم تا فونت و استایل‌ها لود بشن، بعد پرینت می‌گیریم
618 - setTimeout(() => {
610 + // Print only after iframe fonts/layout settle; never require external font CDNs.
611 + Promise.resolve(doc.fonts?.ready).catch(() => {}).then(() => setTimeout(() => {
612 try {
613 iframe.contentWindow.focus();
614 iframe.contentWindow.print();
@@ -626,8 +619,8 @@ class InvoicePrintImpl {
619 // پاک کردن iframe بعد از بسته شدن پنجره چاپ
620 setTimeout(() => {
621 if (iframe.parentNode) iframe.parentNode.removeChild(iframe);
629 - }, 2000);
630 - }, 800);
622 + }, 5000);
623 + }, 200));
624 }
625 _paymentLabel(method) {
626 const labels = { cash: 'نقدی ☑', credit: 'نسیه/چک ☑', partial: 'پرداخت جزئی ☑' };
src/views/AccountingView.js new
+564
@@ -0,0 +1,564 @@
1 +// Factor-easyPro V2 / Phase 1: isolated accounting workbench.
2 +// Existing invoice, inventory and treasury workflows are deliberately untouched.
3 +import { AccountingService as Ledger } from '../core/AccountingService.js';
4 +import { RetailPostingService as Retail } from '../core/RetailPostingService.js';
5 +import { DataScope } from '../core/DataScope.js';
6 +import { Auth } from '../core/Auth.js';
7 +import { Modal } from '../core/Modal.js';
8 +import { Toast } from '../core/Toast.js';
9 +import { Formatters } from '../utils/Formatters.js';
10 +import { Jalali } from '../utils/Jalali.js';
11 +import { ACCOUNT_LEVELS, ACCOUNT_TYPES } from '../core/AccountingCore.mjs';
12 +
13 +const levelNames = { group: 'گروه', general: 'کل', subsidiary: 'معین', detail: 'تفصیلی' };
14 +const typeNames = { asset: 'دارایی', liability: 'بدهی', equity: 'حقوق مالکانه', revenue: 'درآمد', expense: 'هزینه' };
15 +const html = value => String(value ?? '').replace(/[&<>"']/g, c => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]));
16 +const digits = input => String(input ?? '').replace(/[۰-۹]/g, c => String(c.charCodeAt(0) - 1776)).replace(/[٠-٩]/g, c => String(c.charCodeAt(0) - 1632));
17 +const rial = input => {
18 + const raw = digits(input).replace(/[,_،\s]/g, '');
19 + if (!raw) return 0;
20 + if (!/^\d+$/.test(raw) || !Number.isSafeInteger(Number(raw))) throw new Error('مبلغ باید عدد صحیح و غیرمنفی به ریال باشد');
21 + return Number(raw);
22 +};
23 +const safeDate = () => Jalali.today();
24 +
25 +class AccountingViewImpl {
26 + constructor() {
27 + this.tab = 'journals';
28 + this.accounts = [];
29 + this.periods = [];
30 + this.journals = [];
31 + this.busy = false;
32 + }
33 + async reload() {
34 + [this.accounts, this.periods, this.journals] = await Promise.all([
35 + Ledger.listAccounts(), Ledger.listPeriods(), Ledger.listJournals()
36 + ]);
37 + }
38 + async render() {
39 + await this.reload();
40 + const tabs = [
41 + ['journals', 'اسناد حسابداری'],
42 + ['accounts', 'کدینگ حساب‌ها'],
43 + ['periods', 'دوره‌های مالی'],
44 + ['trial', 'تراز آزمایشی'],
45 + ['reports', 'گزارش‌های مالی'],
46 + ['integration', 'عملیات یکپارچه و انبار']
47 + ];
48 + return `<div class="page-title"><h2>حسابداری دوبل</h2>
49 + <p>گردش‌های مالی و موجودی برای شرکت‌های فعال‌شده به‌صورت اتمیک ثبت می‌شوند؛ داده‌های قدیمی بدون مهاجرت تأییدشده تغییر نمی‌کنند.</p></div>
50 + <div class="toolbar" style="gap:8px;flex-wrap:wrap">
51 + ${tabs.map(([id, label]) => `<button class="btn ${this.tab === id ? '' : 'btn-secondary'}" onclick="window.AccountingView.switchTab('${id}')">${label}</button>`).join('')}
52 + </div>
53 + <div id="accountingWorkbench">${await this.body()}</div>`;
54 + }
55 + onMount() { window.AccountingView = this; }
56 + async switchTab(tab) {
57 + this.tab = tab;
58 + await this.refresh();
59 + }
60 + async refresh() {
61 + try {
62 + await this.reload();
63 + const host = document.getElementById('accountingWorkbench');
64 + if (host) host.innerHTML = await this.body();
65 + } catch (error) {
66 + Toast.error('خطای حسابداری: ' + error.message);
67 + }
68 + }
69 + async body() {
70 + switch (this.tab) {
71 + case 'accounts': return this.renderAccounts();
72 + case 'periods': return this.renderPeriods();
73 + case 'trial': return this.renderTrial();
74 + case 'reports': return this.renderReports();
75 + case 'integration': return this.renderIntegration();
76 + default: return this.renderJournals();
77 + }
78 + }
79 + openPeriods() {
80 + this.tab = 'periods';
81 + return this.refresh();
82 + }
83 + renderPeriods() {
84 + const rows = this.periods.map(p => `<tr>
85 + <td><strong>${html(p.name)}</strong></td>
86 + <td>${html(p.startDate)}</td><td>${html(p.endDate)}</td>
87 + <td><span class="badge ${p.closed ? 'badge-muted' : 'badge-success'}">${p.closed ? 'بسته' : 'باز'}</span></td>
88 + <td>${p.closed ? '—' : `<button class="btn btn-secondary" onclick="window.AccountingView.closePeriod('${html(p.id)}')">بستن دوره</button>`}</td></tr>`).join('');
89 + return `<div class="card">
90 + <div class="toolbar"><strong>دوره‌های مالی</strong>
91 + <button class="btn" onclick="window.AccountingView.openPeriodModal()">افزودن دوره مالی</button></div>
92 + <div class="table-wrap"><table><thead><tr><th>نام دوره</th><th>شروع</th><th>پایان</th><th>وضعیت</th><th>عملیات</th></tr></thead>
93 + <tbody>${rows || '<tr><td colspan="5">هنوز دوره مالی تعریف نشده است.</td></tr>'}</tbody></table></div></div>`;
94 + }
95 + renderAccounts() {
96 + const rows = this.accounts.slice().sort((a, b) => String(a.code).localeCompare(String(b.code), 'fa')).map(a => `<tr>
97 + <td>${html(a.code)}</td><td>${html(a.name)}</td><td>${levelNames[a.level] || html(a.level)}</td>
98 + <td>${typeNames[a.type] || html(a.type)}</td><td>${html(a.parentCode || '—')}</td>
99 + <td>${a.active === false ? 'غیرفعال' : 'فعال'}</td></tr>`).join('');
100 + return `<div class="card">
101 + <div class="toolbar"><strong>سرفصل‌های حسابداری</strong>
102 + <button class="btn btn-secondary" onclick="window.AccountingView.seedChart()">ایجاد کدینگ پیشنهادی</button>
103 + <button class="btn" onclick="window.AccountingView.openAccountModal()">افزودن حساب</button></div>
104 + <p style="font-size:12px;color:var(--text-muted);margin:10px 0">کدینگ پیشنهادی مختص این پروژه است و رونوشتی از کدینگ اختصاصی هلو نیست. حساب دارای زیرمجموعه قابل انتخاب در سند نیست.</p>
105 + <div class="table-wrap"><table><thead><tr><th>کد</th><th>نام</th><th>سطح</th><th>ماهیت</th><th>والد</th><th>وضعیت</th></tr></thead>
106 + <tbody>${rows || '<tr><td colspan="6">حسابی تعریف نشده است.</td></tr>'}</tbody></table></div></div>`;
107 + }
108 + renderJournals() {
109 + const rows = this.journals.slice().reverse().map(j => `<tr>
110 + <td>${html(j.date)}</td><td>${html(j.description || '—')}</td>
111 + <td>${this.periods.find(p => p.id === j.periodId)?.name ? html(this.periods.find(p => p.id === j.periodId).name) : '—'}</td>
112 + <td>${Formatters.number(j.debit || 0)}</td><td>${Formatters.number(j.credit || 0)}</td>
113 + <td><span class="badge ${j.status === 'posted' ? 'badge-success' : 'badge-warning'}">${j.status === 'posted' ? 'قطعی' : 'پیش‌نویس'}</span>${j.reversedById ? ' / برگشت‌خورده' : ''}</td>
114 + <td style="white-space:nowrap">
115 + <button class="btn btn-secondary" onclick="window.AccountingView.showJournal('${html(j.id)}')">مشاهده</button>
116 + ${j.status === 'draft' ? `<button class="btn btn-secondary" onclick="window.AccountingView.openJournalModal('${html(j.id)}')">ویرایش</button>
117 + <button class="btn" onclick="window.AccountingView.postDraft('${html(j.id)}')">قطعی</button>
118 + <button class="btn btn-secondary" onclick="window.AccountingView.deleteDraft('${html(j.id)}')">حذف پیش‌نویس</button>` : ''}
119 + ${j.status === 'posted' && !j.reversedById && !j.reversalOfId
120 + ? `<button class="btn btn-secondary" onclick="window.AccountingView.openReversal('${html(j.id)}')">برگشت</button>` : ''}
121 + </td></tr>`).join('');
122 + return `<div class="card">
123 + <div class="toolbar"><strong>اسناد حسابداری مستقل</strong>
124 + <button class="btn" onclick="window.AccountingView.openJournalModal()">ایجاد سند دستی</button></div>
125 + <p style="font-size:12px;color:var(--text-muted);margin:10px 0">اسناد این قسمت فعلاً مستقل از فاکتورها هستند. برای ثبت سند حداقل یک دوره باز و حساب قابل ثبت لازم است.</p>
126 + <div class="table-wrap"><table><thead><tr>
127 + <th>تاریخ</th><th>شرح</th><th>دوره</th><th>بدهکار (ریال)</th><th>بستانکار (ریال)</th><th>وضعیت</th><th>عملیات</th>
128 + </tr></thead><tbody>${rows || '<tr><td colspan="7">سندی ثبت نشده است.</td></tr>'}</tbody></table></div></div>`;
129 + }
130 + async renderTrial() {
131 + if (!this.periods.length) return '<div class="card">ابتدا دوره مالی تعریف کنید.</div>';
132 + const periodId = this.selectedTrialPeriod && this.periods.some(p => p.id === this.selectedTrialPeriod)
133 + ? this.selectedTrialPeriod : this.periods[0].id;
134 + this.selectedTrialPeriod = periodId;
135 + const result = await Ledger.trialBalance({ periodId });
136 + const opts = this.periods.map(p => `<option value="${html(p.id)}" ${p.id === periodId ? 'selected' : ''}>${html(p.name)}</option>`).join('');
137 + const rows = result.rows.map(r => `<tr><td>${html(r.code)}</td><td>${html(r.name)}</td>
138 + <td>${Formatters.number(r.debit)}</td><td>${Formatters.number(r.credit)}</td><td>${Formatters.number(r.balance)}</td></tr>`).join('');
139 + return `<div class="card"><div class="toolbar"><strong>تراز آزمایشی اسناد قطعی</strong>
140 + <select class="form-control" style="max-width:210px" onchange="window.AccountingView.setTrialPeriod(this.value)">${opts}</select></div>
141 + <div class="table-wrap"><table><thead><tr><th>کد</th><th>حساب</th><th>گردش بدهکار</th><th>گردش بستانکار</th><th>مانده بدهکار - بستانکار</th></tr></thead>
142 + <tbody>${rows || '<tr><td colspan="5">گردشی وجود ندارد.</td></tr>'}</tbody>
143 + <tfoot><tr><th colspan="2">جمع</th><th>${Formatters.number(result.totals.debit)}</th><th>${Formatters.number(result.totals.credit)}</th><th>۰</th></tr></tfoot>
144 + </table></div></div>`;
145 + }
146 + async renderReports() {
147 + const r = await Ledger.financialReports();
148 + const rows = r.trial.map(x => `<tr><td>${html(x.code)}</td><td>${html(x.name)}</td><td>${Formatters.number(x.debit)}</td><td>${Formatters.number(x.credit)}</td><td>${Formatters.number(x.balance)}</td></tr>`).join('');
149 + const detail = r.detail.map(x => `<tr><td>${html(x.date)}</td><td>${html(x.description)}</td><td>${html(x.code+' — '+x.name)}</td><td>${Formatters.number(x.debit)}</td><td>${Formatters.number(x.credit)}</td></tr>`).join('');
150 + return `<div class="card"><div class="toolbar"><strong>گزارش‌های مبتنی بر اسناد قطعی دفتر کل</strong><button class="btn btn-secondary" onclick="window.AccountingView.exportReports()">خروجی CSV</button></div>
151 + <p>درآمد: ${Formatters.number(r.profitLoss.revenue)} ریال | هزینه و بهای تمام‌شده: ${Formatters.number(r.profitLoss.expenses)} ریال | سود خالص: ${Formatters.number(r.profitLoss.netProfit)} ریال</p>
152 + <p>دارایی: ${Formatters.number(r.balanceSheet.assets)} | بدهی: ${Formatters.number(r.balanceSheet.liabilities)} | حقوق مالکانه با سود جاری: ${Formatters.number(r.balanceSheet.equityWithProfit)} | اختلاف ترازنامه: ${Formatters.number(r.balanceSheet.difference)}</p>
153 + <h3>تراز حساب‌ها</h3><div class="table-wrap"><table><thead><tr><th>کد</th><th>حساب</th><th>بدهکار</th><th>بستانکار</th><th>مانده</th></tr></thead><tbody>${rows||'<tr><td colspan="5">بدون گردش</td></tr>'}</tbody></table></div>
154 + <h3>روزنامه و ریز دفتر کل</h3><div class="table-wrap"><table><thead><tr><th>تاریخ</th><th>شرح</th><th>حساب</th><th>بدهکار</th><th>بستانکار</th></tr></thead><tbody>${detail||'<tr><td colspan="5">بدون گردش</td></tr>'}</tbody></table></div></div>`;
155 + }
156 + async exportReports() {
157 + try {
158 + const r = await Ledger.financialReports();
159 + const esc = v => '"'+String(v??'').replace(/"/g,'""')+'"';
160 + const csv = [['date','description','account_code','account_name','debit_irr','credit_irr'],...r.detail.map(x=>[x.date,x.description,x.code,x.name,x.debit,x.credit])].map(a=>a.map(esc).join(',')).join('\r\n');
161 + const blob = new Blob(['\ufeff',csv],{type:'text/csv;charset=utf-8'});
162 + const url = URL.createObjectURL(blob);
163 + const a=document.createElement('a');a.href=url;a.download='factor-easypro-ledger.csv';document.body.appendChild(a);a.click();a.remove();
164 + setTimeout(()=>URL.revokeObjectURL(url),3000);
165 + } catch(error) { Toast.error(error.message); }
166 + }
167 + setTrialPeriod(id) { this.selectedTrialPeriod = id; return this.refresh(); }
168 + openPeriodModal() {
169 + const body = `<div class="form-group"><label class="form-label">نام دوره</label>
170 + <input id="acPeriodName" class="form-control" value="سال مالی جدید"></div>
171 + <div class="form-row"><div class="form-group"><label class="form-label">از تاریخ شمسی</label>
172 + <input id="acPeriodStart" class="form-control" placeholder="1405/01/01"></div>
173 + <div class="form-group"><label class="form-label">تا تاریخ شمسی</label>
174 + <input id="acPeriodEnd" class="form-control" placeholder="1405/12/29"></div></div>`;
175 + const footer = '<button class="btn btn-secondary" onclick="FINORA.Modal.close()">انصراف</button><button class="btn" onclick="window.AccountingView.savePeriod()">ذخیره دوره</button>';
176 + Modal.open({ title: 'دوره مالی جدید', body, footer, size: 'sm', closeOnBackdrop: false });
177 + }
178 + async savePeriod() {
179 + if (this.busy) return;
180 + this.busy = true;
181 + try {
182 + await Ledger.createPeriod({
183 + name: document.getElementById('acPeriodName').value,
184 + startDate: digits(document.getElementById('acPeriodStart').value).trim(),
185 + endDate: digits(document.getElementById('acPeriodEnd').value).trim()
186 + });
187 + Modal.close();
188 + Toast.success('دوره مالی ایجاد شد');
189 + await this.refresh();
190 + } catch (error) { Toast.error(error.message); }
191 + finally { this.busy = false; }
192 + }
193 + closePeriod(id) {
194 + Modal.confirm({ title: 'بستن دوره مالی', danger: true,
195 + message: 'بعد از بستن، ثبت یا برگشت سند در این دوره مجاز نیست. ابتدا پشتیبان تهیه کرده و پیش‌نویس‌ها را تعیین تکلیف کنید.',
196 + confirmText: 'بستن قطعی دوره', onConfirm: async () => {
197 + try {
198 + await Ledger.closePeriod(id);
199 + Toast.success('دوره مالی بسته شد');
200 + await this.refresh();
201 + } catch (error) { Toast.error(error.message); }
202 + }
203 + });
204 + }
205 + seedChart() {
206 + Modal.confirm({ title: 'ایجاد کدینگ پیشنهادی', message:
207 + 'سرفصل‌های پایه نمونه به شرکت فعال اضافه می‌شوند؛ حساب‌های قبلی حذف یا تغییر نمی‌کنند. ادامه می‌دهید؟',
208 + onConfirm: async () => {
209 + try {
210 + const r = await Ledger.seedDefaultChart();
211 + Toast.success(`${r.added} سرفصل جدید ایجاد شد`);
212 + await this.refresh();
213 + } catch (error) { Toast.error(error.message); }
214 + }
215 + });
216 + }
217 + openAccountModal() {
218 + const parents = this.accounts.map(a => `<option value="${html(a.code)}">${html(a.code + ' — ' + a.name)}</option>`).join('');
219 + const levelOptions = ACCOUNT_LEVELS.map(l => `<option value="${l}">${levelNames[l]}</option>`).join('');
220 + const typeOptions = ACCOUNT_TYPES.map(t => `<option value="${t}">${typeNames[t]}</option>`).join('');
221 + const body = `<div class="form-row"><div class="form-group"><label class="form-label">کد حساب</label>
222 + <input class="form-control" id="acCode" inputmode="text"></div>
223 + <div class="form-group"><label class="form-label">عنوان</label>
224 + <input class="form-control" id="acName"></div></div>
225 + <div class="form-row"><div class="form-group"><label class="form-label">سطح</label>
226 + <select class="form-control" id="acLevel" onchange="window.AccountingView.toggleParent()">${levelOptions}</select></div>
227 + <div class="form-group"><label class="form-label">ماهیت</label>
228 + <select class="form-control" id="acType">${typeOptions}</select></div></div>
229 + <div class="form-group" id="acParentGroup" style="display:none"><label class="form-label">کد حساب والد</label>
230 + <select class="form-control" id="acParent"><option value="">انتخاب والد</option>${parents}</select></div>`;
231 + const footer = '<button class="btn btn-secondary" onclick="FINORA.Modal.close()">انصراف</button><button class="btn" onclick="window.AccountingView.saveAccount()">ثبت حساب</button>';
232 + Modal.open({ title: 'حساب جدید', body, footer, size: 'sm', closeOnBackdrop: false });
233 + }
234 + toggleParent() {
235 + document.getElementById('acParentGroup').style.display = document.getElementById('acLevel').value === 'group' ? 'none' : '';
236 + }
237 + async saveAccount() {
238 + if (this.busy) return;
239 + this.busy = true;
240 + try {
241 + await Ledger.addAccount({
242 + code: digits(document.getElementById('acCode').value).trim(),
243 + name: document.getElementById('acName').value.trim(),
244 + level: document.getElementById('acLevel').value,
245 + type: document.getElementById('acType').value,
246 + parentCode: document.getElementById('acLevel').value === 'group' ? null : document.getElementById('acParent').value
247 + });
248 + Modal.close();
249 + Toast.success('حساب اضافه شد');
250 + await this.refresh();
251 + } catch (error) { Toast.error(error.message); }
252 + finally { this.busy = false; }
253 + }
254 + accountOptions(selected = '') {
255 + const postable = this.accounts.filter(a => a.level !== 'group' && a.active !== false && a.postable !== false &&
256 + !this.accounts.some(child => child.parentCode === a.code));
257 + return '<option value="">انتخاب حساب</option>' + postable.map(a => `<option value="${html(a.id)}" ${a.id === selected ? 'selected' : ''}>${html(a.code + ' — ' + a.name)}</option>`).join('');
258 + }
259 + journalRow(line = {}) {
260 + return `<tr class="ac-journal-line">
261 + <td><select class="form-control ac-line-account">${this.accountOptions(line.accountId)}</select></td>
262 + <td><input class="form-control ac-line-debit" inputmode="text" placeholder="۰" value="${html(line.debit ?? '0')}"></td>
263 + <td><input class="form-control ac-line-credit" inputmode="text" placeholder="۰" value="${html(line.credit ?? '0')}"></td>
264 + <td><input class="form-control ac-line-note" value="${html(line.description || '')}"></td>
265 + <td><button class="btn btn-secondary" onclick="this.closest('tr').remove()">حذف</button></td>
266 + </tr>`;
267 + }
268 + async openJournalModal(id = null) {
269 + if (!this.periods.some(p => !p.closed)) {
270 + Toast.warning('ابتدا یک دوره مالی باز تعریف کنید');
271 + return;
272 + }
273 + if (!this.accounts.some(a => a.level !== 'group')) {
274 + Toast.warning('ابتدا کدینگ حسابداری را تعریف کنید');
275 + return;
276 + }
277 + try {
278 + const draft = id ? await Ledger.getJournal(id) : null;
279 + if (draft && draft.status !== 'draft') throw new Error('تنها اسناد پیش‌نویس قابل ویرایش‌اند');
280 + const periods = this.periods.filter(p => !p.closed);
281 + const selected = draft?.periodId || periods.find(p => safeDate() >= p.startDate && safeDate() <= p.endDate)?.id || periods[0].id;
282 + const options = periods.map(p => `<option value="${html(p.id)}" ${p.id === selected ? 'selected' : ''}>${html(p.name)}</option>`).join('');
283 + const body = `<input id="acDraftId" type="hidden" value="${html(id || '')}">
284 + <div class="form-row"><div class="form-group"><label class="form-label">دوره مالی</label>
285 + <select id="acJournalPeriod" class="form-control">${options}</select></div>
286 + <div class="form-group"><label class="form-label">تاریخ شمسی</label>
287 + <input id="acJournalDate" class="form-control" value="${html(draft?.date || safeDate())}"></div></div>
288 + <div class="form-group"><label class="form-label">شرح سند</label>
289 + <input id="acJournalDescription" class="form-control" value="${html(draft?.description || '')}"></div>
290 + <div class="table-wrap"><table><thead><tr><th>حساب</th><th>بدهکار (ریال)</th>
291 + <th>بستانکار (ریال)</th><th>شرح ردیف</th><th>عملیات</th></tr></thead>
292 + <tbody id="acJournalLines">${(draft?.lines?.length ? draft.lines : [{}, {}]).map(l => this.journalRow(l)).join('')}</tbody>
293 + </table></div><button class="btn btn-secondary" style="margin-top:10px" onclick="window.AccountingView.addJournalRow()">افزودن ردیف</button>
294 + <p style="font-size:12px;color:var(--text-muted);margin-top:10px">مبالغ باید عدد صحیح به ریال باشند. پیش‌نویس می‌تواند نامتوازن باشد؛ سند قطعی باید تراز شود.</p>`;
295 + const footer = `<button class="btn btn-secondary" onclick="FINORA.Modal.close()">انصراف</button>
296 + <button class="btn btn-secondary" onclick="window.AccountingView.saveJournal('draft')">ذخیره پیش‌نویس</button>
297 + <button class="btn" onclick="window.AccountingView.saveJournal('posted')">ثبت قطعی</button>`;
298 + Modal.open({ title: id ? 'ویرایش پیش‌نویس' : 'سند حسابداری دستی', body, footer, size: 'lg', closeOnBackdrop: false });
299 + } catch (error) { Toast.error(error.message); }
300 + }
301 + addJournalRow() {
302 + document.getElementById('acJournalLines')?.insertAdjacentHTML('beforeend', this.journalRow());
303 + }
304 + readJournalForm() {
305 + const lines = [...document.querySelectorAll('#acJournalLines .ac-journal-line')].map(row => ({
306 + accountId: row.querySelector('.ac-line-account').value,
307 + debit: rial(row.querySelector('.ac-line-debit').value),
308 + credit: rial(row.querySelector('.ac-line-credit').value),
309 + description: row.querySelector('.ac-line-note').value.trim()
310 + }));
311 + return {
312 + periodId: document.getElementById('acJournalPeriod').value,
313 + date: digits(document.getElementById('acJournalDate').value).trim(),
314 + description: document.getElementById('acJournalDescription').value.trim(),
315 + lines
316 + };
317 + }
318 + async saveJournal(mode) {
319 + if (this.busy) return;
320 + this.busy = true;
321 + try {
322 + const draftId = document.getElementById('acDraftId').value;
323 + const data = this.readJournalForm();
324 + if (draftId) {
325 + await Ledger.updateDraftJournal(draftId, data, { post: mode === 'posted' });
326 + } else if (mode === 'posted') {
327 + await Ledger.postJournal(data);
328 + } else {
329 + await Ledger.saveDraftJournal(data);
330 + }
331 + Modal.close();
332 + Toast.success(mode === 'posted' ? 'سند حسابداری قطعی شد' : 'پیش‌نویس ذخیره شد');
333 + await this.refresh();
334 + } catch (error) { Toast.error('خطای ثبت سند: ' + error.message); }
335 + finally { this.busy = false; }
336 + }
337 + deleteDraft(id) {
338 + Modal.confirm({ title: 'حذف پیش‌نویس', danger: true,
339 + message: 'فقط سند پیش‌نویس و ردیف‌های آن حذف می‌شوند. سند قطعی هرگز از این مسیر حذف نخواهد شد.',
340 + confirmText: 'حذف پیش‌نویس', onConfirm: async () => {
341 + try {
342 + await Ledger.discardDraftJournal(id);
343 + Toast.success('پیش‌نویس حذف شد');
344 + await this.refresh();
345 + } catch (error) { Toast.error(error.message); }
346 + }
347 + });
348 + }
349 + async postDraft(id) {
350 + Modal.confirm({ title: 'قطعی‌سازی سند', message: 'پس از قطعی شدن امکان ویرایش مستقیم وجود ندارد. ادامه می‌دهید؟',
351 + confirmText: 'ثبت قطعی', onConfirm: async () => {
352 + try {
353 + await Ledger.postDraftJournal(id);
354 + Toast.success('سند قطعی شد');
355 + await this.refresh();
356 + } catch (error) { Toast.error(error.message); }
357 + }
358 + });
359 + }
360 + async showJournal(id) {
361 + try {
362 + const j = await Ledger.getJournal(id);
363 + const lines = j.lines.map(l => {
364 + const a = this.accounts.find(x => x.id === l.accountId);
365 + return `<tr><td>${html(a ? a.code + ' — ' + a.name : l.accountId)}</td>
366 + <td>${Formatters.number(l.debit)}</td><td>${Formatters.number(l.credit)}</td><td>${html(l.description)}</td></tr>`;
367 + }).join('');
368 + Modal.open({ title: 'جزئیات سند حسابداری', size: 'lg',
369 + body: `<p style="margin-bottom:10px">تاریخ: ${html(j.date)} | وضعیت: ${html(j.status)} | شرح: ${html(j.description)}</p>
370 + <div class="table-wrap"><table><thead><tr><th>حساب</th><th>بدهکار</th><th>بستانکار</th><th>شرح</th></tr></thead>
371 + <tbody>${lines}</tbody><tfoot><tr><th>جمع</th><th>${Formatters.number(j.debit)}</th><th>${Formatters.number(j.credit)}</th><th></th></tr></tfoot></table></div>`,
372 + footer: '<button class="btn btn-secondary" onclick="FINORA.Modal.close()">بستن</button>'
373 + });
374 + } catch (error) { Toast.error(error.message); }
375 + }
376 + async renderIntegration() {
377 + const active = await Retail.isEnabled();
378 + if (!active) return `<div class="card">
379 + <h3>اتصال یکپارچه خرید، فروش و حسابداری</h3>
380 + <p style="line-height:2;margin:12px 0">فعال‌سازی فقط برای شرکت بدون گردش مالی قبلی مجاز است. اگر شرکت سابقه فاکتور، انبار یا خزانه دارد، ابتدا مانده افتتاحیه و مهاجرت آن باید تأیید شود. داده‌های قبلی پاک یا تبدیل خودکار نمی‌شوند.</p>
381 + <p style="line-height:2;margin-bottom:14px">پیش از فعال‌سازی، دوره مالی باز بسازید و دکمه «ایجاد کدینگ پیشنهادی» را از تب کدینگ اجرا کنید.</p>
382 + <button class="btn" onclick="window.AccountingView.activateRetail()">فعال‌سازی حسابداری یکپارچه برای شرکت خالی</button></div>`;
383 + const [warehouses, balances, stocktakes, products] = await Promise.all([
384 + Retail.warehouses(),Retail.stockBalances(),Retail.getStocktakes(),DataScope.list('products')
385 + ]);
386 + const names = Object.fromEntries(products.map(p=>[p.id,p.name]));
387 + const warehouseNames = Object.fromEntries(warehouses.map(w=>[w.id,w.name]));
388 + const stockRows = balances.map(b=>`<tr><td>${html(names[b.productId]||b.productId)}</td>
389 + <td>${html(warehouseNames[b.warehouseId]||b.warehouseId)}</td>
390 + <td>${Formatters.number(b.quantityUnits/1000)}</td><td>${Formatters.number(b.value)} ریال</td></tr>`).join('');
391 + const takeRows=stocktakes.map(s=>`<tr><td>${html(warehouseNames[s.warehouseId]||s.warehouseId)}</td>
392 + <td>${html(s.date)}</td><td>${s.status==='draft'?'در انتظار شمارش':'قطعی'}</td>
393 + <td><button class="btn btn-secondary" onclick="window.AccountingView.openStocktake('${html(s.id)}')">مشاهده و شمارش</button></td></tr>`).join('');
394 + return `<div class="card"><div class="toolbar"><strong>حسابداری یکپارچه فعال است</strong>
395 + <button class="btn" onclick="window.AccountingView.openWarehouse()">انبار جدید</button>
396 + <button class="btn btn-secondary" onclick="window.AccountingView.openTransfer()">انتقال کالا</button>
397 + <button class="btn" onclick="window.AccountingView.openStocktakeCreate()">انبارگردانی جدید</button></div>
398 + <p style="margin:10px 0">فاکتور جدید، دریافت و پرداخت، هزینه و چک به دفتر حسابداری متصل‌اند. تغییر اسناد قطعی فقط با فرآیند اصلاح و برگشت مجاز است.</p>
399 + <h4>موجودی و ارزش انبار</h4><div class="table-wrap"><table><thead><tr><th>کالا</th><th>انبار</th><th>مقدار</th><th>ارزش (ریال)</th></tr></thead>
400 + <tbody>${stockRows||'<tr><td colspan="4">موجودی ثبت نشده است.</td></tr>'}</tbody></table></div>
401 + <h4 style="margin-top:16px">جلسات انبارگردانی</h4><div class="table-wrap"><table><thead><tr><th>انبار</th><th>تاریخ</th><th>وضعیت</th><th>عملیات</th></tr></thead>
402 + <tbody>${takeRows||'<tr><td colspan="4">جلسه‌ای وجود ندارد.</td></tr>'}</tbody></table></div></div>`;
403 + }
404 + activateRetail() {
405 + Modal.confirm({title:'فعال‌سازی ثبت مالی یکپارچه',danger:true,
406 + message:'این کار گردش جدید فروش، خرید، خزانه و انبار را به حسابداری دوبل متصل می‌کند. شرکت دارای گردش قبلی بدون مهاجرت تأییدشده فعال نمی‌شود. ابتدا نسخه پشتیبان بگیرید.',
407 + confirmText:'فعال‌سازی برای شرکت خالی',
408 + onConfirm:async()=>{
409 + try{await Retail.activate();Toast.success('ثبت یکپارچه فعال شد');await this.refresh()}
410 + catch(e){Toast.error(e.message)}
411 + }});
412 + }
413 + openWarehouse() {
414 + Modal.open({title:'ایجاد انبار',size:'sm',closeOnBackdrop:false,
415 + body:'<label class="form-label">نام انبار</label><input id="acWhName" class="form-control">',
416 + footer:'<button class="btn btn-secondary" onclick="FINORA.Modal.close()">انصراف</button><button class="btn" onclick="window.AccountingView.saveWarehouse()">ثبت انبار</button>'});
417 + }
418 + async saveWarehouse() {
419 + if(this.busy)return;this.busy=true;
420 + try{await Retail.addWarehouse(document.getElementById('acWhName').value);
421 + Modal.close();Toast.success('انبار ایجاد شد');await this.refresh()}
422 + catch(e){Toast.error(e.message)}finally{this.busy=false}
423 + }
424 + async openTransfer() {
425 + try {
426 + const [warehouses,products]=await Promise.all([Retail.warehouses(),DataScope.list('products')]);
427 + if(warehouses.length<2){Toast.warning('برای انتقال کالا حداقل دو انبار لازم است');return}
428 + const opts=warehouses.map(w=>`<option value="${html(w.id)}">${html(w.name)}</option>`).join('');
429 + const prod=products.filter(p=>p.trackInventory!==false)
430 + .map(p=>`<option value="${html(p.id)}">${html(p.name)}</option>`).join('');
431 + Modal.open({title:'انتقال کالا بین انبارها',size:'sm',closeOnBackdrop:false,
432 + body:`<div class="form-group"><label class="form-label">کالا</label><select class="form-control" id="acTrProduct">${prod}</select></div>
433 + <div class="form-group"><label class="form-label">انبار مبدا</label><select class="form-control" id="acTrFrom">${opts}</select></div>
434 + <div class="form-group"><label class="form-label">انبار مقصد</label><select class="form-control" id="acTrTo">${opts}</select></div>
435 + <div class="form-group"><label class="form-label">مقدار</label><input id="acTrQty" class="form-control" value="1"></div>
436 + <div class="form-group"><label class="form-label">تاریخ</label><input id="acTrDate" class="form-control" value="${safeDate()}"></div>`,
437 + footer:'<button class="btn btn-secondary" onclick="FINORA.Modal.close()">انصراف</button><button class="btn" onclick="window.AccountingView.saveTransfer()">ثبت انتقال</button>'});
438 + }catch(e){Toast.error(e.message)}
439 + }
440 + async saveTransfer() {
441 + if(this.busy)return;this.busy=true;
442 + try {
443 + await Retail.transferStock({
444 + productId:document.getElementById('acTrProduct').value,
445 + fromWarehouseId:document.getElementById('acTrFrom').value,
446 + toWarehouseId:document.getElementById('acTrTo').value,
447 + quantity:Number(digits(document.getElementById('acTrQty').value)),
448 + date:digits(document.getElementById('acTrDate').value)});
449 + Modal.close();Toast.success('انتقال انبار ثبت شد');await this.refresh();
450 + }catch(e){Toast.error(e.message)}finally{this.busy=false}
451 + }
452 + async openStocktakeCreate() {
453 + try {
454 + const warehouses=await Retail.warehouses();
455 + const options=warehouses.map(w=>`<option value="${html(w.id)}">${html(w.name)}</option>`).join('');
456 + Modal.open({title:'شروع شمارش انبار',size:'sm',closeOnBackdrop:false,
457 + body:`<label class="form-label">انبار</label><select class="form-control" id="acStWarehouse">${options}</select>
458 + <label class="form-label">تاریخ شمسی</label><input class="form-control" id="acStDate" value="${safeDate()}">
459 + <p style="margin-top:12px">موجودی مبنا ثابت ثبت می‌شود؛ برای تأیید، شمارش همه اقلام ضروری است.</p>`,
460 + footer:'<button class="btn btn-secondary" onclick="FINORA.Modal.close()">انصراف</button><button class="btn" onclick="window.AccountingView.createStocktake()">ایجاد جلسه</button>'});
461 + }catch(e){Toast.error(e.message)}
462 + }
463 + async createStocktake() {
464 + if(this.busy)return;this.busy=true;
465 + try {
466 + const take=await Retail.newStocktake({warehouseId:document.getElementById('acStWarehouse').value,
467 + date:digits(document.getElementById('acStDate').value)});
468 + Modal.close();Toast.success('جلسه شمارش ایجاد شد');await this.refresh();await this.openStocktake(take.id);
469 + }catch(e){Toast.error(e.message)}finally{this.busy=false}
470 + }
471 + async openStocktake(id) {
472 + try {
473 + const sessions=await Retail.getStocktakes(),take=sessions.find(s=>s.id===id);
474 + if(!take)throw Error('جلسه شمارش یافت نشد');
475 + const lines=await Retail.getStocktakeLines(id),products=await DataScope.list('products');
476 + const names=Object.fromEntries(products.map(p=>[p.id,p.name]));
477 + const extras=products.filter(p=>p.trackInventory!==false&&!lines.some(l=>l.productId===p.id));
478 + const extraOptions=extras.map(p=>`<option value="${html(p.id)}">${html(p.name)}</option>`).join('');
479 + const existing=lines.map(l=>`<tr data-product="${html(l.productId)}">
480 + <td>${html(names[l.productId]||l.productId)}</td><td>${l.expectedUnits/1000}</td>
481 + <td><input class="form-control ac-count" value="${l.countedUnits===null?'':l.countedUnits/1000}" ${take.status!=='draft'?'disabled':''}></td>
482 + <td><input class="form-control ac-cost" placeholder="ریال" value="${l.unitCost??''}" ${take.status!=='draft'?'disabled':''}></td></tr>`).join('');
483 + Modal.open({title:'برگه انبارگردانی',size:'lg',closeOnBackdrop:false,
484 + body:`<input type="hidden" id="acStocktakeId" value="${html(id)}">
485 + <p style="margin-bottom:10px">مقدار شمارش واقعی و در صورت مازاد کالای بدون مانده، قیمت تمام‌شده واحد را وارد کنید.</p>
486 + <div class="table-wrap"><table><thead><tr><th>کالا</th><th>مبنای سیستم</th><th>شمارش واقعی</th><th>بهای واحد مازاد</th></tr></thead>
487 + <tbody id="acTakeRows">${existing}</tbody></table></div>
488 + ${take.status==='draft'&&extras.length?`<div style="display:flex;gap:8px;margin-top:12px;align-items:center">
489 + <select class="form-control" id="acTakeNewProduct">${extraOptions}</select>
490 + <button class="btn btn-secondary" onclick="window.AccountingView.addStocktakeProduct()">افزودن کالای جدید به شمارش</button>
491 + </div>`:''}`,
492 + footer:take.status==='draft'?'<button class="btn btn-secondary" onclick="FINORA.Modal.close()">بستن</button><button class="btn" onclick="window.AccountingView.saveStocktake()">ذخیره شمارش</button><button class="btn btn-secondary" onclick="window.AccountingView.finishStocktake()">تأیید نهایی</button>':
493 + '<button class="btn btn-secondary" onclick="FINORA.Modal.close()">بستن</button>'});
494 + }catch(e){Toast.error(e.message)}
495 + }
496 + addStocktakeProduct() {
497 + const selector=document.getElementById('acTakeNewProduct');
498 + if(!selector?.value)return;
499 + const id=selector.value;
500 + const label=selector.selectedOptions[0]?.textContent||id;
501 + const body=document.getElementById('acTakeRows');
502 + if(!body||body.querySelector('[data-product="'+id+'"]'))return;
503 + body.insertAdjacentHTML('beforeend',`<tr data-product="${html(id)}">
504 + <td>${html(label)}</td><td>۰</td>
505 + <td><input class="form-control ac-count" value="0"></td>
506 + <td><input class="form-control ac-cost" placeholder="ریال"></td></tr>`);
507 + selector.selectedOptions[0]?.remove();
508 + }
509 + async persistStocktakeCounts(id) {
510 + for(const row of document.querySelectorAll('#acTakeRows tr[data-product]')){
511 + const count=digits(row.querySelector('.ac-count').value).trim();
512 + const cost=digits(row.querySelector('.ac-cost').value).trim();
513 + if(!count)throw Error('برای همه اقلام مقدار شمارش را وارد کنید');
514 + await Retail.countStocktake(id,row.dataset.product,Number(count),cost?Number(cost):null);
515 + }
516 + }
517 + async saveStocktake() {
518 + if(this.busy)return;this.busy=true;
519 + try {
520 + const id=document.getElementById('acStocktakeId').value;
521 + await this.persistStocktakeCounts(id);
522 + Modal.close();Toast.success('شمارش ثبت شد');await this.refresh();
523 + }catch(e){Toast.error(e.message)}finally{this.busy=false}
524 + }
525 + async finishStocktake() {
526 + if(this.busy)return;this.busy=true;
527 + try {
528 + const id=document.getElementById('acStocktakeId').value;
529 + await this.persistStocktakeCounts(id);
530 + await Retail.finalizeStocktake(id);
531 + Modal.close();Toast.success('انبارگردانی تأیید و سند تعدیل ثبت شد');await this.refresh();
532 + }catch(e){Toast.error(e.message)}finally{this.busy=false}
533 + }
534 + openReversal(id) {
535 + const periods = this.periods.filter(p => !p.closed);
536 + if (!periods.length) { Toast.error('دوره باز برای ثبت سند برگشت وجود ندارد'); return; }
537 + const opts = periods.map(p => `<option value="${html(p.id)}">${html(p.name)}</option>`).join('');
538 + Modal.open({ title: 'ثبت سند معکوس', size: 'sm', closeOnBackdrop: false,
539 + body: `<input type="hidden" id="acReversalId" value="${html(id)}">
540 + <p style="font-size:12px;margin-bottom:10px">این عملیات سندی جداگانه با بدهکار/بستانکار معکوس می‌سازد و سند اصلی حذف نمی‌شود.</p>
541 + <div class="form-group"><label class="form-label">دوره باز</label>
542 + <select class="form-control" id="acReversalPeriod">${opts}</select></div>
543 + <div class="form-group"><label class="form-label">تاریخ برگشت</label>
544 + <input class="form-control" id="acReversalDate" value="${html(safeDate())}"></div>`,
545 + footer: '<button class="btn btn-secondary" onclick="FINORA.Modal.close()">انصراف</button><button class="btn" onclick="window.AccountingView.saveReversal()">ثبت سند برگشت</button>'
546 + });
547 + }
548 + async saveReversal() {
549 + if (this.busy) return;
550 + this.busy = true;
551 + try {
552 + await Ledger.reverseJournal(document.getElementById('acReversalId').value, {
553 + periodId: document.getElementById('acReversalPeriod').value,
554 + date: digits(document.getElementById('acReversalDate').value).trim()
555 + });
556 + Modal.close();
557 + Toast.success('سند برگشت مستقل ثبت شد');
558 + await this.refresh();
559 + } catch (error) { Toast.error(error.message); }
560 + finally { this.busy = false; }
561 + }
562 +}
563 +
564 +export const AccountingView = new AccountingViewImpl();
src/views/ContactLedgerModal.js
+1 -1
@@ -268,7 +268,7 @@ class ContactLedgerModalImpl {
268 <tbody>${rowsHtml}</tbody>
269 </table>
270
271 - <div class="footer">فینورا پرو - سامانه مدیریت کسب‌وکار</div>
271 + <div class="footer">Factor-easyPro - سامانه مدیریت کسب‌وکار</div>
272 </body>
273 </html>
274 `);
src/views/InvoiceFormView.js
+122 -31
@@ -10,6 +10,8 @@ import { Toast } from '../core/Toast.js';
10 import { Formatters } from '../utils/Formatters.js';
11 import { numberToWords } from '../utils/NumberToWords.js';
12 import { NumberInput } from '../utils/NumberInput.js';
13 +import { SettingsController } from '../controllers/SettingsController.js';
14 +import { RetailPostingService } from '../core/RetailPostingService.js';
15
16 let ctx = {
17 editId: null,
@@ -17,6 +19,8 @@ let ctx = {
19 contacts: [],
20 products: [],
21 units: [],
22 + invoices: [],
23 + warehouses: [],
24 rowCounter: 0
25 };
26
@@ -29,6 +33,8 @@ class InvoiceFormViewImpl {
33 ctx.contacts = await ContactController.getAll();
34 ctx.products = await ProductController.getProducts();
35 ctx.units = await ProductController.getUnits();
36 + ctx.invoices = await InvoiceController.getAll();
37 + ctx.warehouses = await RetailPostingService.isEnabled() ? await RetailPostingService.warehouses() : [];
38 ctx.rowCounter = 0;
39
40 if (invoiceId) {
@@ -52,6 +58,11 @@ class InvoiceFormViewImpl {
58 };
59 }
60
61 + ctx.invoiceSettings = await SettingsController.getInvoiceSettings();
62 + if (!invoiceId) {
63 + ctx.data.number = await InvoiceController.getNextNumber(ctx.data.kind);
64 + }
65 +
66 // اگه فاکتور جدید بدون اقلام، یک ردیف خالی اضافه کن
67 if (!ctx.data.items || ctx.data.items.length === 0) {
68 ctx.data.items = [this._emptyItem()];
@@ -105,9 +116,8 @@ class InvoiceFormViewImpl {
116 `<option value="${k.value}" ${d.kind === k.value ? 'selected' : ''}>${k.label}</option>`
117 ).join('');
118
108 - const contactOptions = ctx.contacts.map(c =>
109 - `<option value="${c.id}" ${d.contactId === c.id ? 'selected' : ''}>${this._esc(c.name)}</option>`
110 - ).join('');
119 + const selectedContact = ctx.contacts.find(c => c.id === d.contactId);
120 + const selectedContactLabel = selectedContact ? selectedContact.name : (d.contactName || '');
121
122 return `
123 <div style="display:grid;grid-template-columns:1fr 1fr 1fr;gap:10px;margin-bottom:14px">
@@ -117,7 +127,7 @@ class InvoiceFormViewImpl {
127 </div>
128 <div class="form-group" style="margin-bottom:0">
129 <label class="form-label">شماره فاکتور</label>
120 - <input type="text" class="form-control" value="${d.number ? '#' + d.number : '(خودکار)'}" disabled style="background:var(--bg)" />
130 + <input type="text" class="form-control" id="invNumber" value="${this._esc(d.number || '')}" ${ctx.invoiceSettings?.numberingMode === 'manual' && !ctx.editId ? '' : 'disabled'} style="background:var(--bg)" placeholder="شماره فاکتور" />
131 </div>
132 <div class="form-group" style="margin-bottom:0">
133 <label class="form-label">تاریخ (شمسی)</label>
@@ -125,14 +135,26 @@ class InvoiceFormViewImpl {
135 </div>
136 </div>
137
138 + ${ctx.warehouses.length ? `<div class="form-group" style="margin-bottom:12px">
139 + <label class="form-label">انبار محل گردش کالا</label><select class="form-control" id="invWarehouse">
140 + ${ctx.warehouses.map(w=>`<option value="${this._esc(w.id)}" ${(d.warehouseId||ctx.warehouses.find(x=>x.isDefault)?.id)===w.id?'selected':''}>${this._esc(w.name)}</option>`).join('')}
141 + </select></div>` : ''}
142 + <div class="form-group" id="invOriginalWrap" style="margin-bottom:12px;${['sale_return','purchase_return'].includes(d.kind)?'':'display:none'}">
143 + <label class="form-label">شماره فاکتور اولیه (الزامی برای مرجوعی)</label>
144 + <select class="form-control" id="invOriginalInvoice">
145 + <option value="">انتخاب فاکتور مرجع</option>
146 + ${ctx.invoices.filter(i=>['sale','non_formal','purchase'].includes(i.kind)&&!i.isPreInvoice)
147 + .map(i=>`<option data-kind="${this._esc(i.kind)}" value="${this._esc(i.id)}" ${d.originalInvoiceId===i.id?'selected':''}>${this._esc('#'+i.number+' — '+(i.contactName||''))}</option>`).join('')}
148 + </select></div>
149 <div style="display:grid;grid-template-columns:2fr 1fr;gap:10px;margin-bottom:14px">
150 <div class="form-group" style="margin-bottom:0">
151 <label class="form-label">طرف حساب</label>
152 <div style="display:flex;gap:6px">
132 - <select class="form-control" id="invContact" style="flex:1">
133 - <option value="">— انتخاب کنید —</option>
134 - ${contactOptions}
135 - </select>
153 + <div style="position:relative;flex:1;min-width:0">
154 + <input type="hidden" id="invContact" value="${this._esc(d.contactId || '')}" />
155 + <input type="text" class="form-control" id="invContactSearch" autocomplete="off" value="${this._esc(selectedContactLabel)}" placeholder="جستجوی نام یا کد طرف حساب" onfocus="window.InvoiceFormView._showContactOptions()" oninput="window.InvoiceFormView._showContactOptions(true)" />
156 + <div id="invContactOptions" style="display:none;position:absolute;z-index:10010;top:100%;right:0;left:0;max-height:230px;overflow:auto;background:var(--card-bg,#fff);border:1px solid var(--border);border-radius:8px;box-shadow:0 8px 20px #0002"></div>
157 + </div>
158 <button class="btn btn-secondary" style="min-height:42px;padding:0 12px" onclick="window.InvoiceFormView._openQuickContact()" title="افزودن شخص جدید">➕</button>
159 </div>
160 </div>
@@ -153,7 +175,7 @@ class InvoiceFormViewImpl {
175 </div>
176 </div>
177
156 - <div class="table-wrap" style="max-height:340px;overflow-y:auto">
178 + <div class="table-wrap" style="overflow:visible">
179 <table>
180 <thead>
181 <tr>
@@ -268,17 +290,17 @@ class InvoiceFormViewImpl {
290 const row = document.createElement('tr');
291 row.dataset.idx = idx;
292
271 - const productOptions = ctx.products.map(p =>
272 - `<option value="${p.id}" ${item.productId === p.id ? 'selected' : ''}>${this._esc(p.name)}${p.code ? ' (' + this._esc(p.code) + ')' : ''}</option>`
273 - ).join('');
293 + const selectedProduct = ctx.products.find(p => p.id === item.productId);
294 + const selectedProductLabel = selectedProduct ? selectedProduct.name : (item.productName || '');
295
296 row.innerHTML = `
297 <td style="text-align:center;font-weight:700">${Formatters.toPersianDigits(idx + 1)}</td>
298 <td>
278 - <select class="form-control row-product" style="min-height:36px" onchange="window.InvoiceFormView._onProductChange(${idx}, this.value)">
279 - <option value="">— انتخاب کالا —</option>
280 - ${productOptions}
281 - </select>
299 + <div style="position:relative;min-width:190px">
300 + <input type="hidden" class="row-product" value="${this._esc(item.productId || '')}" />
301 + <input type="text" class="form-control row-product-search" autocomplete="off" value="${this._esc(selectedProductLabel)}" placeholder="جستجوی کالا یا کد" onfocus="window.InvoiceFormView._showProductOptions(${idx})" oninput="window.InvoiceFormView._showProductOptions(${idx}, true)" />
302 + <div class="row-product-options" style="display:none;position:absolute;z-index:10010;top:100%;right:0;left:0;max-height:220px;overflow:auto;background:var(--card-bg,#fff);border:1px solid var(--border);border-radius:8px;box-shadow:0 8px 20px #0002"></div>
303 + </div>
304 </td>
305 <td><input type="text" class="form-control row-unit" style="min-height:36px;text-align:center" value="${this._esc(item.unit)}" oninput="window.InvoiceFormView._onFieldChange(${idx}, 'unit', this.value)" /></td>
306 <td><input type="text" inputmode="numeric" class="form-control row-qty" style="min-height:36px;text-align:center" value="${NumberInput.format(item.qty)}" oninput="window.InvoiceFormView._onFieldChange(${idx}, 'qty', this.value)" /></td>
@@ -300,6 +322,57 @@ class InvoiceFormViewImpl {
322 tbody.appendChild(row);
323 }
324
325 + _matchesOption(record, query) {
326 + const normalize = value => String(value ?? '').toLocaleLowerCase('fa').replace(/ي/g, 'ی').replace(/ك/g, 'ک').trim();
327 + return normalize([record.name, record.code, record.customerCode, record.contactCode].join(' ')).includes(normalize(query));
328 + }
329 +
330 + _showContactOptions(changed = false) {
331 + const input = document.getElementById('invContactSearch');
332 + const list = document.getElementById('invContactOptions');
333 + const hidden = document.getElementById('invContact');
334 + if (!input || !list || !hidden) return;
335 + if (changed) hidden.value = '';
336 + const matches = ctx.contacts.filter(c => this._matchesOption(c, input.value)).slice(0, 60);
337 + list.innerHTML = matches.length ? matches.map(c =>
338 + `<div class="contact-option" data-id="${this._esc(c.id)}" style="padding:9px 12px;cursor:pointer;border-bottom:1px solid var(--border)">${this._esc(c.name)} ${c.code ? '— ' + this._esc(c.code) : ''}</div>`
339 + ).join('') : '<div style="padding:10px">موردی یافت نشد</div>';
340 + list.style.display = 'block';
341 + list.querySelectorAll('.contact-option').forEach(el => el.addEventListener('mousedown', event => {
342 + event.preventDefault();
343 + const contact = ctx.contacts.find(c => c.id === el.dataset.id);
344 + if (!contact) return;
345 + hidden.value = contact.id;
346 + input.value = contact.name;
347 + list.style.display = 'none';
348 + }));
349 + }
350 +
351 + _showProductOptions(idx, changed = false) {
352 + const row = document.querySelector(`#itemsBody tr[data-idx="${idx}"]`);
353 + const input = row?.querySelector('.row-product-search');
354 + const list = row?.querySelector('.row-product-options');
355 + if (!input || !list) return;
356 + if (changed) {
357 + row.querySelector('.row-product').value = '';
358 + ctx.data.items[idx].productId = null;
359 + }
360 + const matches = ctx.products.filter(p => this._matchesOption(p, input.value)).slice(0, 60);
361 + list.innerHTML = matches.length ? matches.map(p =>
362 + `<div class="product-option" data-id="${this._esc(p.id)}" style="padding:9px 12px;cursor:pointer;border-bottom:1px solid var(--border)">${this._esc(p.name)} ${p.code ? '— ' + this._esc(p.code) : ''}</div>`
363 + ).join('') : '<div style="padding:10px">کالایی یافت نشد</div>';
364 + list.style.display = 'block';
365 + list.querySelectorAll('.product-option').forEach(el => el.addEventListener('mousedown', event => {
366 + event.preventDefault();
367 + const product = ctx.products.find(p => p.id === el.dataset.id);
368 + if (!product) return;
369 + row.querySelector('.row-product').value = product.id;
370 + input.value = product.name;
371 + list.style.display = 'none';
372 + this._onProductChange(idx, product.id);
373 + }));
374 + }
375 +
376 _addRow() {
377 ctx.data.items.push(this._emptyItem());
378 this._renderItems();
@@ -356,9 +429,26 @@ class InvoiceFormViewImpl {
429 this._recalc();
430 }
431
359 - _onKindChange() {
432 + async _onKindChange() {
433 const kind = document.getElementById('invKind').value;
434 ctx.data.kind = kind;
435 + if (!ctx.editId) {
436 + const number = await InvoiceController.getNextNumber(kind);
437 + ctx.data.number = number;
438 + const el = document.getElementById('invNumber');
439 + if (el) el.value = number;
440 + }
441 + const originalWrap = document.getElementById('invOriginalWrap');
442 + if (originalWrap) originalWrap.style.display = ['sale_return','purchase_return'].includes(kind) ? '' : 'none';
443 + const originalSelect = document.getElementById('invOriginalInvoice');
444 + if (originalSelect) {
445 + for (const option of originalSelect.options) {
446 + if (!option.value) continue;
447 + option.disabled = kind === 'sale_return' ? !['sale','non_formal'].includes(option.dataset.kind) :
448 + kind === 'purchase_return' ? option.dataset.kind !== 'purchase' : false;
449 + }
450 + if (originalSelect.selectedOptions[0]?.disabled) originalSelect.value = '';
451 + }
452 const vatRow = document.getElementById('vatRow');
453 const sumVatRow = document.getElementById('sumVatRow');
454 if (kind === 'non_formal') {
@@ -550,14 +640,6 @@ class InvoiceFormViewImpl {
640 Toast.success('کالا اضافه شد و به فاکتور اضافه می‌شود');
641 Modal.close();
642
553 - // اضافه کردن به dropdown همه‌ی ردیف‌ها
554 - document.querySelectorAll('#itemsBody .row-product').forEach(select => {
555 - const opt = document.createElement('option');
556 - opt.value = newProduct.id;
557 - opt.textContent = newProduct.name + (newProduct.code ? ` (${newProduct.code})` : '');
558 - select.appendChild(opt);
559 - });
560 -
643 const emptyIdx = ctx.data.items.findIndex(it => !it.productId);
644 let targetIdx;
645 if (emptyIdx >= 0) {
@@ -613,12 +695,13 @@ class InvoiceFormViewImpl {
695 entityType: 'natural', role: 'customer', name, mobile
696 });
697 Toast.success('شخص اضافه شد');
698 + ctx.contacts.push(newContact);
699 const select = document.getElementById('invContact');
617 - const opt = document.createElement('option');
618 - opt.value = newContact.id;
619 - opt.textContent = newContact.name;
620 - opt.selected = true;
621 - select.appendChild(opt);
700 + if (select) select.value = newContact.id;
701 + const search = document.getElementById('invContactSearch');
702 + if (search) search.value = newContact.name;
703 + const options = document.getElementById('invContactOptions');
704 + if (options) options.style.display = 'none';
705 Modal.close();
706 } catch (err) {
707 Toast.error('خطا: ' + err.message);
@@ -646,8 +729,10 @@ class InvoiceFormViewImpl {
729 return;
730 }
731
732 + this._recalc(); // read payment state from the same calculation shown in the summary
733 const data = {
734 kind: document.getElementById('invKind').value,
735 + number: document.getElementById('invNumber')?.value,
736 isPreInvoice: document.getElementById('invPreInvoice').checked,
737 date: document.getElementById('invDate').value,
738 contactId: contact.id,
@@ -658,10 +743,14 @@ class InvoiceFormViewImpl {
743 vatEnabled: document.getElementById('invVatEnabled')?.checked || false,
744 vatRate: NumberInput.parse(document.getElementById('invVatRate')?.value),
745 paymentMethod: document.getElementById('invPayment').value,
661 - paidAmount: NumberInput.parse(document.getElementById('invPaidAmount')?.value),
746 + paidAmount: ctx.totals?.paidAmount ?? 0,
747 + originalInvoiceId: document.getElementById('invOriginalInvoice')?.value || null,
748 + warehouseId: document.getElementById('invWarehouse')?.value || null,
749 description: document.getElementById('invDescription').value
750 };
751
752 + if (this._saving) return;
753 + this._saving = true;
754 try {
755 const saved = await InvoiceController.save(data, ctx.editId);
756 Toast.success(ctx.editId ? 'فاکتور ویرایش شد' : `فاکتور #${saved.number} صادر شد`);
@@ -675,6 +764,8 @@ class InvoiceFormViewImpl {
764 } catch (err) {
765 console.error(err);
766 Toast.error('خطا: ' + err.message);
767 + } finally {
768 + this._saving = false;
769 }
770 }
771
src/views/ReportsView.js
+1 -1
@@ -566,7 +566,7 @@ class ReportsViewImpl {
566 <h1>گزارش ${tabNames[currentTab]}</h1>
567 <div class="header-info">بازه: ${rangeText} | تاریخ چاپ: ${Jalali.today()}</div>
568 ${content}
569 - <div class="footer">فینورا پرو - سامانه مدیریت کسب‌وکار</div>
569 + <div class="footer">Factor-easyPro - سامانه مدیریت کسب‌وکار</div>
570 </body>
571 </html>
572 `);
src/views/SettingsView.js
+87 -13
@@ -12,7 +12,7 @@ import { Formatters } from '../utils/Formatters.js';
12 import { Auth } from '../core/Auth.js';
13 import { ExcelController } from '../controllers/ExcelController.js';
14
15 -let cache = { company: {}, stats: {} };
15 +let cache = { company: {}, stats: {}, invoiceSettings: { numberingMode: 'auto', nextNumber: 1 } };
16
17 class SettingsViewImpl {
18 async render() {
@@ -25,6 +25,7 @@ class SettingsViewImpl {
25
26 <div class="settings-grid">
27 ${this._renderCompanyCard()}
28 + ${this._renderInvoiceSettingsCard()}
29 ${this._renderExcelCard()}
30 ${this._renderShortcutsCard()}
31 ${this._renderBackupCard()}
@@ -40,8 +41,19 @@ class SettingsViewImpl {
41 }
42
43 async reload() {
43 - cache.company = await SettingsController.getCompanyInfo();
44 - cache.stats = await this._collectStats();
44 + const results = await Promise.allSettled([
45 + SettingsController.getCompanyInfo(),
46 + SettingsController.getInvoiceSettings(),
47 + this._collectStats()
48 + ]);
49 + const defaults = [{}, { numberingMode: 'auto', nextNumber: 1 }, {}];
50 + const values = results.map((result, index) => {
51 + if (result.status === 'fulfilled') return result.value;
52 + console.error('Settings load failed:', index, result.reason);
53 + Toast.error('بخشی از تنظیمات بارگذاری نشد: ' + (result.reason?.message || 'خطای نامشخص'));
54 + return defaults[index];
55 + });
56 + [cache.company, cache.invoiceSettings, cache.stats] = values;
57 }
58
59 async _collectStats() {
@@ -89,13 +101,58 @@ class SettingsViewImpl {
101 ` : `
102 <div class="empty-mini">هنوز اطلاعاتی وارد نشده</div>
103 `}
92 - <button class="btn" onclick="window.SettingsView.openCompanyModal()">
93 - ${c.name ? '✏️ ویرایش اطلاعات' : '➕ وارد کردن اطلاعات'}
94 - </button>
104 + <div style="display:flex;gap:8px;flex-wrap:wrap">
105 + <button class="btn" onclick="window.SettingsView.openCompanyModal()">${c.name ? '✏️ ویرایش اطلاعات' : '➕ وارد کردن اطلاعات'}</button>
106 + <button class="btn" onclick="window.SettingsView.openCompanySwitcher()">🔄 تغییر شرکت</button>
107 + ${Auth.isAdmin() ? '<button class="btn" onclick="window.SettingsView.createCompany()">➕ شرکت جدید</button>' : ''}
108 + </div>
109 </div>
110 `;
111 }
112
113 + _renderInvoiceSettingsCard() {
114 + const s = cache.invoiceSettings || { numberingMode: 'auto', nextNumber: 1 };
115 + return `
116 + <div class="card settings-card">
117 + <div class="settings-card-header">
118 + <div class="settings-card-icon">🧾</div>
119 + <div>
120 + <h3 class="settings-card-title">تنظیمات فاکتور</h3>
121 + <p class="settings-card-desc">نحوه شماره‌گذاری فاکتورهای جدید</p>
122 + </div>
123 + </div>
124 + <div class="form-group">
125 + <label class="form-label">نحوه شماره‌گذاری</label>
126 + <select class="form-control" id="invoiceNumberingMode">
127 + <option value="auto" ${s.numberingMode === 'auto' ? 'selected' : ''}>خودکار</option>
128 + <option value="manual" ${s.numberingMode === 'manual' ? 'selected' : ''}>دستی</option>
129 + </select>
130 + </div>
131 + <div class="form-group">
132 + <label class="form-label">شماره بعدی فاکتور</label>
133 + <input class="form-control" id="invoiceNextNumber" type="number" min="1" value="${Number(s.nextNumber) || 1}" />
134 + </div>
135 + <button class="btn" onclick="window.SettingsView.saveInvoiceSettings()">💾 ذخیره تنظیمات فاکتور</button>
136 + </div>
137 + `;
138 + }
139 +
140 + async saveInvoiceSettings() {
141 + const numberingMode = document.getElementById('invoiceNumberingMode').value;
142 + const nextNumber = Number(document.getElementById('invoiceNextNumber').value);
143 + if (!Number.isInteger(nextNumber) || nextNumber < 1) {
144 + Toast.warning('شماره بعدی باید عدد صحیح بزرگ‌تر از صفر باشد');
145 + return;
146 + }
147 + try {
148 + cache.invoiceSettings = await SettingsController.saveInvoiceSettings({ numberingMode, nextNumber });
149 + Toast.success('تنظیمات فاکتور ذخیره شد');
150 + } catch (err) {
151 + console.error('Invoice settings save failed:', err);
152 + Toast.error('خطا در ذخیره تنظیمات فاکتور: ' + err.message);
153 + }
154 + }
155 +
156 // ============================================================
157 // کارت Excel (جدید)
158 // ============================================================
@@ -410,8 +467,8 @@ class SettingsViewImpl {
467 <div class="settings-card-header">
468 <div class="settings-card-icon" style="background:linear-gradient(135deg,#3b82f6,#1e40af)">💾</div>
469 <div>
413 - <h3 class="settings-card-title">پشتیبان‌گیری JSON</h3>
414 - <p class="settings-card-desc">پشتیبان‌گیری کامل از دیتابیس (فقط JSON، نه Excel)</p>
470 + <h3 class="settings-card-title">پشتیبان‌گیری رمزگذاری‌شده</h3>
471 + <p class="settings-card-desc">اطلاعات عملیاتی و حسابداری شرکت فعال؛ بازیابی بدون بازنویسی کاربران و تنظیمات سراسری</p>
472 </div>
473 </div>
474
@@ -505,7 +562,7 @@ class SettingsViewImpl {
562 <div class="settings-card-icon">ℹ️</div>
563 <div>
564 <h3 class="settings-card-title">درباره فینورا پرو</h3>
508 - <p class="settings-card-desc">نسخه ۰.۱.۰</p>
565 + <p class="settings-card-desc">نسخه ۲.۰.۰</p>
566 </div>
567 </div>
568 <div style="font-size:13px;line-height:1.9;color:var(--text-muted)">
@@ -521,6 +578,7 @@ class SettingsViewImpl {
578
579 _renderAllCards() {
580 return this._renderCompanyCard()
581 + + this._renderInvoiceSettingsCard()
582 + this._renderExcelCard()
583 + this._renderShortcutsCard()
584 + this._renderBackupCard()
@@ -532,6 +590,22 @@ class SettingsViewImpl {
590 // ============================================================
591 // فرم اطلاعات شرکت
592 // ============================================================
593 + async openCompanySwitcher() {
594 + const companies = await globalThis.FINORA.Company.list();
595 + const body = companies.map(c => `<button class="btn" style="width:100%;margin:4px 0" onclick="window.SettingsView.selectCompany('${c.id}')">${this._esc(c.name || 'شرکت')}</button>`).join('');
596 + Modal.open({ title: 'تغییر شرکت فعال', body: body || '<div class="empty-mini">شرکتی یافت نشد</div>', footer: '', size: 'sm' });
597 + }
598 +
599 + async selectCompany(id) {
600 + await globalThis.FINORA.Company.select(id); Modal.close(); await this.reload(); Toast.success('شرکت فعال تغییر کرد');
601 + }
602 +
603 + async createCompany() {
604 + const name = prompt('نام شرکت جدید را وارد کنید:'); if (!name?.trim()) return;
605 + const company = await globalThis.FINORA.Company.create({ name: name.trim(), entityType: 'legal' });
606 + await globalThis.FINORA.Company.select(company.id); await this.reload(); Toast.success('شرکت جدید ایجاد شد');
607 + }
608 +
609 openCompanyModal() {
610 const c = cache.company;
611 const body = `
@@ -636,19 +710,19 @@ class SettingsViewImpl {
710 openRestoreModal() {
711 const body = `
712 <div class="backup-warning" style="margin-bottom:14px">
639 - ⚠️ <strong>هشدار:</strong> در حالت Merge، داده‌های تکراری skip می‌شن. در حالت Replace، همه‌چیز با بکاپ جایگزین می‌شه.
713 + ⚠️ <strong>هشدار:</strong> در حالت Merge، داده‌های تکراری skip می‌شن. در حالت Replace، فقط رکوردهای دارای شناسه یکسان بازنویسی می‌شوند و سایر داده‌ها حذف نمی‌شوند.
714 </div>
715
716 <div class="form-group">
643 - <label class="form-label">فایل بکاپ (JSON)</label>
644 - <input type="file" class="form-control" id="restoreFile" accept=".json,application/json" />
717 + <label class="form-label">فایل بکاپ رمزگذاری‌شده یا JSON</label>
718 + <input type="file" class="form-control" id="restoreFile" accept=".json,.fbackup,application/json,application/octet-stream" />
719 </div>
720
721 <div class="form-group">
722 <label class="form-label">حالت بازیابی</label>
723 <select class="form-control" id="restoreMode">
724 <option value="merge">🔀 ادغام (Merge) — داده‌های جدید اضافه می‌شن</option>
651 - <option value="replace">🔄 جایگزینی (Replace) — همه‌چیز با بکاپ عوض می‌شه</option>
725 + <option value="replace">🔄 بازنویسی شناسه‌های یکسان (Replace) — بدون حذف سایر رکوردها</option>
726 </select>
727 </div>
728 `;
src/views/StockKardexModal.js
+1 -1
@@ -313,7 +313,7 @@ class StockKardexModalImpl {
313 </thead>
314 <tbody>${rowsHtml}</tbody>
315 </table>
316 - <div class="footer">فینورا پرو - سامانه مدیریت کسب‌وکار</div>
316 + <div class="footer">Factor-easyPro - سامانه مدیریت کسب‌وکار</div>
317 </body>
318 </html>
319 `);
tests/accounting-core.test.mjs new
+18
@@ -0,0 +1,18 @@
1 +import test from 'node:test';
2 +import assert from 'node:assert/strict';
3 +import { validateAccount, validateJournal, journalSourceKey, DEFAULT_CHART } from '../src/core/AccountingCore.mjs';
4 +const companyId = 'c1';
5 +const accounts = [
6 + { id: 'a', code: '101', companyId, level: 'general', type: 'asset', name: 'Cash' },
7 + { id: 'b', code: '401', companyId, level: 'general', type: 'revenue', name: 'Sales' }
8 +];
9 +const journal = { companyId, date: '1405/07/16', lines: [{ accountId: 'a', debit: 100, credit: 0 }, { accountId: 'b', debit: 0, credit: 100 }] };
10 +const period = { companyId, startDate: '1405/01/01', endDate: '1405/12/29', closed: false };
11 +test('default chart has base groups', () => assert.equal(DEFAULT_CHART.filter(a => a.level === 'group').length, 5));
12 +test('balanced journal', () => assert.deepEqual(validateJournal(journal, accounts, period), { debit: 100, credit: 100 }));
13 +test('reject unbalanced', () => assert.throws(() => validateJournal({ ...journal, lines: [{ accountId: 'a', debit: 101, credit: 0 }, journal.lines[1]] }, accounts, period)));
14 +test('reject cross-company', () => assert.throws(() => validateJournal({ ...journal, companyId: 'c2' }, accounts, period)));
15 +test('reject closed period', () => assert.throws(() => validateJournal(journal, accounts, { ...period, closed: true })));
16 +test('reject duplicate account', () => assert.throws(() => validateAccount({ ...accounts[0] }, accounts)));
17 +test('reject invalid account parent', () => assert.throws(() => validateAccount({ ...accounts[0], id: 'x', code: '10101', level: 'subsidiary', parentCode: '999' }, accounts)));
18 +test('source key scoped', () => assert.notEqual(journalSourceKey('c1', 'invoice', '1'), journalSourceKey('c2', 'invoice', '1')));
tests/accounting-migration.test.mjs new
+35
@@ -0,0 +1,35 @@
1 +import test from 'node:test';
2 +import assert from 'node:assert/strict';
3 +import 'fake-indexeddb/auto';
4 +import { StorageService } from '../src/core/StorageService.js';
5 +
6 +test('migration: upgrading legacy IndexedDB v4 preserves invoices and creates V2 accounting stores', async () => {
7 + const db = await new Promise((resolve, reject) => {
8 + const r = indexedDB.open('finora_pro_db', 4);
9 + r.onupgradeneeded = () => {
10 + const legacy = r.result.createObjectStore('invoices', { keyPath: 'id' });
11 + legacy.put({ id: 'legacy-inv-1', number: 120, kind: 'sale', companyId: 'company_default', grandTotal: 2000 });
12 + r.result.createObjectStore('products', { keyPath: 'id' })
13 + .put({ id: 'legacy-product', name: 'کالای قبلی', sellPrice: 2000 });
14 + };
15 + r.onsuccess = () => resolve(r.result);
16 + r.onerror = () => reject(r.error);
17 + });
18 + db.close();
19 + const upgraded = await StorageService.init();
20 + assert.equal(upgraded.version, 6);
21 + assert.deepEqual((await StorageService.get('invoices', 'legacy-inv-1')).number, 120);
22 + assert.equal((await StorageService.get('products', 'legacy-product')).name, 'کالای قبلی');
23 + for (const name of ['account_chart', 'fiscal_periods', 'journal_entries', 'journal_lines']) {
24 + assert.ok(upgraded.objectStoreNames.contains(name), name);
25 + }
26 + await StorageService.put('account_chart', {
27 + id: 'acc-old-safe', companyId: 'company_default', code: '1',
28 + name: 'دارایی‌ها', level: 'group', type: 'asset'
29 + });
30 + assert.equal((await StorageService.getAllByIndex('account_chart', 'companyId', 'company_default')).length, 1);
31 + const backup = await StorageService.exportAll();
32 + assert.equal(backup.data.invoices.length, 1);
33 + assert.equal(backup.data.products.length, 1);
34 + assert.equal(backup.data.account_chart.length, 1);
35 +});
tests/accounting-phase1.test.mjs new
+279
@@ -0,0 +1,279 @@
1 +import test from 'node:test';
2 +import assert from 'node:assert/strict';
3 +import 'fake-indexeddb/auto';
4 +import { StorageService } from '../src/core/StorageService.js';
5 +import { Auth } from '../src/core/Auth.js';
6 +import { CompanyService } from '../src/core/CompanyService.js';
7 +import { DataScope } from '../src/core/DataScope.js';
8 +import { SettingsController } from '../src/controllers/SettingsController.js';
9 +import { AccountingService as ledger } from '../src/core/AccountingService.js';
10 +import {
11 + validateAccount, validateFiscalPeriod, validateJournal, validateJournalLines,
12 + assertJalaliDate, reversingLines
13 +} from '../src/core/AccountingCore.mjs';
14 +
15 +const year = { startDate: '1405/01/01', endDate: '1405/12/29' };
16 +const select = companyId => { CompanyService.activeCompanyId = companyId; };
17 +const entries = async store => StorageService.getAll(store);
18 +const reset = async () => {
19 + await StorageService.clearAll();
20 + await StorageService.put('companies', { id: 'c1', name: 'Alpha' });
21 + await StorageService.put('companies', { id: 'c2', name: 'Beta' });
22 + Auth.currentUser = { id: 'test_admin', role: 'admin', username: 'tester' };
23 + select('c1');
24 +};
25 +const setup = async () => {
26 + await reset();
27 + const period = await ledger.createPeriod({ name: 'سال ۱۴۰۵', ...year });
28 + await ledger.seedDefaultChart();
29 + const accounts = await ledger.listAccounts();
30 + return { period, cash: accounts.find(a => a.code === '101'), sales: accounts.find(a => a.code === '401') };
31 +};
32 +const balanced = (period, cash, sales, sourceId) => ({
33 + periodId: period.id, date: '1405/07/18', description: 'فروش تست',
34 + ...(sourceId ? { sourceType: 'test_invoice', sourceId } : {}),
35 + lines: [
36 + { accountId: cash.id, debit: 10000, credit: 0 },
37 + { accountId: sales.id, debit: 0, credit: 10000 }
38 + ]
39 +});
40 +
41 +test('core: Jalali dates and fiscal period boundaries', () => {
42 + assert.equal(assertJalaliDate('1405/07/18'), '1405/07/18');
43 + assert.throws(() => assertJalaliDate('1405/07/31'));
44 + assert.throws(() => assertJalaliDate('1405/12/30'));
45 + assert.equal(assertJalaliDate('1403/12/30'), '1403/12/30');
46 + assert.throws(() => assertJalaliDate('1405/7/18'));
47 + assert.throws(() => validateFiscalPeriod({ companyId: 'c1', startDate: '1405/10/01', endDate: '1405/01/01' }));
48 + assert.throws(() => validateFiscalPeriod({ companyId: 'c1', ...year }, [{ id: 'p', companyId: 'c1', ...year }]));
49 + assert.doesNotThrow(() => validateFiscalPeriod({ companyId: 'c2', ...year }, [{ id: 'p', companyId: 'c1', ...year }]));
50 +});
51 +
52 +test('core: reject incorrect accounts, posting to parent and amount overflow', () => {
53 + const list = [
54 + { id: 'root', companyId: 'c1', code: '1', level: 'group', type: 'asset', name: 'assets' },
55 + { id: 'general', companyId: 'c1', code: '101', parentCode: '1', level: 'general', type: 'asset', name: 'cash' },
56 + { id: 'sub', companyId: 'c1', code: '10101', parentCode: '101', level: 'subsidiary', type: 'asset', name: 'box' }
57 + ];
58 + assert.throws(() => validateAccount({ ...list[0], id: 'another', parentCode: '101' }, list));
59 + assert.throws(() => validateAccount({ id: 'x', companyId: 'c1', code: '10102', parentCode: '101', level: 'subsidiary', type: 'expense', name: 'wrong' }, list));
60 + assert.throws(() => validateJournalLines({ companyId: 'c1', lines: [{ accountId: 'general', debit: 10, credit: 0 }] }, list, { requireBalance: false }));
61 + assert.throws(() => validateJournalLines({ companyId: 'c1', lines: [{ accountId: 'sub', debit: 9007199254740991, credit: 0 }, { accountId: 'sub', debit: 1, credit: 0 }] }, list));
62 + assert.deepEqual(reversingLines([{ accountId: 'x', debit: 4, credit: 0 }, { accountId: 'y', debit: 0, credit: 4 }]).map(l => [l.debit, l.credit]), [[0, 4], [4, 0]]);
63 +});
64 +
65 +test('integration: chart seed is idempotent; parent relationships and company isolation', async () => {
66 + await reset();
67 + assert.equal((await ledger.seedDefaultChart()).added, 19);
68 + assert.equal((await ledger.seedDefaultChart()).added, 0);
69 + assert.equal((await ledger.listAccounts()).length, 19);
70 + await assert.rejects(ledger.addAccount({ code: '101', name: 'duplicate', type: 'asset', level: 'general', parentCode: '1' }));
71 + const general = await ledger.addAccount({ code: '107', name: 'دیگر دارایی', type: 'asset', level: 'general', parentCode: '1' });
72 + assert.equal(general.companyId, 'c1');
73 + select('c2');
74 + assert.equal((await ledger.listAccounts()).length, 0);
75 + assert.equal((await ledger.seedDefaultChart()).added, 19);
76 +});
77 +
78 +test('integration: overlapping periods rejected but same calendar interval is allowed in another company', async () => {
79 + await reset();
80 + const p = await ledger.createPeriod({ name: 'سال', ...year });
81 + assert.ok(p.id);
82 + await assert.rejects(ledger.createPeriod({ name: 'همپوشان', startDate: '1405/10/01', endDate: '1406/01/01' }), /هم‌پوشانی/);
83 + await ledger.createPeriod({ name: 'بعدی', startDate: '1406/01/01', endDate: '1406/12/29' });
84 + select('c2');
85 + const separate = await ledger.createPeriod({ name: 'شرکت دوم', ...year });
86 + assert.equal(separate.companyId, 'c2');
87 +});
88 +
89 +test('integration: posting account cannot gain a child after financial movements', async () => {
90 + const { period, cash, sales } = await setup();
91 + await ledger.postJournal(balanced(period, cash, sales));
92 + await assert.rejects(ledger.addAccount({
93 + code: '10101', name: 'صندوق زیرمجموعه', level: 'subsidiary', type: 'asset', parentCode: cash.code
94 + }), /گردش مالی/);
95 + assert.equal((await ledger.listAccounts()).length, 19);
96 +});
97 +
98 +test('integration: atomic posting, balanced trial balance and duplicate-source rejection', async () => {
99 + const { period, cash, sales } = await setup();
100 + const source = balanced(period, cash, sales, 'inv-42');
101 + const posted = await ledger.postJournal(source);
102 + assert.equal(posted.status, 'posted');
103 + assert.equal((await ledger.getJournal(posted.id)).lines.length, 2);
104 + assert.equal((await ledger.listJournals()).length, 1);
105 + const trial = await ledger.trialBalance({ periodId: period.id });
106 + assert.deepEqual(trial.totals, { debit: 10000, credit: 10000 });
107 + assert.equal(trial.rows.length, 2);
108 + await assert.rejects(ledger.postJournal(source), /تکرار|ثبت دوباره/);
109 + assert.equal((await entries('journal_entries')).length, 1);
110 + assert.equal((await entries('journal_lines')).length, 2);
111 +});
112 +
113 +test('integration: posting failures roll back all journal tables', async () => {
114 + const { period, cash, sales } = await setup();
115 + const invalid = balanced(period, cash, sales);
116 + invalid.lines[1].credit = 9000;
117 + await assert.rejects(ledger.postJournal(invalid), /تراز نیست/);
118 + assert.equal((await entries('journal_entries')).length, 0);
119 + assert.equal((await entries('journal_lines')).length, 0);
120 + invalid.lines[1].credit = 10000;
121 + invalid.lines[1].accountId = 'other-company-account';
122 + await assert.rejects(ledger.postJournal(invalid), /شرکت دیگر|غیرمجاز/);
123 + assert.equal((await entries('journal_entries')).length, 0);
124 +});
125 +
126 +test('integration: draft may be unbalanced; posting draft requires balance', async () => {
127 + const { period, cash } = await setup();
128 + const draft = await ledger.saveDraftJournal({
129 + periodId: period.id, date: '1405/04/22',
130 + lines: [{ accountId: cash.id, debit: 100, credit: 0 }]
131 + });
132 + assert.equal(draft.status, 'draft');
133 + await assert.rejects(ledger.postDraftJournal(draft.id), /سطرها|تراز نیست|نامعتبر/);
134 + assert.equal((await ledger.getJournal(draft.id)).status, 'draft');
135 + assert.equal((await ledger.trialBalance()).rows.length, 0);
136 + await assert.rejects(ledger.closePeriod(period.id), /پیش‌نویس/);
137 +});
138 +
139 +test('integration: editing and finalizing a draft is atomic; failed finalization leaves draft unchanged', async () => {
140 + const { period, cash, sales } = await setup();
141 + const draft = await ledger.saveDraftJournal({
142 + periodId: period.id, date: '1405/07/18',
143 + lines: [{ accountId: cash.id, debit: 1000, credit: 0 }]
144 + });
145 + const invalid = {
146 + periodId: period.id, date: '1405/07/19',
147 + lines: [{ accountId: cash.id, debit: 2000, credit: 0 }, { accountId: sales.id, debit: 0, credit: 1000 }]
148 + };
149 + await assert.rejects(ledger.updateDraftJournal(draft.id, invalid, { post: true }), /تراز نیست/);
150 + const original = await ledger.getJournal(draft.id);
151 + assert.equal(original.status, 'draft');
152 + assert.equal(original.date, '1405/07/18');
153 + assert.equal(original.lines.length, 1);
154 + await ledger.updateDraftJournal(draft.id, { ...invalid, lines: [
155 + { accountId: cash.id, debit: 2000, credit: 0 },
156 + { accountId: sales.id, debit: 0, credit: 2000 }
157 + ] }, { post: true });
158 + assert.equal((await ledger.getJournal(draft.id)).status, 'posted');
159 + assert.equal((await ledger.getJournal(draft.id)).lines.length, 2);
160 + await assert.rejects(ledger.updateDraftJournal(draft.id, invalid), /پیش‌نویس/);
161 + assert.equal((await entries('journal_lines')).length, 2);
162 +});
163 +
164 +test('integration: reversal is immutable, balanced and cannot be repeated', async () => {
165 + const { period, cash, sales } = await setup();
166 + const original = await ledger.postJournal(balanced(period, cash, sales));
167 + const reversed = await ledger.reverseJournal(original.id, { periodId: period.id, date: '1405/07/19' });
168 + assert.equal(reversed.reversalOfId, original.id);
169 + assert.equal((await ledger.getJournal(original.id)).reversedById, reversed.id);
170 + const rows = (await ledger.getJournal(reversed.id)).lines;
171 + assert.deepEqual(rows.map(r => [r.debit, r.credit]), [[0, 10000], [10000, 0]]);
172 + assert.deepEqual((await ledger.trialBalance()).totals, { debit: 20000, credit: 20000 });
173 + assert.equal((await ledger.trialBalance()).rows.every(r => r.balance === 0), true);
174 + await assert.rejects(ledger.reverseJournal(original.id, { periodId: period.id, date: '1405/07/20' }), /قابل برگشت نیست/);
175 + assert.equal((await entries('journal_entries')).length, 2);
176 +});
177 +
178 +test('integration: draft removal is atomic; posted journals are immutable', async () => {
179 + const { period, cash, sales } = await setup();
180 + const draft = await ledger.saveDraftJournal({
181 + periodId: period.id, date: '1405/07/18',
182 + lines: [{ accountId: cash.id, debit: 8000, credit: 0 }]
183 + });
184 + await ledger.discardDraftJournal(draft.id);
185 + assert.equal((await entries('journal_entries')).length, 0);
186 + assert.equal((await entries('journal_lines')).length, 0);
187 + const posted = await ledger.postJournal(balanced(period, cash, sales));
188 + await assert.rejects(ledger.discardDraftJournal(posted.id), /پیش‌نویس/);
189 + assert.equal((await entries('journal_entries')).length, 1);
190 +});
191 +
192 +test('integration: reversal works when a previously posted account was deactivated', async () => {
193 + const { period, cash, sales } = await setup();
194 + const posted = await ledger.postJournal(balanced(period, cash, sales));
195 + await StorageService.put('account_chart', { ...cash, active: false });
196 + await assert.rejects(ledger.postJournal(balanced(period, cash, sales)), /غیرفعال/);
197 + const reversed = await ledger.reverseJournal(posted.id, { periodId: period.id, date: '1405/07/20' });
198 + assert.equal(reversed.status, 'posted');
199 + assert.equal((await ledger.trialBalance()).rows.every(r => r.balance === 0), true);
200 +});
201 +
202 +test('integration: closing period prevents posting and reversing; company data cannot cross', async () => {
203 + const { period, cash, sales } = await setup();
204 + const j = await ledger.postJournal(balanced(period, cash, sales));
205 + await ledger.closePeriod(period.id);
206 + await assert.rejects(ledger.postJournal(balanced(period, cash, sales)), /بسته/);
207 + await assert.rejects(ledger.reverseJournal(j.id, { periodId: period.id, date: '1405/07/19' }), /بسته/);
208 + select('c2');
209 + assert.equal((await ledger.listJournals()).length, 0);
210 + assert.equal((await DataScope.list('journal_entries')).length, 0);
211 + await assert.rejects(ledger.getJournal(j.id), /این شرکت/);
212 + await assert.rejects(ledger.reverseJournal(j.id, { periodId: period.id, date: '1405/07/19' }), /قابل برگشت نیست/);
213 +});
214 +
215 +test('integration: Settings backup contains V2 ledger and restores it atomically', async () => {
216 + const { period, cash, sales } = await setup();
217 + await ledger.postJournal(balanced(period, cash, sales, 'restore-test'));
218 + await StorageService.put('users', { id: 'some-user', username: 'demo', pwHash: 'test-hash', pwSalt: 'test-salt' });
219 + await StorageService.put('account_chart', { id: 'foreign-account', companyId: 'c2', code: '1', name: 'Foreign assets', type: 'asset', level: 'group' });
220 + const backup = await SettingsController.exportBackup();
221 + assert.equal(backup.data.users[0].pwHash, undefined);
222 + assert.equal((await StorageService.get('users', 'some-user')).pwHash, 'test-hash');
223 + assert.equal(backup.data.account_chart.length, 19);
224 + assert.equal(backup.data.fiscal_periods.length, 1);
225 + assert.equal(backup.data.journal_entries.length, 1);
226 + assert.equal(backup.data.journal_lines.length, 2);
227 + await reset();
228 + const first = await SettingsController.importBackup(backup, { mode: 'merge' });
229 + assert.ok(first.added >= 17);
230 + assert.deepEqual((await ledger.trialBalance()).totals, { debit: 10000, credit: 10000 });
231 + const again = await SettingsController.importBackup(backup, { mode: 'merge' });
232 + assert.ok(again.skipped >= 17);
233 + assert.equal((await ledger.listJournals()).length, 1);
234 +});
235 +
236 +test('integration: broken V2 restore rolls back all stores and rejects cross-company ID collisions', async () => {
237 + const { period, cash, sales } = await setup();
238 + await ledger.postJournal(balanced(period, cash, sales));
239 + const backup = await SettingsController.exportBackup();
240 + await reset();
241 + const broken = structuredClone(backup);
242 + broken.data.journal_lines[0].accountId = 'missing-account';
243 + await assert.rejects(SettingsController.importBackup(broken), /حساب|ناموجود/);
244 + assert.equal((await entries('account_chart')).length, 0);
245 + assert.equal((await entries('journal_entries')).length, 0);
246 + select('c2');
247 + await StorageService.put('account_chart', { id: backup.data.account_chart[0].id,
248 + companyId: 'c2', code: '1', name: 'Foreign', type: 'asset', level: 'group' });
249 + select('c1');
250 + await assert.rejects(SettingsController.importBackup(backup), /شرکت دیگر/);
251 + assert.equal((await ledger.listAccounts()).length, 0);
252 + assert.equal((await entries('journal_entries')).length, 0);
253 +});
254 +
255 +test('integration: backup export and restore preserves accounting records without user credentials', async () => {
256 + const { period, cash, sales } = await setup();
257 + await ledger.postJournal(balanced(period, cash, sales));
258 + const snapshot = await StorageService.exportAll();
259 + assert.equal(snapshot.data.journal_entries.length, 1);
260 + assert.equal(snapshot.data.journal_lines.length, 2);
261 + assert.equal(snapshot.data.account_chart.length, 19);
262 + await StorageService.clearAll();
263 + await StorageService.importAll(snapshot);
264 + select('c1');
265 + assert.equal((await ledger.getJournal(snapshot.data.journal_entries[0].id)).lines.length, 2);
266 + assert.deepEqual((await ledger.trialBalance()).totals, { debit: 10000, credit: 10000 });
267 +});
268 +
269 +test('role security: normal user cannot alter chart, periods, manual journals or restore backup',async()=>{
270 + const {period,cash,sales}=await setup();
271 + const backup=await SettingsController.exportBackup();
272 + Auth.currentUser={id:'limited-user',role:'user',username:'cashier',companyIds:['c1']};
273 + await assert.rejects(ledger.addAccount({code:'900',name:'unauthorized',level:'group',type:'asset'}),/مدیر/);
274 + await assert.rejects(ledger.createPeriod({name:'unauthorized',...year}),/مدیر/);
275 + await assert.rejects(ledger.seedDefaultChart(),/مدیر/);
276 + await assert.rejects(ledger.postJournal(balanced(period,cash,sales)),/مدیر/);
277 + await assert.rejects(SettingsController.importBackup(backup),/مدیر/);
278 + assert.equal((await ledger.listJournals()).length,0);
279 +});
tests/cdp-actions-smoke.cjs new
+3
@@ -0,0 +1,3 @@
1 +process.env.CDP_PORT='9232';
2 +process.env.CDP_EXPR=`(async()=>{const wait=()=>new Promise(r=>setTimeout(r,500));const results={};await window.FINORA.Router.go('invoices');let b=[...document.querySelectorAll('#pageContent button')].find(x=>x.textContent.includes('فاکتور جدید'));b?.click();await wait();results.invoice=!!document.querySelector('.modal-backdrop');window.FINORA.Modal.closeAll();await window.FINORA.Router.go('products');b=[...document.querySelectorAll('#pageContent button')].find(x=>x.textContent.includes('کالای جدید')||x.textContent.includes('کالا جدید')||x.textContent.includes('افزودن کالا'));results.productButton=b?.outerHTML||'NOT_FOUND';b?.click();await wait();results.product=!!document.querySelector('.modal-backdrop');window.FINORA.Modal.closeAll();await window.FINORA.Router.go('contacts');b=[...document.querySelectorAll('#pageContent button')].find(x=>x.textContent.includes('شخص جدید'));b?.click();await wait();results.contact=!!document.querySelector('.modal-backdrop');window.FINORA.Modal.closeAll();results.username=window.FINORA.Auth.current()?.username;return JSON.stringify(results)})()`;
3 +require('./cdp-smoke.cjs');
\ No newline at end of file
tests/cdp-click-smoke.cjs new
+3
@@ -0,0 +1,3 @@
1 +process.env.CDP_PORT='9231';
2 +process.env.CDP_EXPR=`(async()=>{const b=document.querySelector('#pageContent button[onclick]');b.click();await new Promise(r=>setTimeout(r,600));return JSON.stringify({hash:location.hash,view:typeof window.InvoicesView,html:document.getElementById('pageContent')?.innerText.slice(0,200),error:document.querySelector('.toast')?.innerText})})()`;
3 +require('./cdp-smoke.cjs');
\ No newline at end of file
tests/cdp-login-existing-smoke.cjs new
+3
@@ -0,0 +1,3 @@
1 +process.env.CDP_PORT='9232';
2 +process.env.CDP_EXPR=`document.getElementById('faUser').value='مدیر';document.getElementById('faPass').value='SmokeTestOnly-83471!';document.getElementById('faSubmit').click();'submitted'`;
3 +require('./cdp-smoke.cjs');
\ No newline at end of file
tests/cdp-login-smoke.cjs new
+3
@@ -0,0 +1,3 @@
1 +process.env.CDP_PORT='9231';
2 +process.env.CDP_EXPR=`document.getElementById('faPass').value='SmokeTestOnly-83471!';document.getElementById('faPass2').value='SmokeTestOnly-83471!';document.getElementById('faSubmit').click();'submitted'`;
3 +require('./cdp-smoke.cjs');
\ No newline at end of file
tests/cdp-phase1-tauri-login-smoke.cjs new
+3
@@ -0,0 +1,3 @@
1 +process.env.CDP_PORT='9242';
2 +process.env.CDP_EXPR=`document.getElementById('faPass').value='SmokeTestOnly-83471!';document.getElementById('faPass2').value='SmokeTestOnly-83471!';document.getElementById('faSubmit').click();'submitted'`;
3 +require('./cdp-smoke.cjs');
tests/cdp-phase1-tauri-ui-smoke.cjs new
+59
@@ -0,0 +1,59 @@
1 +// UI smoke on a disposable browser profile, after a user has initialized test login.
2 +// Run with a local Vite preview server and Chrome CDP on port 9242.
3 +process.env.CDP_PORT = '9242';
4 +process.env.CDP_EXPR = `(async () => {
5 + const wait = ms => new Promise(resolve => setTimeout(resolve, ms));
6 + const assert = (yes, reason) => { if (!yes) throw new Error(reason); };
7 + const results = {};
8 + assert(!document.getElementById('finoraAuthOverlay'), 'Test login is required');
9 + await window.FINORA.Router.go('dashboard');
10 + await wait(300);
11 + await window.FINORA.Router.go('accounting');
12 + for (let i = 0; i < 30 && !document.getElementById('pageContent')?.textContent.includes('حسابداری دوبل'); i++) await wait(100);
13 + assert(window.AccountingView, 'Accounting view not mounted');
14 + assert(document.getElementById('pageContent')?.textContent.includes('حسابداری دوبل'), 'Accounting route failed');
15 + await window.AccountingView.switchTab('periods');
16 + if (!window.AccountingView.periods.length) {
17 + window.AccountingView.openPeriodModal();
18 + assert(document.getElementById('acPeriodName'), 'Fiscal-period modal is missing');
19 + document.getElementById('acPeriodName').value = 'دوره تست ۱۴۰۵';
20 + document.getElementById('acPeriodStart').value = '1405/01/01';
21 + document.getElementById('acPeriodEnd').value = '1405/12/29';
22 + await window.AccountingView.savePeriod();
23 + }
24 + assert(window.AccountingView.periods.length > 0, 'Fiscal period not persisted');
25 + results.period = 'ok';
26 + await window.AccountingView.switchTab('accounts');
27 + window.AccountingView.seedChart();
28 + document.querySelector('.modal-footer [data-action="confirm"]').click();
29 + await wait(250);
30 + assert(window.AccountingView.accounts.some(a => a.code === '101'), 'Chart seed failed');
31 + results.chart = window.AccountingView.accounts.length;
32 + await window.AccountingView.switchTab('journals');
33 + await window.AccountingView.openJournalModal();
34 + assert(document.getElementById('acJournalLines'), 'Manual journal form did not open');
35 + const cash = window.AccountingView.accounts.find(a => a.code === '101');
36 + const sales = window.AccountingView.accounts.find(a => a.code === '401');
37 + const selects = document.querySelectorAll('.ac-line-account');
38 + const debit = document.querySelectorAll('.ac-line-debit');
39 + const credit = document.querySelectorAll('.ac-line-credit');
40 + assert(selects.length === 2, 'Expected two journal lines');
41 + selects[0].value = cash.id;
42 + selects[1].value = sales.id;
43 + debit[0].value = '12,000';
44 + credit[0].value = '0';
45 + debit[1].value = '0';
46 + credit[1].value = '12,000';
47 + document.getElementById('acJournalDate').value = '1405/07/18';
48 + document.getElementById('acJournalDescription').value = 'سند تست مرورگر';
49 + await window.AccountingView.saveJournal('posted');
50 + assert(window.AccountingView.journals.length > 0, 'Journal did not persist');
51 + results.journal = window.AccountingView.journals[0].status;
52 + await window.AccountingView.switchTab('trial');
53 + assert(document.getElementById('accountingWorkbench').textContent.includes('موجودی نقد و بانک') && document.getElementById('accountingWorkbench').textContent.includes('فروش کالا'), 'Trial balance missing accounts');
54 + results.trial = 'ok';
55 + const problems = [...document.querySelectorAll('.toast-error')].map(x => x.textContent);
56 + assert(problems.length === 0, 'Unexpected UI error: ' + problems.join('; '));
57 + return JSON.stringify(results);
58 +})()`;
59 +require('./cdp-smoke.cjs');
tests/cdp-phase1-ui-smoke.cjs new
+58
@@ -0,0 +1,58 @@
1 +// Phase-1 smoke. Run only with a disposable CDP browser profile.
2 +process.env.CDP_PORT = process.env.CDP_PORT || '9231';
3 +process.env.CDP_EXPR = `(async () => {
4 + const wait = ms => new Promise(resolve => setTimeout(resolve, ms));
5 + const assert = (yes, reason) => { if (!yes) throw new Error(reason); };
6 + const results = {};
7 + assert(!document.getElementById('finoraAuthOverlay'), 'Test login is required');
8 + await window.FINORA.Router.go('dashboard');
9 + await wait(200);
10 + await window.FINORA.Router.go('accounting');
11 + for (let i = 0; i < 30 && !document.getElementById('pageContent')?.textContent.includes('حسابداری دوبل'); i++) await wait(100);
12 + assert(window.AccountingView, 'Accounting view not mounted');
13 + assert(document.getElementById('pageContent')?.textContent.includes('حسابداری دوبل'), 'Accounting route failed');
14 + await window.AccountingView.switchTab('periods');
15 + if (!window.AccountingView.periods.length) {
16 + window.AccountingView.openPeriodModal();
17 + assert(document.getElementById('acPeriodName'), 'Fiscal-period modal is missing');
18 + document.getElementById('acPeriodName').value = 'دوره تست ۱۴۰۵';
19 + document.getElementById('acPeriodStart').value = '1405/01/01';
20 + document.getElementById('acPeriodEnd').value = '1405/12/29';
21 + await window.AccountingView.savePeriod();
22 + }
23 + assert(window.AccountingView.periods.length > 0, 'Fiscal period not persisted');
24 + results.period = 'ok';
25 + await window.AccountingView.switchTab('accounts');
26 + window.AccountingView.seedChart();
27 + document.querySelector('.modal-footer [data-action="confirm"]').click();
28 + await wait(250);
29 + assert(window.AccountingView.accounts.some(a => a.code === '101'), 'Chart seed failed');
30 + results.chart = window.AccountingView.accounts.length;
31 + await window.AccountingView.switchTab('journals');
32 + await window.AccountingView.openJournalModal();
33 + assert(document.getElementById('acJournalLines'), 'Manual journal form did not open');
34 + const cash = window.AccountingView.accounts.find(a => a.code === '101');
35 + const sales = window.AccountingView.accounts.find(a => a.code === '401');
36 + const selects = document.querySelectorAll('.ac-line-account');
37 + const debit = document.querySelectorAll('.ac-line-debit');
38 + const credit = document.querySelectorAll('.ac-line-credit');
39 + assert(selects.length === 2, 'Expected two journal lines');
40 + selects[0].value = cash.id;
41 + selects[1].value = sales.id;
42 + debit[0].value = '12,000';
43 + credit[0].value = '0';
44 + debit[1].value = '0';
45 + credit[1].value = '12,000';
46 + document.getElementById('acJournalDate').value = '1405/07/18';
47 + document.getElementById('acJournalDescription').value = 'سند تست مرورگر';
48 + await window.AccountingView.saveJournal('posted');
49 + assert(window.AccountingView.journals.some(j => j.status === 'posted'), 'Journal did not persist');
50 + results.journal = 'posted';
51 + await window.AccountingView.switchTab('trial');
52 + assert(document.getElementById('accountingWorkbench').textContent.includes('موجودی نقد و بانک') && document.getElementById('accountingWorkbench').textContent.includes('فروش کالا'), 'Trial balance missing accounts');
53 + results.trial = 'ok';
54 + const problems = [...document.querySelectorAll('.toast-error')].map(x => x.textContent);
55 + assert(problems.length === 0, 'Unexpected UI error: ' + problems.join('; '));
56 + return JSON.stringify(results);
57 +})()`;
58 +require('./cdp-smoke.cjs');
tests/cdp-phase2-invoice-smoke.cjs new
+43
@@ -0,0 +1,43 @@
1 +// Disposable browser profile must already be initialized and phase 2 activated.
2 +process.env.CDP_PORT=process.env.CDP_PORT||'9252';
3 +process.env.CDP_EXPR=`(async()=>{
4 + const wait=ms=>new Promise(r=>setTimeout(r,ms));
5 + const assert=(ok,m)=>{if(!ok)throw Error(m)};
6 + const c=await window.ContactController.create({name:'مشتری تست فاز دو',role:'both'});
7 + const p=await window.ProductController.createProduct({name:'کالای تست فاز دو',
8 + code:'V2-DEMO',trackInventory:true,buyPrice:100,sellPrice:200});
9 + await FINORA.Router.go('invoices');await wait(300);
10 + await window.InvoiceFormView.open();await wait(200);
11 + assert(document.getElementById('invWarehouse'),'Warehouse picker missing');
12 + document.getElementById('invKind').value='purchase';
13 + await window.InvoiceFormView._onKindChange();
14 + document.getElementById('invDate').value='1405/07/18';
15 + const contact=document.getElementById('invContactSearch');
16 + contact.value='مشتری تست فاز دو';
17 + window.InvoiceFormView._showContactOptions(true);
18 + const contactOption=document.querySelector('.contact-option[data-id="'+c.id+'"]');
19 + assert(contactOption,'Contact search failed');
20 + contactOption.dispatchEvent(new MouseEvent('mousedown',{bubbles:true}));
21 + const prod=document.querySelector('.row-product-search');
22 + prod.value='V2-DEMO';
23 + window.InvoiceFormView._showProductOptions(0,true);
24 + const option=document.querySelector('.product-option[data-id="'+p.id+'"]');
25 + assert(option,'Product search failed');
26 + option.dispatchEvent(new MouseEvent('mousedown',{bubbles:true}));
27 + const qty=document.querySelector('.row-qty');
28 + qty.value='10';window.InvoiceFormView._onFieldChange(0,'qty','10');
29 + const price=document.querySelector('.row-price');
30 + price.value='100';window.InvoiceFormView._onFieldChange(0,'price','100');
31 + await window.InvoiceFormView._save(false);await wait(120);
32 + const invoices=await FINORA.Storage.getAll('invoices');
33 + const saved=invoices.find(i=>i.contactId===c.id&&i.kind==='purchase');
34 + assert(saved&&saved.financePosted,'Invoice was not financially posted');
35 + const journals=await FINORA.Storage.getAll('journal_entries');
36 + const movements=await FINORA.Storage.getAll('stock_movements');
37 + assert(journals.some(j=>j.sourceId===saved.id),'Ledger source missing');
38 + assert(movements.some(m=>m.refId===saved.id&&m.type==='in'),'Inventory entry missing');
39 + assert(!document.querySelector('.modal-backdrop'),'Invoice modal failed to close');
40 + return JSON.stringify({invoice:saved.number,amount:saved.grandTotal,
41 + journals:journals.length,stock:movements.length});
42 +})()`;
43 +require('./cdp-smoke.cjs');
tests/cdp-phase2-login-smoke.cjs new
+3
@@ -0,0 +1,3 @@
1 +process.env.CDP_PORT='9252';
2 +process.env.CDP_EXPR=`document.getElementById('faPass').value='SmokeTestOnly-83471!';document.getElementById('faPass2').value='SmokeTestOnly-83471!';document.getElementById('faSubmit').click();'submitted'`;
3 +require('./cdp-smoke.cjs');
tests/cdp-phase2-sale-smoke.cjs new
+43
@@ -0,0 +1,43 @@
1 +process.env.CDP_PORT=process.env.CDP_PORT||'9252';
2 +process.env.CDP_EXPR=`(async()=>{
3 + const wait=ms=>new Promise(r=>setTimeout(r,ms));
4 + const assert=(yes,msg)=>{if(!yes)throw Error(msg)};
5 + await FINORA.Router.go('treasury');await wait(250);
6 + if(!(await FINORA.Storage.getAll('treasury')).some(a=>a.recordType==='account')){
7 + await window.TreasuryView.openAccountModal();
8 + document.getElementById('accName').value='صندوق فاز دوم';
9 + document.getElementById('accInitialBalance').value='0';
10 + await window.TreasuryView.saveAccount(null);
11 + }
12 + assert(!document.querySelector('.modal-backdrop'),'Cash account form failed to save');
13 + const accounts=(await FINORA.Storage.getAll('treasury')).filter(a=>a.recordType==='account');
14 + assert(accounts.length>=1 && accounts[0].ledgerAccountId,'Treasury subledger missing');
15 + const person=(await FINORA.Storage.getAll('contacts')).find(x=>x.name.includes('فاز دو'));
16 + const product=(await FINORA.Storage.getAll('products')).find(x=>x.code==='V2-DEMO');
17 + await FINORA.Router.go('invoices');await wait(250);
18 + await window.InvoiceFormView.open();await wait(120);
19 + document.getElementById('invKind').value='sale';
20 + await window.InvoiceFormView._onKindChange();
21 + document.getElementById('invDate').value='1405/07/18';
22 + const input=document.getElementById('invContactSearch');
23 + input.value=person.name;window.InvoiceFormView._showContactOptions(true);
24 + document.querySelector('.contact-option[data-id="'+person.id+'"]').dispatchEvent(new MouseEvent('mousedown',{bubbles:true}));
25 + const prod=document.querySelector('.row-product-search');
26 + prod.value='V2-DEMO';window.InvoiceFormView._showProductOptions(0,true);
27 + document.querySelector('.product-option[data-id="'+product.id+'"]').dispatchEvent(new MouseEvent('mousedown',{bubbles:true}));
28 + document.querySelector('.row-qty').value='3';window.InvoiceFormView._onFieldChange(0,'qty','3');
29 + document.querySelector('.row-price').value='200';window.InvoiceFormView._onFieldChange(0,'price','200');
30 + document.getElementById('invPayment').value='partial';
31 + window.InvoiceFormView._onPaymentChange();
32 + document.getElementById('invPaidAmount').value='200';window.InvoiceFormView._recalc();
33 + await window.InvoiceFormView._save(false);await wait(150);
34 + const sale=(await FINORA.Storage.getAll('invoices')).filter(x=>x.kind==='sale'&&x.contactId===person.id).sort((a,b)=>Number(a.number)-Number(b.number)).at(-1);
35 + assert(sale?.financePosted,'Sale not financially posted');
36 + assert(sale.paidAmount===200 && sale.remaining===400,'Sale payment mismatch');
37 + const lines=await FINORA.Storage.getAll('journal_lines');
38 + assert(lines.some(x=>x.accountId===accounts[0].ledgerAccountId && x.debit===200),'Cash ledger mapping missing');
39 + return JSON.stringify({sale:sale.number,paid:sale.paidAmount,remaining:sale.remaining,
40 + stockMoves:(await FINORA.Storage.getAll('stock_movements')).length,
41 + journals:(await FINORA.Storage.getAll('journal_entries')).length});
42 +})()`;
43 +require('./cdp-smoke.cjs');
tests/cdp-phase2-ui-smoke.cjs new
+36
@@ -0,0 +1,36 @@
1 +// Runs in an isolated Chrome profile; never point to a live user session.
2 +process.env.CDP_PORT=process.env.CDP_PORT||'9252';
3 +process.env.CDP_EXPR=`(async()=>{
4 + const wait=ms=>new Promise(r=>setTimeout(r,ms));
5 + const assert=(yes,msg)=>{if(!yes)throw Error(msg)};
6 + assert(!document.getElementById('finoraAuthOverlay'),'test login missing');
7 + await FINORA.Router.go('accounting');await wait(200);
8 + const view=window.AccountingView;
9 + assert(view&&document.getElementById('pageContent')?.textContent.includes('حسابداری دوبل'),'accounting missing');
10 + await view.switchTab('periods');
11 + if(!view.periods.length){
12 + view.openPeriodModal();
13 + document.getElementById('acPeriodName').value='فاز دوم آزمایشی';
14 + document.getElementById('acPeriodStart').value='1405/01/01';
15 + document.getElementById('acPeriodEnd').value='1405/12/29';
16 + await view.savePeriod();
17 + }
18 + await view.switchTab('accounts');
19 + view.seedChart();
20 + document.querySelector('.modal-footer [data-action="confirm"]').click();
21 + await wait(200);
22 + assert(view.accounts.some(x=>x.code==='402'),'Phase2 chart missing');
23 + await view.switchTab('integration');
24 + assert(document.getElementById('accountingWorkbench')?.textContent.includes('فعال‌سازی'),'Activation UI missing');
25 + view.activateRetail();
26 + document.querySelector('.modal-footer [data-action="confirm"]').click();
27 + await wait(250);
28 + const status=document.getElementById('accountingWorkbench')?.textContent;
29 + assert(status.includes('یکپارچه فعال است'),'Activation failed: '+status.slice(0,180));
30 + view.openWarehouse();
31 + document.getElementById('acWhName').value='انبار آزمون';
32 + await view.saveWarehouse();
33 + assert((await view.renderIntegration()).includes('انبارگردانی جدید'),'Stocktake controls missing');
34 + return JSON.stringify({phase:'2',activation:true,warehouses:'ok',charts:view.accounts.length});
35 +})()`;
36 +require('./cdp-smoke.cjs');
tests/cdp-smoke.cjs new
+14
@@ -0,0 +1,14 @@
1 +const http=require('http');
2 +const port=Number(process.env.CDP_PORT||9229);
3 +http.get(`http://127.0.0.1:${port}/json`,r=>{let raw='';r.on('data',x=>raw+=x);r.on('end',()=>{
4 + const pages=JSON.parse(raw),url=pages.find(p=>p.type==='page')?.webSocketDebuggerUrl;
5 + if(!url)throw Error('No page');
6 + const ws=new WebSocket(url);
7 + ws.onopen=()=>{const expression=process.env.CDP_EXPR||'JSON.stringify({title:document.title,overlay:!!document.getElementById("finoraAuthOverlay"),page:document.getElementById("pageContent")?.innerText.slice(0,300),view:typeof window.InvoicesView,button:document.querySelector("#pageContent button")?.outerHTML})';ws.send(JSON.stringify({id:1,method:'Runtime.evaluate',params:{expression,returnByValue:true,awaitPromise:true}}));};
8 + ws.onmessage=e=>{const msg=JSON.parse(e.data);if(msg.id===1){
9 + console.log(JSON.stringify(msg.result||msg.error));
10 + if(msg.error||msg.result?.exceptionDetails||msg.result?.result?.subtype==='error') process.exitCode=1;
11 + ws.close();
12 + }};
13 + ws.onerror=e=>{process.exitCode=1;console.error('CDP error',e.message);};
14 + });});
\ No newline at end of file
tests/entitlement.test.mjs new
+4
@@ -0,0 +1,4 @@
1 +import test from 'node:test';import assert from 'node:assert/strict';import {canonical,validateEntitlementPayload} from '../src/core/EntitlementVerifier.mjs';
2 +test('canonical payload is key-order stable',()=>assert.equal(canonical({b:2,a:1}),canonical({a:1,b:2})));
3 +test('entitlement is installation-bound',()=>assert.equal(validateEntitlementPayload({product:'Factor-easyPro',installationId:'other',perpetual:true,maxCompanies:1,maxUsers:1,maxDevices:1},'this'),false));
4 +test('entitlement enforces normalized caps',()=>assert.equal(validateEntitlementPayload({product:'Factor-easyPro',installationId:'x',perpetual:true,maxCompanies:6,maxUsers:4,maxDevices:1},'x'),false));
tests/ledger-reports.test.mjs new
+37
@@ -0,0 +1,37 @@
1 +import test from 'node:test';
2 +import assert from 'node:assert/strict';
3 +import {buildLedgerReports} from '../src/core/LedgerReports.mjs';
4 +const accounts=[
5 +{id:'cash',code:'101',name:'Cash',type:'asset'},
6 +{id:'stock',code:'103',name:'Inventory',type:'asset'},
7 +{id:'sales',code:'401',name:'Sales',type:'revenue'},
8 +{id:'cogs',code:'501',name:'COGS',type:'expense'}];
9 +const journals=[{id:'purchase',status:'posted',date:'1405/01/01',periodId:'p'},{id:'sale',status:'posted',date:'1405/01/02',periodId:'p'},{id:'draft',status:'draft',date:'1405/01/02',periodId:'p'}];
10 +const lines=[
11 +{journalId:'purchase',accountId:'stock',debit:100,credit:0},{journalId:'purchase',accountId:'cash',debit:0,credit:100},
12 +{journalId:'sale',accountId:'cash',debit:200,credit:0},{journalId:'sale',accountId:'sales',debit:0,credit:200},
13 +{journalId:'sale',accountId:'cogs',debit:70,credit:0},{journalId:'sale',accountId:'stock',debit:0,credit:70},
14 +{journalId:'draft',accountId:'sales',debit:900,credit:0}];
15 +test('posted journal reports use historical COGS, exclude drafts, and balance',()=>{
16 +const r=buildLedgerReports(accounts,journals,lines);
17 +assert.equal(r.profitLoss.netProfit,130);assert.equal(r.profitLoss.expenses,70);
18 +assert.equal(r.balanceSheet.difference,0);assert.equal(r.postedCount,2);assert.equal(r.detail.length,6);
19 +assert.deepEqual(r.totals,{debit:370,credit:370});
20 +});
21 +test('report date filter and invalid ledger detection',()=>{
22 +const r=buildLedgerReports(accounts,journals,lines,{to:'1405/01/01'});
23 +assert.equal(r.profitLoss.netProfit,0);assert.equal(r.postedCount,1);
24 +assert.throws(()=>buildLedgerReports(accounts,journals,[...lines,{journalId:'sale',accountId:'cash',debit:1,credit:0}]),/تراز نیست/);
25 +});
26 +test('balance sheet stays cumulative when P&L is filtered to later period',()=>{
27 + const extended=[...journals,{id:'later',status:'posted',date:'1405/02/01',periodId:'q'}];
28 + const movements=[...lines,{journalId:'later',accountId:'cash',debit:40,credit:0},{journalId:'later',accountId:'sales',debit:0,credit:40}];
29 + const r=buildLedgerReports(accounts,extended,movements,{periodId:'q'});
30 + assert.equal(r.profitLoss.netProfit,40);
31 + assert.equal(r.balanceSheet.assets,170);
32 + assert.equal(r.balanceSheet.equityWithProfit,170);
33 + assert.equal(r.balanceSheet.difference,0);
34 + assert.equal(r.postedCount,1);
35 + assert.equal(r.trial.length,2);
36 + assert.equal(r.cumulativeTrial.length,4);
37 +});
tests/license-policy.test.mjs new
+7
@@ -0,0 +1,7 @@
1 +import test from 'node:test';import assert from 'node:assert/strict';import {trialStatus,licensedStatus} from '../src/core/LicensePolicy.mjs';
2 +const DAY=86400000,now=Date.UTC(2026,9,7);
3 +test('trial expires at 15 days',()=>assert.equal(trialStatus({trialStartedAt:new Date(now-15*DAY).toISOString(),issuedInvoiceCount:0},now).readOnly,true));
4 +test('trial expires at 20 issued invoices',()=>assert.equal(trialStatus({trialStartedAt:new Date(now).toISOString(),issuedInvoiceCount:20},now).readOnly,true));
5 +test('trial remains writable before both limits',()=>assert.equal(trialStatus({trialStartedAt:new Date(now-14*DAY).toISOString(),issuedInvoiceCount:19},now).readOnly,false));
6 +test('licensed offline lease warns at day 25',()=>assert.equal(licensedStatus({active:true,perpetual:true,lastOnlineCheckAt:new Date(now-25*DAY).toISOString()},now).warning,true));
7 +test('licensed offline lease is read only after day 30',()=>assert.equal(licensedStatus({active:true,perpetual:true,lastOnlineCheckAt:new Date(now-31*DAY).toISOString()},now).readOnly,true));
tests/retail-finance-core.test.mjs new
+26
@@ -0,0 +1,26 @@
1 +import test from 'node:test';
2 +import assert from 'node:assert/strict';
3 +import { allocateDiscount, receiveStock, issueStock, qtyUnits } from '../src/core/RetailFinanceCore.mjs';
4 +test('discount allocation uses integer largest remainder and never increases line value',()=>{
5 + const lines=[2,2,2,2,1].map(lineTotal=>({lineTotal}));
6 + const distribution=allocateDiscount(lines,3);
7 + assert.deepEqual(distribution.map(x=>x.netLineTotal),[1,1,1,2,1]);
8 + assert.equal(distribution.reduce((a,b)=>a+b.netLineTotal,0),6);
9 + for(const x of distribution)assert.ok(x.netLineTotal>=0&&x.netLineTotal<=x.lineTotal);
10 +});
11 +test('weighted average handles exact large integer rial amounts',()=>{
12 + const before={quantityUnits:3000,value:Number.MAX_SAFE_INTEGER-1000};
13 + const after=issueStock(before,1);
14 + assert.equal(after.quantityUnits,2000);
15 + assert.equal(after.value+after.cost,before.value);
16 + assert.ok(Number.isSafeInteger(after.cost));
17 +});
18 +test('fractional units validated and exact last-stock cost emptied',()=>{
19 + assert.equal(qtyUnits(.125),125);
20 + assert.throws(()=>qtyUnits(.0001));
21 + const first=receiveStock(null,2.5,2500);
22 + const last=issueStock(first,2.5);
23 + assert.equal(last.quantityUnits,0);
24 + assert.equal(last.value,0);
25 + assert.equal(last.cost,2500);
26 +});
tests/retail-migration.test.mjs new
+33
@@ -0,0 +1,33 @@
1 +import test from 'node:test';
2 +import assert from 'node:assert/strict';
3 +import 'fake-indexeddb/auto';
4 +import { StorageService } from '../src/core/StorageService.js';
5 +
6 +test('V2 schema upgrade from phase-one v5 preserves ledgers, stock and people',async()=>{
7 + const raw=await new Promise((resolve,reject)=>{
8 + const request=indexedDB.open('finora_pro_db',5);
9 + request.onupgradeneeded=()=>{
10 + const db=request.result;
11 + for(const name of ['companies','contacts','products','invoices',
12 + 'account_chart','fiscal_periods','journal_entries','journal_lines']) {
13 + if(!db.objectStoreNames.contains(name))db.createObjectStore(name,{keyPath:'id'});
14 + }
15 + const tx=request.transaction;
16 + tx.objectStore('invoices').put({id:'old-finance-inv',companyId:'company_default',number:'119'});
17 + tx.objectStore('journal_entries').put({id:'old-journal',companyId:'company_default',
18 + status:'posted',debit:100,credit:100});
19 + };
20 + request.onsuccess=()=>resolve(request.result);
21 + request.onerror=()=>reject(request.error);
22 + });
23 + raw.close();
24 + const db=await StorageService.init();
25 + assert.equal(db.version,6);
26 + assert.equal((await StorageService.get('invoices','old-finance-inv')).number,'119');
27 + assert.equal((await StorageService.get('journal_entries','old-journal')).debit,100);
28 + for(const store of ['warehouses','inventory_balances','stocktakes','stocktake_lines',
29 + 'settlements','account_mappings'])assert.ok(db.objectStoreNames.contains(store),store);
30 + const snapshot=await StorageService.exportAll();
31 + assert.equal(snapshot.data.invoices.length,1);
32 + assert.equal(snapshot.data.journal_entries.length,1);
33 +});
tests/retail-phase2.test.mjs new
+333
@@ -0,0 +1,333 @@
1 +import test from 'node:test';
2 +import assert from 'node:assert/strict';
3 +import 'fake-indexeddb/auto';
4 +import { StorageService as db } from '../src/core/StorageService.js';
5 +import { AccountingService as accounts } from '../src/core/AccountingService.js';
6 +import { RetailPostingService as retail } from '../src/core/RetailPostingService.js';
7 +import { Auth } from '../src/core/Auth.js';
8 +import { CompanyService } from '../src/core/CompanyService.js';
9 +
10 +const date='1405/07/18';
11 +const company='c2-phase2';
12 +async function setup(){
13 + await db.clearAll();
14 + await db.put('companies',{id:company,name:'Store 2'});
15 + Auth.currentUser={id:'phase2-admin',role:'admin',username:'admin'};
16 + CompanyService.activeCompanyId=company;
17 + const period=await accounts.createPeriod({name:'۱۴۰۵',startDate:'1405/01/01',endDate:'1405/12/29'});
18 + await accounts.seedDefaultChart();
19 + const bank={id:'cash-1',companyId:company,recordType:'account',
20 + type:'cashbox',name:'صندوق',isActive:true,isDefault:true,initialBalance:0};
21 + const product={id:'product-1',companyId:company,name:'کالای تست',
22 + code:'X1',buyPrice:100,sellPrice:200,trackInventory:true};
23 + const contact={id:'contact-1',companyId:company,name:'مشتری'};
24 + await db.put('treasury',bank);await db.put('products',product);await db.put('contacts',contact);
25 + assert.deepEqual(await retail.activate(),{enabled:true});
26 + return {period,bank,product,contact,warehouse:(await retail.warehouses())[0]};
27 +}
28 +let seq=100;
29 +function invoice(kind,qty,price,rest={}){
30 + const total=qty*price;
31 + return {id:'phase2-inv-'+(++seq),companyId:company,
32 + number:String(seq),clientUuid:'test-'+seq,ownerUserId:'phase2-admin',kind,
33 + date,contactId:'contact-1',contactName:'مشتری',isPreInvoice:false,
34 + items:[{productId:'product-1',productName:'کالای تست',qty,price,
35 + lineSubtotal:total,lineTotal:total,discount:0}],subtotal:total,
36 + totalDiscount:0,vatAmount:0,grandTotal:total,paidAmount:0,
37 + paymentMethod:'cash',status:'unpaid',remaining:total,...rest};
38 +}
39 +async function purchase10(){return retail.issueInvoice(invoice('purchase',10,100))}
40 +async function sale3(rest={}){return retail.issueInvoice(invoice('sale',3,200,rest))}
41 +test('v2 sale-purchase cash settlement balance, weighted average and exactly once',async()=>{
42 + const {warehouse}=await setup();
43 + const p=await purchase10();
44 + const first=(await retail.stockBalances())[0];
45 + assert.equal(first.quantityUnits,10000);assert.equal(first.value,1000);
46 + const sold=await sale3({paidAmount:200});
47 + assert.equal(sold.paidAmount,200);assert.equal(sold.remaining,400);
48 + const second=(await retail.stockBalances())[0];
49 + assert.equal(second.quantityUnits,7000);assert.equal(second.value,700);
50 + const stock=await db.getAllByIndex('stock_movements','productId','product-1');
51 + assert.equal(stock.filter(m=>m.financePosted).length,0);
52 + assert.equal(stock.length,2);
53 + const journals=await accounts.listJournals();
54 + assert.equal(journals.length,3);
55 + const trial=await accounts.trialBalance();
56 + assert.equal(trial.totals.debit,trial.totals.credit);
57 + await assert.rejects(retail.issueInvoice(sold),/قطعی|تکراری/);
58 + assert.equal((await accounts.listJournals()).length,3);
59 + const receipt=await retail.postTransaction({id:'receipt-1',type:'receipt',date,amount:400,
60 + contactId:'contact-1',refInvoiceId:sold.id,toAccountId:'cash-1',method:'cash'});
61 + assert.equal(receipt.amount,400);
62 + assert.equal((await db.get('invoices',sold.id)).remaining,0);
63 + assert.equal((await db.getAllByIndex('settlements','invoiceId',sold.id)).length,2);
64 + assert.deepEqual((await accounts.trialBalance()).totals.debit,(await accounts.trialBalance()).totals.credit);
65 + assert.equal((await retail.stockBalances({warehouseId:warehouse.id}))[0].value,700);
66 +});
67 +test('v2 stock over-issue aborts invoice, stock and journal atomically',async()=>{
68 + await setup();await purchase10();
69 + const invoiceTooBig=invoice('sale',11,200);
70 + await assert.rejects(retail.issueInvoice(invoiceTooBig),/موجودی/);
71 + assert.equal(await db.get('invoices',invoiceTooBig.id),undefined);
72 + assert.equal((await accounts.listJournals()).length,1);
73 + assert.equal((await retail.stockBalances())[0].quantityUnits,10000);
74 +});
75 +test('v2 sale return references original COGS and limits cumulative returned quantity',async()=>{
76 + await setup();await purchase10();
77 + const sold=await sale3();
78 + const back=invoice('sale_return',1,200,{originalInvoiceId:sold.id});
79 + const returned=await retail.issueInvoice(back);
80 + assert.equal(returned.kind,'sale_return');
81 + assert.equal((await retail.stockBalances())[0].value,800);
82 + assert.equal((await retail.stockBalances())[0].quantityUnits,8000);
83 + await assert.rejects(retail.issueInvoice(invoice('sale_return',3,200,{originalInvoiceId:sold.id})),/بیشتر/);
84 + assert.equal((await accounts.listJournals()).length,3);
85 +});
86 +test('v2 cash expense, cheque deposit and bank transfer produce balanced journals',async()=>{
87 + await setup();await purchase10();await sale3();
88 + const e=await retail.postExpense({id:'exp-phase2',kind:'expense',date,amount:60,method:'cash',category:'اجاره'});
89 + assert.equal(e.financePosted,true);
90 + await assert.rejects(retail.postExpense(e),/تکراری/);
91 + const c=await retail.postCheque({id:'cheque-in-1',issueDate:date,dueDate:date,
92 + direction:'inbound',status:'pending',contactId:'contact-1',amount:250,chequeNumber:'C1'});
93 + assert.equal(c.status,'pending');
94 + const cleared=await retail.changeChequeStatus(c.id,'cleared',{date});
95 + assert.equal(cleared.status,'cleared');
96 + await assert.rejects(retail.changeChequeStatus(c.id,'cleared',{date}),/در جریان/);
97 + assert.equal((await db.getAll('treasury')).filter(r=>r.refChequeId===c.id).length,1);
98 + const b=await retail.addWarehouse('انبار دوم');
99 + assert.ok(b.id);
100 + const trial=await accounts.trialBalance();
101 + assert.equal(trial.totals.credit,trial.totals.debit);
102 +});
103 +test('v2 multiwarehouse transfer and stocktake adjustment preserve value reconciliation',async()=>{
104 + const {warehouse}=await setup();await purchase10();
105 + const other=await retail.addWarehouse('شعبه دوم');
106 + const transfer=await retail.transferStock({fromWarehouseId:warehouse.id,
107 + toWarehouseId:other.id,productId:'product-1',quantity:4,date});
108 + assert.equal(transfer.cost,400);
109 + let balances=await retail.stockBalances();
110 + assert.equal(balances.reduce((s,x)=>s+x.value,0),1000);
111 + assert.equal(balances.find(x=>x.warehouseId===warehouse.id).quantityUnits,6000);
112 + const take=await retail.newStocktake({warehouseId:other.id,date});
113 + const count=(await retail.getStocktakeLines(take.id))[0];
114 + assert.equal(count.expectedUnits,4000);
115 + await retail.countStocktake(take.id,'product-1',3);
116 + const done=await retail.finalizeStocktake(take.id);
117 + assert.equal(done.decrease,100);
118 + balances=await retail.stockBalances();
119 + assert.equal(balances.reduce((s,x)=>s+x.value,0),900);
120 + await assert.rejects(retail.finalizeStocktake(take.id),/قبلاً/);
121 + assert.equal((await accounts.trialBalance()).totals.debit,(await accounts.trialBalance()).totals.credit);
122 +});
123 +test('v2 activation refuses silently migrating legacy movements',async()=>{
124 + await db.clearAll();
125 + await db.put('companies',{id:company,name:'old'});
126 + Auth.currentUser={id:'phase2-admin',role:'admin'};
127 + CompanyService.activeCompanyId=company;
128 + await accounts.createPeriod({name:'۱۴۰۵',startDate:'1405/01/01',endDate:'1405/12/29'});
129 + await accounts.seedDefaultChart();
130 + await db.put('stock_movements',{id:'historical',companyId:company,productId:'old',type:'in',qty:5});
131 + await assert.rejects(retail.activate(),/گردش قبلی/);
132 + assert.equal(await retail.isEnabled(),false);
133 +});
134 +
135 +test('v2 standalone GL reversal of a commercial invoice is prohibited',async()=>{
136 + const {period}=await setup();await purchase10();
137 + const journal=(await accounts.listJournals())[0];
138 + await assert.rejects(accounts.reverseJournal(journal.id,{periodId:period.id,date}),/تجاری/);
139 + assert.equal((await accounts.listJournals()).length,1);
140 +});
141 +test('v2 cross-company contact and treasury references roll back without leakage',async()=>{
142 + await setup();await purchase10();
143 + await db.put('contacts',{id:'foreign-person',companyId:'elsewhere',name:'foreign'});
144 + const receipt={id:'foreign-receipt',date,type:'receipt',amount:100,contactId:'foreign-person',toAccountId:'cash-1'};
145 + await assert.rejects(retail.postTransaction(receipt),/شرکت/);
146 + assert.equal(await db.get('treasury',receipt.id),undefined);
147 + const issued=invoice('sale',2,200,{contactId:'foreign-person'});
148 + await assert.rejects(retail.issueInvoice(issued),/شرکت/);
149 + assert.equal(await db.get('invoices',issued.id),undefined);
150 + assert.equal((await retail.stockBalances())[0].quantityUnits,10000);
151 +});
152 +test('v2 purchase-return financial variance remains balanced when costs and sale price differ',async()=>{
153 + await setup();const purchased=await purchase10();
154 + const result=await retail.issueInvoice(invoice('purchase_return',2,120,{originalInvoiceId:purchased.id}));
155 + assert.equal(result.grandTotal,240);
156 + assert.equal((await retail.stockBalances())[0].quantityUnits,8000);
157 + assert.equal((await retail.stockBalances())[0].value,800);
158 + const trial=await accounts.trialBalance();
159 + assert.equal(trial.totals.debit,trial.totals.credit);
160 + const chart=await accounts.listAccounts();
161 + const variance=chart.find(x=>x.code==='503');
162 + assert.ok(trial.rows.some(row=>row.accountId===variance.id));
163 +});
164 +test('v2 open stocktake locks other inventory transactions until approval',async()=>{
165 + const {warehouse}=await setup();await purchase10();
166 + const take=await retail.newStocktake({warehouseId:warehouse.id,date});
167 + const attempted=invoice('sale',1,200);
168 + await assert.rejects(retail.issueInvoice(attempted),/شمارش/);
169 + assert.equal(await db.get('invoices',attempted.id),undefined);
170 + await retail.countStocktake(take.id,'product-1',10);
171 + await retail.finalizeStocktake(take.id);
172 + const issued=await retail.issueInvoice(invoice('sale',1,200));
173 + assert.equal(issued.financePosted,true);
174 +});
175 +test('v2 full company backup/restore round trip preserves stock valuation and financial postings',async()=>{
176 + const {warehouse}=await setup();
177 + await purchase10();await sale3({paidAmount:200});
178 + const { SettingsController }=await import('../src/controllers/SettingsController.js');
179 + const backup=await SettingsController.exportBackup();
180 + assert.equal(backup.data.inventory_balances.length,1);
181 + assert.equal(backup.data.settlements.length,1);
182 + assert.equal(backup.data.journal_entries.length,3);
183 + await db.clearAll();
184 + await db.put('companies',{id:company,name:'restored'});
185 + CompanyService.activeCompanyId=company;
186 + const counts=await SettingsController.importBackup(backup,{mode:'merge'});
187 + assert.ok(counts.added>=10);
188 + assert.equal(await retail.isEnabled(),true);
189 + assert.equal((await retail.stockBalances())[0].value,700);
190 + assert.equal((await accounts.listJournals()).length,3);
191 + assert.equal((await db.getAllByIndex('settlements','companyId',company)).length,1);
192 + const corrupted=structuredClone(backup);
193 + corrupted.data.inventory_balances[0].warehouseId='missing-warehouse';
194 + await assert.rejects(SettingsController.importBackup(corrupted,{mode:'replace'}),/موجودی|انبار/);
195 + assert.equal((await retail.stockBalances())[0].value,700);
196 +});
197 +test('v2 fiscal period closure forbids invoice and stock writes atomically',async()=>{
198 + const {period}=await setup();await purchase10();
199 + await accounts.closePeriod(period.id);
200 + const newSale=invoice('sale',1,200);
201 + await assert.rejects(retail.issueInvoice(newSale),/دوره مالی باز/);
202 + assert.equal(await db.get('invoices',newSale.id),undefined);
203 + assert.equal((await accounts.listJournals()).length,1);
204 + assert.equal((await retail.stockBalances())[0].quantityUnits,10000);
205 +});
206 +test('v2 tax input/output and mixed transaction amounts remain balanced',async()=>{
207 + await setup();await retail.issueInvoice(invoice('purchase',10,100,
208 + {vatAmount:100,grandTotal:1100}));
209 + const s=await retail.issueInvoice(invoice('sale',1,200,
210 + {vatAmount:20,grandTotal:220}));
211 + assert.equal(s.remaining,220);
212 + const trial=await accounts.trialBalance();
213 + assert.equal(trial.totals.debit,trial.totals.credit);
214 + const chart=await accounts.listAccounts();
215 + assert.ok(trial.rows.find(x=>x.accountId===chart.find(a=>a.code==='104').id)?.debit===100);
216 + assert.ok(trial.rows.find(x=>x.accountId===chart.find(a=>a.code==='202').id)?.credit===20);
217 +});
218 +test('v2 stocktake can post shortage and surplus together in one balanced journal',async()=>{
219 + const {warehouse}=await setup();
220 + await purchase10();
221 + await db.put('products',{id:'product-extra',companyId:company,name:'extra',trackInventory:true});
222 + const second=invoice('purchase',4,100,{
223 + items:[{productId:'product-extra',qty:4,price:100,lineTotal:400,discount:0}],
224 + subtotal:400,grandTotal:400
225 + });
226 + await retail.issueInvoice(second);
227 + const take=await retail.newStocktake({warehouseId:warehouse.id,date});
228 + await retail.countStocktake(take.id,'product-1',9);
229 + await retail.countStocktake(take.id,'product-extra',5);
230 + const result=await retail.finalizeStocktake(take.id);
231 + assert.equal(result.increase,100);
232 + assert.equal(result.decrease,100);
233 + const trial=await accounts.trialBalance();
234 + assert.equal(trial.totals.debit,trial.totals.credit);
235 +});
236 +test('v2 concurrent posting of same invoice commits exactly once',async()=>{
237 + await setup();await purchase10();
238 + const same=invoice('sale',1,200);
239 + const [a,b]=await Promise.allSettled([retail.issueInvoice(same),retail.issueInvoice(same)]);
240 + assert.equal([a,b].filter(x=>x.status==='fulfilled').length,1);
241 + assert.equal([a,b].filter(x=>x.status==='rejected').length,1);
242 + assert.equal((await accounts.listJournals()).length,2);
243 + assert.equal((await retail.stockBalances())[0].quantityUnits,9000);
244 + assert.equal((await db.getAll('stock_movements')).length,2);
245 +});
246 +test('v2 concurrent invoice number collision commits only one',async()=>{
247 + await setup();await purchase10();
248 + const first=invoice('sale',1,200),second=invoice('sale',2,200);
249 + second.number=first.number;
250 + const results=await Promise.allSettled([retail.issueInvoice(first),retail.issueInvoice(second)]);
251 + assert.equal(results.filter(x=>x.status==='fulfilled').length,1);
252 + assert.equal(results.filter(x=>x.status==='rejected').length,1);
253 + assert.equal((await accounts.listJournals()).length,2);
254 +});
255 +test('v2 all partial sale returns restore every rial of original COGS',async()=>{
256 + await setup();
257 + const buy=invoice('purchase',3,33);
258 + buy.items[0].lineTotal=100;buy.items[0].lineSubtotal=100;buy.subtotal=100;buy.grandTotal=100;buy.remaining=100;
259 + await retail.issueInvoice(buy);
260 + const sale=await retail.issueInvoice(invoice('sale',3,200));
261 + for(let j=0;j<3;j++){
262 + const returned=invoice('sale_return',1,200,{originalInvoiceId:sale.id});
263 + await retail.issueInvoice(returned);
264 + }
265 + const balance=(await retail.stockBalances())[0];
266 + assert.equal(balance.quantityUnits,3000);
267 + assert.equal(balance.value,100);
268 + assert.equal((await accounts.trialBalance()).totals.debit,(await accounts.trialBalance()).totals.credit);
269 +});
270 +test('v2 duplicate product lines on last sale return do not overvalue returned goods',async()=>{
271 + await setup();
272 + const buy=invoice('purchase',3,33);
273 + buy.items[0].lineTotal=100;buy.subtotal=100;buy.grandTotal=100;buy.remaining=100;
274 + await retail.issueInvoice(buy);
275 + const sale=await retail.issueInvoice(invoice('sale',3,200));
276 + const returned=invoice('sale_return',3,200,{originalInvoiceId:sale.id});
277 + returned.items=[{...returned.items[0],qty:1,lineTotal:200},
278 + {...returned.items[0],qty:2,lineTotal:400}];
279 + await retail.issueInvoice(returned);
280 + assert.equal((await retail.stockBalances())[0].value,100);
281 +});
282 +test('v2 product controller forbids bypass stock writes and uses inventory book valuation',async()=>{
283 + await setup();
284 + globalThis.window??={};
285 + const { ProductController } = await import('../src/controllers/ProductController.js');
286 + await purchase10();
287 + const b=invoice('purchase',10,200);
288 + await retail.issueInvoice(b);
289 + const valuation=await ProductController.getTotalStockValue();
290 + assert.equal(valuation.totalBuyValue,3000);
291 + assert.equal((await ProductController.getStockMap(['product-1']))['product-1'],20);
292 + await assert.rejects(
293 + ProductController.addStockMovement('product-1','in',100,'manual'),/دستی/
294 + );
295 + await assert.rejects(
296 + ProductController.updateProduct('product-1',{name:'کالای آزمایش',trackInventory:false}),
297 + /نوع کالا/
298 + );
299 + assert.equal((await retail.stockBalances())[0].value,3000);
300 +});
301 +test('v2 purchase returns require a matching original invoice and cannot exceed quantity',async()=>{
302 + await setup();const original=await purchase10();
303 + const without=invoice('purchase_return',1,100);
304 + await assert.rejects(retail.issueInvoice(without),/اولیه/);
305 + const returned=await retail.issueInvoice(invoice('purchase_return',4,100,{originalInvoiceId:original.id}));
306 + assert.equal(returned.financePosted,true);
307 + await assert.rejects(retail.issueInvoice(invoice('purchase_return',7,100,{originalInvoiceId:original.id})),/بیشتر/);
308 + assert.equal((await retail.stockBalances())[0].quantityUnits,6000);
309 +});
310 +test('v2 integrated issuance commits invoice item rows and rolls back on failure',async()=>{
311 + await setup();await purchase10();
312 + const rows=await db.getAll('invoice_items');
313 + assert.equal(rows.length,1);
314 + assert.equal(rows[0].invoiceId,(await db.getAll('invoices'))[0].id);
315 + assert.equal(rows[0].companyId,company);
316 + const bad=invoice('sale',100,200);
317 + await assert.rejects(retail.issueInvoice(bad),/موجودی/);
318 + assert.equal((await db.getAll('invoice_items')).length,1);
319 +});
320 +test('fresh-company activation creates default cash account and chart subledger',async()=>{
321 + await db.clearAll();
322 + await db.put('companies',{id:company,name:'empty'});
323 + Auth.currentUser={id:'phase2-admin',role:'admin'};
324 + CompanyService.activeCompanyId=company;
325 + await accounts.createPeriod({name:'سال',startDate:'1405/01/01',endDate:'1405/12/29'});
326 + await accounts.seedDefaultChart();
327 + await retail.activate();
328 + const banks=(await db.getAll('treasury')).filter(x=>x.companyId===company&&x.recordType==='account');
329 + assert.equal(banks.length,1);
330 + assert.ok(banks[0].ledgerAccountId);
331 + assert.ok((await accounts.listAccounts()).some(a=>a.id===banks[0].ledgerAccountId));
332 + assert.equal((await db.getAll('journal_entries')).length,0);
333 +});
vite.config.mjs renamed