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

Add Iran payroll petty cash ABC and group controls

davoodmehraban89 committed Sep 30, 2026 at 01:47 UTC cf428a93fb2af4b96ae836307c9605874204deeb
9 files changed +51 -7
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 expands Finora into a high-assurance Iran-first enterprise ERP governed by current Iranian Accounting Standards and applicable Iranian tax, VAT/Taxpayer System, commerce, labor/social-security and related compliance rules. Required domains include standards-aware financial statements and chart templates; employee end-of-service benefits and leave obligations; HR/payroll/employment/insurance; treasury/petty-cash and branch/currency cashboxes; inventory/cost accounting including ABC and performance-based budgeting where appropriate; holding/intercompany/consolidation and parent-level liquidity/inventory controls; management reporting across subsidiaries; and legal/compliance traceability. Owner also explicitly approves continuing and finishing previously prepared remaining work, including applying the prepared authoritative license company-capacity migration. Immediate UX correction: natural-person/counterparty/company forms must conditionally remove legal-entity-only fields such as registration number and must not model holding-parent/subsidiary position as a property of a natural person; legal identity, operational activity and group-company structure must be separate concepts. | IN PROGRESS | Verified pre-change head `b58dbc59`; latest executable head `8f8824a8` has Quality `36633047472` PASS including Real DOM and Golden Journey and Security `36633047693` PASS; docs head Pages `36633139737` PASS. Production Supabase is ACTIVE_HEALTHY with 17 migrations through `20260929193357`, RLS enabled on profiles/licenses/records, 97 records, performance advisor clean; five reviewed SECURITY DEFINER warnings and leaked-password protection warning remain. Next: archive official-source Iran compliance matrix, fix natural/legal person conditional UX and validation, apply/verify prepared license-capacity migration now explicitly authorized, then implement ERP domains as tested vertical slices without presenting roadmap-only modules as complete. Iran compliance baseline is now codified in `docs/IRAN_COMPLIANCE_MATRIX_V1.md`; volatile tax/rate/deadline values are explicitly effective-dated and source-referenced rather than treated as timeless constants. Preflight before the authorized license migration found existing company counts of 4 for one owner and 1 for another; migration SQL is therefore revised to grandfather each existing owner to at least their current company count while retaining default 1 for new licenses, preventing a retroactive entitlement inconsistency. Natural/legal entity correction is included in the same implementation checkpoint and is gated in Real DOM. Authorized production migration applied as `20260929220543 license_company_capacity`; existing capacities verify 4/4 and 1/1 for the two owners with companies, while zero-company licenses remain at default 1. Follow-up migration `20260929220613 restrict_company_limit_rpc` explicitly revoked anonymous execution; authenticated execution remains intentional and is protected by the internal `is_admin()` guard. Rollback-only non-admin JWT test confirmed `admin_set_company_limit` cannot mutate capacity (target remained 1). Iran-first implementation has now begun in code: `4c89a3f3` expands the editable starter chart with petty cash, rial/foreign cashboxes, intercompany receivable/payable, payroll/insurance/leave/end-of-service obligation accounts and corrects new manufacturing WIP classification to an asset; `f9cf28e4` clears hidden legal-only fields when a counterparty switches to natural person; `7d2bc806` adds the first HR/leave/treasury/compliance-registry vertical slice; `343c05fa`/`52b6cd55` expose and Real-DOM-gate the organization workspace. These are foundations, NOT a claim that payroll, tax submission, consolidation, ABC/ABB or all Iranian legal rules are complete. Production reconciliation correction: the owner’s current instruction to apply and finish these ERP changes was acted on for this non-destructive collection expansion. Production migration `20260929221252 iran_enterprise_foundation_collections` is APPLIED and archived exactly as `supabase/migrations/20260929221252_iran_enterprise_foundation_collections.sql`; it expands the existing owner-scoped `records` collection constraint and adds uniqueness indexes for personnel number, nonblank national ID, employee/year leave and cashbox code. The later prepared `20260930222500` placeholder is neutralized as a no-op to prevent duplicate DDL. Production index verification PASS; performance advisor remains clean. Combined Quality/Security/Real-DOM verification is still required before this enterprise slice is accepted. |\n| 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. Real-DOM fixture is updated so its synthetic admin has completed professional onboarding; this prevents the intentional first-login modal from masking unrelated shell acceptance while preserving a production onboarding path. Superseded Quality run `36632890281` on `7e7e5264` passed JavaScript syntax and failed only because the new static gate incorrectly searched `index.html` for Chart-of-Accounts controls that are intentionally generated by `accounting-foundation-ui.js`; this checkpoint corrects that gate to inspect the owning module. The prepared trigger function also has PUBLIC/anon/authenticated EXECUTE revoked because it is trigger-only. Superseded run `36632957187` on `22040d37` also stopped at the same already-corrected static-gate defect before later phases. Latest executable/test head `8f8824a8` is now verified: Quality run `36633047472` PASS including JavaScript syntax, application invariants, Phase 2–6, Golden Accounting Journey and Real DOM smoke; Security run `36633047693` PASS. The following docs-only head `78af1011` deployed successfully via Pages run `36633139737`. Prepared schema/RPC migration remains unapplied. Prepare (do not apply) the server migration for license company capacity. Prepared migration `supabase/migrations/20260930213000_license_company_capacity.sql` adds `licenses.max_companies default 1`, guarded admin RPC `admin_set_company_limit`, and a server-side AFTER INSERT company-count trigger so direct/sync inserts cannot bypass entitlement. It is intentionally NOT APPLIED pending the mandatory explicit schema/RPC approval. ERP/holding/CRM/payroll research and prioritization is archived in `docs/FINORA_ERP_EXPANSION_ROADMAP_V4.md`; CRM and payroll are P1 after financial-control P0, while true holding consolidation is P2 because it requires intercompany, mapping, translation, eliminations and consolidated close rather than just parent IDs. 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 expands Finora into a high-assurance Iran-first enterprise ERP governed by current Iranian Accounting Standards and applicable Iranian tax, VAT/Taxpayer System, commerce, labor/social-security and related compliance rules. Required domains include standards-aware financial statements and chart templates; employee end-of-service benefits and leave obligations; HR/payroll/employment/insurance; treasury/petty-cash and branch/currency cashboxes; inventory/cost accounting including ABC and performance-based budgeting where appropriate; holding/intercompany/consolidation and parent-level liquidity/inventory controls; management reporting across subsidiaries; and legal/compliance traceability. Owner also explicitly approves continuing and finishing previously prepared remaining work, including applying the prepared authoritative license company-capacity migration. Immediate UX correction: natural-person/counterparty/company forms must conditionally remove legal-entity-only fields such as registration number and must not model holding-parent/subsidiary position as a property of a natural person; legal identity, operational activity and group-company structure must be separate concepts. | IN PROGRESS | Verified pre-change head `b58dbc59`; latest executable head `8f8824a8` has Quality `36633047472` PASS including Real DOM and Golden Journey and Security `36633047693` PASS; docs head Pages `36633139737` PASS. Production Supabase is ACTIVE_HEALTHY with 17 migrations through `20260929193357`, RLS enabled on profiles/licenses/records, 97 records, performance advisor clean; five reviewed SECURITY DEFINER warnings and leaked-password protection warning remain. Next: archive official-source Iran compliance matrix, fix natural/legal person conditional UX and validation, apply/verify prepared license-capacity migration now explicitly authorized, then implement ERP domains as tested vertical slices without presenting roadmap-only modules as complete. Iran compliance baseline is now codified in `docs/IRAN_COMPLIANCE_MATRIX_V1.md`; volatile tax/rate/deadline values are explicitly effective-dated and source-referenced rather than treated as timeless constants. Enterprise v1 now exists in the live code for employees/contracts/leave/cashbox/petty-cash masters/compliance. This checkpoint extends it with accounting-connected payroll (1405 salary-tax rule version + social/unemployment rule versions), employee end-service/leave obligation accruals, posted petty-cash issue/expense/return with ceiling control, performance budgets, ABC cost-driver allocation, reciprocal intercompany matching and parent-level cash/intercompany control. The prior end-service estimator is corrected to use Jalali service periods rather than Gregorian JavaScript Date parsing. Statutory AS39 consolidated statements are intentionally not claimed until mapping/elimination/NCI/policy-period/FX translation controls exist. Preflight before the authorized license migration found existing company counts of 4 for one owner and 1 for another; migration SQL is therefore revised to grandfather each existing owner to at least their current company count while retaining default 1 for new licenses, preventing a retroactive entitlement inconsistency. Natural/legal entity correction is included in the same implementation checkpoint and is gated in Real DOM. Authorized production migration applied as `20260929220543 license_company_capacity`; existing capacities verify 4/4 and 1/1 for the two owners with companies, while zero-company licenses remain at default 1. Follow-up migration `20260929220613 restrict_company_limit_rpc` explicitly revoked anonymous execution; authenticated execution remains intentional and is protected by the internal `is_admin()` guard. Rollback-only non-admin JWT test confirmed `admin_set_company_limit` cannot mutate capacity (target remained 1). Iran-first implementation has now begun in code: `4c89a3f3` expands the editable starter chart with petty cash, rial/foreign cashboxes, intercompany receivable/payable, payroll/insurance/leave/end-of-service obligation accounts and corrects new manufacturing WIP classification to an asset; `f9cf28e4` clears hidden legal-only fields when a counterparty switches to natural person; `7d2bc806` adds the first HR/leave/treasury/compliance-registry vertical slice; `343c05fa`/`52b6cd55` expose and Real-DOM-gate the organization workspace. These are foundations, NOT a claim that payroll, tax submission, consolidation, ABC/ABB or all Iranian legal rules are complete. Production reconciliation correction: the owner’s current instruction to apply and finish these ERP changes was acted on for this non-destructive collection expansion. Production migration `20260929221252 iran_enterprise_foundation_collections` is APPLIED and archived exactly as `supabase/migrations/20260929221252_iran_enterprise_foundation_collections.sql`; it expands the existing owner-scoped `records` collection constraint and adds uniqueness indexes for personnel number, nonblank national ID, employee/year leave and cashbox code. The later prepared `20260930222500` placeholder is neutralized as a no-op to prevent duplicate DDL. Production index verification PASS; performance advisor remains clean. Combined Quality/Security/Real-DOM verification is still required before this enterprise slice is accepted. |\n| 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. Real-DOM fixture is updated so its synthetic admin has completed professional onboarding; this prevents the intentional first-login modal from masking unrelated shell acceptance while preserving a production onboarding path. Superseded Quality run `36632890281` on `7e7e5264` passed JavaScript syntax and failed only because the new static gate incorrectly searched `index.html` for Chart-of-Accounts controls that are intentionally generated by `accounting-foundation-ui.js`; this checkpoint corrects that gate to inspect the owning module. The prepared trigger function also has PUBLIC/anon/authenticated EXECUTE revoked because it is trigger-only. Superseded run `36632957187` on `22040d37` also stopped at the same already-corrected static-gate defect before later phases. Latest executable/test head `8f8824a8` is now verified: Quality run `36633047472` PASS including JavaScript syntax, application invariants, Phase 2–6, Golden Accounting Journey and Real DOM smoke; Security run `36633047693` PASS. The following docs-only head `78af1011` deployed successfully via Pages run `36633139737`. Prepared schema/RPC migration remains unapplied. Prepare (do not apply) the server migration for license company capacity. Prepared migration `supabase/migrations/20260930213000_license_company_capacity.sql` adds `licenses.max_companies default 1`, guarded admin RPC `admin_set_company_limit`, and a server-side AFTER INSERT company-count trigger so direct/sync inserts cannot bypass entitlement. It is intentionally NOT APPLIED pending the mandatory explicit schema/RPC approval. ERP/holding/CRM/payroll research and prioritization is archived in `docs/FINORA_ERP_EXPANSION_ROADMAP_V4.md`; CRM and payroll are P1 after financial-control P0, while true holding consolidation is P2 because it requires intercompany, mapping, translation, eliminations and consolidated close rather than just parent IDs. 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
+1 -1
@@ -886,7 +886,7 @@ body{background:#f6f9fc}
886 <script src="js/phase5-domain.js?v=20260929-phase5-v1"></script>
887 <script src="js/phase5-enterprise.js?v=20260929-phase5-v1"></script>
888 <script src="js/phase6-reporting.js?v=20260929-phase6-v1"></script>
889 -<script src="js/enterprise-iran.js?v=20260930-iran-erp-v1"></script>
889 +<script src="js/enterprise-iran.js?v=20260930-iran-erp-v1"></script>\n<script src="js/enterprise-iran-v2.js?v=20260930-iran-erp-v2"></script>
890 <script src="js/selfcheck.js?v=20260928-release-1-0"></script>
891
892 </body>
js/core.js
+1 -1
@@ -34,7 +34,7 @@ const SUPABASE_URL='https://hcsixhqbyuhpshfwqpjx.supabase.co';
34 const SUPABASE_KEY='sb_publishable_2y8IsGdhqeLDPkEp7mBF4w_X4yji16D'; // publishable (public by design); access is enforced by RLS on the server
35 const sb=window.supabase.createClient(SUPABASE_URL,SUPABASE_KEY,{auth:{persistSession:true,autoRefreshToken:true,detectSessionInUrl:true,flowType:'pkce'}});
36 const ID_RE=/^[A-Za-z0-9_-]{1,64}$/;
37 -const COLLS=['companies','contacts','products','invoices','purchases','cheques','expenses','payments','settings','fiscalYears','accounts','dimensionTypes','dimensionValues','accountDimensionRules','branches','projects','projectLinks','postingProfiles','journalVouchers','journalLines','journalLineDimensions','contracts','contractAmendments','contractParties','contractDeductions','guarantees','guaranteeEvents','contractStatements','phase4Audit','warehouses','stockMovements','inventoryCounts','fixedAssets','assetDepreciations','currencies','exchangeRates','costCenters','importBatches','integrationConnections','integrationOutbox','phase5Audit','employees','employmentContracts','employeeLeave','cashboxes','pettyCashFunds','complianceRules'];
37 +const COLLS=['companies','contacts','products','invoices','purchases','cheques','expenses','payments','settings','fiscalYears','accounts','dimensionTypes','dimensionValues','accountDimensionRules','branches','projects','projectLinks','postingProfiles','journalVouchers','journalLines','journalLineDimensions','contracts','contractAmendments','contractParties','contractDeductions','guarantees','guaranteeEvents','contractStatements','phase4Audit','warehouses','stockMovements','inventoryCounts','fixedAssets','assetDepreciations','currencies','exchangeRates','costCenters','importBatches','integrationConnections','integrationOutbox','phase5Audit','employees','employmentContracts','employeeLeave','cashboxes','pettyCashFunds','complianceRules','payrollRuns','payrollLines','employeeBenefitAccruals','pettyCashTransactions','budgets','costDrivers','costAllocations','intercompanyTransactions','enterpriseAudit'];
38
39 function esc(v){return String(v==null?'':v).replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/"/g,'&quot;').replace(/'/g,'&#39;');}
40 function todayISO(){return new Intl.DateTimeFormat('en-CA',{timeZone:'Asia/Tehran',year:'numeric',month:'2-digit',day:'2-digit'}).format(new Date());}
js/enterprise-iran-v2.js new
+31
@@ -0,0 +1,31 @@
1 +/* Iran enterprise v2 — payroll, employee obligations, petty-cash posting, ABC/budget and group controls. */
2 +const enterpriseRenderV1=window.enterpriseRender;
3 +const IR_V2={salaryTax1405:'IR-TAX-SALARY-1405',social:'IR-SSI-28',unemployment:'IR-UNEMPLOYMENT-5',vat1405:'IR-VAT-1405'};
4 +function entV2Rows(k,all=false){const cid=entCid();return entRows(k).filter(x=>all||x.companyId===cid)}
5 +function entV2Num(v){const n=Number(String(v??'').replace(/,/g,''));return Number.isFinite(n)?Math.round(n):0}
6 +function entV2Audit(action,entity,id,after){datastore.enterpriseAudit.push({id:entId('EA'),ownerUserId:currentUser.id,companyId:entCid(),action,entity,entityId:id,after:after||null,at:new Date().toISOString()})}
7 +function entSalaryTax1405(x){x=Math.max(0,entV2Num(x));const b=[[400000000,0],[800000000,.10],[1000000000,.15],[1200000000,.20],[1400000000,.25],[Infinity,.30]];let p=0,t=0;for(const [c,r] of b){const q=Math.min(x,c);if(q>p)t+=(q-p)*r;if(x<=c)break;p=c}return Math.round(t)}
8 +function entEnsureFinancialAccounts(){const cid=entCid(),co=getMyCompanies().find(x=>x.id===cid);if(!cid||!co?.accountingTemplate)return;const specs=[['1109','تنخواه‌گردان','debit','11','asset'],['1110','حساب‌های فی‌مابین دریافتنی','debit','11','asset'],['2106','حقوق و دستمزد پرداختنی','credit','21','liability'],['2107','بیمه پرداختنی','credit','21','liability'],['2108','مالیات حقوق پرداختنی','credit','21','liability'],['2109','ذخیره مزایای پایان خدمت کارکنان','credit','21','liability'],['2110','حساب‌های فی‌مابین پرداختنی','credit','21','liability'],['2111','تعهد مرخصی استفاده‌نشده','credit','21','liability'],['6110','هزینه بیمه سهم کارفرما','debit','61','expense'],['6111','هزینه مزایای پایان خدمت کارکنان','debit','61','expense'],['6112','هزینه مرخصی کارکنان','debit','61','expense']];const by=Object.fromEntries(getMyAccounts().map(a=>[a.code,a]));let ch=false;for(const [code,title,normalBalance,parentCode,accountType] of specs){if(by[code])continue;const p=by[parentCode];if(!p)continue;const a={id:afId('ACC'),ownerUserId:currentUser.id,companyId:cid,code,title,level:'detail',parentId:p.id,normalBalance,accountType,postingAllowed:true,active:true,template:'iran-enterprise-v2'};datastore.accounts.push(a);by[code]=a;ch=true}if(ch)saveDatastore()}
9 +function entV2Acc(code){return getMyAccounts().find(a=>a.code===code&&a.active!==false&&a.postingAllowed)||null}
10 +function entServiceYears(start,end){const p=s=>String(s||'').replace(/-/g,'/').split('/').map(Number);const a=p(start),b=p(end||getJalaliNumeric());if(a.length<3||b.length<3||a.some(Number.isNaN)||b.some(Number.isNaN))return 0;return Math.max(0,(b[0]-a[0])+(b[1]-a[1])/12+(b[2]-a[2])/365)}
11 +enterpriseEndServiceEstimate=function(c){return Math.max(0,Math.round(Number(c.lastMonthlyWage||0)*entServiceYears(c.startDate,c.endDate)))};
12 +function entSavePayrollLine(){if(!requireWrite())return;const period=document.getElementById('ent2-pay-period')?.value.trim(),employeeId=document.getElementById('ent2-pay-employee')?.value,gross=entV2Num(document.getElementById('ent2-pay-gross')?.value),insuranceBase=entV2Num(document.getElementById('ent2-pay-ins')?.value),taxable=entV2Num(document.getElementById('ent2-pay-taxable')?.value);if(!period||!employeeId||gross<=0||insuranceBase<0||taxable<0)return alert('اطلاعات حقوق معتبر نیست.');let run=entV2Rows('payrollRuns').find(x=>x.period===period&&x.status==='draft');if(!run){run={id:entId('PR'),ownerUserId:currentUser.id,companyId:entCid(),period,status:'draft',ruleVersions:{salaryTax:IR_V2.salaryTax1405,social:IR_V2.social,unemployment:IR_V2.unemployment},createdAt:new Date().toISOString()};datastore.payrollRuns.push(run)}if(entV2Rows('payrollLines').some(x=>x.runId===run.id&&x.employeeId===employeeId))return alert('این کارکن در این دوره قبلاً ثبت شده است.');const employeeInsurance=Math.round(insuranceBase*.07),employerInsurance=Math.round(insuranceBase*.23),tax=period.startsWith('1405/')?entSalaryTax1405(taxable):0,net=gross-employeeInsurance-tax;if(net<0)return alert('خالص پرداختنی منفی است.');const r={id:entId('PL'),ownerUserId:currentUser.id,companyId:entCid(),runId:run.id,employeeId,gross,insuranceBase,taxable,employeeInsurance,employerInsurance,tax,net,ruleVersions:run.ruleVersions};datastore.payrollLines.push(r);entV2Audit('create','payrollLine',r.id,r);saveDatastore();enterpriseRender('payroll')}
13 +function entPostPayroll(id){if(!requireWrite())return;const run=entV2Rows('payrollRuns').find(x=>x.id===id&&x.status==='draft'),ls=entV2Rows('payrollLines').filter(x=>x.runId===id);if(!run||!ls.length)return alert('دوره حقوق معتبر نیست.');entEnsureFinancialAccounts();const wage=entV2Acc('6101')||jeExpenseAccount(),insExp=entV2Acc('6110'),pay=entV2Acc('2106'),insPay=entV2Acc('2107'),taxPay=entV2Acc('2108');if(!wage||!insExp||!pay||!insPay||!taxPay)return alert('کدینگ حقوق، بیمه و مالیات کامل نیست.');const gross=ls.reduce((s,x)=>s+x.gross,0),er=ls.reduce((s,x)=>s+x.employerInsurance,0),ee=ls.reduce((s,x)=>s+x.employeeInsurance,0),tax=ls.reduce((s,x)=>s+x.tax,0),net=ls.reduce((s,x)=>s+x.net,0);try{const v=jeCreateDraft({date:run.period+'/29',description:'حقوق و دستمزد '+run.period,sourceType:'payroll_run',sourceId:run.id,lines:[{accountId:wage.id,debit:gross,credit:0,description:'حقوق ناخالص',dimensions:[]},{accountId:insExp.id,debit:er,credit:0,description:'بیمه سهم کارفرما',dimensions:[]},{accountId:pay.id,debit:0,credit:net,description:'خالص پرداختنی',dimensions:[]},{accountId:insPay.id,debit:0,credit:ee+er,description:'بیمه پرداختنی',dimensions:[]},{accountId:taxPay.id,debit:0,credit:tax,description:'مالیات حقوق پرداختنی',dimensions:[]}]});jePost(v.id);Object.assign(run,{status:'posted',accountingStatus:'posted',journalVoucherId:v.id,postedAt:new Date().toISOString()});entV2Audit('post','payrollRun',run.id,{journalVoucherId:v.id});saveDatastore();enterpriseRender('payroll')}catch(e){alert(e.message)}}
14 +function entAccrueBenefit(){if(!requireWrite())return;const employeeId=document.getElementById('ent2-ben-employee')?.value,kind=document.getElementById('ent2-ben-kind')?.value,period=document.getElementById('ent2-ben-period')?.value.trim(),amount=entV2Num(document.getElementById('ent2-ben-amount')?.value),basis=document.getElementById('ent2-ben-basis')?.value.trim();if(!employeeId||!period||amount<=0||!basis)return alert('کارکن، دوره، مبلغ و مبنای برآورد الزامی است.');entEnsureFinancialAccounts();const exp=entV2Acc(kind==='end_service'?'6111':'6112'),liab=entV2Acc(kind==='end_service'?'2109':'2111');if(!exp||!liab)return alert('کدینگ تعهدات کارکنان کامل نیست.');const r={id:entId('BEN'),ownerUserId:currentUser.id,companyId:entCid(),employeeId,kind,period,amount,basis,status:'draft',ruleVersion:kind==='end_service'?'IR-LABOR-24':'IR-LABOR-66/71'};datastore.employeeBenefitAccruals.push(r);try{const v=jeCreateDraft({date:period+'/29',description:(kind==='end_service'?'برآورد مزایای پایان خدمت':'برآورد تعهد مرخصی')+' '+period,sourceType:'employee_benefit_accrual',sourceId:r.id,lines:[{accountId:exp.id,debit:amount,credit:0,description:basis,dimensions:[]},{accountId:liab.id,debit:0,credit:amount,description:basis,dimensions:[]}]});jePost(v.id);Object.assign(r,{status:'posted',accountingStatus:'posted',journalVoucherId:v.id,postedAt:new Date().toISOString()});entV2Audit('post','employeeBenefitAccrual',r.id,r);saveDatastore();enterpriseRender('benefits')}catch(e){datastore.employeeBenefitAccruals=datastore.employeeBenefitAccruals.filter(x=>x.id!==r.id);saveDatastore();alert(e.message)}}
15 +function entPettyBalance(id){return entV2Rows('pettyCashTransactions').filter(x=>x.fundId===id&&x.status==='posted').reduce((s,x)=>s+(x.kind==='issue'?x.amount:-x.amount),0)}
16 +function entPostPetty(){if(!requireWrite())return;const fundId=document.getElementById('ent2-pt-fund')?.value,kind=document.getElementById('ent2-pt-kind')?.value,amount=entV2Num(document.getElementById('ent2-pt-amount')?.value),date=document.getElementById('ent2-pt-date')?.value.trim()||getJalaliNumeric(),description=document.getElementById('ent2-pt-desc')?.value.trim(),fund=entV2Rows('pettyCashFunds').find(x=>x.id===fundId);if(!fund||amount<=0||!description)return alert('تنخواه، مبلغ و شرح الزامی است.');const bal=entPettyBalance(fundId);if(kind!=='issue'&&amount>bal)return alert('مانده تنخواه کافی نیست.');if(kind==='issue'&&bal+amount>Number(fund.approvedLimit||0))return alert('سقف مصوب تنخواه رعایت نشده است.');entEnsureFinancialAccounts();const cash=jeCashAccount(),petty=entV2Acc('1109'),expense=jeExpenseAccount();if(!cash||!petty||(kind==='expense'&&!expense))return alert('کدینگ صندوق/تنخواه/هزینه کامل نیست.');const r={id:entId('PT'),ownerUserId:currentUser.id,companyId:entCid(),fundId,kind,amount,date,description,status:'draft'};datastore.pettyCashTransactions.push(r);const lines=kind==='issue'?[{accountId:petty.id,debit:amount,credit:0,description,dimensions:[]},{accountId:cash.id,debit:0,credit:amount,description,dimensions:[]}]:kind==='expense'?[{accountId:expense.id,debit:amount,credit:0,description,dimensions:[]},{accountId:petty.id,debit:0,credit:amount,description,dimensions:[]}]:[{accountId:cash.id,debit:amount,credit:0,description,dimensions:[]},{accountId:petty.id,debit:0,credit:amount,description,dimensions:[]}];try{const v=jeCreateDraft({date,description:'تنخواه — '+description,sourceType:'petty_cash',sourceId:r.id,lines});jePost(v.id);Object.assign(r,{status:'posted',accountingStatus:'posted',journalVoucherId:v.id,postedAt:new Date().toISOString()});entV2Audit('post','pettyCashTransaction',r.id,r);saveDatastore();enterpriseRender('pettyops')}catch(e){datastore.pettyCashTransactions=datastore.pettyCashTransactions.filter(x=>x.id!==r.id);saveDatastore();alert(e.message)}}
17 +function entSaveBudget(){if(!requireWrite())return;const period=document.getElementById('ent2-b-period')?.value.trim(),amount=entV2Num(document.getElementById('ent2-b-amount')?.value),measure=document.getElementById('ent2-b-measure')?.value.trim(),target=Number(document.getElementById('ent2-b-target')?.value||0);if(!period||amount<0)return alert('بودجه معتبر نیست.');const r={id:entId('BDG'),ownerUserId:currentUser.id,companyId:entCid(),period,amount,measure,target,method:measure?'performance':'financial',status:'approved'};datastore.budgets.push(r);entV2Audit('create','budget',r.id,r);saveDatastore();enterpriseRender('costing')}
18 +function entSaveDriver(){if(!requireWrite())return;const name=document.getElementById('ent2-d-name')?.value.trim(),unit=document.getElementById('ent2-d-unit')?.value.trim(),poolCost=entV2Num(document.getElementById('ent2-d-cost')?.value),totalQty=Number(document.getElementById('ent2-d-total')?.value||0);if(!name||!unit||poolCost<0||totalQty<=0)return alert('محرک هزینه معتبر نیست.');datastore.costDrivers.push({id:entId('DRV'),ownerUserId:currentUser.id,companyId:entCid(),name,unit,poolCost,totalQty,status:'active'});saveDatastore();enterpriseRender('costing')}
19 +function entAllocateABC(){if(!requireWrite())return;const driverId=document.getElementById('ent2-a-driver')?.value,objectName=document.getElementById('ent2-a-object')?.value.trim(),qty=Number(document.getElementById('ent2-a-qty')?.value||0),d=entV2Rows('costDrivers').find(x=>x.id===driverId);if(!d||!objectName||qty<0||qty>d.totalQty)return alert('تخصیص معتبر نیست.');datastore.costAllocations.push({id:entId('ALC'),ownerUserId:currentUser.id,companyId:entCid(),driverId,objectName,driverQty:qty,allocatedAmount:Math.round(d.poolCost*qty/d.totalQty),method:'ABC'});saveDatastore();enterpriseRender('costing')}
20 +function entSaveIntercompany(){if(!requireWrite())return;const fromCompanyId=document.getElementById('ent2-ic-from')?.value,toCompanyId=document.getElementById('ent2-ic-to')?.value,amount=entV2Num(document.getElementById('ent2-ic-amount')?.value),reference=document.getElementById('ent2-ic-ref')?.value.trim(),date=document.getElementById('ent2-ic-date')?.value.trim()||getJalaliNumeric();if(!fromCompanyId||!toCompanyId||fromCompanyId===toCompanyId||amount<=0||!reference)return alert('فی‌مابین معتبر نیست.');const r={id:entId('IC'),ownerUserId:currentUser.id,companyId:entCid(),fromCompanyId,toCompanyId,amount,reference,date,status:'open'};datastore.intercompanyTransactions.push(r);entV2Audit('create','intercompanyTransaction',r.id,r);saveDatastore();enterpriseRender('group')}
21 +function entMatchIntercompany(id){if(!requireWrite())return;const a=entV2Rows('intercompanyTransactions',true).find(x=>x.id===id&&x.status==='open');if(!a)return;const b=entV2Rows('intercompanyTransactions',true).find(x=>x.id!==a.id&&x.status==='open'&&x.fromCompanyId===a.toCompanyId&&x.toCompanyId===a.fromCompanyId&&x.amount===a.amount&&x.reference===a.reference);if(!b)return alert('رکورد متقابل پیدا نشد.');a.status=b.status='matched';a.matchedWith=b.id;b.matchedWith=a.id;saveDatastore();enterpriseRender('group')}
22 +function entGroupRows(){const cs=getMyCompanies(),vs=(datastore.journalVouchers||[]).filter(v=>v.ownerUserId===currentUser?.id&&['posted','reversed'].includes(v.status)),ls=(datastore.journalLines||[]).filter(l=>l.ownerUserId===currentUser?.id);return cs.map(c=>{const vids=new Set(vs.filter(v=>v.companyId===c.id).map(v=>v.id)),acc=(datastore.accounts||[]).filter(a=>a.ownerUserId===currentUser?.id&&a.companyId===c.id),cashIds=new Set(acc.filter(a=>a.systemRole==='cash_default'||String(a.title||'').includes('صندوق')||String(a.title||'').includes('بانک')).map(a=>a.id)),cash=ls.filter(l=>vids.has(l.voucherId)&&cashIds.has(l.accountId)).reduce((s,l)=>s+Number(l.debit||0)-Number(l.credit||0),0),open=entV2Rows('intercompanyTransactions',true).filter(x=>x.status==='open'&&(x.fromCompanyId===c.id||x.toCompanyId===c.id)).reduce((s,x)=>s+x.amount,0);return{c,vouchers:vids.size,cash,open}})}
23 +function entRenderV2(task){const r=ensureEnterpriseView(),emps=entV2Rows('employees'),eo='<option value="">— کارکن —</option>'+emps.map(x=>'<option value="'+esc(x.id)+'">'+esc(x.personnelNo+' · '+x.fullName)+'</option>').join(''),runs=entV2Rows('payrollRuns'),funds=entV2Rows('pettyCashFunds'),drivers=entV2Rows('costDrivers'),companies=getMyCompanies(),ics=entV2Rows('intercompanyTransactions',true),group=entGroupRows();let h='';
24 + if(task==='payroll')h='<div class="card"><h2>حقوق، بیمه و مالیات حقوق</h2><p class="af-hint">قواعد ۱۴۰۵ نسخه‌دار؛ ۷٪ سهم کارکن و ۲۳٪ هزینه کارفرما برای کارکن مشمول استاندارد. موارد خاص باید با پرونده بیمه کنترل شود.</p><div class="form-row"><input id="ent2-pay-period" class="form-control" value="'+esc(String(getJalaliNumeric()).slice(0,7))+'"><select id="ent2-pay-employee" class="form-control">'+eo+'</select><input id="ent2-pay-gross" class="form-control" placeholder="حقوق ناخالص"><input id="ent2-pay-ins" class="form-control" placeholder="مبنای بیمه"><input id="ent2-pay-taxable" class="form-control" placeholder="مشمول مالیات"></div><button class="btn" onclick="entSavePayrollLine()">افزودن ردیف</button></div><div class="card"><table><tbody>'+runs.map(x=>{const l=entV2Rows('payrollLines').filter(y=>y.runId===x.id);return'<tr><td>'+esc(x.period)+'</td><td>'+esc(x.status)+'</td><td>'+entMoney(l.reduce((s,y)=>s+y.gross,0))+'</td><td>'+(x.status==='draft'?'<button class="btn btn-inline" onclick="entPostPayroll(\''+x.id+'\')">ثبت قطعی و سند</button>':'سند '+esc(x.journalVoucherId||''))+'</td></tr>'}).join('')+'</tbody></table></div>';
25 + if(task==='benefits')h='<div class="card"><h2>تعهدات کارکنان</h2><p class="af-hint">پایان‌کار قانون کار با مزایای بازنشستگی استاندارد ۳۳ یکسان فرض نمی‌شود.</p><div class="form-row"><select id="ent2-ben-employee" class="form-control">'+eo+'</select><select id="ent2-ben-kind" class="form-control"><option value="end_service">مزایای پایان خدمت</option><option value="leave">تعهد مرخصی</option></select><input id="ent2-ben-period" class="form-control" value="'+esc(String(getJalaliNumeric()).slice(0,7))+'"><input id="ent2-ben-amount" class="form-control" placeholder="مبلغ"><input id="ent2-ben-basis" class="form-control" placeholder="مبنای برآورد"></div><button class="btn" onclick="entAccrueBenefit()">ثبت تعهد و سند</button></div>';
26 + if(task==='pettyops')h='<div class="card"><h2>عملیات تنخواه</h2><div class="form-row"><select id="ent2-pt-fund" class="form-control">'+funds.map(x=>'<option value="'+esc(x.id)+'">'+esc(x.title)+' — مانده '+entMoney(entPettyBalance(x.id))+'</option>').join('')+'</select><select id="ent2-pt-kind" class="form-control"><option value="issue">پرداخت وجه</option><option value="expense">ثبت هزینه</option><option value="return">برگشت وجه</option></select><input id="ent2-pt-amount" class="form-control" placeholder="مبلغ"><input id="ent2-pt-date" class="form-control" value="'+esc(getJalaliNumeric())+'"><input id="ent2-pt-desc" class="form-control" placeholder="شرح/مدرک"></div><button class="btn" onclick="entPostPetty()">ثبت قطعی و سند</button></div>';
27 + if(task==='costing')h='<div class="card"><h2>بودجه‌ریزی عملکرد</h2><div class="form-row"><input id="ent2-b-period" class="form-control" placeholder="دوره"><input id="ent2-b-amount" class="form-control" placeholder="بودجه"><input id="ent2-b-measure" class="form-control" placeholder="شاخص عملکرد"><input id="ent2-b-target" class="form-control" placeholder="هدف"></div><button class="btn" onclick="entSaveBudget()">ثبت بودجه</button></div><div class="card"><h2>ABC — محرک هزینه</h2><div class="form-row"><input id="ent2-d-name" class="form-control" placeholder="محرک"><input id="ent2-d-unit" class="form-control" placeholder="واحد"><input id="ent2-d-cost" class="form-control" placeholder="هزینه مخزن"><input id="ent2-d-total" class="form-control" placeholder="مقدار کل"></div><button class="btn" onclick="entSaveDriver()">ثبت محرک</button><div class="form-row"><select id="ent2-a-driver" class="form-control">'+drivers.map(x=>'<option value="'+esc(x.id)+'">'+esc(x.name)+'</option>').join('')+'</select><input id="ent2-a-object" class="form-control" placeholder="موضوع هزینه"><input id="ent2-a-qty" class="form-control" placeholder="مصرف محرک"></div><button class="btn" onclick="entAllocateABC()">تخصیص ABC</button></div>';
28 + if(task==='group')h='<div class="card"><h2>کنترل مدیریتی گروه</h2><table><tbody>'+group.map(x=>'<tr><td>'+esc(x.c.name)+'</td><td>اسناد '+x.vouchers+'</td><td>نقد '+entMoney(x.cash)+'</td><td>فی‌مابین باز '+entMoney(x.open)+'</td></tr>').join('')+'</tbody></table><p class="af-hint">این کنترل مدیریتی است، نه صورت مالی تلفیقی استاندارد ۳۹؛ تلفیق قانونی به mapping، حذف درون‌گروهی، NCI، یکنواختی رویه/دوره و ترجمه ارز نیاز دارد.</p></div><div class="card"><h2>فی‌مابین</h2><div class="form-row"><select id="ent2-ic-from" class="form-control">'+companies.map(x=>'<option value="'+esc(x.id)+'">'+esc(x.name)+'</option>').join('')+'</select><select id="ent2-ic-to" class="form-control">'+companies.map(x=>'<option value="'+esc(x.id)+'">'+esc(x.name)+'</option>').join('')+'</select><input id="ent2-ic-amount" class="form-control" placeholder="مبلغ"><input id="ent2-ic-date" class="form-control" value="'+esc(getJalaliNumeric())+'"><input id="ent2-ic-ref" class="form-control" placeholder="مرجع مشترک"></div><button class="btn" onclick="entSaveIntercompany()">ثبت</button><table><tbody>'+ics.map(x=>'<tr><td>'+esc(x.reference)+'</td><td>'+entMoney(x.amount)+'</td><td>'+esc(x.status)+'</td><td>'+(x.status==='open'?'<button class="btn btn-inline" onclick="entMatchIntercompany(\''+x.id+'\')">تطبیق</button>':'—')+'</td></tr>').join('')+'</tbody></table></div>';
29 + r.innerHTML='<div class="af-head"><div><h1>ERP سازمانی ایران</h1><p>کنترل‌های مالی و عملیاتی سازمان</p></div></div>'+h
30 +}
31 +window.enterpriseRender=function(task='employees'){return ['payroll','benefits','pettyops','costing','group'].includes(task)?entRenderV2(task):enterpriseRenderV1(task)};
js/sync.js
+1 -1
@@ -1,4 +1,4 @@
1 -let datastore={companies:[],contacts:[],products:[],invoices:[],purchases:[],cheques:[],expenses:[],payments:[],settings:[],fiscalYears:[],accounts:[],dimensionTypes:[],dimensionValues:[],accountDimensionRules:[],branches:[],projects:[],projectLinks:[],postingProfiles:[],journalVouchers:[],journalLines:[],journalLineDimensions:[],contracts:[],contractAmendments:[],contractParties:[],contractDeductions:[],guarantees:[],guaranteeEvents:[],contractStatements:[],phase4Audit:[],warehouses:[],stockMovements:[],inventoryCounts:[],fixedAssets:[],assetDepreciations:[],currencies:[],exchangeRates:[],costCenters:[],importBatches:[],integrationConnections:[],integrationOutbox:[],phase5Audit:[]};
1 +let datastore={companies:[],contacts:[],products:[],invoices:[],purchases:[],cheques:[],expenses:[],payments:[],settings:[],fiscalYears:[],accounts:[],dimensionTypes:[],dimensionValues:[],accountDimensionRules:[],branches:[],projects:[],projectLinks:[],postingProfiles:[],journalVouchers:[],journalLines:[],journalLineDimensions:[],contracts:[],contractAmendments:[],contractParties:[],contractDeductions:[],guarantees:[],guaranteeEvents:[],contractStatements:[],phase4Audit:[],warehouses:[],stockMovements:[],inventoryCounts:[],fixedAssets:[],assetDepreciations:[],currencies:[],exchangeRates:[],costCenters:[],importBatches:[],integrationConnections:[],integrationOutbox:[],phase5Audit:[],employees:[],employmentContracts:[],employeeLeave:[],cashboxes:[],pettyCashFunds:[],complianceRules:[],payrollRuns:[],payrollLines:[],employeeBenefitAccruals:[],pettyCashTransactions:[],budgets:[],costDrivers:[],costAllocations:[],intercompanyTransactions:[],enterpriseAudit:[]};
2 function getMyProducts(){return !currentUser?[]:datastore.products.filter(p=>p.ownerUserId===currentUser.id);}
3 function getMyContacts(){return !currentUser?[]:datastore.contacts.filter(c=>c.ownerUserId===currentUser.id);}
4 function getMyCompanies(){return !currentUser?[]:datastore.companies.filter(c=>c.ownerUserId===currentUser.id);}
js/ui.js
+1 -1
@@ -75,7 +75,7 @@ const FINORA_MODULES={
75 projects:{title:'پیمان‌ها',context:'پیمان، پروژه/کارگاه، کسورات، تضمین و صورت‌وضعیت',groups:[{title:'اطلاعات پایه',items:[['پروژه‌ها و کارگاه‌ها','view-accounting-foundation','▧','','projects']]},{title:'عملیات پیمان',items:[['پیمان‌ها و قراردادهای اجرایی','view-contracting','▦']]},{title:'گزارش',items:[['گزارش پیمان و پروژه','view-accounting-reports','▥','','projects']]}]},
76 inventory:{title:'انبار',context:'انبار، گردش، شمارش و بهای موجودی',groups:[{title:'اطلاعات پایه',items:[['تعریف انبار','view-inventory','▦','','warehouse']]},{title:'عملیات',items:[['گردش انبار','view-inventory','⇄','','movement'],['انبارگردانی','view-inventory','✓','','count']]},{title:'گزارش و کنترل',items:[['موجودی و بهای میانگین','view-inventory','▥','','stock']]}]},
77 assets:{title:'دارایی ثابت',context:'دارایی، استهلاک و ارزش دفتری',groups:[{title:'اطلاعات پایه',items:[['ثبت دارایی','view-assets','◆','','asset-new']]},{title:'عملیات و دفاتر',items:[['دفتر دارایی‌ها','view-assets','▤','','asset-register'],['استهلاک و سوابق','view-assets','◷','','depreciation']]}]},
78 - enterprise:{title:'سازمان',context:'منابع انسانی، خزانه و انطباق ایران',groups:[{title:'منابع انسانی',items:[['کارکنان','view-enterprise','♙','','employees'],['قرارداد کار و پایان‌کار','view-enterprise','▤','','contracts'],['مرخصی و ذخیره','view-enterprise','◷','','leave']]},{title:'خزانه تکمیلی',items:[['صندوق و تنخواه','view-enterprise','¤','','treasury']]},{title:'انطباق',items:[['رجیستری قوانین و استانداردها','view-enterprise','✓','','compliance']]}]},
78 + enterprise:{title:'سازمان',context:'منابع انسانی، حقوق، خزانه، بهای تمام‌شده و کنترل گروه',groups:[{title:'منابع انسانی',items:[['کارکنان','view-enterprise','♙','','employees'],['قرارداد کار و پایان‌کار','view-enterprise','▤','','contracts'],['مرخصی و ذخیره','view-enterprise','◷','','leave'],['حقوق، بیمه و مالیات','view-enterprise','▥','','payroll'],['تعهدات کارکنان','view-enterprise','◌','','benefits']]},{title:'خزانه تکمیلی',items:[['صندوق و تعریف تنخواه','view-enterprise','¤','','treasury'],['عملیات تنخواه و تسویه','view-enterprise','↔','','pettyops']]},{title:'کنترل مدیریت',items:[['بودجه عملکرد و ABC','view-enterprise','◎','','costing'],['گروه، نقدینگی و فی‌مابین','view-enterprise','▦','','group']]},{title:'انطباق',items:[['رجیستری قوانین و استانداردها','view-enterprise','✓','','compliance']]}]},
79 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']]}]},
80 settings:{title:'تنظیمات',context:'شرکت، داده، دسترسی و یکپارچه‌سازی',groups:[{title:'حساب و شرکت',items:[['شرکت‌ها','view-settings','▦','','company'],['حساب کاربری و رمز','view-settings','♙','','account'],['پیش‌فرض فاکتور','view-settings','▤','','invoice-defaults']]},{title:'عملیات و داده',items:[['تنظیمات عملیاتی','view-data-center','◌','','ops-settings'],['ورود/خروج داده و پشتیبان','view-data-center','⇅','','data-backup']]},{title:'یکپارچه‌سازی',items:[['اتصالات و API','view-integrations','⇆']]},{title:'سیستم',items:[['درباره فینورا','view-settings','ⓘ','','about'],['کاربران و لایسنس','view-admin','♙','admin']]}]}
81 };
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);await expect(page.locator('[data-module="enterprise"]')).toHaveCount(1);await page.waitForFunction(()=>typeof enterpriseRender==='function');await expect(page.locator('[data-module="enterprise"]')).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',maxCompanies:1,subscription:{type:'lifetime',status:'active',endDate:'2099-01-01'}});pullAll=async()=>{datastore.settings=[{ownerUserId:'smoke-user',user_display_name:'Smoke Admin',professional_role:'accountant'}]};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.fill('#company-reg-input','SHOULD_CLEAR');await page.selectOption('#company-organization-role','holding_parent');await page.evaluate(()=>handleCompanyEntityTypeChange());await expect(page.locator('#company-legal-form-box')).toBeHidden();await expect(page.locator('#company-sector-box')).toBeHidden();await expect(page.locator('#company-organization-box')).toBeHidden();await expect(page.locator('#company-registration-box')).toBeHidden();await expect(page.locator('#company-national-label')).toHaveText('کد ملی');expect(await page.inputValue('#company-reg-input')).toBe('');expect(await page.inputValue('#company-organization-role')).toBe('standalone');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-box')).toBeVisible();await expect(page.locator('#company-registration-box')).toBeVisible();await expect(page.locator('#company-national-label')).toHaveText('شناسه ملی');await expect(page.locator('#company-organization-role')).toContainText('شرکت مادر / هلدینگ');await expect(page.locator('#company-organization-role')).toContainText('شرکت تابعه');await page.evaluate(()=>switchView('view-contacts'));await page.selectOption('#contact-entity-type','legal');await page.fill('#contact-economic-input','LEGAL-ONLY');await page.fill('#contact-reg-input','REG-ONLY');await page.selectOption('#contact-entity-type','natural');await expect(page.locator('#box-contact-economic')).toBeHidden();await expect(page.locator('#box-contact-reg')).toBeHidden();await expect(page.locator('#label-contact-national')).toHaveText('کد ملی');expect(await page.inputValue('#contact-economic-input')).toBe('');expect(await page.inputValue('#contact-reg-input')).toBe('');await page.evaluate(()=>navigateShell('enterprise','view-enterprise','compliance'));await expect(page.locator('#view-enterprise')).toContainText('رجیستری انطباق ایران');await expect(page.locator('#view-enterprise')).toContainText('IR-LABOR-24');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 page.evaluate(()=>navigateShell('enterprise','view-enterprise','compliance'));await expect(page.locator('#view-enterprise')).toContainText('رجیستری انطباق ایران');await expect(page.locator('#view-enterprise')).toContainText('IR-LABOR-24');await page.evaluate(()=>navigateShell('enterprise','view-enterprise','leave'));await expect(page.locator('#view-enterprise')).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([]);});
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);await expect(page.locator('[data-module="enterprise"]')).toHaveCount(1);await page.waitForFunction(()=>typeof enterpriseRender==='function');await expect(page.locator('[data-module="enterprise"]')).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',maxCompanies:1,subscription:{type:'lifetime',status:'active',endDate:'2099-01-01'}});pullAll=async()=>{datastore.settings=[{ownerUserId:'smoke-user',user_display_name:'Smoke Admin',professional_role:'accountant'}]};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.fill('#company-reg-input','SHOULD_CLEAR');await page.selectOption('#company-organization-role','holding_parent');await page.evaluate(()=>handleCompanyEntityTypeChange());await expect(page.locator('#company-legal-form-box')).toBeHidden();await expect(page.locator('#company-sector-box')).toBeHidden();await expect(page.locator('#company-organization-box')).toBeHidden();await expect(page.locator('#company-registration-box')).toBeHidden();await expect(page.locator('#company-national-label')).toHaveText('کد ملی');expect(await page.inputValue('#company-reg-input')).toBe('');expect(await page.inputValue('#company-organization-role')).toBe('standalone');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-box')).toBeVisible();await expect(page.locator('#company-registration-box')).toBeVisible();await expect(page.locator('#company-national-label')).toHaveText('شناسه ملی');await expect(page.locator('#company-organization-role')).toContainText('شرکت مادر / هلدینگ');await expect(page.locator('#company-organization-role')).toContainText('شرکت تابعه');await page.evaluate(()=>switchView('view-contacts'));await page.selectOption('#contact-entity-type','legal');await page.fill('#contact-economic-input','LEGAL-ONLY');await page.fill('#contact-reg-input','REG-ONLY');await page.selectOption('#contact-entity-type','natural');await expect(page.locator('#box-contact-economic')).toBeHidden();await expect(page.locator('#box-contact-reg')).toBeHidden();await expect(page.locator('#label-contact-national')).toHaveText('کد ملی');expect(await page.inputValue('#contact-economic-input')).toBe('');expect(await page.inputValue('#contact-reg-input')).toBe('');await page.evaluate(()=>navigateShell('enterprise','view-enterprise','compliance'));await expect(page.locator('#view-enterprise')).toContainText('رجیستری انطباق ایران');await expect(page.locator('#view-enterprise')).toContainText('IR-LABOR-24');await page.evaluate(()=>navigateShell('enterprise','view-enterprise','payroll'));await expect(page.locator('#view-enterprise')).toContainText('حقوق، بیمه و مالیات حقوق');await page.evaluate(()=>navigateShell('enterprise','view-enterprise','costing'));await expect(page.locator('#view-enterprise')).toContainText('ABC');await page.evaluate(()=>navigateShell('enterprise','view-enterprise','group'));await expect(page.locator('#view-enterprise')).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 page.evaluate(()=>navigateShell('enterprise','view-enterprise','compliance'));await expect(page.locator('#view-enterprise')).toContainText('رجیستری انطباق ایران');await expect(page.locator('#view-enterprise')).toContainText('IR-LABOR-24');await page.evaluate(()=>navigateShell('enterprise','view-enterprise','leave'));await expect(page.locator('#view-enterprise')).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
+1 -1
@@ -107,7 +107,7 @@ for(const x of ['p5SaveCompanyOpsSettings','p5-set-default-wh','p5-set-base-cur'
107 for(const x of ['p5ApplyRestore','importProductsFromExcel(event)','validated-backup.json'])if(!all['phase5-enterprise.js'].includes(x))throw new Error('Phase5 import center missing '+x);
108
109 const p6=all['phase6-reporting.js']||'';for(const x of ['ledger','cashFlow','projectContractSummary','legacyCutoverPreview','postLegacyInvoice'])if(!p6.includes(x))throw new Error('Phase6 report capability missing '+x);
110 -if(!index.includes('id="view-accounting-reports"')||!index.includes('phase6-reporting.js'))throw new Error('Phase6 report workspace missing');
110 +if(!index.includes('id="view-accounting-reports"')||!index.includes('phase6-reporting.js'))throw new Error('Phase6 report workspace missing');\nconst ent2=fs.readFileSync(path.join(root,'js','enterprise-iran-v2.js'),'utf8');for(const x of ['entPostPayroll','entAccrueBenefit','entPostPetty','entAllocateABC','entMatchIntercompany','entSalaryTax1405','enterpriseEndServiceEstimate'])if(!ent2.includes(x))throw new Error('Iran enterprise v2 control missing '+x);for(const c of ['payrollRuns','payrollLines','employeeBenefitAccruals','pettyCashTransactions','budgets','costDrivers','costAllocations','intercompanyTransactions','enterpriseAudit'])if(!fs.readFileSync(path.join(root,'js','core.js'),'utf8').includes("'"+c+"'")||!fs.readFileSync(path.join(root,'js','sync.js'),'utf8').includes(c))throw new Error('Iran enterprise v2 persistence missing '+c);
111
112
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');
supabase/migrations/20260930223000_iran_enterprise_financial_controls.sql new
+13
@@ -0,0 +1,13 @@
1 +alter table public.records drop constraint if exists records_collection_check;
2 +alter table public.records add constraint records_collection_check check (collection = any (array['companies','contacts','products','invoices','cheques','expenses','settings','purchases','payments','fiscalYears','accounts','dimensionTypes','dimensionValues','accountDimensionRules','branches','projects','projectLinks','postingProfiles','journalVouchers','journalLines','journalLineDimensions','contracts','contractAmendments','contractParties','contractDeductions','guarantees','guaranteeEvents','contractStatements','phase4Audit','warehouses','stockMovements','inventoryCounts','fixedAssets','assetDepreciations','currencies','exchangeRates','costCenters','importBatches','integrationConnections','integrationOutbox','phase5Audit','employees','employmentContracts','employeeLeave','cashboxes','pettyCashFunds','complianceRules','payrollRuns','payrollLines','employeeBenefitAccruals','pettyCashTransactions','budgets','costDrivers','costAllocations','intercompanyTransactions','enterpriseAudit']::text[]));
3 +create or replace function public.finora_guard_posted_source_records()
4 +returns trigger language plpgsql set search_path=public as $$
5 +declare vid text:=coalesce(old.data->>'journalVoucherId',''); voucher_status text:=''; source_locked boolean:=false;
6 +begin
7 + if old.collection not in ('invoices','purchases','payments','expenses','cheques','contractStatements','payrollRuns','employeeBenefitAccruals','pettyCashTransactions') then return case when tg_op='DELETE' then old else new end; end if;
8 + if vid<>'' then select coalesce(r.data->>'status','') into voucher_status from public.records r where r.owner_id=old.owner_id and r.collection='journalVouchers' and r.id=vid; end if;
9 + source_locked:=coalesce(old.data->>'accountingStatus','')='posted' or (old.collection='cheques' and coalesce(old.data->>'status','') in ('cleared','bounced','cancelled')) or (old.collection='contractStatements' and coalesce(old.data->>'status','') in ('posted','reversed')) or (old.collection in ('payrollRuns','employeeBenefitAccruals','pettyCashTransactions') and coalesce(old.data->>'status','') in ('posted','reversed')) or voucher_status in ('posted','reversed');
10 + if not source_locked then return case when tg_op='DELETE' then old else new end; end if;
11 + if tg_op='UPDATE' and new.data=old.data then return new; end if;
12 + raise exception 'source record linked to posted/reversed accounting history is immutable';
13 +end $$;
\ No newline at end of file