@davoodmehraban89 / Factor-easy-2 Mirror · read-only / commits / 42f814b
Fork 0

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

Mirrored from https://github.com/davoodmehraban89/Factor-easy.git

Synced Dec 3, 20:45 UTC

Build accountant-first onboarding coding and contract UX

davoodmehraban89 committed Sep 30, 2026 at 00:51 UTC 42f814bc8d823b7b651ebd46ecd76a741f3e9f5f
11 files changed +50 -34
PROJECT_STATE.md
+1 -1
@@ -34,7 +34,7 @@ Before doing any project work:
34 ## Current change ledger
35 | Date | Request / decision | Status | Evidence / next action |
36 |---|---|---|---|
37 -| 2026-09-30 | Owner directs Finora toward a daily-use accountant-first ERP, with defect elimination and Chart-of-Accounts UX as highest priorities. Immediate product requirements: rename the primary `پروژه` subsystem to `پیمان‌ها`; after a new user verifies/signs in, collect their real display name and non-privileged professional usage role (e.g. owner/manager, financial manager, accountant) without allowing self-escalation to system admin; make license company capacity commercially controllable by the central system admin with default 1 company and explicit N-company licenses; distinguish ordinary multi-company licensing from a true holding/group model; research holding/company classification (private/public/government/cooperative/etc. and parent/subsidiary structures); expand ERP roadmap to integrated CRM and payroll/HR plus other evidence-backed gaps from leading Iranian/international ERP products. | IN PROGRESS | Live DB confirms `profiles.full_name` already exists, so display-name onboarding needs no schema change. `profiles.role` is intentionally only `user/admin`; professional role must remain separate and must never self-grant admin. Current `licenses` has no company-capacity field, so authoritative max-company enforcement requires a prepared DB migration/RPC update and must NOT be applied until the required explicit schema/role-change approval checkpoint. Holding is architecturally distinct from N independent companies: benchmark evidence from Dynamics/Acumatica/Odoo/SAP shows legal entities/subsidiaries, intercompany entries, consolidation, eliminations and currency translation as separate concerns. Immediate executable slice: rename rail to `پیمان‌ها`, implement first-login name/professional-role onboarding using existing profile/records storage, strengthen company creation with a default-one client guard ready to consume authoritative license capacity, improve Chart-of-Accounts daily workflow, and archive a benchmark-backed ERP gap/holding roadmap. Prepare (do not apply) the server migration for license company capacity. CRM/payroll/holding are roadmap modules until their lifecycle/persistence/accounting/permissions/tests exist; do not expose fake operational modules. |
37 +| 2026-09-30 | Owner directs Finora toward a daily-use accountant-first ERP, with defect elimination and Chart-of-Accounts UX as highest priorities. Immediate product requirements: rename the primary `پروژه` subsystem to `پیمان‌ها`; after a new user verifies/signs in, collect their real display name and non-privileged professional usage role (e.g. owner/manager, financial manager, accountant) without allowing self-escalation to system admin; make license company capacity commercially controllable by the central system admin with default 1 company and explicit N-company licenses; distinguish ordinary multi-company licensing from a true holding/group model; research holding/company classification (private/public/government/cooperative/etc. and parent/subsidiary structures); expand ERP roadmap to integrated CRM and payroll/HR plus other evidence-backed gaps from leading Iranian/international ERP products. | IN PROGRESS | Live DB confirms `profiles.full_name` already exists, so display-name onboarding needs no schema change. `profiles.role` is intentionally only `user/admin`; professional role must remain separate and must never self-grant admin. Current `licenses` has no company-capacity field, so authoritative max-company enforcement requires a prepared DB migration/RPC update and must NOT be applied until the required explicit schema/role-change approval checkpoint. Holding is architecturally distinct from N independent companies: benchmark evidence from Dynamics/Acumatica/Odoo/SAP shows legal entities/subsidiaries, intercompany entries, consolidation, eliminations and currency translation as separate concerns. Immediate executable slice: rename rail to `پیمان‌ها`, implement first-login name/professional-role onboarding using existing profile/records storage, strengthen company creation with a default-one client guard ready to consume authoritative license capacity, improve Chart-of-Accounts daily workflow, and archive a benchmark-backed ERP gap/holding roadmap. This code checkpoint implements the non-schema portion: primary rail/panel is visibly `پیمان‌ها`; first-login onboarding stores display name + non-privileged professional role in the existing owner-scoped `settings` record (system `user/admin` role is untouched); company master gains organizational position (`standalone`/`holding_parent`/`subsidiary`) and parent-company relation metadata with an explicit warning that consolidation is separate; company creation enforces the current license capacity with default 1; admin UI is capacity-aware but keeps the capacity field disabled until the server column/RPC exists; Chart of Accounts gains search/level/type/status filters, hierarchy path, safe unused-account editing, and deactivate/reactivate for historical accounts. No DB/auth/RLS/role mutation in this checkpoint. Prepare (do not apply) the server migration for license company capacity. CRM/payroll/holding are roadmap modules until their lifecycle/persistence/accounting/permissions/tests exist; do not expose fake operational modules. |
38 | 2026-09-30 | Owner rejects the current first-pass accountant UX as insufficient and requests a broader evidence-based redesign synthesis from strong Iranian and international accounting/ERP products. Apply the best compatible patterns to Finora without cloning a vendor: preserve the narrow primary rail + adjacent contextual subsystem panel; remove repeated/unrelated accounting-document surfaces leaking into other subsystem workspaces; replace the disappearing `×` close affordance with a persistent edge-mounted collapse/expand handle so the contextual panel is always recoverable; and extend company definition so operational activity type (trading/service/manufacturing/etc.) is separate from person/legal identity and legal form (natural person, joint-stock/private/public, LLC, partnership, etc., plus institution/public/government/other where applicable). User supplied four current Finora screenshots as direct defect/design evidence. | IMPLEMENTED / FINAL CI VERIFICATION PENDING | Benchmark reviewed across Iranian patterns (Rahkaran/System Group, Sepidar, Parmis Star, Mahak and prior repo research) and international official structures (Microsoft Dynamics 365 Finance, Oracle Fusion Financials, SAP S/4HANA Finance, Xero, Zoho Books, QuickBooks, Sage Intacct, Acumatica, Odoo/NetSuite references). Strong recurring pattern: stable top-level financial domains, task-focused contextual navigation, global create/search, separation of master/setup vs transactions vs reports, and legal-entity/company context distinct from operational accounting classification. Current screenshots prove `اسناد حسابداری` is leaking below Inventory and Settings task content and the contextual panel uses a top `×` that becomes unavailable after collapse. Root cause confirmed in code: `ensureJournalView()` created `#view-journal` with class `view` instead of the shell's canonical `view-pane`, so `switchView()` never hid it; this is why the screenshots show Accounting Journal under unrelated modules. Implementation in this checkpoint converts it to a true view pane, removes the internal `فاز ۳` production badge, adds the persistent edge handle and global quick-create menu, and separates company person/sector/legal-form/activity metadata without a database schema change. Benchmark synthesis is archived in `docs/FINORA_UX_ACCOUNTING_BENCHMARK_V3.md`. Information architecture is also normalized around the recurring benchmark pattern: Accounting now groups `ساختار مالی` → `ثبت و عملیات` → `دفاتر و کنترل` → `صورت‌های مالی و تحلیل`; expense/income is owned by Accounting instead of Commerce; Commerce is reduced to people/items + sales + purchasing; Treasury keeps operational receive/pay/cheques plus contextual aging/cash-flow links. These are navigation ownership changes over existing implemented capabilities, not new fake modules. Static and real-DOM navigation expectations are updated in the same checkpoint so CI validates the new accountant-first IA instead of preserving obsolete labels. Before product edits, reconcile latest CI: run `36627449874` on `fb275453` passed syntax + application + Phase 2–6 + Golden Journey; only Real-DOM failed on non-formal paper-kind expectation and a brittle raw-PDF regex parser. Implemented through code head `db7784d1`: benchmark archive `docs/FINORA_UX_ACCOUNTING_BENCHMARK_V3.md`; persistent edge collapse/reopen handle; global quick-create over existing workflows; journal `view-pane` isolation and removal of the internal Phase-3 badge; accountant-first Accounting/Commerce/Treasury grouping; company person type + ownership/sector + legal form + operational activity metadata; non-formal print accepts both `non_formal` and legacy `informal`; PDF acceptance now uses `pdf-lib` instead of raw-byte regex. Superseded run `36629795213` on `4df0825f` passed repository syntax but failed the old static IA labels; `db7784d1` updates those stale static/DOM expectations. Local connector-side parse checks PASS for `ui.js`, `companies.js`, `journal-ui.js`, `print.js` and `dom-smoke.spec.js`. No failure notification has appeared yet for `db7784d1`, but its exact push-run ID/result is not exposed, so Quality/real-DOM/PDF remains NOT VERIFIED rather than assumed PASS. Supabase rechecked ACTIVE_HEALTHY, 17 migrations through `20260929193357`, RLS enabled on all three public tables, performance advisor clean; known 5 SECURITY DEFINER warnings + leaked-password warning unchanged. No schema/RLS/auth/role mutation was made. Physical-printer validation remains NOT VERIFIED. No schema/RLS/auth/role change is planned; company metadata remains inside the existing records model. |
39 | 2026-09-29 | Owner clarified the navigation interaction after reviewing Rahkaran web: primary modules must NOT expand accordion-style beneath themselves; selecting Accounting/another module must populate the adjacent vertical contextual panel, matching the approved screenshot. Owner also supplied three real browser-print PDFs proving a severe print-isolation regression: formal invoice and pre-invoice include application UI pages before the invoice; non-formal A5 also includes UI pages and opens with incorrect A4/default behavior. Research Rahkaran web/module concepts, then repair all invoice print modes so only the print document enters the print tree with deterministic paper/orientation/pagination. | IMPLEMENTED / CI FINAL VERIFICATION PENDING | External review confirms Rahkaran Cloud is web-delivered and organized as modular financial/sales/logistics/etc. solutions; Rahkaran accounting training exposes distinct account-definition, voucher-entry and reporting tasks rather than one dumped workspace. User PDFs are stronger direct evidence for the print defect: UI is printed before the invoice in all three samples. Rahkaran review confirms the useful pattern is modular task separation (base information/account structure, voucher operations, reporting) while the owner explicitly rejects Rahkaran-style cascading expansion for Finora. Current Finora desktop already renders those groups in the adjacent vertical `module-panel` rather than nested beneath the rail, so that interaction is retained and now treated as a contract. Print root cause confirmed: browser printing still depended on hiding the live application DOM; the supplied PDFs demonstrate that this isolation is not reliable enough. This checkpoint moves invoice/electronic-document printing into a dedicated same-origin iframe document containing only invoice pages, with explicit CSS `@page` A4-landscape for formal/pre-invoice and A5-landscape for non-formal, plus a strict live-DOM fallback. Real-DOM tests now assert zero application-shell nodes in the print document and Chromium PDF generation checks actual A4/A5 landscape MediaBox dimensions. Immediate pre-CI syntax review caught over-escaped regex literals in the newly added PDF MediaBox test itself (product print code parsed cleanly); `6686c9ed` replaced them with explicit RegExp constructors and the full DOM smoke script parses successfully. Superseded Quality run `36627088224` on `49c16bcf` then passed the repository syntax gate and failed only because `quality-check.mjs` still required the removed legacy local-page-size variable `const a4Landscape=isFormal||isPreInvoice`. `cc4fa1f` updated the general quality contract. Quality run `36627278247` then passed syntax, application invariants and Phase 2, and its Phase 3 engine checks themselves printed PASS before a second stale print needle in `phase3-check.mjs` stopped the workflow. This checkpoint updates that remaining Phase 3 static print contract to the isolated-frame/A4/A5 invariants; no accounting behavior is changed. Final implementation head before this docs-only checkpoint is `fb275453`: isolated print implementation `49c16bcf`, test-syntax repair `6686c9ed`, general print gate `cc4fa1f`, Phase 3 print gate `fb275453`. Superseded runs `36627088224` and `36627278247` are fully diagnosed stale-gate failures, not product-print failures. No failure notification is currently present for `fb275453`, but push-run IDs/success notifications are not exposed by the connector, so latest Quality/real-DOM/PDF acceptance remains NOT VERIFIED rather than assumed PASS. Supabase was rechecked ACTIVE_HEALTHY with 17 migrations through `20260929193357`, and RLS remains enabled on profiles/licenses/records; this slice made no database/schema/RLS/auth changes. Physical printer behavior remains NOT VERIFIED even after browser-PDF acceptance. |
40 | 2026-09-29 | Owner rejected the current workspace-dump navigation. Redesign Finora around the approved two-tier enterprise shell shown in the canonical screenshot: primary module rail + rich contextual subsystem menu; replace `خانه` with `داشبورد`; keep owner-approved domain grouping such as sales/purchases/contacts under بازرگانی; give accounting and every major module organized groups (e.g. پایه/عملیات/دفاتر و گزارش‌ها/ابزارها) with one clear action/view per menu item. Before implementation, research multiple Iranian accounting/ERP products (not one vendor), official product structures/demos plus user/accounting-community feedback, synthesize patterns without copying a vendor, then migrate existing working views into the hierarchy without feature loss or fake modules. | IMPLEMENTED / CI FINAL VERIFICATION PENDING | Research completed across the approved screenshot, live shell, Sepidar official system/accounting pages and training UI, Rahkaran/System Group module structure, Holoo task/report material, Gheyas/user feedback and independent review feedback. Synthesis is recorded in `docs/FINORA_INFORMATION_ARCHITECTURE_V2.md`: nine primary business modules, rich grouped contextual menus, task-level navigation, no `خانه`, no standalone `کالا`, no generic `ERP`, and no fake future modules. IA contract committed at `9631f6ef`. This implementation checkpoint replaces the rail with Dashboard/Accounting/Commerce/Treasury/Projects/Inventory/Fixed Assets/Reports/Settings; removes `خانه`, standalone `کالا` and generic `ERP`; expands Accounting into grouped base/operations/books-report commands; and introduces task-level workspace focusing so account chart, floating dimensions, rules, fiscal years, branches, projects, journal entry/register, reports, inventory/assets/data-center tasks no longer dump unrelated cards together. Commerce retains contacts/products/sales/purchases. Real-DOM gates are extended to verify the new hierarchy and focused task behavior. Pre-CI review found and corrected one contradictory legacy `erp` rail assertion, added task-aware command-search routing/context, and hides the empty fiscal/branch grid wrapper when another accounting task is focused. Quality run `36624026541` on `dcb0d4ab` proved JavaScript syntax PASS but exposed a stale Phase 5 gate that still required every Phase 5 view to map to the removed generic `erp` module. The gate is updated in this checkpoint to verify the new canonical ownership (`inventory`, `assets`, accounting currency, settings data/integrations), reject deprecated `home/catalog/erp` rail entries, and require the new accounting hierarchy. Dashboard is also rebuilt in this checkpoint to match the approved analytical direction without fabricated values: white enterprise KPI cards for assets/cash/receivables/payables, six-month cash-in/out SVG from actual payment records, account-status bars, task-level quick access and latest journal vouchers. All values are derived from the existing ledger/operational data and remain zero/empty when no production accounting data exists. Quality run `36624183478` on the pre-dashboard `c254e5f1` passed syntax, application invariants, Phase 2–6, Golden Journey and browser installation; Real-DOM alone failed because `openModule()` rendered the selected task and then `switchView()` reset the contextual panel before the non-rerendering navigation returned. The product navigation state bug is fixed here by making `openModule()` complete the canonical task navigation/rerender path. The analytical dashboard checkpoint `96adf600` is retained. Direct-view compatibility is hardened: switchView clears any previous task filter; task navigation then reapplies the requested focus. Real-DOM verifies focused mode and reset-to-full-view behavior. Settings is also decomposed into task-level routes: company, account/password, invoice defaults, operational settings, data/backup, integrations, about, and admin/license. Topbar company and fiscal-year pills now deep-link directly to their canonical tasks instead of dumping the full settings page. Real-DOM adds a focused company-settings assertion. Run `36624545469` on `f3f15aa` proved the new enterprise shell/task navigation Real-DOM PASS; the only failure was the separate expired-license test because the dashboard visual rebuild had removed the legacy `user-license-status-badge` element that `updateLicenseDisplay()` owns. This is a real UI regression, not a test-only issue. The badge is restored inside the new dashboard header in this checkpoint, preserving license visibility/enforcement while keeping the new analytical layout. Real-DOM acceptance is extended once more to render the redesigned dashboard under the stubbed authenticated session and require the assets KPI, cash-flow SVG and recent-journal surface to exist before continuing accounting/inventory/print checks. CI verification is required next. Durable implementation chain: IA research/contract `9631f6ef`; shell/task routing `22bb7a27`; navigation/search gates `dcb0d4ab`; stale CI ownership gate repair `c254e5f1`; analytical dashboard `96adf600`; module-open state fix `4cecc1f6`; direct-view task reset `f3f15aa2`; focused settings `b2fff128`; restored license badge `9b99e7e1`; dashboard DOM gate `761131c6`. Run `36624545469` proved the enterprise shell/task navigation itself passes real DOM and all Phase 2–6/Golden gates; its remaining expired-license failure was caused by the dashboard badge regression fixed at `9b99e7e1`. No failure notification has been observed yet for the latest code head `761131c6`, but the exact latest push-run ID is unavailable through the connector, so final combined CI remains NOT VERIFIED. |
index.html
+6 -4
@@ -249,7 +249,7 @@ body{background:#f6f9fc}
249 <button class="module-tab" data-module="accounting" data-view="view-accounting-foundation" onclick="openModule('accounting','view-accounting-foundation','accounts')" title="حسابداری"><span>▦</span><b>حسابداری</b></button>
250 <button class="module-tab" data-module="commerce" data-view="view-invoices" onclick="openModule('commerce','view-invoices')" title="بازرگانی"><span>⇄</span><b>بازرگانی</b></button>
251 <button class="module-tab" data-module="treasury" data-view="view-payments" onclick="openModule('treasury','view-payments')" title="خزانه‌داری"><span>◈</span><b>خزانه</b></button>
252 - <button class="module-tab" data-module="projects" data-view="view-contracting" onclick="openModule('projects','view-contracting')" title="پروژه و قرارداد"><span>▧</span><b>پروژه</b></button>
252 + <button class="module-tab" data-module="projects" data-view="view-contracting" onclick="openModule('projects','view-contracting')" title="پیمان‌ها"><span>▧</span><b>پیمان‌ها</b></button>
253 <button class="module-tab" data-module="inventory" data-view="view-inventory" onclick="openModule('inventory','view-inventory','stock')" title="انبار"><span>▦</span><b>انبار</b></button>
254 <button class="module-tab" data-module="assets" data-view="view-assets" onclick="openModule('assets','view-assets','asset-register')" title="دارایی ثابت"><span>◆</span><b>دارایی</b></button>
255 <button class="module-tab" data-module="reports" data-view="view-reports" onclick="openModule('reports','view-reports')" title="گزارش‌ها"><span>▥</span><b>گزارش</b></button>
@@ -635,7 +635,7 @@ body{background:#f6f9fc}
635 <div class="accordion-body">
636 <div class="form-row">
637 <div class="form-group"><label>نوع شخص</label><select id="company-entity-type" class="form-control" onchange="handleCompanyEntityTypeChange()"><option value="legal">حقوقی</option><option value="natural">حقیقی / کسب‌وکار فردی</option></select></div>
638 -<div class="form-group" id="company-sector-box"><label>ماهیت مالکیت / بخش</label><select id="company-sector" class="form-control"><option value="private">خصوصی</option><option value="cooperative">تعاونی</option><option value="public_non_government">عمومی غیردولتی</option><option value="government">دولتی / حکومتی</option><option value="other">سایر</option></select></div>
638 +<div class="form-group" id="company-sector-box"><label>ماهیت مالکیت / بخش</label><select id="company-sector" class="form-control"><option value="private">خصوصی</option><option value="cooperative">تعاونی</option><option value="public_non_government">عمومی غیردولتی</option><option value="government">دولتی / حکومتی</option><option value="other">سایر</option></select></div><div class="form-group"><label>جایگاه در ساختار سازمانی</label><select id="company-organization-role" class="form-control" onchange="handleCompanyOrganizationRoleChange()"><option value="standalone">شرکت / واحد مستقل</option><option value="holding_parent">شرکت مادر / هلدینگ</option><option value="subsidiary">شرکت تابعه</option></select></div><div class="form-group" id="company-parent-box" style="display:none"><label>شرکت مادر</label><select id="company-parent-id" class="form-control"><option value="">— انتخاب شرکت مادر —</option></select><small style="color:var(--text-muted)">این رابطه فعلاً ساختار سازمانی را ثبت می‌کند؛ تلفیق، حذف معاملات درون‌گروهی و گزارش گروهی ماژول جداگانه خواهند بود.</small></div>
639 <div class="form-group" id="company-legal-form-box"><label>قالب حقوقی ثبت</label><select id="company-legal-form" class="form-control"><option value="private_joint_stock">سهامی خاص</option><option value="public_joint_stock">سهامی عام</option><option value="limited_liability">با مسئولیت محدود</option><option value="general_partnership">تضامنی</option><option value="relative_partnership">نسبی</option><option value="mixed_non_stock">مختلط غیرسهامی</option><option value="mixed_stock">مختلط سهامی</option><option value="cooperative">تعاونی</option><option value="noncommercial_institution">مؤسسه غیرتجاری</option><option value="other">سایر / نامشخص</option></select></div>
640 <div class="form-group"><label>نوع فعالیت عملیاتی</label><select id="company-activity-type" class="form-control"><option value="trading">بازرگانی</option><option value="service">خدماتی</option><option value="manufacturing">تولیدی</option><option value="contracting">پیمانکاری</option><option value="retail">فروشگاهی</option><option value="distribution">پخش</option><option value="nonprofit">غیرانتفاعی</option><option value="professional">خدمات حرفه‌ای</option></select></div>
641 </div>
@@ -724,7 +724,7 @@ body{background:#f6f9fc}
724 </div>
725 <div style="background:#eff6ff;border:1px solid #bfdbfe;border-radius:10px;padding:14px;margin-bottom:20px;font-size:13px;line-height:1.9">کاربران خودشان از صفحه ورود ثبت‌نام می‌کنند و ۱۵ روز آزمایشی می‌گیرند. در این پنل فقط لایسنس‌ها (فعال‌سازی، تمدید، تغییر طرح، لغو) مدیریت می‌شود و کنترل نهایی روی سرور انجام می‌شود.</div>
726 <div class="table-responsive">
727 -<table><thead><tr><th>کاربر (ایمیل)</th><th>وضعیت حساب</th><th>نوع اشتراک</th><th>تاریخ شروع</th><th>تاریخ پایان</th><th>روزهای باقیمانده</th><th>عملیات مدیریت لایسنس</th></tr></thead><tbody id="admin-users-table-body"><tr><td colspan="7" style="text-align:center;padding:20px">در حال بارگذاری کاربران...</td></tr></tbody></table>
727 +<table><thead><tr><th>کاربر</th><th>وضعیت حساب</th><th>نوع اشتراک</th><th>ظرفیت شرکت</th><th>تاریخ شروع</th><th>تاریخ پایان</th><th>روزهای باقیمانده</th><th>عملیات مدیریت لایسنس</th></tr></thead><tbody id="admin-users-table-body"><tr><td colspan="8" style="text-align:center;padding:20px">در حال بارگذاری کاربران...</td></tr></tbody></table>
728 </div>
729 </div>
730 </section>
@@ -733,6 +733,8 @@ body{background:#f6f9fc}
733 </main>
734 </div>
735
736 +<div class="modal-backdrop" id="modal-user-onboarding"><div class="modal-card" style="max-width:520px"><h3 style="font-size:18px;margin-bottom:6px">خوش آمدید به فینورا</h3><p style="font-size:12.5px;color:var(--text-muted);line-height:1.9;margin-bottom:14px">برای شخصی‌سازی محیط کاری، نام و نقش حرفه‌ای خودتان را مشخص کنید. این نقش فقط برای تجربه کاربری است و دسترسی «مدیر سیستم» ایجاد نمی‌کند.</p><div class="form-group"><label>نام و نام خانوادگی</label><input id="onboarding-full-name" class="form-control" maxlength="80" placeholder="مثلاً محمد رضایی" autocomplete="name"></div><div class="form-group"><label>در فینورا با چه نقشی کار می‌کنید؟</label><select id="onboarding-professional-role" class="form-control"><option value="business_owner">مالک / مدیر کسب‌وکار</option><option value="financial_manager">مدیر مالی</option><option value="chief_accountant">رئیس حسابداری</option><option value="accountant">حسابدار</option><option value="treasury">خزانه‌دار</option><option value="sales">فروش / بازرگانی</option><option value="warehouse">انباردار</option><option value="auditor">حسابرس / ناظر</option><option value="other">سایر</option></select></div><button class="btn btn-primary" style="width:100%;margin-top:12px" onclick="saveUserOnboarding()">ذخیره و ورود به محیط کار</button></div></div>
737 +
738 <div class="modal-backdrop" id="modal-quick-contact">
739 <div class="modal-card">
740 <h3 style="font-size:16px;margin-bottom:12px">➕ تعریف سریع خریدار</h3>
@@ -782,7 +784,7 @@ body{background:#f6f9fc}
784 <div class="modal-card">
785 <h3 style="font-size:16px;margin-bottom:12px" id="modal-license-user-title">تغییر مدت و لایسنس کاربر</h3>
786 <input type="hidden" id="modal-license-target-username" />
785 -<div class="form-group"><label>انتخاب مدت و نوع لایسنس جدید</label><select id="modal-license-duration-select" class="form-control"><option value="monthly">اشتراک ۱ ماهه (۳۰ روز)</option><option value="three_months">اشتراک ۳ ماهه (۹۰ روز)</option><option value="annual">اشتراک ۱ ساله (۳۶۵ روز)</option><option value="lifetime">اشتراک دائمی (Lifetime)</option></select></div>
787 +<div class="form-group"><label>انتخاب مدت و نوع لایسنس جدید</label><select id="modal-license-duration-select" class="form-control"><option value="monthly">اشتراک ۱ ماهه (۳۰ روز)</option><option value="three_months">اشتراک ۳ ماهه (۹۰ روز)</option><option value="annual">اشتراک ۱ ساله (۳۶۵ روز)</option><option value="lifetime">اشتراک دائمی (Lifetime)</option></select></div><div class="form-group"><label>حداکثر تعداد شرکت قابل تعریف</label><input id="modal-license-company-limit" type="number" min="1" max="1000" value="1" class="form-control"><small id="modal-license-company-limit-hint" style="color:var(--text-muted)">پیش‌فرض هر لایسنس: ۱ شرکت</small></div>
788 <div style="display:flex;gap:10px;margin-top:16px">
789 <button class="btn btn-success" style="flex:1" onclick="applyLicenseDurationChange()">تایید و اعمال لایسنس</button>
790 <button class="btn btn-secondary" style="flex:1" onclick="closeLicenseEditModal()">انصراف</button>
js/accounting-foundation-render.js
+2 -1
@@ -3,7 +3,8 @@ function afChip(text,fn){return '<span class="af-chip">'+text+(fn?' <button oncl
3 function renderAccountingFoundation(){
4 ensureAccountingFoundationView();if(!currentUser)return;afSeed();afMigrateLegacyProjects();
5 const A=getMyAccounts().slice().sort((a,b)=>String(a.code).localeCompare(String(b.code),'fa',{numeric:true})),D=getMyDimensionTypes(),B=getMyBranches(),P=getMyGlobalProjects(),C=getMyContacts();
6 - const ab=document.getElementById('af-accounts-body');if(ab)ab.innerHTML=A.length?A.map(a=>'<tr><td>'+esc(a.code)+'</td><td>'+esc(a.title)+'</td><td>'+AF_LEVELS[a.level]+'</td><td>'+esc(({asset:'دارایی',liability:'بدهی',equity:'حقوق مالکانه',revenue:'درآمد',expense:'هزینه',memorandum:'انتظامی',control:'کنترلی'})[a.accountType]||'—')+'</td><td>'+esc(AF_SYSTEM_ROLES[a.systemRole]||'—')+'</td><td>'+AF_NATURE[a.normalBalance]+'</td><td>'+(a.postingAllowed?'بله':'خیر')+'</td><td><button class="btn btn-danger btn-inline" onclick="afDeleteAccount(\''+a.id+'\')">حذف</button></td></tr>').join(''):'<tr><td colspan="8" class="af-empty">حسابی تعریف نشده است.</td></tr>';afParents();
6 + const q=String(document.getElementById('af-account-search')?.value||'').trim().toLowerCase(),lf=document.getElementById('af-account-level-filter')?.value||'',tf=document.getElementById('af-account-type-filter')?.value||'',afilter=document.getElementById('af-account-active-filter')?.value||'active',byId=new Map(A.map(x=>[x.id,x]));const pathOf=a=>{const parts=[];let cur=a,guard=0;while(cur&&guard++<8){parts.unshift(cur.title);cur=byId.get(cur.parentId)}return parts.join(' ← ')};const shown=A.filter(a=>(!q||(String(a.code)+' '+String(a.title)+' '+pathOf(a)).toLowerCase().includes(q))&&(!lf||a.level===lf)&&(!tf||a.accountType===tf)&&(afilter==='all'||(afilter==='inactive'?a.active===false:a.active!==false)));const summary=document.getElementById('af-account-summary');if(summary)summary.textContent='نمایش '+shown.length.toLocaleString('fa-IR')+' از '+A.length.toLocaleString('fa-IR')+' حساب · '+A.filter(x=>x.active!==false).length.toLocaleString('fa-IR')+' فعال';
7 + const ab=document.getElementById('af-accounts-body');if(ab)ab.innerHTML=shown.length?shown.map(a=>{const locked=afAccountStructuralUse(a.id),depth=a.level==='gl'?0:a.level==='subsidiary'?1:2;return '<tr'+(a.active===false?' style="opacity:.55"':'')+'><td><strong>'+esc(a.code)+'</strong></td><td><div style="padding-right:'+(depth*16)+'px"><strong>'+esc(a.title)+'</strong><small style="display:block;color:var(--text-muted)">'+esc(pathOf(a))+'</small></div></td><td>'+AF_LEVELS[a.level]+'</td><td>'+esc(({asset:'دارایی',liability:'بدهی',equity:'حقوق مالکانه',revenue:'درآمد',expense:'هزینه',memorandum:'انتظامی',control:'کنترلی'})[a.accountType]||'—')+'</td><td>'+esc(AF_SYSTEM_ROLES[a.systemRole]||'—')+'</td><td>'+AF_NATURE[a.normalBalance]+'</td><td>'+(a.active===false?'<span class="badge badge-warning">غیرفعال</span>':'<span class="badge badge-success">فعال</span>')+'</td><td style="display:flex;gap:5px;flex-wrap:wrap">'+(!locked?'<button class="btn btn-secondary btn-inline" onclick="afStartAccountEdit(\''+a.id+'\')">اصلاح</button>':'')+'<button class="btn btn-secondary btn-inline" onclick="afToggleAccountActive(\''+a.id+'\')">'+(a.active===false?'فعال‌سازی':'غیرفعال')+'</button>'+(!locked?'<button class="btn btn-danger btn-inline" onclick="afDeleteAccount(\''+a.id+'\')">حذف</button>':'')+'</td></tr>'}).join(''):'<tr><td colspan="8" class="af-empty">حسابی با این فیلتر پیدا نشد.</td></tr>';afParents();
8 const ra=document.getElementById('af-rule-account');if(ra)ra.innerHTML=A.filter(x=>x.postingAllowed).map(x=>'<option value="'+x.id+'">'+esc(x.code)+' — '+esc(x.title)+'</option>').join('');
9 const rd=document.getElementById('af-rule-dimension');if(rd)rd.innerHTML=D.map(x=>'<option value="'+x.id+'">'+esc(x.title)+'</option>').join('');
10 const rl=document.getElementById('af-rules-list');if(rl)rl.innerHTML=getMyAccountDimensionRules().map(r=>{const a=A.find(x=>x.id===r.accountId),d=D.find(x=>x.id===r.dimensionTypeId);return a&&d?afChip(esc(a.code)+' / '+esc(d.title)+' : '+(r.applicability==='required'?'الزامی':r.applicability==='optional'?'اختیاری':'غیرمجاز'),"afDeleteRule('"+r.id+"')"):''}).join('')||'<span class="af-hint">قاعده‌ای ثبت نشده است.</span>';
js/accounting-foundation-ui.js
+4 -4
@@ -2,13 +2,13 @@
2 function ensureAccountingFoundationView(){
3 if(document.getElementById('view-accounting-foundation'))return;
4 const s=document.createElement('section');s.id='view-accounting-foundation';s.className='view-pane';
5 - s.innerHTML=`<div class="af-head"><div><h1>هسته حسابداری</h1><p>کدینگ، تفصیلی شناور، سال مالی، شعب و پروژه‌های سراسری</p></div><span class="badge badge-info">فاز ۲</span></div>
6 - <div class="card" data-finora-task="accounts"><div style="display:flex;justify-content:space-between;gap:8px;align-items:center;flex-wrap:wrap"><div><h3>کدینگ حساب‌ها — کل ← معین ← تفصیلی</h3><p class="af-hint">می‌توانید کدینگ پیشنهادی نوع شرکت را بپذیرید، کدینگ را دستی بسازید یا روی شرکتِ دارای کدینگ خالی از Excel وارد کنید.</p></div><div style="display:flex;gap:6px;flex-wrap:wrap"><label class="btn btn-secondary btn-inline">ورود کدینگ از Excel<input type="file" accept=".xlsx,.xls" style="display:none" onchange="afImportAccountsFromExcel(event)"></label><button class="btn btn-secondary btn-inline" onclick="downloadAccountsExcelTemplate()">نمونه Excel کدینگ</button></div></div><div class="form-row">
5 + s.innerHTML=`<div class="af-head"><div><h1>ساختار حسابداری</h1><p>کدینگ حساب‌ها، تفصیلی‌های شناور، سال مالی، شعب و پروژه‌های سراسری</p></div></div>
6 + <div class="card" data-finora-task="accounts"><div style="display:flex;justify-content:space-between;gap:8px;align-items:center;flex-wrap:wrap"><div><h3>کدینگ حساب‌ها — کل ← معین ← تفصیلی</h3><p class="af-hint">کدینگ، ستون فقرات گزارش و ثبت است. حساب استفاده‌شده حذف یا بازتعریف ساختاری نمی‌شود؛ برای حفظ تاریخچه غیرفعال می‌شود.</p></div><div style="display:flex;gap:6px;flex-wrap:wrap"><label class="btn btn-secondary btn-inline">ورود کدینگ از Excel<input type="file" accept=".xlsx,.xls" style="display:none" onchange="afImportAccountsFromExcel(event)"></label><button class="btn btn-secondary btn-inline" onclick="downloadAccountsExcelTemplate()">نمونه Excel کدینگ</button></div></div><div class="form-row" style="margin-top:12px"><div class="form-group" style="grid-column:span 2"><label>جست‌وجوی حساب</label><input id="af-account-search" class="form-control" placeholder="کد یا عنوان حساب..." oninput="renderAccountingFoundation()"></div><div class="form-group"><label>سطح</label><select id="af-account-level-filter" class="form-control" onchange="renderAccountingFoundation()"><option value="">همه سطوح</option><option value="gl">کل</option><option value="subsidiary">معین</option><option value="detail">تفصیلی</option></select></div><div class="form-group"><label>نوع حساب</label><select id="af-account-type-filter" class="form-control" onchange="renderAccountingFoundation()"><option value="">همه انواع</option><option value="asset">دارایی</option><option value="liability">بدهی</option><option value="equity">حقوق مالکانه</option><option value="revenue">درآمد</option><option value="expense">هزینه</option><option value="memorandum">انتظامی</option><option value="control">کنترلی</option></select></div><div class="form-group"><label>وضعیت</label><select id="af-account-active-filter" class="form-control" onchange="renderAccountingFoundation()"><option value="active">فعال</option><option value="all">همه</option><option value="inactive">غیرفعال</option></select></div></div><div id="af-account-summary" class="af-hint" style="margin:-2px 0 12px"></div><div class="form-row">
7 <div class="form-group"><label>سطح</label><select id="af-account-level" class="form-control" onchange="afParents()"><option value="gl">کل</option><option value="subsidiary">معین</option><option value="detail">تفصیلی</option></select></div>
8 <div class="form-group"><label>کد</label><input id="af-account-code" class="form-control"></div><div class="form-group"><label>عنوان</label><input id="af-account-title" class="form-control"></div>
9 <div class="form-group"><label>ماهیت</label><select id="af-account-nature" class="form-control"><option value="debit">بدهکار</option><option value="credit">بستانکار</option><option value="both">دوماهیتی</option></select></div><div class="form-group"><label>نوع حساب</label><select id="af-account-type" class="form-control"><option value="asset">دارایی</option><option value="liability">بدهی</option><option value="equity">حقوق مالکانه</option><option value="revenue">درآمد</option><option value="expense">هزینه</option><option value="memorandum">انتظامی</option><option value="control">کنترلی</option></select></div><div class="form-group"><label>نقش سیستمی ثبت خودکار</label><select id="af-account-role" class="form-control"><option value="">— بدون نقش پیش‌فرض —</option><option value="cash_default">نقد/بانک پیش‌فرض</option><option value="receivable_control">دریافتنی تجاری</option><option value="payable_control">پرداختنی تجاری</option><option value="revenue_default">درآمد/فروش پیش‌فرض</option><option value="purchase_default">خرید/بهای تمام‌شده پیش‌فرض</option><option value="expense_default">هزینه پیش‌فرض</option><option value="other_income_default">سایر درآمد پیش‌فرض</option><option value="vat_payable">مالیات پرداختنی</option><option value="vat_recoverable">مالیات دریافتنی</option></select></div></div>
10 - <div class="form-group"><label>حساب والد</label><select id="af-account-parent" class="form-control"></select></div><button class="btn btn-success" onclick="afSaveAccount()">ثبت حساب</button>
11 - <div class="table-responsive af-space"><table><thead><tr><th>کد</th><th>عنوان</th><th>سطح</th><th>نوع</th><th>نقش سیستمی</th><th>ماهیت</th><th>ثبت</th><th></th></tr></thead><tbody id="af-accounts-body"></tbody></table></div></div>
10 + <div class="form-group"><label>حساب والد</label><select id="af-account-parent" class="form-control"></select></div><div style="display:flex;gap:8px;flex-wrap:wrap"><button id="af-account-save-btn" class="btn btn-success" onclick="afSaveAccount()">ثبت حساب</button><button id="af-account-edit-cancel" class="btn btn-secondary" style="display:none" onclick="afCancelAccountEdit()">انصراف از اصلاح</button></div>
11 + <div class="table-responsive af-space"><table><thead><tr><th>کد</th><th>عنوان / مسیر</th><th>سطح</th><th>نوع</th><th>نقش سیستمی</th><th>ماهیت</th><th>وضعیت</th><th>عملیات</th></tr></thead><tbody id="af-accounts-body"></tbody></table></div></div>
12 <div class="card" data-finora-task="rules"><h3>قواعد تفصیلی شناور</h3><div class="form-row"><div class="form-group"><label>حساب</label><select id="af-rule-account" class="form-control"></select></div><div class="form-group"><label>تفصیلی</label><select id="af-rule-dimension" class="form-control"></select></div><div class="form-group"><label>کاربرد</label><select id="af-rule-app" class="form-control"><option value="required">الزامی</option><option value="optional">اختیاری</option><option value="unavailable">غیرمجاز</option></select></div></div><button class="btn btn-primary" onclick="afSaveRule()">ثبت قاعده</button><div id="af-rules-list" class="af-list"></div></div>
13 <div class="card" data-finora-task="dimensions"><h3>ابعاد تحلیلی / تفصیلی‌های شناور</h3><p class="af-hint">چهار جایگاه سازگار با قرارداد: شناور ۱ شعبه، شناور ۲ طرف‌حساب، شناور ۳ پروژه، شناور ۴ قرارداد/پیمان. موتور داخلی Generic است و می‌توانید ابعاد بیشتری هم تعریف کنید. عمق ساختار بعد از ایجاد اولین مقدار قفل می‌شود و فقط Leaf نهایی قابل ثبت است.</p><div class="form-row"><div class="form-group"><label>کد</label><input id="af-dim-code" class="form-control"></div><div class="form-group"><label>عنوان</label><input id="af-dim-title" class="form-control"></div><div class="form-group"><label>منبع</label><select id="af-dim-source" class="form-control"><option value="manual">دستی</option><option value="contact">اشخاص</option><option value="project">پروژه‌ها</option><option value="branch">شعب</option><option value="contract">قرارداد / پیمان</option><option value="costCenter">مرکز هزینه</option></select></div><div class="form-group"><label>عمق ساختار (Hierarchy Depth)</label><input id="af-dim-depth" type="number" min="1" max="8" value="1" class="form-control"></div></div><button class="btn btn-success" onclick="afSaveDimension()">ثبت تفصیلی</button><div id="af-dimensions-list" class="af-list"></div>
14 <hr><div class="form-row"><div class="form-group"><label>تفصیلی دستی</label><select id="af-value-dim" class="form-control" onchange="renderAccountingFoundation()"></select></div><div class="form-group"><label>کد مقدار</label><input id="af-value-code" class="form-control"></div><div class="form-group"><label>عنوان مقدار</label><input id="af-value-title" class="form-control"></div><div class="form-group"><label>والد / سطح بالاتر</label><select id="af-value-parent" class="form-control"></select></div></div><button class="btn btn-primary" onclick="afSaveDimensionValue()">ثبت مقدار</button><div id="af-values-list" class="af-list"></div></div>
js/accounting-foundation.js
+8 -2
@@ -1,3 +1,4 @@
1 +let editingAccountId='';
2 /* Phase 2: accounting foundation — safety-first master data */
3 const AF_LEVELS={gl:'کل',subsidiary:'معین',detail:'تفصیلی'},AF_NATURE={debit:'بدهکار',credit:'بستانکار',both:'دوماهیتی'};
4 const AF_COMPANY_TYPES={
@@ -95,12 +96,17 @@ function afImportAccountsFromExcel(event){
96 if(!requireWrite())return;const file=event.target.files?.[0];if(!file)return;if(file.size>5*1024*1024){event.target.value='';return alert('حجم فایل کدینگ نباید بیشتر از ۵ مگابایت باشد.')}if(getMyAccounts().length){event.target.value='';return alert('ورود کدینگ فقط روی کدینگ خالی مجاز است؛ برای جلوگیری از ادغام ناامن، ابتدا شرکت با «شروع با کدینگ خالی» ایجاد شود.')}if(typeof XLSX==='undefined'){event.target.value='';return alert('موتور Excel در دسترس نیست.')}const reader=new FileReader();reader.onload=()=>{try{const wb=XLSX.read(reader.result,{type:'array'}),ws=wb.Sheets[wb.SheetNames[0]],rows=XLSX.utils.sheet_to_json(ws,{defval:''});if(rows.length>10000)throw new Error('حداکثر ۱۰٬۰۰۰ ردیف کدینگ در هر فایل مجاز است.');const items=afNormalizeAccountImportRows(rows),counts=items.reduce((m,x)=>(m[x.level]=(m[x.level]||0)+1,m),{});if(!confirm('پیش‌نمایش کدینگ: '+items.length.toLocaleString('fa-IR')+' حساب — کل '+(counts.gl||0).toLocaleString('fa-IR')+'، معین '+(counts.subsidiary||0).toLocaleString('fa-IR')+'، تفصیلی '+(counts.detail||0).toLocaleString('fa-IR')+'.\nپس از تأیید، فایل به‌صورت افزایشی روی کدینگ خالی وارد می‌شود.'))return;const cid=afNeedCompany();if(!cid)return;const byCode={};['gl','subsidiary','detail'].forEach(level=>items.filter(x=>x.level===level).forEach(x=>{const parentId=x.parentCode?byCode[x.parentCode]?.id||'':'';const a={id:afId('ACC'),ownerUserId:currentUser.id,companyId:cid,code:x.code,title:x.title,level,parentId,normalBalance:x.normalBalance,accountType:x.accountType||afAccountTypeForCode(x.code),systemRole:x.systemRole||'',postingAllowed:level==='detail',active:true,importedFrom:'excel',createdAt:new Date().toISOString()};datastore.accounts.push(a);byCode[x.code]=a}));saveDatastore();if(typeof jeEnsureDefaultProfiles==='function')jeEnsureDefaultProfiles();renderAccountingFoundation();alert(items.length.toLocaleString('fa-IR')+' حساب با موفقیت وارد شد.')}catch(e){alert('ورود کدینگ انجام نشد: '+e.message)}finally{event.target.value=''}};reader.readAsArrayBuffer(file);
97 }
98 function downloadAccountsExcelTemplate(){if(typeof XLSX==='undefined')return alert('موتور Excel در دسترس نیست.');const rows=[{code:'1',title:'دارایی‌ها',level:'کل',parent_code:'',normal_balance:'بدهکار',account_type:'دارایی'},{code:'11',title:'دارایی‌های جاری',level:'معین',parent_code:'1',normal_balance:'بدهکار',account_type:'دارایی'},{code:'1101',title:'بانک',level:'تفصیلی',parent_code:'11',normal_balance:'بدهکار',account_type:'دارایی',system_role:'cash_default'}],ws=XLSX.utils.json_to_sheet(rows),wb=XLSX.utils.book_new();XLSX.utils.book_append_sheet(wb,ws,'ChartOfAccounts');XLSX.writeFile(wb,'Finora-Chart-Of-Accounts-Template.xlsx')}
99 +function afAccountStructuralUse(id){return (datastore.journalLines||[]).some(x=>x.accountId===id)||(datastore.postingProfiles||[]).some(x=>x.debitAccountId===id||x.creditAccountId===id)||getMyAccounts().some(x=>x.parentId===id)||getMyAccountDimensionRules().some(x=>x.accountId===id)}
100 +function afStartAccountEdit(id){if(!requireWrite())return;const a=getMyAccounts().find(x=>x.id===id);if(!a)return;if(afAccountStructuralUse(id))return alert('این حساب در ساختار یا سوابق مالی استفاده شده است. برای حفظ تاریخچه، مشخصات ساختاری آن قابل بازتعریف نیست؛ در صورت نیاز آن را غیرفعال و حساب جدید ایجاد کنید.');editingAccountId=id;const vals={'af-account-level':a.level,'af-account-code':a.code,'af-account-title':a.title,'af-account-nature':a.normalBalance,'af-account-type':a.accountType||afAccountTypeForCode(a.code),'af-account-role':a.systemRole||''};Object.entries(vals).forEach(([id,v])=>{const el=document.getElementById(id);if(el)el.value=v});afParents();const parent=document.getElementById('af-account-parent');if(parent)parent.value=a.parentId||'';const b=document.getElementById('af-account-save-btn'),c=document.getElementById('af-account-edit-cancel');if(b)b.textContent='ذخیره اصلاح حساب';if(c)c.style.display='inline-flex';document.getElementById('af-account-code')?.focus();}
101 +function afCancelAccountEdit(){editingAccountId='';const b=document.getElementById('af-account-save-btn'),c=document.getElementById('af-account-edit-cancel');if(b)b.textContent='ثبت حساب';if(c)c.style.display='none';['af-account-code','af-account-title'].forEach(id=>{const el=document.getElementById(id);if(el)el.value=''})}
102 +function afToggleAccountActive(id){if(!requireWrite())return;const a=getMyAccounts().find(x=>x.id===id);if(!a)return;if(a.active===false)a.active=true;else{if(getMyAccounts().some(x=>x.parentId===id&&x.active!==false))return alert('ابتدا زیرحساب‌های فعال را غیرفعال کنید.');a.active=false;}a.updatedAt=new Date().toISOString();saveDatastore();renderAccountingFoundation()}
103 function afSaveAccount(){
104 if(!requireWrite())return;const cid=afNeedCompany();if(!cid)return;
105 const level=document.getElementById('af-account-level').value,code=afCode(document.getElementById('af-account-code').value),title=document.getElementById('af-account-title').value.trim(),normalBalance=document.getElementById('af-account-nature').value,accountType=document.getElementById('af-account-type')?.value||afAccountTypeForCode(code),systemRole=document.getElementById('af-account-role')?.value||'',parentId=document.getElementById('af-account-parent').value;
101 - if(!code||!title)return alert('کد و عنوان حساب الزامی است.');if(getMyAccounts().some(x=>x.code===code))return alert('کد حساب تکراری است.');if(systemRole&&level!=='detail')return alert('نقش سیستمی فقط برای حساب تفصیلی/ثبت‌پذیر مجاز است.');if(systemRole&&getMyAccounts().some(x=>x.systemRole===systemRole))return alert('برای این نقش سیستمی قبلاً یک حساب پیش‌فرض تعیین شده است.');
106 + if(!code||!title)return alert('کد و عنوان حساب الزامی است.');if(getMyAccounts().some(x=>x.code===code&&x.id!==editingAccountId))return alert('کد حساب تکراری است.');if(systemRole&&level!=='detail')return alert('نقش سیستمی فقط برای حساب تفصیلی/ثبت‌پذیر مجاز است.');if(systemRole&&getMyAccounts().some(x=>x.systemRole===systemRole&&x.id!==editingAccountId))return alert('برای این نقش سیستمی قبلاً یک حساب پیش‌فرض تعیین شده است.');
107 const need=level==='subsidiary'?'gl':level==='detail'?'subsidiary':'';if(need&&!getMyAccounts().some(x=>x.id===parentId&&x.level===need))return alert('حساب والد معتبر انتخاب کنید.');
103 - datastore.accounts.push({id:afId('ACC'),ownerUserId:currentUser.id,companyId:cid,code,title,level,parentId:parentId||'',normalBalance,accountType,systemRole,postingAllowed:level==='detail',active:true});saveDatastore();renderAccountingFoundation();
108 + if(editingAccountId){const a=getMyAccounts().find(x=>x.id===editingAccountId);if(!a)return afCancelAccountEdit();if(afAccountStructuralUse(a.id))return alert('حساب در این فاصله مورد استفاده قرار گرفته و دیگر قابل بازتعریف نیست.');Object.assign(a,{code,title,level,parentId:parentId||'',normalBalance,accountType,systemRole,postingAllowed:level==='detail',updatedAt:new Date().toISOString()});afCancelAccountEdit();}else datastore.accounts.push({id:afId('ACC'),ownerUserId:currentUser.id,companyId:cid,code,title,level,parentId:parentId||'',normalBalance,accountType,systemRole,postingAllowed:level==='detail',active:true});
109 + saveDatastore();renderAccountingFoundation();
110 }
111 function afDeleteAccount(id){if(!requireWrite())return;if((datastore.journalLines||[]).some(x=>x.accountId===id))return alert('این حساب در دفتر حسابداری استفاده شده و قابل حذف نیست؛ فقط غیرفعال‌سازی مجاز است.');if((datastore.postingProfiles||[]).some(x=>x.debitAccountId===id||x.creditAccountId===id))return alert('این حساب در پروفایل ثبت خودکار استفاده شده و قابل حذف نیست. ابتدا پروفایل مرتبط را جایگزین کنید.');if(getMyAccounts().some(x=>x.parentId===id))return alert('حساب دارای زیرحساب است.');if(getMyAccountDimensionRules().some(x=>x.accountId===id))return alert('ابتدا قواعد تفصیلی حساب را حذف کنید.');if(confirm('حساب حذف شود؟')){datastore.accounts=datastore.accounts.filter(x=>x.id!==id);saveDatastore();renderAccountingFoundation()}}
112 function afSaveRule(){if(!requireWrite())return;const cid=afNeedCompany(),accountId=document.getElementById('af-rule-account').value,dimensionTypeId=document.getElementById('af-rule-dimension').value,applicability=document.getElementById('af-rule-app').value,a=getMyAccounts().find(x=>x.id===accountId),d=getMyDimensionTypes().find(x=>x.id===dimensionTypeId);if(!cid||!a?.postingAllowed||!d?.active)return alert('حساب ثبت‌پذیر و تفصیلی فعال انتخاب کنید.');let r=getMyAccountDimensionRules().find(x=>x.accountId===accountId&&x.dimensionTypeId===dimensionTypeId);if(r)r.applicability=applicability;else datastore.accountDimensionRules.push({id:afId('ADR'),ownerUserId:currentUser.id,companyId:cid,accountId,dimensionTypeId,applicability,allowedValuesMode:'all',active:true});saveDatastore();renderAccountingFoundation()}
js/admin.js
+8 -13
@@ -2,15 +2,15 @@ let adminUsersCache=[];
2 async function renderAdminPanel(){
3 const tbody=document.getElementById('admin-users-table-body');
4 if(!tbody||!currentUser||currentUser.role!=='admin')return;
5 - tbody.innerHTML='<tr><td colspan="7" style="text-align:center;padding:20px">در حال بارگذاری کاربران...</td></tr>';
5 + tbody.innerHTML='<tr><td colspan="8" style="text-align:center;padding:20px">در حال بارگذاری کاربران...</td></tr>';
6 const [p,l]=await Promise.all([
7 - sb.from('profiles').select('id,email,username,role,created_at').order('created_at',{ascending:false}),
8 - sb.from('licenses').select('user_id,plan,status,starts_at,ends_at')
7 + sb.from('profiles').select('id,email,username,full_name,role,created_at').order('created_at',{ascending:false}),
8 + sb.from('licenses').select('*')
9 ]);
10 - if(p.error||l.error){tbody.innerHTML='<tr><td colspan="7" style="text-align:center;padding:20px;color:var(--danger)">خطا در دریافت لیست کاربران.</td></tr>';return;}
10 + if(p.error||l.error){tbody.innerHTML='<tr><td colspan="8" style="text-align:center;padding:20px;color:var(--danger)">خطا در دریافت لیست کاربران.</td></tr>';return;}
11 const lic=new Map((l.data||[]).map(x=>[x.user_id,x]));
12 adminUsersCache=(p.data||[]).map(u=>Object.assign({},u,{lic:lic.get(u.id)||null}));
13 - if(adminUsersCache.length===0){tbody.innerHTML='<tr><td colspan="7" style="text-align:center;padding:20px">هیچ کاربری یافت نشد.</td></tr>';return;}
13 + if(adminUsersCache.length===0){tbody.innerHTML='<tr><td colspan="8" style="text-align:center;padding:20px">هیچ کاربری یافت نشد.</td></tr>';return;}
14 const planLabels={monthly:'طرح ۱ ماهه',three_months:'طرح ۳ ماهه',annual:'طرح ۱ ساله',lifetime:'دائمی (Lifetime)',trial:'آزمایشی (Trial)'};
15 tbody.innerHTML=adminUsersCache.map(u=>{
16 const sub=u.lic?{type:u.lic.plan,startDate:u.lic.starts_at,endDate:u.lic.ends_at,status:u.lic.status}:{type:'trial',startDate:'',endDate:'',status:'cancelled'};
@@ -23,7 +23,7 @@ async function renderAdminPanel(){
23 const endJalali=sub.type==='lifetime'?'نامحدود':formatToJalali(sub.endDate);
24 const remDaysText=sub.type==='lifetime'?'نامحدود':toPersianDigits(Math.max(0,remDays))+' روز';
25 const uid=esc(u.id);
26 - return `<tr><td><strong>${esc(u.email||u.username||'—')}</strong> ${u.role==='admin'?'<span class="badge badge-info">مدیر</span>':''}</td><td>${statusBadge}</td><td>${esc(planLabels[sub.type]||sub.type)}</td><td>${formatToJalali(sub.startDate)}</td><td>${endJalali}</td><td>${remDaysText}</td><td style="display:flex;gap:6px;flex-wrap:wrap"><button class="btn btn-success btn-inline" style="padding:3px 8px;font-size:11px;min-height:30px" onclick="adminActivateLicense('${uid}')">فعال‌سازی</button><button class="btn btn-secondary btn-inline" style="padding:3px 8px;font-size:11px;min-height:30px" onclick="openLicenseEditModal('${uid}')">تغییر مدت</button><button class="btn btn-secondary btn-inline" style="padding:3px 8px;font-size:11px;min-height:30px" onclick="adminExtendSubscription('${uid}', 30)">+۳۰ روز</button>${sub.status!=='cancelled'?`<button class="btn btn-danger btn-inline" style="padding:3px 8px;font-size:11px;min-height:30px" onclick="adminCancelSubscription('${uid}')">لغو اشتراک</button>`:''}</td></tr>`;
26 + const capacity=Math.max(1,Number(u.lic?.max_companies||1));return `<tr><td><strong>${esc(u.full_name||u.email||u.username||'—')}</strong><small style="display:block;color:var(--text-muted)">${esc(u.email||'')}</small> ${u.role==='admin'?'<span class="badge badge-info">مدیر سیستم</span>':''}</td><td>${statusBadge}</td><td>${esc(planLabels[sub.type]||sub.type)}</td><td><strong>${toPersianDigits(capacity)}</strong> شرکت</td><td>${formatToJalali(sub.startDate)}</td><td>${endJalali}</td><td>${remDaysText}</td><td style="display:flex;gap:6px;flex-wrap:wrap"><button class="btn btn-success btn-inline" style="padding:3px 8px;font-size:11px;min-height:30px" onclick="adminActivateLicense('${uid}')">فعال‌سازی</button><button class="btn btn-secondary btn-inline" style="padding:3px 8px;font-size:11px;min-height:30px" onclick="openLicenseEditModal('${uid}')">تغییر مدت</button><button class="btn btn-secondary btn-inline" style="padding:3px 8px;font-size:11px;min-height:30px" onclick="adminExtendSubscription('${uid}', 30)">+۳۰ روز</button>${sub.status!=='cancelled'?`<button class="btn btn-danger btn-inline" style="padding:3px 8px;font-size:11px;min-height:30px" onclick="adminCancelSubscription('${uid}')">لغو اشتراک</button>`:''}</td></tr>`;
27 }).join('');
28 }
29 function refreshAdminPanel(){renderAdminPanel();}
@@ -43,16 +43,11 @@ function openLicenseEditModal(uid){
43 document.getElementById('modal-license-target-username').value=uid;
44 document.getElementById('modal-license-user-title').innerText='تغییر مدت و نوع لایسنس: '+(u.email||u.username);
45 const cur=u.lic&&u.lic.plan!=='trial'?u.lic.plan:'monthly';
46 - document.getElementById('modal-license-duration-select').value=cur;
46 + document.getElementById('modal-license-duration-select').value=cur;const cap=document.getElementById('modal-license-company-limit'),hint=document.getElementById('modal-license-company-limit-hint'),ready=!!(u.lic&&Object.prototype.hasOwnProperty.call(u.lic,'max_companies'));if(cap){cap.value=String(Math.max(1,Number(u.lic?.max_companies||1)));cap.disabled=!ready;}if(hint)hint.textContent=ready?'ظرفیت این لایسنس در سرور اعمال می‌شود.':'ظرفیت فعلاً روی پیش‌فرض ۱ شرکت است؛ Migration سرور آماده شده ولی هنوز اعمال نشده است.';
47 document.getElementById('modal-admin-license-edit').classList.add('active');
48 }
49 function closeLicenseEditModal(){document.getElementById('modal-admin-license-edit').classList.remove('active');}
50 -function applyLicenseDurationChange(){
51 - const uid=document.getElementById('modal-license-target-username').value;
52 - const plan=document.getElementById('modal-license-duration-select').value;
53 - closeLicenseEditModal();
54 - return adminRpc('admin_set_license',{target:uid,new_plan:plan,new_status:'active'},'طرح لایسنس کاربر تغییر یافت.');
55 -}
50 +async function applyLicenseDurationChange(){const uid=document.getElementById('modal-license-target-username').value,plan=document.getElementById('modal-license-duration-select').value,u=adminUsersCache.find(x=>x.id===uid),ready=!!(u?.lic&&Object.prototype.hasOwnProperty.call(u.lic,'max_companies')),cap=Math.max(1,Math.min(1000,Number(document.getElementById('modal-license-company-limit')?.value||1)));closeLicenseEditModal();const ok=await adminRpc('admin_set_license',{target:uid,new_plan:plan,new_status:'active'},'');if(!ok)return false;if(ready)return adminRpc('admin_set_company_limit',{target:uid,new_max_companies:cap},'لایسنس و ظرفیت شرکت کاربر اعمال شد.');alert('طرح لایسنس اعمال شد. ظرفیت شرکت فعلاً روی پیش‌فرض ۱ باقی می‌ماند تا Migration ظرفیت شرکت در سرور اعمال شود.');return true;}
51 function adminExtendSubscription(uid,days){
52 const u=adminUsersCache.find(x=>x.id===uid);
53 if(u&&u.lic&&u.lic.plan==='lifetime'){alert('این حساب دائمی است و نیازی به تمدید ندارد.');return;}
js/companies.js
+7 -4
@@ -2,6 +2,7 @@ let editingCompanyId='';
2 const COMPANY_ACTIVITY_LABELS={trading:'بازرگانی',service:'خدماتی',manufacturing:'تولیدی',contracting:'پیمانکاری',retail:'فروشگاهی',distribution:'پخش',nonprofit:'غیرانتفاعی',professional:'خدمات حرفه‌ای'};
3 const COMPANY_LEGAL_FORM_LABELS={natural_person:'شخص حقیقی',private_joint_stock:'سهامی خاص',public_joint_stock:'سهامی عام',limited_liability:'با مسئولیت محدود',general_partnership:'تضامنی',relative_partnership:'نسبی',mixed_non_stock:'مختلط غیرسهامی',mixed_stock:'مختلط سهامی',cooperative:'تعاونی',noncommercial_institution:'مؤسسه غیرتجاری',other:'سایر / نامشخص'};
4 const COMPANY_SECTOR_LABELS={private:'خصوصی',cooperative:'تعاونی',public_non_government:'عمومی غیردولتی',government:'دولتی / حکومتی',other:'سایر'};
5 +function handleCompanyOrganizationRoleChange(){const role=document.getElementById('company-organization-role')?.value||'standalone',box=document.getElementById('company-parent-box'),sel=document.getElementById('company-parent-id');if(box)box.style.display=role==='subsidiary'?'':'none';if(sel){const current=sel.value,editing=editingCompanyId;sel.innerHTML='<option value="">— انتخاب شرکت مادر —</option>'+getMyCompanies().filter(c=>c.id!==editing&&(c.organizationRole==='holding_parent'||c.organizationRole==='standalone')).map(c=>'<option value="'+esc(c.id)+'">'+esc(c.name)+'</option>').join('');if([...sel.options].some(o=>o.value===current))sel.value=current;}}
6 function handleCompanyEntityTypeChange(){
7 const entity=document.getElementById('company-entity-type'),sectorBox=document.getElementById('company-sector-box'),legalBox=document.getElementById('company-legal-form-box'),sector=document.getElementById('company-sector'),legal=document.getElementById('company-legal-form');
8 const isLegal=(entity?.value||'legal')==='legal';
@@ -23,7 +24,7 @@ function resetCompanyForm(){
24 const entity=document.getElementById('company-entity-type');if(entity)entity.value='legal';
25 const sector=document.getElementById('company-sector');if(sector)sector.value='private';
26 const legal=document.getElementById('company-legal-form');if(legal)legal.value='limited_liability';
26 - handleCompanyEntityTypeChange();
27 + handleCompanyEntityTypeChange();const orgRole=document.getElementById('company-organization-role');if(orgRole)orgRole.value='standalone';const parent=document.getElementById('company-parent-id');if(parent)parent.value='';handleCompanyOrganizationRoleChange();
28 const activity=document.getElementById('company-activity-type');if(activity)activity.value='trading';
29 const template=document.getElementById('company-accounting-template');if(template){template.value='recommended';template.disabled=false;}
30 const saveBtn=document.getElementById('company-save-btn');
@@ -36,9 +37,9 @@ function editCompany(id){
37 const comp=getMyCompanies().find(c=>c.id===id);
38 if(!comp)return;
39 editingCompanyId=id;
39 - const values={'company-entity-type':comp.entity_type||'legal','company-sector':comp.organizationSector||'private','company-legal-form':comp.legalForm||'other','company-activity-type':comp.activityType||'trading','company-name-input':comp.name||'','company-phone-input':comp.phone||'','company-national-input':comp.national_id||'','company-economic-input':comp.economic_code||'','company-reg-input':comp.reg_number||'','company-postal-input':comp.postal_code||'','company-address-input':comp.address||'','company-footer-input':comp.footer||''};
40 + const values={'company-entity-type':comp.entity_type||'legal','company-sector':comp.organizationSector||'private','company-legal-form':comp.legalForm||'other','company-organization-role':comp.organizationRole||'standalone','company-parent-id':comp.parentCompanyId||'','company-activity-type':comp.activityType||'trading','company-name-input':comp.name||'','company-phone-input':comp.phone||'','company-national-input':comp.national_id||'','company-economic-input':comp.economic_code||'','company-reg-input':comp.reg_number||'','company-postal-input':comp.postal_code||'','company-address-input':comp.address||'','company-footer-input':comp.footer||''};
41 Object.keys(values).forEach(id=>{const el=document.getElementById(id);if(el)el.value=values[id];});
41 - handleCompanyEntityTypeChange();
42 + handleCompanyEntityTypeChange();handleCompanyOrganizationRoleChange();const parentSel=document.getElementById('company-parent-id');if(parentSel&&comp.parentCompanyId)parentSel.value=comp.parentCompanyId;
43 const template=document.getElementById('company-accounting-template');if(template){const hasChart=(datastore.accounts||[]).some(a=>a.ownerUserId===currentUser.id&&a.companyId===comp.id);template.value=comp.accountingTemplate?'recommended':'empty';template.disabled=!!comp.accountingTemplate||hasChart;}
44 const saveBtn=document.getElementById('company-save-btn');
45 if(saveBtn){saveBtn.innerHTML='💾 ذخیره اصلاحات';saveBtn.className='btn btn-primary';}
@@ -57,8 +58,9 @@ function commitSaveCompany(){
58 const activityType=document.getElementById('company-activity-type')?.value||'trading';
59 const organizationSector=entity_type==='legal'?(document.getElementById('company-sector')?.value||'private'):'private';
60 const legalForm=entity_type==='legal'?(document.getElementById('company-legal-form')?.value||'other'):'natural_person';
61 + const organizationRole=document.getElementById('company-organization-role')?.value||'standalone',parentCompanyId=organizationRole==='subsidiary'?(document.getElementById('company-parent-id')?.value||''):'';if(organizationRole==='subsidiary'&&!parentCompanyId){alert('برای شرکت تابعه، شرکت مادر را مشخص کنید.');return;}
62 const templateChoice=document.getElementById('company-accounting-template')?.value||'empty';
61 - const payload={entity_type,organizationSector,legalForm,activityType,name:formatEntityName(raw_name,entity_type),phone:document.getElementById('company-phone-input').value||'',national_id:document.getElementById('company-national-input').value||'',economic_code:document.getElementById('company-economic-input').value||'',reg_number:document.getElementById('company-reg-input').value||'',postal_code:document.getElementById('company-postal-input').value||'',address:document.getElementById('company-address-input').value||'',footer:document.getElementById('company-footer-input')?.value||'از خرید شما سپاسگزاریم.'};
63 + const payload={entity_type,organizationSector,legalForm,organizationRole,parentCompanyId,activityType,name:formatEntityName(raw_name,entity_type),phone:document.getElementById('company-phone-input').value||'',national_id:document.getElementById('company-national-input').value||'',economic_code:document.getElementById('company-economic-input').value||'',reg_number:document.getElementById('company-reg-input').value||'',postal_code:document.getElementById('company-postal-input').value||'',address:document.getElementById('company-address-input').value||'',footer:document.getElementById('company-footer-input')?.value||'از خرید شما سپاسگزاریم.'};
64 if(payload.national_id&&getMyCompanies().some(x=>x.id!==editingCompanyId&&x.national_id===payload.national_id)){alert('شناسه ملی شرکت تکراری است.');return;}
65 if(editingCompanyId){
66 const comp=datastore.companies.find(c=>c.id===editingCompanyId&&c.ownerUserId===currentUser.id);
@@ -70,6 +72,7 @@ function commitSaveCompany(){
72 if(!hadChart&&!hadTemplate&&templateChoice==='recommended'&&typeof afApplyTemplate==='function')afApplyTemplate(comp.id,activityType);
73 alert(templateChoice==='recommended'&&!hadChart&&!hadTemplate?'اطلاعات شرکت اصلاح شد و کدینگ پیشنهادی متناسب با نوع فعالیت اعمال گردید.':'اطلاعات شرکت با موفقیت اصلاح شد.');
74 }else{
75 + const limit=Math.max(1,Number(currentUser.maxCompanies||1)),count=getMyCompanies().length;if(count>=limit){alert('ظرفیت این لایسنس '+toPersianDigits(limit)+' شرکت است. برای تعریف شرکت بیشتر، ظرفیت لایسنس باید توسط مدیر سیستم افزایش یابد.');return;}
76 const newComp={id:'COMP_'+Date.now(),ownerUserId:currentUser.id,...payload};
77 datastore.companies.push(newComp);
78 const s=getMySettings();
js/core.js
+7 -2
@@ -51,14 +51,15 @@ function isStrongPassword(v){const s=String(v||'');return s.length>=8&&/[A-Za-z]
51 function toEnDigits(s){
52 return String(s||'').replace(/[۰-۹]/g,d=>'۰۱۲۳۴۵۶۷۸۹'.indexOf(d)).replace(/[٠-٩]/g,d=>'٠١٢٣٤٥٦٧٨٩'.indexOf(d));
53 }
54 +const PROFESSIONAL_ROLE_LABELS={business_owner:'مالک / مدیر کسب‌وکار',financial_manager:'مدیر مالی',chief_accountant:'رئیس حسابداری',accountant:'حسابدار',treasury:'خزانه‌دار',sales:'فروش / بازرگانی',warehouse:'انباردار',auditor:'حسابرس / ناظر',other:'سایر'};
55 function buildUserFromRows(profile,lic){
56 const sub={type:lic.plan,startDate:lic.starts_at,endDate:lic.ends_at,status:lic.status};
56 - return {id:profile.id,email:profile.email||'',fullName:profile.full_name||'',username:profile.username||profile.email||'',role:profile.role,subscription:sub,subscriptionType:sub.type,subscriptionStart:sub.startDate,subscriptionEnd:sub.endDate,licenseStatus:sub.status};
57 + return {id:profile.id,email:profile.email||'',fullName:profile.full_name||'',username:profile.username||profile.email||'',role:profile.role,maxCompanies:Math.max(1,Number(lic.max_companies||1)),licenseCapacityServerReady:Object.prototype.hasOwnProperty.call(lic,'max_companies'),subscription:sub,subscriptionType:sub.type,subscriptionStart:sub.startDate,subscriptionEnd:sub.endDate,licenseStatus:sub.status};
58 }
59 async function fetchCurrentUser(authUser){
60 const [p,l]=await Promise.all([
61 sb.from('profiles').select('id,email,username,full_name,role').eq('id',authUser.id).single(),
61 - sb.from('licenses').select('plan,status,starts_at,ends_at').eq('user_id',authUser.id).single()
62 + sb.from('licenses').select('*').eq('user_id',authUser.id).single()
63 ]);
64 if(p.error)throw p.error;
65 if(l.error)throw l.error;
@@ -205,6 +206,7 @@ async function enterApp(authUser){
206 try{
207 currentUser=await fetchCurrentUser(authUser);
208 await pullAll();
209 + const prefs=typeof getMySettings==='function'?getMySettings():null;if(prefs?.user_display_name&&!currentUser.fullName)currentUser.fullName=prefs.user_display_name;if(prefs?.professional_role)currentUser.professionalRole=prefs.professional_role;
210 }catch(err){
211 console.error(err);
212 currentUser=null;
@@ -223,7 +225,10 @@ async function enterApp(authUser){
225 document.body.classList.toggle('is-admin',currentUser.role==='admin');
226 try{refreshAllSurfaces();}catch(e){console.error('refreshAllSurfaces failed',e);}
227 try{maybeMigrateLegacyData();}catch(e){console.error('maybeMigrateLegacyData failed',e);}
228 + try{maybeShowUserOnboarding(authUser);}catch(e){console.error('user onboarding failed',e);}
229 }
230 +function maybeShowUserOnboarding(authUser){if(!currentUser||typeof getMySettings!=='function')return;const s=getMySettings(),name=String(s.user_display_name||currentUser.fullName||authUser?.user_metadata?.full_name||authUser?.user_metadata?.name||'').trim();if(name&&s.professional_role){currentUser.fullName=name;currentUser.professionalRole=s.professional_role;return;}const modal=document.getElementById('modal-user-onboarding');if(!modal)return;const n=document.getElementById('onboarding-full-name'),r=document.getElementById('onboarding-professional-role');if(n)n.value=name;if(r&&s.professional_role)r.value=s.professional_role;modal.classList.add('active');}
231 +function saveUserOnboarding(){if(!currentUser||typeof getMySettings!=='function')return;const name=String(document.getElementById('onboarding-full-name')?.value||'').trim().replace(/\s+/g,' '),role=String(document.getElementById('onboarding-professional-role')?.value||'accountant');if(name.length<2)return alert('نام و نام خانوادگی را وارد کنید.');if(!Object.prototype.hasOwnProperty.call(PROFESSIONAL_ROLE_LABELS,role))return alert('نقش حرفه‌ای معتبر نیست.');const s=getMySettings();s.user_display_name=name;s.professional_role=role;s.onboarding_completed_at=new Date().toISOString();currentUser.fullName=name;currentUser.professionalRole=role;saveDatastore();const label=document.getElementById('logged-user-label');if(label)label.innerText='کاربر: '+name+(currentUser.role==='admin'?' (مدیر سیستم)':'');document.getElementById('modal-user-onboarding')?.classList.remove('active');}
232 async function handleLogout(){
233 if(syncPending&&!confirm('تغییرات ذخیره‌نشده وجود دارد. با خروج ممکن است از بین برود. خارج شوم؟'))return;
234 try{await sb.auth.signOut();}catch(e){}
js/ui.js
+1 -1
@@ -70,7 +70,7 @@ const FINORA_MODULES={
70 ]},
71 commerce:{title:'بازرگانی',context:'اشخاص، کالا، فروش و خرید',groups:[{title:'اشخاص و کالا',items:[['اشخاص','view-contacts','◎'],['کالا و خدمات','view-products','◇']]},{title:'فروش',items:[['فاکتور فروش','view-invoices','▤']]},{title:'خرید و تأمین',items:[['فاکتور خرید','view-purchases','▣']]}]},
72 treasury:{title:'خزانه‌داری',context:'دریافت، پرداخت، چک و کنترل نقدینگی',groups:[{title:'عملیات',items:[['دریافت و پرداخت','view-payments','↔'],['چک‌ها و صیاد','view-cheques','◈']]},{title:'کنترل',items:[['سن مطالبات و بدهی‌ها','view-accounting-reports','◷','','aging'],['جریان وجوه نقد','view-accounting-reports','↕','','cashflow']]}]},
73 - projects:{title:'پروژه و قرارداد',context:'پروژه، پیمان، کسورات، تضمین و صورت‌وضعیت',groups:[{title:'اطلاعات پایه',items:[['پروژه‌ها','view-accounting-foundation','▧','','projects']]},{title:'عملیات پیمان',items:[['قراردادها و پیمان','view-contracting','▦']]},{title:'گزارش',items:[['گزارش پروژه و پیمان','view-accounting-reports','▥','','projects']]}]},
73 + projects:{title:'پیمان‌ها',context:'پیمان، پروژه/کارگاه، کسورات، تضمین و صورت‌وضعیت',groups:[{title:'اطلاعات پایه',items:[['پروژه‌ها و کارگاه‌ها','view-accounting-foundation','▧','','projects']]},{title:'عملیات پیمان',items:[['پیمان‌ها و قراردادهای اجرایی','view-contracting','▦']]},{title:'گزارش',items:[['گزارش پیمان و پروژه','view-accounting-reports','▥','','projects']]}]},
74 inventory:{title:'انبار',context:'انبار، گردش، شمارش و بهای موجودی',groups:[{title:'اطلاعات پایه',items:[['تعریف انبار','view-inventory','▦','','warehouse']]},{title:'عملیات',items:[['گردش انبار','view-inventory','⇄','','movement'],['انبارگردانی','view-inventory','✓','','count']]},{title:'گزارش و کنترل',items:[['موجودی و بهای میانگین','view-inventory','▥','','stock']]}]},
75 assets:{title:'دارایی ثابت',context:'دارایی، استهلاک و ارزش دفتری',groups:[{title:'اطلاعات پایه',items:[['ثبت دارایی','view-assets','◆','','asset-new']]},{title:'عملیات و دفاتر',items:[['دفتر دارایی‌ها','view-assets','▤','','asset-register'],['استهلاک و سوابق','view-assets','◷','','depreciation']]}]},
76 reports:{title:'گزارش‌ها',context:'گزارش‌های حسابداری و مدیریتی',groups:[{title:'مدیریتی',items:[['گزارش‌های عملیاتی','view-reports','▥']]},{title:'حسابداری',items:[['تراز آزمایشی','view-accounting-reports','▥','','trial'],['دفاتر حسابداری','view-accounting-reports','▤','','ledger'],['صورت‌های مالی','view-accounting-reports','◫','','financials'],['جریان وجوه نقد','view-accounting-reports','↕','','cashflow'],['سن مطالبات / بدهی','view-accounting-reports','◷','','aging'],['پروژه / پیمان','view-accounting-reports','▧','','projects']]}]},
scripts/dom-smoke.spec.js
+1 -1
@@ -1,6 +1,6 @@
1 const {test,expect}=require('@playwright/test');
2 const {PDFDocument}=require('pdf-lib');
3 -test('real DOM shell and post-login smoke',async({page})=>{const errs=[];page.on('pageerror',e=>errs.push(String(e)));await page.goto('http://127.0.0.1:4173/index.html',{waitUntil:'domcontentloaded'});await expect(page.locator('#auth-screen')).toBeVisible();await expect(page.locator('[data-module="projects"]')).toHaveCount(1);await expect(page.locator('[data-module="dashboard"]')).toContainText('داشبورد');await expect(page.locator('[data-module="home"]')).toHaveCount(0);await expect(page.locator('[data-module="catalog"]')).toHaveCount(0);await expect(page.locator('[data-module="erp"]')).toHaveCount(0);await expect(page.locator('#view-contracting')).toHaveCount(1);await expect(page.locator('[data-module="inventory"]')).toHaveCount(1);await expect(page.locator('[data-module="assets"]')).toHaveCount(1);for(const id of ['view-inventory','view-assets','view-currency','view-data-center','view-integrations'])await expect(page.locator('#'+id)).toHaveCount(1);expect(await page.evaluate(()=>{const a=[...document.querySelectorAll('[id]')].map(x=>x.id),s=new Set(),d=[];for(const id of a){if(s.has(id))d.push(id);s.add(id)}return d})).toEqual([]);await page.evaluate(async()=>{fetchCurrentUser=async()=>({id:'smoke-user',email:'smoke@example.test',fullName:'Smoke Admin',username:'smoke',role:'admin',subscription:{type:'lifetime',status:'active',endDate:'2099-01-01'}});pullAll=async()=>{};refreshAllSurfaces=()=>{window.__smokeRefresh=true};maybeMigrateLegacyData=()=>{window.__smokeMigrate=true};await enterApp({id:'smoke-user'});});await expect(page.locator('#auth-screen')).toBeHidden();await expect(page.locator('body')).toHaveClass(/is-admin/);await expect(page.locator('#logged-user-label')).toContainText('Smoke Admin');await expect(page.locator('#module-panel-handle')).toBeVisible();await expect(page.locator('.module-panel-head .panel-collapse')).toHaveCount(0);await page.evaluate(()=>toggleModulePanel());await expect(page.locator('body')).toHaveClass(/shell-panel-collapsed/);await expect(page.locator('#module-panel-handle')).toBeVisible();await expect(page.locator('#module-panel-handle')).toHaveAttribute('aria-expanded','false');await page.click('#module-panel-handle');await expect(page.locator('body')).not.toHaveClass(/shell-panel-collapsed/);await page.evaluate(()=>openModule('accounting','view-accounting-foundation','accounts'));await expect(page.locator('#module-panel-links')).toContainText('ساختار مالی');await expect(page.locator('#module-panel-links')).toContainText('ثبت و عملیات');await expect(page.locator('#module-panel-links')).toContainText('دفاتر و کنترل');await expect(page.locator('#module-panel-links')).toContainText('صورت‌های مالی و تحلیل');await expect(page.locator('#module-panel-links [data-task="accounts"]')).toHaveClass(/active/);await page.fill('#global-command-search','تراز آزمایشی');await expect(page.locator('#command-search-results')).toContainText('تراز آزمایشی');await expect(page.locator('#view-accounting-foundation [data-finora-task="accounts"]')).toBeVisible();await expect(page.locator('#view-accounting-foundation [data-finora-task="dimensions"]')).toBeHidden();await page.evaluate(()=>switchView('view-accounting-foundation'));await expect(page.locator('#view-accounting-foundation [data-finora-task="dimensions"]')).toBeVisible();await page.evaluate(()=>navigateShell('accounting','view-accounting-foundation','accounts'));await page.evaluate(()=>navigateShell('settings','view-settings','company'));await expect(page.locator('#view-settings [data-finora-task="company"]')).toBeVisible();await expect(page.locator('#view-settings [data-finora-task="account"]')).toBeHidden();await expect(page.locator('#company-legal-form')).toContainText('سهامی خاص');await expect(page.locator('#company-legal-form')).toContainText('با مسئولیت محدود');await page.selectOption('#company-entity-type','natural');await page.evaluate(()=>handleCompanyEntityTypeChange());await expect(page.locator('#company-legal-form-box')).toBeHidden();await page.selectOption('#company-entity-type','legal');await page.evaluate(()=>handleCompanyEntityTypeChange());await expect(page.locator('#company-legal-form-box')).toBeVisible();await page.evaluate(()=>navigateShell('accounting','view-journal','new'));await expect(page.locator('#view-journal [data-finora-task="new"]')).toBeVisible();await expect(page.locator('#view-journal [data-finora-task="register"]')).toBeHidden();await page.evaluate(()=>navigateShell('accounting','view-journal','register'));await expect(page.locator('#view-journal [data-finora-task="register"]')).toBeVisible();await expect(page.locator('#view-journal [data-finora-task="new"]')).toBeHidden();await page.evaluate(()=>navigateShell('accounting','view-accounting-reports','trial'));await expect(page.locator('#p6-reporting-root [data-finora-task="trial"]')).toBeVisible();await expect(page.locator('#p6-reporting-root [data-finora-task="ledger"]')).toBeHidden();expect(await page.evaluate(()=>({refresh:window.__smokeRefresh,migrate:window.__smokeMigrate,admin:canShowShellCommand({guard:'admin'})}))).toEqual({refresh:true,migrate:true,admin:true});await page.evaluate(()=>{saveDatastore=()=>{};datastore.companies=[{id:'C1',ownerUserId:'smoke-user',name:'Smoke Co'}];datastore.settings=[{ownerUserId:'smoke-user',default_company_id:'C1'}];datastore.products=[{id:'P1',ownerUserId:'smoke-user',companyId:'C1',code:'1',name:'Smoke Product',type:'good',unit:'عدد',buy_price:100,sale_price:150,stock:0}];for(const k of ['warehouses','stockMovements','inventoryCounts','fixedAssets','assetDepreciations','currencies','exchangeRates','costCenters','importBatches','integrationConnections','integrationOutbox','phase5Audit'])datastore[k]=[];switchView('view-inventory');p5Render('view-inventory');});await expect(page.locator('#view-journal')).toBeHidden();await page.evaluate(()=>{switchView('view-dashboard');renderDashboard();});await expect(page.locator('#kpi-assets-sum')).toHaveCount(1);await expect(page.locator('#dashboard-cashflow-chart svg')).toHaveCount(1);await expect(page.locator('#dashboard-recent-journals')).toHaveCount(1);await page.evaluate(()=>{switchView('view-accounting-foundation');renderAccountingFoundation();});await expect(page.locator('#view-accounting-foundation')).toContainText('ورود کدینگ از Excel');await expect(page.locator('#view-accounting-foundation')).toContainText('شناور ۴ قرارداد/پیمان');await expect(page.locator('#af-account-type')).toHaveCount(1);await expect(page.locator('#af-account-role')).toHaveCount(1);await expect(page.locator('#af-dim-source option[value="contract"]')).toHaveCount(1);await page.evaluate(()=>{switchView('view-inventory');p5Render('view-inventory');});await expect(page.locator('#p5-inventory-root')).toContainText('انبار اصلی');await expect(page.locator('#p5-inventory-root')).toContainText('Smoke Product');await page.evaluate(()=>{switchView('view-accounting-reports');P6Reports.render();});await expect(page.locator('#p6-reporting-root')).toContainText('تراز آزمایشی');await expect(page.locator('#p6-reporting-root')).toContainText('صورت جریان وجوه نقد');expect(await page.evaluate(()=>{const a=[...document.querySelectorAll('[id]')].map(x=>x.id),s=new Set(),d=[];for(const id of a){if(s.has(id))d.push(id);s.add(id)}return d})).toEqual([]);await page.evaluate(()=>{window.__FINORA_PRINT_TEST_MODE=true;window.print=()=>{};const items=Array.from({length:25},(_,i)=>({prodName:'Item '+(i+1),qty:1,unit:'عدد',price:100,lineTotal:100}));datastore.invoices=[{id:'PRINT_FORMAL',ownerUserId:'smoke-user',companyId:'C1',contactId:'',kind:'formal',number:'F-1',date:'1405/07/07',items,subtotal:2500,discount:0,vat:250,grandTotal:2750,paymentMethod:'cash'}];renderAndPrintDirect('PRINT_FORMAL');});await expect(page.locator('#printable-invoice .invoice-a4-page')).toHaveCount(3);expect(await page.locator('#dynamic-print-orientation').evaluate(el=>el.innerHTML.includes('A4 landscape'))).toBe(true);await expect(page.locator('#finora-print-frame')).toHaveCount(1);expect(await page.locator('#finora-print-frame').evaluate(f=>({paper:f.contentDocument.querySelector('#finora-print-document')?.dataset.paper,orientation:f.contentDocument.querySelector('#finora-print-document')?.dataset.orientation,appUi:f.contentDocument.querySelectorAll('.view-pane,.app-shell-nav,.module-panel,.topbar').length,pages:f.contentDocument.querySelectorAll('.invoice-a4-page').length}))).toEqual({paper:'A4',orientation:'landscape',appUi:0,pages:3});await page.emulateMedia({media:'print'});expect(await page.locator('#printable-invoice .invoice-a4-page').first().evaluate(el=>getComputedStyle(el).breakAfter)).toBe('page');await page.emulateMedia({media:'screen'});await page.evaluate(()=>{datastore.invoices[0].id='PRINT_NONFORMAL';datastore.invoices[0].kind='informal';renderAndPrintDirect('PRINT_NONFORMAL');});await expect(page.locator('#printable-invoice .invoice-a4-page')).toHaveCount(3);expect(await page.locator('#dynamic-print-orientation').evaluate(el=>el.innerHTML.includes('A5 landscape'))).toBe(true);expect(await page.locator('#finora-print-frame').evaluate(f=>({paper:f.contentDocument.querySelector('#finora-print-document')?.dataset.paper,orientation:f.contentDocument.querySelector('#finora-print-document')?.dataset.orientation,appUi:f.contentDocument.querySelectorAll('.view-pane,.app-shell-nav,.module-panel,.topbar').length,pages:f.contentDocument.querySelectorAll('.invoice-a4-page').length}))).toEqual({paper:'A5',orientation:'landscape',appUi:0,pages:3});expect(errs.filter(x=>!x.includes('ResizeObserver'))).toEqual([]);});
3 +test('real DOM shell and post-login smoke',async({page})=>{const errs=[];page.on('pageerror',e=>errs.push(String(e)));await page.goto('http://127.0.0.1:4173/index.html',{waitUntil:'domcontentloaded'});await expect(page.locator('#auth-screen')).toBeVisible();await expect(page.locator('[data-module="projects"]')).toHaveCount(1);await expect(page.locator('[data-module="dashboard"]')).toContainText('داشبورد');await expect(page.locator('[data-module="home"]')).toHaveCount(0);await expect(page.locator('[data-module="catalog"]')).toHaveCount(0);await expect(page.locator('[data-module="erp"]')).toHaveCount(0);await expect(page.locator('#view-contracting')).toHaveCount(1);await expect(page.locator('[data-module="inventory"]')).toHaveCount(1);await expect(page.locator('[data-module="assets"]')).toHaveCount(1);for(const id of ['view-inventory','view-assets','view-currency','view-data-center','view-integrations'])await expect(page.locator('#'+id)).toHaveCount(1);expect(await page.evaluate(()=>{const a=[...document.querySelectorAll('[id]')].map(x=>x.id),s=new Set(),d=[];for(const id of a){if(s.has(id))d.push(id);s.add(id)}return d})).toEqual([]);await page.evaluate(async()=>{fetchCurrentUser=async()=>({id:'smoke-user',email:'smoke@example.test',fullName:'Smoke Admin',username:'smoke',role:'admin',subscription:{type:'lifetime',status:'active',endDate:'2099-01-01'}});pullAll=async()=>{};refreshAllSurfaces=()=>{window.__smokeRefresh=true};maybeMigrateLegacyData=()=>{window.__smokeMigrate=true};await enterApp({id:'smoke-user'});});await expect(page.locator('#auth-screen')).toBeHidden();await expect(page.locator('body')).toHaveClass(/is-admin/);await expect(page.locator('#logged-user-label')).toContainText('Smoke Admin');await expect(page.locator('#module-panel-handle')).toBeVisible();await expect(page.locator('[data-module="projects"] b')).toHaveText('پیمان‌ها');await expect(page.locator('.module-panel-head .panel-collapse')).toHaveCount(0);await page.evaluate(()=>toggleModulePanel());await expect(page.locator('body')).toHaveClass(/shell-panel-collapsed/);await expect(page.locator('#module-panel-handle')).toBeVisible();await expect(page.locator('#module-panel-handle')).toHaveAttribute('aria-expanded','false');await page.click('#module-panel-handle');await expect(page.locator('body')).not.toHaveClass(/shell-panel-collapsed/);await page.evaluate(()=>openModule('accounting','view-accounting-foundation','accounts'));await expect(page.locator('#module-panel-links')).toContainText('ساختار مالی');await expect(page.locator('#module-panel-links')).toContainText('ثبت و عملیات');await expect(page.locator('#module-panel-links')).toContainText('دفاتر و کنترل');await expect(page.locator('#module-panel-links')).toContainText('صورت‌های مالی و تحلیل');await expect(page.locator('#module-panel-links [data-task="accounts"]')).toHaveClass(/active/);await page.fill('#global-command-search','تراز آزمایشی');await expect(page.locator('#command-search-results')).toContainText('تراز آزمایشی');await expect(page.locator('#view-accounting-foundation [data-finora-task="accounts"]')).toBeVisible();await expect(page.locator('#view-accounting-foundation [data-finora-task="dimensions"]')).toBeHidden();await page.evaluate(()=>switchView('view-accounting-foundation'));await expect(page.locator('#view-accounting-foundation [data-finora-task="dimensions"]')).toBeVisible();await page.evaluate(()=>navigateShell('accounting','view-accounting-foundation','accounts'));await page.evaluate(()=>navigateShell('settings','view-settings','company'));await expect(page.locator('#view-settings [data-finora-task="company"]')).toBeVisible();await expect(page.locator('#view-settings [data-finora-task="account"]')).toBeHidden();await expect(page.locator('#company-legal-form')).toContainText('سهامی خاص');await expect(page.locator('#company-legal-form')).toContainText('با مسئولیت محدود');await page.selectOption('#company-entity-type','natural');await page.evaluate(()=>handleCompanyEntityTypeChange());await expect(page.locator('#company-legal-form-box')).toBeHidden();await page.selectOption('#company-entity-type','legal');await page.evaluate(()=>handleCompanyEntityTypeChange());await expect(page.locator('#company-legal-form-box')).toBeVisible();await expect(page.locator('#company-organization-role')).toContainText('شرکت مادر / هلدینگ');await expect(page.locator('#company-organization-role')).toContainText('شرکت تابعه');await page.evaluate(()=>navigateShell('accounting','view-journal','new'));await expect(page.locator('#view-journal [data-finora-task="new"]')).toBeVisible();await expect(page.locator('#view-journal [data-finora-task="register"]')).toBeHidden();await page.evaluate(()=>navigateShell('accounting','view-journal','register'));await expect(page.locator('#view-journal [data-finora-task="register"]')).toBeVisible();await expect(page.locator('#view-journal [data-finora-task="new"]')).toBeHidden();await page.evaluate(()=>navigateShell('accounting','view-accounting-reports','trial'));await expect(page.locator('#p6-reporting-root [data-finora-task="trial"]')).toBeVisible();await expect(page.locator('#p6-reporting-root [data-finora-task="ledger"]')).toBeHidden();expect(await page.evaluate(()=>({refresh:window.__smokeRefresh,migrate:window.__smokeMigrate,admin:canShowShellCommand({guard:'admin'})}))).toEqual({refresh:true,migrate:true,admin:true});await page.evaluate(()=>{saveDatastore=()=>{};datastore.companies=[{id:'C1',ownerUserId:'smoke-user',name:'Smoke Co'}];datastore.settings=[{ownerUserId:'smoke-user',default_company_id:'C1'}];datastore.products=[{id:'P1',ownerUserId:'smoke-user',companyId:'C1',code:'1',name:'Smoke Product',type:'good',unit:'عدد',buy_price:100,sale_price:150,stock:0}];for(const k of ['warehouses','stockMovements','inventoryCounts','fixedAssets','assetDepreciations','currencies','exchangeRates','costCenters','importBatches','integrationConnections','integrationOutbox','phase5Audit'])datastore[k]=[];switchView('view-inventory');p5Render('view-inventory');});await expect(page.locator('#view-journal')).toBeHidden();await page.evaluate(()=>{switchView('view-dashboard');renderDashboard();});await expect(page.locator('#kpi-assets-sum')).toHaveCount(1);await expect(page.locator('#dashboard-cashflow-chart svg')).toHaveCount(1);await expect(page.locator('#dashboard-recent-journals')).toHaveCount(1);await page.evaluate(()=>{switchView('view-accounting-foundation');renderAccountingFoundation();});await expect(page.locator('#view-accounting-foundation')).toContainText('ورود کدینگ از Excel');await expect(page.locator('#view-accounting-foundation')).toContainText('شناور ۴ قرارداد/پیمان');await expect(page.locator('#af-account-type')).toHaveCount(1);await expect(page.locator('#af-account-search')).toHaveCount(1);await expect(page.locator('#af-account-level-filter')).toHaveCount(1);await expect(page.locator('#af-account-role')).toHaveCount(1);await expect(page.locator('#af-dim-source option[value="contract"]')).toHaveCount(1);await page.evaluate(()=>{switchView('view-inventory');p5Render('view-inventory');});await expect(page.locator('#p5-inventory-root')).toContainText('انبار اصلی');await expect(page.locator('#p5-inventory-root')).toContainText('Smoke Product');await page.evaluate(()=>{switchView('view-accounting-reports');P6Reports.render();});await expect(page.locator('#p6-reporting-root')).toContainText('تراز آزمایشی');await expect(page.locator('#p6-reporting-root')).toContainText('صورت جریان وجوه نقد');expect(await page.evaluate(()=>{const a=[...document.querySelectorAll('[id]')].map(x=>x.id),s=new Set(),d=[];for(const id of a){if(s.has(id))d.push(id);s.add(id)}return d})).toEqual([]);await page.evaluate(()=>{window.__FINORA_PRINT_TEST_MODE=true;window.print=()=>{};const items=Array.from({length:25},(_,i)=>({prodName:'Item '+(i+1),qty:1,unit:'عدد',price:100,lineTotal:100}));datastore.invoices=[{id:'PRINT_FORMAL',ownerUserId:'smoke-user',companyId:'C1',contactId:'',kind:'formal',number:'F-1',date:'1405/07/07',items,subtotal:2500,discount:0,vat:250,grandTotal:2750,paymentMethod:'cash'}];renderAndPrintDirect('PRINT_FORMAL');});await expect(page.locator('#printable-invoice .invoice-a4-page')).toHaveCount(3);expect(await page.locator('#dynamic-print-orientation').evaluate(el=>el.innerHTML.includes('A4 landscape'))).toBe(true);await expect(page.locator('#finora-print-frame')).toHaveCount(1);expect(await page.locator('#finora-print-frame').evaluate(f=>({paper:f.contentDocument.querySelector('#finora-print-document')?.dataset.paper,orientation:f.contentDocument.querySelector('#finora-print-document')?.dataset.orientation,appUi:f.contentDocument.querySelectorAll('.view-pane,.app-shell-nav,.module-panel,.topbar').length,pages:f.contentDocument.querySelectorAll('.invoice-a4-page').length}))).toEqual({paper:'A4',orientation:'landscape',appUi:0,pages:3});await page.emulateMedia({media:'print'});expect(await page.locator('#printable-invoice .invoice-a4-page').first().evaluate(el=>getComputedStyle(el).breakAfter)).toBe('page');await page.emulateMedia({media:'screen'});await page.evaluate(()=>{datastore.invoices[0].id='PRINT_NONFORMAL';datastore.invoices[0].kind='informal';renderAndPrintDirect('PRINT_NONFORMAL');});await expect(page.locator('#printable-invoice .invoice-a4-page')).toHaveCount(3);expect(await page.locator('#dynamic-print-orientation').evaluate(el=>el.innerHTML.includes('A5 landscape'))).toBe(true);expect(await page.locator('#finora-print-frame').evaluate(f=>({paper:f.contentDocument.querySelector('#finora-print-document')?.dataset.paper,orientation:f.contentDocument.querySelector('#finora-print-document')?.dataset.orientation,appUi:f.contentDocument.querySelectorAll('.view-pane,.app-shell-nav,.module-panel,.topbar').length,pages:f.contentDocument.querySelectorAll('.invoice-a4-page').length}))).toEqual({paper:'A5',orientation:'landscape',appUi:0,pages:3});expect(errs.filter(x=>!x.includes('ResizeObserver'))).toEqual([]);});
4
5
6 test('expired license browser enforcement',async({page})=>{const errs=[];page.on('pageerror',e=>errs.push(String(e)));await page.goto('http://127.0.0.1:4173/index.html',{waitUntil:'domcontentloaded'});await page.evaluate(async()=>{window.__licenseAlerts=[];window.alert=m=>window.__licenseAlerts.push(String(m));fetchCurrentUser=async()=>({id:'expired-user',email:'expired@example.test',fullName:'Expired User',username:'expired',role:'user',subscription:{type:'monthly',status:'active',startDate:'2025-01-01',endDate:'2025-01-31'}});pullAll=async()=>{};refreshAllSurfaces=()=>{updateLicenseDisplay(currentUser)};maybeMigrateLegacyData=()=>{};await enterApp({id:'expired-user'});});await expect(page.locator('#auth-screen')).toBeHidden();await expect(page.locator('#user-license-status-badge')).toContainText('منقضی شده');expect(await page.evaluate(()=>canWrite())).toBe(false);expect(await page.evaluate(()=>requireWrite())).toBe(false);expect(await page.evaluate(()=>window.__licenseAlerts.some(x=>x.includes('منقضی')&&x.includes('امکان ثبت یا ویرایش')))).toBe(true);expect(errs.filter(x=>!x.includes('ResizeObserver'))).toEqual([]);});
scripts/quality-check.mjs
+5 -1
@@ -32,7 +32,7 @@ const must={
32 'print.js':['function renderAndPrintDirect','FORMAL_ROWS_PER_PAGE=12','const isPreInvoice=','function getInvoicePrintSpec',"kind==='non_formal'||kind==='informal'",'function buildIsolatedPrintDocument','function printIsolatedDocument',"frame.id='finora-print-frame'","paper:'A4'","paper:'A5'"],
33 'purchases.js':['window.purSave=function','window.purEdit=function','window.purPrint=function','window.purRefreshProjects=function','pur-payment-method','companyId'],
34 'projects.js':['editContactProject','deleteContactProject','addSubproject','editSubproject','deleteSubproject','usedExpense','usedPayment','projectDirectionLabel(s.direction||p.direction)','project-direction-select','return new Promise'],
35 - 'companies.js':['Object.entries(datastore)',"key!=='companies'",'default_company_id','organizationSector','legalForm','handleCompanyEntityTypeChange','companyLegalSummary'],
35 + 'companies.js':['Object.entries(datastore)',"key!=='companies'",'default_company_id','organizationSector','legalForm','organizationRole','parentCompanyId','handleCompanyEntityTypeChange','handleCompanyOrganizationRoleChange','companyLegalSummary','currentUser.maxCompanies'],
36 'operations.js':['editContact','editProduct','editCheque','editExpense','deleteInvoice','refreshExpenseProjects','projectId','getMyPayments','companyId',"q.status&&q.status!=='registered'",'چک تعیین‌تکلیف‌شده برای حفظ سابقه قابل حذف نیست'],
37 'selfcheck.js':['datastore.payments','invoices.has','purchases.has'],
38 'payments.js':['commitSavePayment','invoiceOutstanding','purchaseOutstanding','companyOk','legacyOk','amount>outstanding',"direction!=='inbound'","direction!=='outbound'",'projectId',"paymentMethod!=='credit'","old.invoiceType===invoiceType"],
@@ -113,3 +113,7 @@ if(!index.includes('id="view-accounting-reports"')||!index.includes('phase6-repo
113 if(!all['journal-ui.js']?.includes("s.className='view-pane'")||all['journal-ui.js']?.includes('فاز ۳'))throw new Error('Journal workspace must be isolated as a view-pane without development phase labels');
114 for(const id of ['company-sector','company-legal-form'])if(!ids.includes(id))throw new Error('Company legal identity control missing #'+id);
115 if(index.includes('class="panel-collapse"'))throw new Error('Disappearing panel close button must not return; use persistent edge handle');
116 +
117 +for(const id of ['modal-user-onboarding','onboarding-full-name','onboarding-professional-role','company-organization-role','company-parent-id','modal-license-company-limit','af-account-search','af-account-level-filter','af-account-type-filter','af-account-active-filter'])if(!ids.includes(id))throw new Error('Accountant-first UX control missing #'+id);
118 +if(!index.includes('title="پیمان‌ها"')||!all['ui.js'].includes("projects:{title:'پیمان‌ها'"))throw new Error('Primary projects subsystem must be visibly named پیمان‌ها');
119 +if(!all['core.js'].includes('PROFESSIONAL_ROLE_LABELS')||!all['core.js'].includes('saveUserOnboarding'))throw new Error('Professional onboarding contract missing');