@davoodmehraban89 / Factor-easy / commits / 5e1491c
Fork 0

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

Correct legal-person UX and harden license capacity migration

davoodmehraban89 committed Sep 30, 2026 at 01:35 UTC 5e1491cfaf00936cb9d8f599b575a35b4fe8583b
6 files changed +24 -13
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. |\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. 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. |\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
+4 -4
@@ -635,19 +635,19 @@ body{background:#f6f9fc}
635 <div class="accordion-body">
636 <div class="form-row">
637 <div class="form-group"><label>نوع شخص</label><select id="company-entity-type" class="form-control" onchange="handleCompanyEntityTypeChange()"><option value="legal">حقوقی</option><option value="natural">حقیقی / کسب‌وکار فردی</option></select></div>
638 -<div class="form-group" id="company-sector-box"><label>ماهیت مالکیت / بخش</label><select id="company-sector" class="form-control"><option value="private">خصوصی</option><option value="cooperative">تعاونی</option><option value="public_non_government">عمومی غیردولتی</option><option value="government">دولتی / حکومتی</option><option value="other">سایر</option></select></div><div class="form-group"><label>جایگاه در ساختار سازمانی</label><select id="company-organization-role" class="form-control" onchange="handleCompanyOrganizationRoleChange()"><option value="standalone">شرکت / واحد مستقل</option><option value="holding_parent">شرکت مادر / هلدینگ</option><option value="subsidiary">شرکت تابعه</option></select></div><div class="form-group" id="company-parent-box" style="display:none"><label>شرکت مادر</label><select id="company-parent-id" class="form-control"><option value="">— انتخاب شرکت مادر —</option></select><small style="color:var(--text-muted)">این رابطه فعلاً ساختار سازمانی را ثبت می‌کند؛ تلفیق، حذف معاملات درون‌گروهی و گزارش گروهی ماژول جداگانه خواهند بود.</small></div>
638 +<div class="form-group" id="company-sector-box"><label>ماهیت مالکیت / بخش</label><select id="company-sector" class="form-control"><option value="private">خصوصی</option><option value="cooperative">تعاونی</option><option value="public_non_government">عمومی غیردولتی</option><option value="government">دولتی / حکومتی</option><option value="other">سایر</option></select></div><div class="form-group" id="company-organization-box"><label>جایگاه در گروه شرکت‌ها</label><select id="company-organization-role" class="form-control" onchange="handleCompanyOrganizationRoleChange()"><option value="standalone">شرکت / واحد مستقل</option><option value="holding_parent">شرکت مادر / هلدینگ</option><option value="subsidiary">شرکت تابعه</option></select></div><div class="form-group" id="company-parent-box" style="display:none"><label>شرکت مادر</label><select id="company-parent-id" class="form-control"><option value="">— انتخاب شرکت مادر —</option></select><small style="color:var(--text-muted)">این رابطه فعلاً ساختار سازمانی را ثبت می‌کند؛ تلفیق، حذف معاملات درون‌گروهی و گزارش گروهی ماژول جداگانه خواهند بود.</small></div>
639 <div class="form-group" id="company-legal-form-box"><label>قالب حقوقی ثبت</label><select id="company-legal-form" class="form-control"><option value="private_joint_stock">سهامی خاص</option><option value="public_joint_stock">سهامی عام</option><option value="limited_liability">با مسئولیت محدود</option><option value="general_partnership">تضامنی</option><option value="relative_partnership">نسبی</option><option value="mixed_non_stock">مختلط غیرسهامی</option><option value="mixed_stock">مختلط سهامی</option><option value="cooperative">تعاونی</option><option value="noncommercial_institution">مؤسسه غیرتجاری</option><option value="other">سایر / نامشخص</option></select></div>
640 <div class="form-group"><label>نوع فعالیت عملیاتی</label><select id="company-activity-type" class="form-control"><option value="trading">بازرگانی</option><option value="service">خدماتی</option><option value="manufacturing">تولیدی</option><option value="contracting">پیمانکاری</option><option value="retail">فروشگاهی</option><option value="distribution">پخش</option><option value="nonprofit">غیرانتفاعی</option><option value="professional">خدمات حرفه‌ای</option></select></div>
641 </div>
642 <div class="form-row">
643 <div class="form-group"><label>راه‌اندازی حسابداری</label><select id="company-accounting-template" class="form-control"><option value="recommended">اعمال کدینگ پیشنهادی Finora</option><option value="empty">شروع با کدینگ خالی</option></select></div>
644 -<div class="form-group"><label>نام شرکت / فروشگاه</label><input type="text" id="company-name-input" class="form-control" placeholder="آرا سپهر راستین" /></div>
644 +<div class="form-group"><label id="company-name-label">نام شرکت / کسب‌وکار</label><input type="text" id="company-name-input" class="form-control" placeholder="آرا سپهر راستین" /></div>
645 <div class="form-group"><label>تلفن</label><input type="text" id="company-phone-input" class="form-control" /></div>
646 </div>
647 <div class="form-row">
648 -<div class="form-group"><label>شناسه ملی</label><input type="text" id="company-national-input" class="form-control" /></div>
648 +<div class="form-group"><label id="company-national-label">شناسه ملی</label><input type="text" id="company-national-input" class="form-control" /></div>
649 <div class="form-group"><label>کد اقتصادی</label><input type="text" id="company-economic-input" class="form-control" /></div>
650 -<div class="form-group"><label>شماره ثبت</label><input type="text" id="company-reg-input" class="form-control" /></div>
650 +<div class="form-group" id="company-registration-box"><label>شماره ثبت</label><input type="text" id="company-reg-input" class="form-control" /></div>
651 <div class="form-group"><label>کد پستی</label><input type="text" id="company-postal-input" class="form-control" /></div>
652 </div>
653 <div class="form-group"><label>نشانی کامل</label><input type="text" id="company-address-input" class="form-control" /></div>
js/companies.js
+7 -6
@@ -4,11 +4,12 @@ const COMPANY_LEGAL_FORM_LABELS={natural_person:'شخص حقیقی',private_join
4 const COMPANY_SECTOR_LABELS={private:'خصوصی',cooperative:'تعاونی',public_non_government:'عمومی غیردولتی',government:'دولتی / حکومتی',other:'سایر'};
5 function handleCompanyOrganizationRoleChange(){const role=document.getElementById('company-organization-role')?.value||'standalone',box=document.getElementById('company-parent-box'),sel=document.getElementById('company-parent-id');if(box)box.style.display=role==='subsidiary'?'':'none';if(sel){const current=sel.value,editing=editingCompanyId;sel.innerHTML='<option value="">— انتخاب شرکت مادر —</option>'+getMyCompanies().filter(c=>c.id!==editing&&(c.organizationRole==='holding_parent'||c.organizationRole==='standalone')).map(c=>'<option value="'+esc(c.id)+'">'+esc(c.name)+'</option>').join('');if([...sel.options].some(o=>o.value===current))sel.value=current;}}
6 function handleCompanyEntityTypeChange(){
7 - const entity=document.getElementById('company-entity-type'),sectorBox=document.getElementById('company-sector-box'),legalBox=document.getElementById('company-legal-form-box'),sector=document.getElementById('company-sector'),legal=document.getElementById('company-legal-form');
7 + const entity=document.getElementById('company-entity-type'),sectorBox=document.getElementById('company-sector-box'),legalBox=document.getElementById('company-legal-form-box'),orgBox=document.getElementById('company-organization-box'),parentBox=document.getElementById('company-parent-box'),registrationBox=document.getElementById('company-registration-box'),sector=document.getElementById('company-sector'),legal=document.getElementById('company-legal-form'),orgRole=document.getElementById('company-organization-role'),parent=document.getElementById('company-parent-id'),reg=document.getElementById('company-reg-input'),nameLabel=document.getElementById('company-name-label'),nationalLabel=document.getElementById('company-national-label');
8 const isLegal=(entity?.value||'legal')==='legal';
9 - if(sectorBox)sectorBox.style.display=isLegal?'':'none';if(legalBox)legalBox.style.display=isLegal?'':'none';
10 - if(!isLegal){if(sector)sector.value='private';if(legal)legal.value='other';}
11 - else if(legal&&!legal.value)legal.value='limited_liability';
9 + if(sectorBox)sectorBox.style.display=isLegal?'':'none';if(legalBox)legalBox.style.display=isLegal?'':'none';if(orgBox)orgBox.style.display=isLegal?'':'none';if(registrationBox)registrationBox.style.display=isLegal?'':'none';
10 + if(nameLabel)nameLabel.textContent=isLegal?'نام شرکت / مؤسسه':'نام شخص / کسب‌وکار فردی';if(nationalLabel)nationalLabel.textContent=isLegal?'شناسه ملی':'کد ملی';
11 + if(!isLegal){if(sector)sector.value='private';if(legal)legal.value='natural_person';if(orgRole)orgRole.value='standalone';if(parent)parent.value='';if(parentBox)parentBox.style.display='none';if(reg)reg.value='';}
12 + else{if(legal&&(!legal.value||legal.value==='natural_person'))legal.value='limited_liability';handleCompanyOrganizationRoleChange();}
13 }
14 function companyLegalSummary(c){
15 if((c.entity_type||'legal')==='natural')return 'حقیقی / کسب‌وکار فردی';
@@ -58,9 +59,9 @@ function commitSaveCompany(){
59 const activityType=document.getElementById('company-activity-type')?.value||'trading';
60 const organizationSector=entity_type==='legal'?(document.getElementById('company-sector')?.value||'private'):'private';
61 const legalForm=entity_type==='legal'?(document.getElementById('company-legal-form')?.value||'other'):'natural_person';
61 - const organizationRole=document.getElementById('company-organization-role')?.value||'standalone',parentCompanyId=organizationRole==='subsidiary'?(document.getElementById('company-parent-id')?.value||''):'';if(organizationRole==='subsidiary'&&!parentCompanyId){alert('برای شرکت تابعه، شرکت مادر را مشخص کنید.');return;}
62 + const organizationRole=entity_type==='legal'?(document.getElementById('company-organization-role')?.value||'standalone'):'standalone',parentCompanyId=entity_type==='legal'&&organizationRole==='subsidiary'?(document.getElementById('company-parent-id')?.value||''):'';if(entity_type==='legal'&&organizationRole==='subsidiary'&&!parentCompanyId){alert('برای شرکت تابعه، شرکت مادر را مشخص کنید.');return;}
63 const templateChoice=document.getElementById('company-accounting-template')?.value||'empty';
63 - const payload={entity_type,organizationSector,legalForm,organizationRole,parentCompanyId,activityType,name:formatEntityName(raw_name,entity_type),phone:document.getElementById('company-phone-input').value||'',national_id:document.getElementById('company-national-input').value||'',economic_code:document.getElementById('company-economic-input').value||'',reg_number:document.getElementById('company-reg-input').value||'',postal_code:document.getElementById('company-postal-input').value||'',address:document.getElementById('company-address-input').value||'',footer:document.getElementById('company-footer-input')?.value||'از خرید شما سپاسگزاریم.'};
64 + const payload={entity_type,organizationSector,legalForm,organizationRole,parentCompanyId,activityType,name:formatEntityName(raw_name,entity_type),phone:document.getElementById('company-phone-input').value||'',national_id:document.getElementById('company-national-input').value||'',economic_code:document.getElementById('company-economic-input').value||'',reg_number:entity_type==='legal'?(document.getElementById('company-reg-input').value||''):'',postal_code:document.getElementById('company-postal-input').value||'',address:document.getElementById('company-address-input').value||'',footer:document.getElementById('company-footer-input')?.value||'از خرید شما سپاسگزاریم.'};
65 if(payload.national_id&&getMyCompanies().some(x=>x.id!==editingCompanyId&&x.national_id===payload.national_id)){alert('شناسه ملی شرکت تکراری است.');return;}
66 if(editingCompanyId){
67 const comp=datastore.companies.find(c=>c.id===editingCompanyId&&c.ownerUserId===currentUser.id);
scripts/dom-smoke.spec.js
+1 -1
@@ -1,6 +1,6 @@
1 const {test,expect}=require('@playwright/test');
2 const {PDFDocument}=require('pdf-lib');
3 -test('real DOM shell and post-login smoke',async({page})=>{const errs=[];page.on('pageerror',e=>errs.push(String(e)));await page.goto('http://127.0.0.1:4173/index.html',{waitUntil:'domcontentloaded'});await expect(page.locator('#auth-screen')).toBeVisible();await expect(page.locator('[data-module="projects"]')).toHaveCount(1);await expect(page.locator('[data-module="dashboard"]')).toContainText('داشبورد');await expect(page.locator('[data-module="home"]')).toHaveCount(0);await expect(page.locator('[data-module="catalog"]')).toHaveCount(0);await expect(page.locator('[data-module="erp"]')).toHaveCount(0);await expect(page.locator('#view-contracting')).toHaveCount(1);await expect(page.locator('[data-module="inventory"]')).toHaveCount(1);await expect(page.locator('[data-module="assets"]')).toHaveCount(1);for(const id of ['view-inventory','view-assets','view-currency','view-data-center','view-integrations'])await expect(page.locator('#'+id)).toHaveCount(1);expect(await page.evaluate(()=>{const a=[...document.querySelectorAll('[id]')].map(x=>x.id),s=new Set(),d=[];for(const id of a){if(s.has(id))d.push(id);s.add(id)}return d})).toEqual([]);await page.evaluate(async()=>{fetchCurrentUser=async()=>({id:'smoke-user',email:'smoke@example.test',fullName:'Smoke Admin',username:'smoke',role:'admin',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.evaluate(()=>handleCompanyEntityTypeChange());await expect(page.locator('#company-legal-form-box')).toBeHidden();await page.selectOption('#company-entity-type','legal');await page.evaluate(()=>handleCompanyEntityTypeChange());await expect(page.locator('#company-legal-form-box')).toBeVisible();await expect(page.locator('#company-organization-role')).toContainText('شرکت مادر / هلدینگ');await expect(page.locator('#company-organization-role')).toContainText('شرکت تابعه');await page.evaluate(()=>navigateShell('accounting','view-journal','new'));await expect(page.locator('#view-journal [data-finora-task="new"]')).toBeVisible();await expect(page.locator('#view-journal [data-finora-task="register"]')).toBeHidden();await page.evaluate(()=>navigateShell('accounting','view-journal','register'));await expect(page.locator('#view-journal [data-finora-task="register"]')).toBeVisible();await expect(page.locator('#view-journal [data-finora-task="new"]')).toBeHidden();await page.evaluate(()=>navigateShell('accounting','view-accounting-reports','trial'));await expect(page.locator('#p6-reporting-root [data-finora-task="trial"]')).toBeVisible();await expect(page.locator('#p6-reporting-root [data-finora-task="ledger"]')).toBeHidden();expect(await page.evaluate(()=>({refresh:window.__smokeRefresh,migrate:window.__smokeMigrate,admin:canShowShellCommand({guard:'admin'})}))).toEqual({refresh:true,migrate:true,admin:true});await page.evaluate(()=>{saveDatastore=()=>{};datastore.companies=[{id:'C1',ownerUserId:'smoke-user',name:'Smoke Co'}];datastore.settings=[{ownerUserId:'smoke-user',default_company_id:'C1'}];datastore.products=[{id:'P1',ownerUserId:'smoke-user',companyId:'C1',code:'1',name:'Smoke Product',type:'good',unit:'عدد',buy_price:100,sale_price:150,stock:0}];for(const k of ['warehouses','stockMovements','inventoryCounts','fixedAssets','assetDepreciations','currencies','exchangeRates','costCenters','importBatches','integrationConnections','integrationOutbox','phase5Audit'])datastore[k]=[];switchView('view-inventory');p5Render('view-inventory');});await expect(page.locator('#view-journal')).toBeHidden();await page.evaluate(()=>{switchView('view-dashboard');renderDashboard();});await expect(page.locator('#kpi-assets-sum')).toHaveCount(1);await expect(page.locator('#dashboard-cashflow-chart svg')).toHaveCount(1);await expect(page.locator('#dashboard-recent-journals')).toHaveCount(1);await page.evaluate(()=>{switchView('view-accounting-foundation');renderAccountingFoundation();});await expect(page.locator('#view-accounting-foundation')).toContainText('ورود کدینگ از Excel');await expect(page.locator('#view-accounting-foundation')).toContainText('شناور ۴ قرارداد/پیمان');await expect(page.locator('#af-account-type')).toHaveCount(1);await expect(page.locator('#af-account-search')).toHaveCount(1);await expect(page.locator('#af-account-level-filter')).toHaveCount(1);await expect(page.locator('#af-account-role')).toHaveCount(1);await expect(page.locator('#af-dim-source option[value="contract"]')).toHaveCount(1);await page.evaluate(()=>{switchView('view-inventory');p5Render('view-inventory');});await expect(page.locator('#p5-inventory-root')).toContainText('انبار اصلی');await expect(page.locator('#p5-inventory-root')).toContainText('Smoke Product');await page.evaluate(()=>{switchView('view-accounting-reports');P6Reports.render();});await expect(page.locator('#p6-reporting-root')).toContainText('تراز آزمایشی');await expect(page.locator('#p6-reporting-root')).toContainText('صورت جریان وجوه نقد');expect(await page.evaluate(()=>{const a=[...document.querySelectorAll('[id]')].map(x=>x.id),s=new Set(),d=[];for(const id of a){if(s.has(id))d.push(id);s.add(id)}return d})).toEqual([]);await page.evaluate(()=>{window.__FINORA_PRINT_TEST_MODE=true;window.print=()=>{};const items=Array.from({length:25},(_,i)=>({prodName:'Item '+(i+1),qty:1,unit:'عدد',price:100,lineTotal:100}));datastore.invoices=[{id:'PRINT_FORMAL',ownerUserId:'smoke-user',companyId:'C1',contactId:'',kind:'formal',number:'F-1',date:'1405/07/07',items,subtotal:2500,discount:0,vat:250,grandTotal:2750,paymentMethod:'cash'}];renderAndPrintDirect('PRINT_FORMAL');});await expect(page.locator('#printable-invoice .invoice-a4-page')).toHaveCount(3);expect(await page.locator('#dynamic-print-orientation').evaluate(el=>el.innerHTML.includes('A4 landscape'))).toBe(true);await expect(page.locator('#finora-print-frame')).toHaveCount(1);expect(await page.locator('#finora-print-frame').evaluate(f=>({paper:f.contentDocument.querySelector('#finora-print-document')?.dataset.paper,orientation:f.contentDocument.querySelector('#finora-print-document')?.dataset.orientation,appUi:f.contentDocument.querySelectorAll('.view-pane,.app-shell-nav,.module-panel,.topbar').length,pages:f.contentDocument.querySelectorAll('.invoice-a4-page').length}))).toEqual({paper:'A4',orientation:'landscape',appUi:0,pages:3});await page.emulateMedia({media:'print'});expect(await page.locator('#printable-invoice .invoice-a4-page').first().evaluate(el=>getComputedStyle(el).breakAfter)).toBe('page');await page.emulateMedia({media:'screen'});await page.evaluate(()=>{datastore.invoices[0].id='PRINT_NONFORMAL';datastore.invoices[0].kind='informal';renderAndPrintDirect('PRINT_NONFORMAL');});await expect(page.locator('#printable-invoice .invoice-a4-page')).toHaveCount(3);expect(await page.locator('#dynamic-print-orientation').evaluate(el=>el.innerHTML.includes('A5 landscape'))).toBe(true);expect(await page.locator('#finora-print-frame').evaluate(f=>({paper:f.contentDocument.querySelector('#finora-print-document')?.dataset.paper,orientation:f.contentDocument.querySelector('#finora-print-document')?.dataset.orientation,appUi:f.contentDocument.querySelectorAll('.view-pane,.app-shell-nav,.module-panel,.topbar').length,pages:f.contentDocument.querySelectorAll('.invoice-a4-page').length}))).toEqual({paper:'A5',orientation:'landscape',appUi:0,pages:3});expect(errs.filter(x=>!x.includes('ResizeObserver'))).toEqual([]);});
3 +test('real DOM shell and post-login smoke',async({page})=>{const errs=[];page.on('pageerror',e=>errs.push(String(e)));await page.goto('http://127.0.0.1:4173/index.html',{waitUntil:'domcontentloaded'});await expect(page.locator('#auth-screen')).toBeVisible();await expect(page.locator('[data-module="projects"]')).toHaveCount(1);await expect(page.locator('[data-module="dashboard"]')).toContainText('داشبورد');await expect(page.locator('[data-module="home"]')).toHaveCount(0);await expect(page.locator('[data-module="catalog"]')).toHaveCount(0);await expect(page.locator('[data-module="erp"]')).toHaveCount(0);await expect(page.locator('#view-contracting')).toHaveCount(1);await expect(page.locator('[data-module="inventory"]')).toHaveCount(1);await expect(page.locator('[data-module="assets"]')).toHaveCount(1);for(const id of ['view-inventory','view-assets','view-currency','view-data-center','view-integrations'])await expect(page.locator('#'+id)).toHaveCount(1);expect(await page.evaluate(()=>{const a=[...document.querySelectorAll('[id]')].map(x=>x.id),s=new Set(),d=[];for(const id of a){if(s.has(id))d.push(id);s.add(id)}return d})).toEqual([]);await page.evaluate(async()=>{fetchCurrentUser=async()=>({id:'smoke-user',email:'smoke@example.test',fullName:'Smoke Admin',username:'smoke',role:'admin',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(()=>navigateShell('accounting','view-journal','new'));await expect(page.locator('#view-journal [data-finora-task="new"]')).toBeVisible();await expect(page.locator('#view-journal [data-finora-task="register"]')).toBeHidden();await page.evaluate(()=>navigateShell('accounting','view-journal','register'));await expect(page.locator('#view-journal [data-finora-task="register"]')).toBeVisible();await expect(page.locator('#view-journal [data-finora-task="new"]')).toBeHidden();await page.evaluate(()=>navigateShell('accounting','view-accounting-reports','trial'));await expect(page.locator('#p6-reporting-root [data-finora-task="trial"]')).toBeVisible();await expect(page.locator('#p6-reporting-root [data-finora-task="ledger"]')).toBeHidden();expect(await page.evaluate(()=>({refresh:window.__smokeRefresh,migrate:window.__smokeMigrate,admin:canShowShellCommand({guard:'admin'})}))).toEqual({refresh:true,migrate:true,admin:true});await page.evaluate(()=>{saveDatastore=()=>{};datastore.companies=[{id:'C1',ownerUserId:'smoke-user',name:'Smoke Co'}];datastore.settings=[{ownerUserId:'smoke-user',default_company_id:'C1'}];datastore.products=[{id:'P1',ownerUserId:'smoke-user',companyId:'C1',code:'1',name:'Smoke Product',type:'good',unit:'عدد',buy_price:100,sale_price:150,stock:0}];for(const k of ['warehouses','stockMovements','inventoryCounts','fixedAssets','assetDepreciations','currencies','exchangeRates','costCenters','importBatches','integrationConnections','integrationOutbox','phase5Audit'])datastore[k]=[];switchView('view-inventory');p5Render('view-inventory');});await expect(page.locator('#view-journal')).toBeHidden();await page.evaluate(()=>{switchView('view-dashboard');renderDashboard();});await expect(page.locator('#kpi-assets-sum')).toHaveCount(1);await expect(page.locator('#dashboard-cashflow-chart svg')).toHaveCount(1);await expect(page.locator('#dashboard-recent-journals')).toHaveCount(1);await page.evaluate(()=>{switchView('view-accounting-foundation');renderAccountingFoundation();});await expect(page.locator('#view-accounting-foundation')).toContainText('ورود کدینگ از Excel');await expect(page.locator('#view-accounting-foundation')).toContainText('شناور ۴ قرارداد/پیمان');await expect(page.locator('#af-account-type')).toHaveCount(1);await expect(page.locator('#af-account-search')).toHaveCount(1);await expect(page.locator('#af-account-level-filter')).toHaveCount(1);await expect(page.locator('#af-account-role')).toHaveCount(1);await expect(page.locator('#af-dim-source option[value="contract"]')).toHaveCount(1);await page.evaluate(()=>{switchView('view-inventory');p5Render('view-inventory');});await expect(page.locator('#p5-inventory-root')).toContainText('انبار اصلی');await expect(page.locator('#p5-inventory-root')).toContainText('Smoke Product');await page.evaluate(()=>{switchView('view-accounting-reports');P6Reports.render();});await expect(page.locator('#p6-reporting-root')).toContainText('تراز آزمایشی');await expect(page.locator('#p6-reporting-root')).toContainText('صورت جریان وجوه نقد');expect(await page.evaluate(()=>{const a=[...document.querySelectorAll('[id]')].map(x=>x.id),s=new Set(),d=[];for(const id of a){if(s.has(id))d.push(id);s.add(id)}return d})).toEqual([]);await page.evaluate(()=>{window.__FINORA_PRINT_TEST_MODE=true;window.print=()=>{};const items=Array.from({length:25},(_,i)=>({prodName:'Item '+(i+1),qty:1,unit:'عدد',price:100,lineTotal:100}));datastore.invoices=[{id:'PRINT_FORMAL',ownerUserId:'smoke-user',companyId:'C1',contactId:'',kind:'formal',number:'F-1',date:'1405/07/07',items,subtotal:2500,discount:0,vat:250,grandTotal:2750,paymentMethod:'cash'}];renderAndPrintDirect('PRINT_FORMAL');});await expect(page.locator('#printable-invoice .invoice-a4-page')).toHaveCount(3);expect(await page.locator('#dynamic-print-orientation').evaluate(el=>el.innerHTML.includes('A4 landscape'))).toBe(true);await expect(page.locator('#finora-print-frame')).toHaveCount(1);expect(await page.locator('#finora-print-frame').evaluate(f=>({paper:f.contentDocument.querySelector('#finora-print-document')?.dataset.paper,orientation:f.contentDocument.querySelector('#finora-print-document')?.dataset.orientation,appUi:f.contentDocument.querySelectorAll('.view-pane,.app-shell-nav,.module-panel,.topbar').length,pages:f.contentDocument.querySelectorAll('.invoice-a4-page').length}))).toEqual({paper:'A4',orientation:'landscape',appUi:0,pages:3});await page.emulateMedia({media:'print'});expect(await page.locator('#printable-invoice .invoice-a4-page').first().evaluate(el=>getComputedStyle(el).breakAfter)).toBe('page');await page.emulateMedia({media:'screen'});await page.evaluate(()=>{datastore.invoices[0].id='PRINT_NONFORMAL';datastore.invoices[0].kind='informal';renderAndPrintDirect('PRINT_NONFORMAL');});await expect(page.locator('#printable-invoice .invoice-a4-page')).toHaveCount(3);expect(await page.locator('#dynamic-print-orientation').evaluate(el=>el.innerHTML.includes('A5 landscape'))).toBe(true);expect(await page.locator('#finora-print-frame').evaluate(f=>({paper:f.contentDocument.querySelector('#finora-print-document')?.dataset.paper,orientation:f.contentDocument.querySelector('#finora-print-document')?.dataset.orientation,appUi:f.contentDocument.querySelectorAll('.view-pane,.app-shell-nav,.module-panel,.topbar').length,pages:f.contentDocument.querySelectorAll('.invoice-a4-page').length}))).toEqual({paper:'A5',orientation:'landscape',appUi:0,pages:3});expect(errs.filter(x=>!x.includes('ResizeObserver'))).toEqual([]);});
4
5
6 test('expired license browser enforcement',async({page})=>{const errs=[];page.on('pageerror',e=>errs.push(String(e)));await page.goto('http://127.0.0.1:4173/index.html',{waitUntil:'domcontentloaded'});await page.evaluate(async()=>{window.__licenseAlerts=[];window.alert=m=>window.__licenseAlerts.push(String(m));fetchCurrentUser=async()=>({id:'expired-user',email:'expired@example.test',fullName:'Expired User',username:'expired',role:'user',subscription:{type:'monthly',status:'active',startDate:'2025-01-01',endDate:'2025-01-31'}});pullAll=async()=>{};refreshAllSurfaces=()=>{updateLicenseDisplay(currentUser)};maybeMigrateLegacyData=()=>{};await enterApp({id:'expired-user'});});await expect(page.locator('#auth-screen')).toBeHidden();await expect(page.locator('#user-license-status-badge')).toContainText('منقضی شده');expect(await page.evaluate(()=>canWrite())).toBe(false);expect(await page.evaluate(()=>requireWrite())).toBe(false);expect(await page.evaluate(()=>window.__licenseAlerts.some(x=>x.includes('منقضی')&&x.includes('امکان ثبت یا ویرایش')))).toBe(true);expect(errs.filter(x=>!x.includes('ResizeObserver'))).toEqual([]);});
scripts/quality-check.mjs
+2 -1
@@ -111,7 +111,8 @@ if(!index.includes('id="view-accounting-reports"')||!index.includes('phase6-repo
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');
114 -for(const id of ['company-sector','company-legal-form'])if(!ids.includes(id))throw new Error('Company legal identity control missing #'+id);
114 +for(const id of ['company-sector','company-legal-form','company-organization-box','company-registration-box','company-national-label'])if(!ids.includes(id))throw new Error('Company legal identity control missing #'+id);
115 +if(!all['companies.js'].includes("reg_number:entity_type==='legal'")||!all['companies.js'].includes("organizationRole=entity_type==='legal'"))throw new Error('Natural-person company records must not retain legal-entity registration/group metadata');
116 if(index.includes('class="panel-collapse"'))throw new Error('Disappearing panel close button must not return; use persistent edge handle');
117
118 for(const id of ['modal-user-onboarding','onboarding-full-name','onboarding-professional-role','company-organization-role','company-parent-id','modal-license-company-limit'])if(!ids.includes(id))throw new Error('Accountant-first UX control missing #'+id);
supabase/migrations/20260930213000_license_company_capacity.sql
+9
@@ -8,6 +8,15 @@ alter table public.licenses
8 alter table public.licenses
9 add constraint licenses_max_companies_check check (max_companies between 1 and 1000);
10
11 +-- Preserve existing tenants: default is one for new licenses, but never retroactively
12 +-- place an existing owner below the number of companies already stored.
13 +update public.licenses l
14 +set max_companies = greatest(
15 + l.max_companies,
16 + coalesce((select count(*)::integer from public.records r where r.owner_id=l.user_id and r.collection='companies'),0),
17 + 1
18 +);
19 +
20 create or replace function public.admin_set_company_limit(target uuid, new_max_companies integer)
21 returns void
22 language plpgsql