سامانه صدور فاکتور و حسابداری
Prepare license capacity guard and ERP expansion roadmap
davoodmehraban89 committed
Sep 30, 2026 at 00:52 UTC
7e7e5264e4ffa65d433046717c65b93e8b41aea5
3 files changed
+162
-1
PROJECT_STATE.md
+1
-1
@@ -34,7 +34,7 @@ Before doing any project work:
34
## Current change ledger
35
| Date | Request / decision | Status | Evidence / next action |
36
|---|---|---|---|
37
-| 2026-09-30 | Owner directs Finora toward a daily-use accountant-first ERP, with defect elimination and Chart-of-Accounts UX as highest priorities. Immediate product requirements: rename the primary `پروژه` subsystem to `پیمانها`; after a new user verifies/signs in, collect their real display name and non-privileged professional usage role (e.g. owner/manager, financial manager, accountant) without allowing self-escalation to system admin; make license company capacity commercially controllable by the central system admin with default 1 company and explicit N-company licenses; distinguish ordinary multi-company licensing from a true holding/group model; research holding/company classification (private/public/government/cooperative/etc. and parent/subsidiary structures); expand ERP roadmap to integrated CRM and payroll/HR plus other evidence-backed gaps from leading Iranian/international ERP products. | IN PROGRESS | Live DB confirms `profiles.full_name` already exists, so display-name onboarding needs no schema change. `profiles.role` is intentionally only `user/admin`; professional role must remain separate and must never self-grant admin. Current `licenses` has no company-capacity field, so authoritative max-company enforcement requires a prepared DB migration/RPC update and must NOT be applied until the required explicit schema/role-change approval checkpoint. Holding is architecturally distinct from N independent companies: benchmark evidence from Dynamics/Acumatica/Odoo/SAP shows legal entities/subsidiaries, intercompany entries, consolidation, eliminations and currency translation as separate concerns. Immediate executable slice: rename rail to `پیمانها`, implement first-login name/professional-role onboarding using existing profile/records storage, strengthen company creation with a default-one client guard ready to consume authoritative license capacity, improve Chart-of-Accounts daily workflow, and archive a benchmark-backed ERP gap/holding roadmap. This code checkpoint implements the non-schema portion: primary rail/panel is visibly `پیمانها`; first-login onboarding stores display name + non-privileged professional role in the existing owner-scoped `settings` record (system `user/admin` role is untouched); company master gains organizational position (`standalone`/`holding_parent`/`subsidiary`) and parent-company relation metadata with an explicit warning that consolidation is separate; company creation enforces the current license capacity with default 1; admin UI is capacity-aware but keeps the capacity field disabled until the server column/RPC exists; Chart of Accounts gains search/level/type/status filters, hierarchy path, safe unused-account editing, and deactivate/reactivate for historical accounts. No DB/auth/RLS/role mutation in this checkpoint. Prepare (do not apply) the server migration for license company capacity. CRM/payroll/holding are roadmap modules until their lifecycle/persistence/accounting/permissions/tests exist; do not expose fake operational modules. |
37
+| 2026-09-30 | Owner directs Finora toward a daily-use accountant-first ERP, with defect elimination and Chart-of-Accounts UX as highest priorities. Immediate product requirements: rename the primary `پروژه` subsystem to `پیمانها`; after a new user verifies/signs in, collect their real display name and non-privileged professional usage role (e.g. owner/manager, financial manager, accountant) without allowing self-escalation to system admin; make license company capacity commercially controllable by the central system admin with default 1 company and explicit N-company licenses; distinguish ordinary multi-company licensing from a true holding/group model; research holding/company classification (private/public/government/cooperative/etc. and parent/subsidiary structures); expand ERP roadmap to integrated CRM and payroll/HR plus other evidence-backed gaps from leading Iranian/international ERP products. | IN PROGRESS | Live DB confirms `profiles.full_name` already exists, so display-name onboarding needs no schema change. `profiles.role` is intentionally only `user/admin`; professional role must remain separate and must never self-grant admin. Current `licenses` has no company-capacity field, so authoritative max-company enforcement requires a prepared DB migration/RPC update and must NOT be applied until the required explicit schema/role-change approval checkpoint. Holding is architecturally distinct from N independent companies: benchmark evidence from Dynamics/Acumatica/Odoo/SAP shows legal entities/subsidiaries, intercompany entries, consolidation, eliminations and currency translation as separate concerns. Immediate executable slice: rename rail to `پیمانها`, implement first-login name/professional-role onboarding using existing profile/records storage, strengthen company creation with a default-one client guard ready to consume authoritative license capacity, improve Chart-of-Accounts daily workflow, and archive a benchmark-backed ERP gap/holding roadmap. This code checkpoint implements the non-schema portion: primary rail/panel is visibly `پیمانها`; first-login onboarding stores display name + non-privileged professional role in the existing owner-scoped `settings` record (system `user/admin` role is untouched); company master gains organizational position (`standalone`/`holding_parent`/`subsidiary`) and parent-company relation metadata with an explicit warning that consolidation is separate; company creation enforces the current license capacity with default 1; admin UI is capacity-aware but keeps the capacity field disabled until the server column/RPC exists; Chart of Accounts gains search/level/type/status filters, hierarchy path, safe unused-account editing, and deactivate/reactivate for historical accounts. No DB/auth/RLS/role mutation in this checkpoint. Prepare (do not apply) the server migration for license company capacity. 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. |
docs/FINORA_ERP_EXPANSION_ROADMAP_V4.md
new
+90
@@ -0,0 +1,90 @@
1
+# Finora ERP Expansion Roadmap V4 — Accountant-first, group-ready
2
+
3
+Date: 2026-09-30
4
+
5
+## Product principle
6
+Finora should not become a menu catalog. A capability enters the product only when its master data, transaction lifecycle, accounting impact, permissions, audit trail, reporting, migration and tests are coherent. The current financial/accounting core remains the system of record.
7
+
8
+## Evidence from mature ERP suites
9
+- Microsoft Dynamics 365 Finance separates General Ledger, AP, AR, Budgeting, Cash/Bank, Cost Accounting and Fixed Assets, and pairs them with Supply Chain, Project Operations and Human Resources. Chart of Accounts is explicitly designed around main accounts + financial dimensions + account structures.
10
+ https://learn.microsoft.com/en-us/dynamics365/finance/
11
+ https://learn.microsoft.com/en-us/dynamics365/finance/general-ledger/plan-chart-of-accounts
12
+- Oracle Fusion groups ERP around Financials, Accounting Hub, Procurement, Project Management, Risk/Compliance and Analytics, while SCM, HCM, Sales and Service remain integrated suites.
13
+ https://docs.oracle.com/en/cloud/saas/index.html
14
+- SAP describes ERP as an integrated system across finance, HR, manufacturing, procurement, supply chain and sales.
15
+ https://www.sap.com/products/erp/what-is-erp.html
16
+- NetSuite OneWorld, Acumatica and Odoo all treat multi-company/entity operation as more than “many company records”: subsidiaries/entities, intercompany flows, currencies, consolidation/reporting and permissions matter.
17
+ https://www.netsuite.com/portal/products/erp/financial-management/finance-accounting/consolidation.shtml
18
+ https://www.acumatica.com/cloud-erp-software/financial-management/
19
+ https://www.odoo.com/documentation/18.0/applications/general/companies/multi_company.html
20
+- Odoo CRM models leads → opportunities plus assigned sales teams, next activities, calls/meetings/tasks and pipeline/forecasting.
21
+ https://www.odoo.com/documentation/18.0/applications/sales/crm.html
22
+- Iranian suites such as Rahkaran/System Group, Sepidar, Parmis and Mahak reinforce the local need for accounting, treasury, sales/purchase, inventory, payroll and industry-specific flows rather than a single flat workspace.
23
+ https://www.systemgroup.net/
24
+ https://www.sepidarsystem.com/products/sepidar/
25
+ https://www.parmisit.com/products/parmis-star-erp-solution
26
+ https://www.mahaksoft.com/
27
+
28
+## Company vs license vs holding
29
+These are three different concepts and must never be merged:
30
+1. **License company capacity** — commercial entitlement. Default = 1. Admin may sell 2, 10, N companies. This does not create a group relationship.
31
+2. **Company/legal entity** — an accounting/reporting entity with person type, ownership/sector, legal form, activity type and its own books.
32
+3. **Holding/group structure** — parent/subsidiary hierarchy. A real holding module additionally requires intercompany counterparties, due-to/due-from rules, intercompany matching, group currency, ownership/effective dates, consolidation mapping, elimination journals, minority/NCI treatment where relevant, consolidated statements, group close and access boundaries.
33
+
34
+Current implementation records organizational position and parent-company relation only. It does **not** claim consolidation.
35
+
36
+## Prioritized ERP gaps
37
+
38
+### P0 — Financial control / accountant daily work
39
+- Chart of Accounts UX: fast search/filter, hierarchy/path, safe edit/deactivate, duplicate/role validation, Excel import/export, account usage visibility.
40
+- Account inquiry/drill-down from balance → voucher → source document.
41
+- Bank accounts + bank statement import/reconciliation + unmatched items.
42
+- Reconciliation workspace: GL ↔ AR/AP/bank/tax/inventory.
43
+- Period-close workspace/checklist, period locks, closing evidence and exception list.
44
+- Approval workflow for sensitive journals/payments and separation of duties.
45
+- Audit log viewer with who/when/before/after for critical masters and transactions.
46
+- Saved filters/favorites/recent items and keyboard-first navigation.
47
+
48
+### P1 — Commercial ERP
49
+- CRM: lead, opportunity, pipeline stage, probability, expected revenue, activities, reminders, salesperson/team, quote conversion, customer 360.
50
+- Sales order lifecycle: quotation → order → delivery/service → invoice → collection.
51
+- Procurement: request → RFQ → supplier quote comparison → PO → receipt → supplier invoice → payment.
52
+- Inventory: reservations, transfers, multi-warehouse, reorder points, valuation layers and stock/account reconciliation.
53
+- Budgeting: versions, dimensions, approval, actual-vs-budget, commitment control.
54
+- Tax/local compliance workflow around Iranian invoicing/tax requirements with controlled mappings and audit evidence.
55
+
56
+### P1 — People / payroll
57
+- HR master: employee, employment, organization/unit, position, contract, attendance/leave.
58
+- Payroll engine: earnings/deductions, benefits, loans/advances, insurance/tax parameters, payroll period, calculation preview, approval, payslip.
59
+- Payroll posting: generated accounting voucher with traceability and reversal; cost-center/project allocation.
60
+- Access segregation: HR confidentiality must not reuse ordinary accounting visibility.
61
+
62
+### P2 — Group / enterprise
63
+- Holding/group master, subsidiaries and ownership/effective dates.
64
+- Intercompany documents and automated due-to/due-from.
65
+- Group chart mapping and reporting dimensions.
66
+- Currency translation, consolidation, elimination and consolidated statements.
67
+- Group close monitor and subsidiary submission/lock workflow.
68
+
69
+### P2 — Operations / industry depth
70
+- Manufacturing: BOM, routing, work order, material issue/receipt, WIP, overhead and production costing.
71
+- Service management: service orders, SLA, technician scheduling and service profitability.
72
+- Advanced project/contract costing: WBS, budget, commitments, progress, change orders, retention/guarantees, revenue recognition policy.
73
+- Asset maintenance / maintenance orders where asset-heavy customers need it.
74
+
75
+### P3 — Platform
76
+- Role/permission matrix by company + module + action; professional role remains separate from privileged system role.
77
+- Notifications/action center.
78
+- Document attachments and immutable evidence links.
79
+- API/webhook delivery service with secrets stored server-side and DNS-aware SSRF protection.
80
+- Import/migration workbench with preview, validation, mapping, rollback and reconciliation.
81
+- Observability, job queue, background processing and release/rollback controls.
82
+
83
+## Next vertical slices
84
+1. Finish/verify current accountant-first shell + Chart of Accounts slice.
85
+2. Apply company-capacity server migration only after explicit approval; verify non-admin denial and rollback-only boundary tests.
86
+3. Build Account Inquiry + drill-down + reconciliation foundations.
87
+4. Build bank account/reconciliation vertical slice.
88
+5. Build CRM MVP integrated with existing contacts/quotes/invoices, without duplicating customer master.
89
+6. Design payroll security/data model before exposing any payroll menu.
90
+7. Design holding consolidation model only after ordinary multi-company licensing is stable.
supabase/migrations/20260930213000_license_company_capacity.sql
new
+71
@@ -0,0 +1,71 @@
1
+-- Prepared 2026-09-30. DO NOT apply without explicit schema/RPC approval.
2
+-- Commercial license capacity: every license defaults to one company.
3
+alter table public.licenses
4
+ add column if not exists max_companies integer not null default 1;
5
+
6
+alter table public.licenses
7
+ drop constraint if exists licenses_max_companies_check;
8
+alter table public.licenses
9
+ add constraint licenses_max_companies_check check (max_companies between 1 and 1000);
10
+
11
+create or replace function public.admin_set_company_limit(target uuid, new_max_companies integer)
12
+returns void
13
+language plpgsql
14
+security definer
15
+set search_path = public
16
+as $$
17
+declare existing_count integer;
18
+begin
19
+ if not public.is_admin() then
20
+ raise exception 'forbidden' using errcode = '42501';
21
+ end if;
22
+ if new_max_companies is null or new_max_companies < 1 or new_max_companies > 1000 then
23
+ raise exception 'invalid company limit';
24
+ end if;
25
+ select count(*) into existing_count
26
+ from public.records
27
+ where owner_id = target and collection = 'companies';
28
+ if existing_count > new_max_companies then
29
+ raise exception 'company limit below existing company count';
30
+ end if;
31
+ update public.licenses
32
+ set max_companies = new_max_companies,
33
+ updated_at = now()
34
+ where user_id = target;
35
+ if not found then raise exception 'user not found'; end if;
36
+end
37
+$$;
38
+
39
+create or replace function public.finora_enforce_company_license_limit()
40
+returns trigger
41
+language plpgsql
42
+security definer
43
+set search_path = public
44
+as $$
45
+declare allowed_count integer;
46
+declare actual_count integer;
47
+begin
48
+ if new.collection <> 'companies' then return new; end if;
49
+ select max_companies into allowed_count
50
+ from public.licenses
51
+ where user_id = new.owner_id;
52
+ if allowed_count is null then allowed_count := 1; end if;
53
+ select count(*) into actual_count
54
+ from public.records
55
+ where owner_id = new.owner_id and collection = 'companies';
56
+ if actual_count > allowed_count then
57
+ raise exception 'company license limit exceeded' using errcode = '23514';
58
+ end if;
59
+ return new;
60
+end
61
+$$;
62
+
63
+drop trigger if exists trg_finora_company_license_limit on public.records;
64
+create trigger trg_finora_company_license_limit
65
+after insert on public.records
66
+for each row
67
+when (new.collection = 'companies')
68
+execute function public.finora_enforce_company_license_limit();
69
+
70
+revoke all on function public.admin_set_company_limit(uuid, integer) from public;
71
+grant execute on function public.admin_set_company_limit(uuid, integer) to authenticated;