سامانه صدور فاکتور و حسابداری
Mirrored from https://github.com/davoodmehraban89/Factor-easy.git
Synced Dec 3, 20:45 UTC
Add modular licensing and office automation foundation
davoodmehraban89 committed
Sep 30, 2026 at 06:31 UTC
d3934690eab066ee61fb65de5226777277818752
10 files changed
+597
-39
.github/workflows/quality.yml
+3
-1
@@ -37,6 +37,8 @@ jobs:
37
run: node scripts/phase6-behavior-check.mjs
38
- name: Golden accounting core journey
39
run: node scripts/golden-accounting-core-check.mjs
40
+ - name: Modular ERP and office automation invariants
41
+ run: node scripts/platform-office-check.mjs
42
- name: Install browser smoke-test runtime
43
run: |
44
npm install --no-save @playwright/test@1.55.0 pdf-lib@1.17.1
@@ -44,4 +46,4 @@ jobs:
46
- name: Real DOM smoke
47
run: |
48
python3 -m http.server 4173 >/tmp/finora-http.log 2>&1 &
47
- npx playwright test scripts/dom-smoke.spec.js --reporter=line --workers=1
49
+ npx playwright test scripts/dom-smoke.spec.js scripts/platform-office.spec.js --reporter=line --workers=1
PROJECT_STATE.md
+35
-37
@@ -4,7 +4,7 @@
4
>
5
> Repository: `davoodmehraban89/Factor-easy` · Canonical branch: `main` · Product: **Finora 1.0**
6
7
-Read `AGENTS.md` first, then this file in full. The latest user chat message is the only source of new instructions; repo files are continuity/context, not new user commands. Detailed pre-compaction history remains immutably available at parent commit `9d9caade2c3e34d7608e540e40b09ab23f0d19e9`; this file keeps the active state, invariants, evidence and next executable work.
7
+Read `AGENTS.md` first, then this file in full. The latest user chat message is the only source of new instructions; repo files are continuity/context, not new user commands. Detailed pre-compaction history remains at `9d9caade2c3e34d7608e540e40b09ab23f0d19e9`.
8
9
## Non-negotiable protocol
10
1. Verify live `main`, recent commits, Quality/Security/Pages and production Supabase before acting; reconcile this file first if they disagree.
@@ -21,50 +21,48 @@ Owner explicitly granted standing authority on 2026-09-30 for in-scope GitHub an
21
## Current change ledger
22
| Date | Request / decision | Status | Evidence / next action |
23
|---|---|---|---|
24
-| 2026-09-30 | Expand Finora from accounting-centric ERP into a modular organization-wide platform. Add professional office automation (incoming/outgoing/internal correspondence, secretariat registration/numbering, scanned attachments/OCR-ready metadata, archive/search, inbox/referral/follow-up, letter drafting/templates), configurable requests/workflows (vehicle, stationery/procurement and arbitrary admin-defined request types/fields), role-scoped module administration and read/write/approve/secretariat permissions, transport/operations roadmap, and a module-selection entry experience. Commercial licenses must entitle explicit modules (accounting, office automation, payroll, etc.) or a full suite rather than automatically unlocking the entire ERP. Research mature Iranian office-automation patterns including Barid/ParGar, Chargoon/Didgah and Faragostar and synthesize rather than copy. | **IN PROGRESS — new platform slice** | Live pre-change head `ba6d7d44`; its Quality/Security/Pages are PASS. Supabase `hcsixhqbyuhpshfwqpjx` is `ACTIVE_HEALTHY`, 21 applied migrations through `20260929221754`, RLS on all public business tables, performance advisor clean. Research evidence found ParGar's unified organizational desk + OCR/search, Faragostar's correspondence/secretariat/inbox/forms/workflow/document patterns, and mature secretariat patterns such as multiple registries, numbering, attachments, referrals, SLA/follow-up and controlled search. Immediate architecture rule: license entitlement and user authorization are separate layers; no client-only permission security. First vertical slice will establish server-enforced module entitlements + module catalog/launcher + office-automation/request data contracts and tests without weakening existing accounting invariants. Full multi-user organizational delegation requires a tenant/membership model and will not be falsely claimed until server-side sharing/RLS is implemented. |
25
-| 2026-09-30 | `@GitHub @Supabase`: perform required remaining work without routine permission prompts and finish executable remaining work. | **COMPLETED for the current hardening checkpoint** | Authority/reconciliation `38beab7f`; Real-DOM natural/legal ordering repair `23ed19b2`; browser enterprise-v2 routing repair `b0278172ba2110dcaf9cd0d2edb784417a0fdff5`. Quality `36661446705` **PASS** including syntax, application invariants, Phase 2–6, enterprise payroll/service-period behavior, Golden Accounting Journey and all 3 Real-DOM/PDF tests. Security `36661446688` **PASS**. Pages `36661445458` **PASS**. Production Supabase remains `ACTIVE_HEALTHY`, 21 migrations through `20260929221754`, RLS enabled on `profiles/licenses/records`, performance advisor clean. No DB mutation was required in this checkpoint. |
26
-| 2026-09-30 | Iran-first high-assurance enterprise ERP: current Iranian accounting/tax/VAT/Taxpayer-System/commerce/labor/social-security controls; standards-aware chart/statements; HR/payroll/benefits/leave; treasury/petty cash; inventory/costing/ABC/performance budgets; intercompany/group controls; compliance traceability. Keep natural/legal identity, activity and group structure separate. | **IN PROGRESS — broader roadmap** | Baseline `docs/IRAN_COMPLIANCE_MATRIX_V1.md`; implemented foundations include chart roles, entity cleanup, employees/contracts/leave/cashboxes/petty cash/compliance, accounting-connected payroll, benefit accruals, posted petty-cash lifecycle, budgets, ABC and intercompany/group management controls. Applied+archived migrations: `20260929220543`, `20260929220613`, `20260929221252`, `20260929221754`. Do not claim statutory consolidation, full tax submission, full HR/CRM or every Iranian rule complete until lifecycle/accounting/permissions/tests exist. |
27
-| 2026-09-30 | Accountant-first daily ERP: `پروژه`→`پیمانها`, first-login display/professional role, commercial company capacity, multi-company vs true holding separation, improved Chart of Accounts. | IMPLEMENTED / VERIFIED AT CURRENT PRODUCT CHECKPOINT | License capacity is live with server enforcement; professional role is separate from system `user/admin`; Chart of Accounts search/filter/hierarchy/safe edit/deactivate exists; roadmap `docs/FINORA_ERP_EXPANSION_ROADMAP_V4.md`. |
28
-| 2026-09-30 | Approved two-tier shell, persistent contextual handle, task-focused navigation, isolated printing, separate company legal/activity/group metadata. | IMPLEMENTED / VERIFIED IN BROWSER | UX evidence `docs/FINORA_UX_ACCOUNTING_BENCHMARK_V3.md`; Chromium A4/A5 isolated-PDF tests PASS in `36661446705`. Physical-printer validation remains `NOT VERIFIED`. |
24
+| 2026-09-30 | Expand Finora into a modular organization-wide ERP: professional office automation, scanned correspondence/attachments, secretariat numbering, configurable requests/forms, module managers and granular read/write/approve/secretariat permissions, modular entry experience, module-by-module commercial licensing/full suite, and future transport/operations modules. Research mature Iranian patterns including Barid/ParGar, Chargoon/Didgah and Faragostar. | **SLICE A IMPLEMENTED / CI VERIFICATION PENDING** | Request recorded at `0b622439`. Research/architecture: `docs/FINORA_MODULAR_ERP_OFFICE_AUTOMATION_V1.md`. Production migrations applied: `20260930025546 modular_entitlements_office_automation_foundation` and `20260930025647 office_secretariat_atomic_registration`; both are archived exactly in this implementation commit. `licenses.modules` supports explicit modules or `full_suite`; existing users are grandfathered to full suite. RLS + atomic sync enforce module entitlement. Private `office-attachments` bucket has owner/module policies. Office slice includes secretariat registries, incoming/outgoing/internal metadata, draft + server-atomic registration number, private PDF/image attachments, archive metadata search and OCR-ready fields. Requests slice includes admin-defined request types/fields and submission. Module launcher and admin license module picker are implemented; unimplemented CRM/transport/manufacturing/maintenance are visible only in architecture/catalog and disabled for sale. Full multi-login organization sharing/module-manager RBAC is deliberately **not claimed** until tenant membership/RLS Slice B. Fresh Quality/Security/Pages required before marking verified. |
25
+| 2026-09-30 | `@GitHub @Supabase`: perform required remaining work without routine permission prompts and finish executable remaining work. | COMPLETED for prior hardening checkpoint | Quality `36661446705` PASS; Security `36661446688` PASS; Pages `36661445458` PASS on prior product checkpoint. |
26
+| 2026-09-30 | Iran-first high-assurance enterprise ERP with accounting/tax/VAT/commerce/labor/social-security controls and enterprise modules. | IN PROGRESS — broader roadmap | Baseline `docs/IRAN_COMPLIANCE_MATRIX_V1.md`; production enterprise migrations through `20260929221754` remain applied and archived. Do not claim statutory consolidation/full tax submission/full HR/CRM until complete lifecycle/accounting/permissions/tests exist. |
27
30
-## Current verified live state — 2026-09-30
31
-- Live pre-platform-expansion head: `ba6d7d44402d97e007c2490b0a77d7e343a1642b`; current request-recording commit follows it.
32
-- Quality/Security/Pages on `ba6d7d44`: PASS.
33
-- Supabase `hcsixhqbyuhpshfwqpjx`: `ACTIVE_HEALTHY`, PostgreSQL `17.6.1.166`, 21 migrations through `20260929221754 iran_enterprise_financial_controls`.
34
-- Public data: `profiles` 4 rows, `licenses` 4, `records` 97; RLS enabled on all three; `licenses.max_companies default 1` exists.
35
-- Performance advisor: no findings.
36
-- Security advisor: 6 WARN SECURITY DEFINER functions (`admin_cancel_license`, `admin_extend_license`, `admin_set_company_limit`, `admin_set_license`, `has_active_license`, `is_admin`) plus leaked-password protection disabled. Admin mutation RPCs previously passed non-admin negative checks; required authenticated admin RPC access must not be revoked merely to silence lint.
37
-- Supabase Sep-2026 changelog review: PostgreSQL 17.11 is available while project is 17.6.1; available connector actions do not expose platform database upgrade or Auth leaked-password-policy configuration, so neither was changed.
28
+## Current production state — 2026-09-30
29
+- Pre-slice repo head: `0b622439fb03b64b029cbc7b0c7987c55160ad0c`; new implementation commit is pending creation/CI in this file version.
30
+- Supabase `hcsixhqbyuhpshfwqpjx`: `ACTIVE_HEALTHY`, PostgreSQL `17.6.1.166`.
31
+- Applied migrations: 23 through `20260930025647 office_secretariat_atomic_registration`.
32
+- `licenses.modules` exists, default `['full_suite']`; `admin_set_license_modules` exists.
33
+- `records` RLS now includes server module-entitlement checks; `finora_sync_records` rejects unentitled collection writes.
34
+- Office collections allowed: `officeRegistries`, `correspondence`, `correspondenceAttachments`, `correspondenceReferrals`, `correspondenceAudit`.
35
+- Request collections allowed: `requestTypes`, `requests`, `requestActions`.
36
+- Private Storage bucket `office-attachments`: max 20 MB/object; PDF/JPEG/PNG/TIFF; owner + office-module RLS.
37
+- Secretariat registration RPC uses row lock on registry counter plus unique owner/registry/register-number index.
38
+- Performance advisor before this slice: clean. Security advisor before this slice: 6 public SECURITY DEFINER warnings + leaked-password protection disabled. Recheck after CI.
39
40
## Master roadmap status
40
-Phases 1–6 remain accepted and completed: UX shell; master data/accounting foundation; double-entry accounting; projects/contracts; inventory/costing/assets/multi-currency/import/integrations; professional reports/reconciliation/release. Current work is post-release hardening + Iran-first enterprise/platform expansion, not a reset.
41
+Phases 1–6 remain accepted/completed: UX shell; accounting foundation; double-entry accounting; projects/contracts; inventory/costing/assets/multi-currency/import/integrations; reports/reconciliation/release. Current work is post-release hardening + Iran-first enterprise/platform expansion, not a reset.
42
42
-## Accounting/data invariants
43
-- Posted journal lines are accounting truth; source documents remain traceable.
44
-- Posted/reversed history is immutable; correction uses reversal/amendment.
45
-- Posted vouchers balance debit=credit and obey fiscal locks/dates; source event/version uniqueness prevents duplicate posting/orphan failure residue.
46
-- Account/system roles support custom/manual/Excel charts; reports must not depend only on Persian title/code.
47
-- Counterparties/projects/branches/contracts are global masters/analytics, not one ledger account per entity; analytic dimensions stay normalized/generic and group/non-leaf nodes are non-postable where leaf-only rules apply.
48
-- Tenant isolation is mandatory at RLS/data boundary; authorization never relies on user-editable metadata.
49
-- Restore/sync preserves immutable financial history and resolves server uniqueness/immutability conflicts authoritatively.
50
-- **New platform invariant:** commercial module entitlement (what the customer bought) and member authorization (what a person may read/write/approve/administer) are independent checks; effective access is the intersection of both. UI hiding is never a security boundary.
43
+## Platform / accounting invariants
44
+- Posted journal lines are accounting truth; posted/reversed history is immutable; correction uses reversal/amendment.
45
+- Posted vouchers balance and obey fiscal locks; source event/version uniqueness prevents duplicate posting.
46
+- Tenant isolation is mandatory at the data boundary; authorization never relies on user-editable metadata.
47
+- Commercial module entitlement and member authorization are independent. Effective access is their intersection plus tenant/record scope. UI hiding is never a security boundary.
48
+- Office registration numbers are allocated server-side atomically; binary scans live in private Storage, not JSON records.
49
+- Do not expose/sell roadmap-only modules as operational.
50
51
## Required evidence
53
-`docs/PHASE_1_REDESIGN_VERIFICATION.md` · `docs/PHASE_2_REDESIGN_VERIFICATION.md` · `docs/PHASE_3_REDESIGN_VERIFICATION.md` · `docs/PHASE_4_REDESIGN_VERIFICATION.md` · `docs/PHASE_5_VERIFICATION.md` · `docs/PHASE_6_VERIFICATION.md` · `docs/ACCOUNTING_CORE_ROADMAP_V1.md` · `docs/RD_IRAN_ACCOUNTING_ERP_2026-09-28.md` · `docs/IRAN_COMPLIANCE_MATRIX_V1.md` · `docs/FINORA_ERP_EXPANSION_ROADMAP_V4.md` · `docs/FINORA_UX_ACCOUNTING_BENCHMARK_V3.md` · `docs/PRODUCTION_RUNBOOK.md` · `supabase/migrations/`.
52
+`docs/PHASE_1_REDESIGN_VERIFICATION.md` · `docs/PHASE_2_REDESIGN_VERIFICATION.md` · `docs/PHASE_3_REDESIGN_VERIFICATION.md` · `docs/PHASE_4_REDESIGN_VERIFICATION.md` · `docs/PHASE_5_VERIFICATION.md` · `docs/PHASE_6_VERIFICATION.md` · `docs/IRAN_COMPLIANCE_MATRIX_V1.md` · `docs/FINORA_ERP_EXPANSION_ROADMAP_V4.md` · `docs/FINORA_UX_ACCOUNTING_BENCHMARK_V3.md` · `docs/FINORA_MODULAR_ERP_OFFICE_AUTOMATION_V1.md` · `docs/PRODUCTION_RUNBOOK.md` · exact SQL under `supabase/migrations/`.
53
54
## NOT VERIFIED / external boundary
56
-- Authenticated production-user browser E2E: NOT VERIFIED; no production user credential/session is available here.
55
+- Multi-login organization membership/module-manager RBAC/shared inbox/referral: NOT YET IMPLEMENTED. Existing business record ownership is still user-owned; Slice B must migrate this securely.
56
+- OCR engine accuracy on real Persian scans: NOT VERIFIED; only OCR-ready metadata exists.
57
+- Authenticated production-user browser E2E: NOT VERIFIED; no production user credential/session supplied here.
58
- Physical-printer behavior: NOT VERIFIED.
58
-- Live third-party webhook delivery: NOT VERIFIED; no target endpoint/credential supplied.
59
-- OCR engine quality on real Persian scans: NOT VERIFIED; the new office-automation design must be OCR-ready but may not claim OCR accuracy before a real engine/pilot is connected.
60
-- Multi-user organization sharing/delegation: NOT YET IMPLEMENTED; existing `records.owner_id = auth.uid()` model is user-owned and must not be represented as secure organizational RBAC.
61
-- Supabase leaked-password-protection enablement: NOT VERIFIED/current advisor says disabled; connector exposes no Auth password-policy mutation.
62
-- PostgreSQL 17.11 platform upgrade/reindex: NOT PERFORMED; connector exposes no database-upgrade action.
59
+- Live third-party webhook/ECE/email gateway delivery: NOT VERIFIED.
60
+- Supabase leaked-password-protection enablement: current platform connector exposes no Auth password-policy mutation.
61
+- PostgreSQL 17.11 upgrade/reindex: NOT PERFORMED; connector exposes no database-upgrade action.
62
63
## Exact next executable work
65
-1. Write the researched office-automation + modular ERP architecture/IA and explicit module catalog, licensing/RBAC model and phased roadmap.
66
-2. Implement a server-enforced module-entitlement migration/RPC while preserving existing customers via an explicit backward-compatible entitlement policy; archive the exact applied migration.
67
-3. Implement the client module catalog/launcher and admin license module selection; gate modules from the server-derived license, not only CSS/UI.
68
-4. Add office-automation/request collections and a working first slice: secretariat registries + incoming/outgoing/internal correspondence metadata + attachment metadata + request-type/form schema foundations, with tests.
69
-5. Design then implement organization tenant/membership/RBAC as a separate high-risk slice before claiming module managers, secretariat operators or shared inboxes across multiple login accounts.
70
-6. Run full Quality/Security/Pages + Supabase advisors and update this file with exact evidence.
64
+1. Commit this Slice A code/docs/migration archive and run full Quality/Security/Pages, including the new platform-office static check and Chromium test.
65
+2. Recheck production migrations, RLS/storage policies and Supabase advisors; fix any current-head defect before moving on.
66
+3. Slice B: design/migrate organization tenant + memberships + module roles/capabilities + row scopes + confidentiality clearance + immutable permission/referral audit. Only after positive/negative RLS tests may shared secretariat inboxes and module-manager roles be claimed.
67
+4. Slice C: letter templates/editor/signature/approval/referral/read receipts/SLA/reply graph/archive classification/OCR service and quality benchmark/full-text search/integration adapters.
68
+5. Slice D/E: versioned workflow engine, then transport/procurement/service/CRM/manufacturing/maintenance as complete tested vertical modules.
docs/FINORA_MODULAR_ERP_OFFICE_AUTOMATION_V1.md
new
+160
@@ -0,0 +1,160 @@
1
+# Finora Modular ERP + Office Automation Architecture v1
2
+
3
+Date: 2026-09-30
4
+Status: APPROVED DIRECTION / first vertical slice implemented in production schema
5
+
6
+## Product decision
7
+Finora is no longer modeled as “accounting plus extra pages”. It is a modular organization platform. A customer may buy one or several modules or the full suite. A signed-in person must only see and use modules that are both commercially entitled and individually authorized.
8
+
9
+**Effective access = customer/module entitlement ∩ member permission ∩ record/tenant scope.**
10
+
11
+The first production slice implements server-enforced commercial module entitlements and working single-account office/request foundations. Multi-login organization membership/RBAC is intentionally a separate migration because the existing production record store is owned by `auth.uid()`; UI-only sharing would be insecure.
12
+
13
+## Research synthesis — patterns adopted, not copied
14
+Research was used as product evidence, not as a UI/template to clone.
15
+
16
+### Barid / ParGar
17
+Public Barid material describes ParGar as a unified organizational desk spanning financial, HR and office automation rather than isolated systems. Public product material and company posts emphasize paperless correspondence, work desk/inbox, archive and OCR so scanned correspondence becomes searchable. These patterns support Finora's unified launcher, correspondence archive, attachment/OCR-ready metadata and later cross-module work inbox.
18
+
19
+Evidence:
20
+- https://www.linkedin.com/company/baridsoft
21
+- https://www.linkedin.com/products/baridsoft-%D8%B3%DB%8C%D8%B3%D8%AA%D9%85-%D8%AC%D8%A7%D9%85%D8%B9-%D9%BE%D8%B1%DA%AF%D8%A7%D8%B1
22
+- https://www.linkedin.com/posts/baridsoft_%D9%BE%D8%B1%D8%AF%D8%A7%D8%B2%D8%B4%D8%AA%D8%B5%D9%88%DB%8C%D8%B1-ocr-%D8%A7%D8%AA%D9%88%D9%85%D8%A7%D8%B3%DB%8C%D9%88%D9%86%D8%A7%D8%AF%D8%A7%D8%B1%DB%8C-activity-7266786695159664640-kH26
23
+
24
+### Chargoon / Didgah
25
+Chargoon material describes correspondence as part of a broader office-automation family, with production/circulation of letters, mobile access, tasks, meetings and organizational information. Public implementation material also stresses preserving historical letters/attachments and removing referral bottlenecks. Finora therefore treats correspondence history and attachments as durable records and keeps tasks/meetings as future modules rather than cramming them into “letters”.
26
+
27
+Evidence:
28
+- https://www.linkedin.com/products/chargoon-%D9%86%D8%B1%D9%85-%D8%A7%D9%81%D8%B2%D8%A7%D8%B1-%D8%A7%D8%AA%D9%88%D9%85%D8%A7%D8%B3%DB%8C%D9%88%D9%86-%D8%A7%D8%AF%D8%A7%D8%B1%DB%8C/
29
+- https://www.linkedin.com/posts/chargoon_%D8%AF%DB%8C%D8%AF%DA%AF%D8%A7%D9%87-%D8%A7%D8%AA%D9%88%D9%85%D8%A7%D8%B3%DB%8C%D9%88%D9%86%D8%A7%D8%AF%D8%A7%D8%B1%DB%8C-activity-7210897661120417793-DLXE
30
+
31
+### Faragostar
32
+Public Faragostar material exposes a useful mature capability split: correspondence inbox/circulation, web secretariat, document/archive, tasks, file exchange, meetings, communication channels, multi-organization gateways, classified correspondence and modular add-ons. Its public product material also explicitly separates user groups such as managers, secretariat operators and ordinary experts. Finora adopts the capability separation and security concepts, not product-specific terminology or screens.
33
+
34
+Evidence:
35
+- https://www.linkedin.com/products/faragostar-%D8%A7%D8%AA%D9%88%D9%85%D8%A7%D8%B3%DB%8C%D9%88%D9%86-%D9%BE%D8%A7%DB%8C%D9%87/
36
+- https://www.linkedin.com/products/faragostar-%D8%A7%D9%85%D9%86%DB%8C%D8%AA/
37
+- https://www.linkedin.com/products/faragostar-%D9%85%D8%AF%DB%8C%D8%B1%DB%8C%D8%AA-%D8%A7%D8%B1%D8%AA%D8%A8%D8%A7%D8%B7%D8%A7%D8%AA/
38
+
39
+## Module catalog
40
+### Operational now
41
+- `core` — company/account/platform settings; always present.
42
+- `accounting` — GL, chart, dimensions, journals, fiscal years, financial statements/control.
43
+- `commerce` — contacts, products/services, sales and purchases.
44
+- `treasury` — receipts/payments, cheques, cashboxes and petty cash.
45
+- `contracting` — projects/contracts, amendments, deductions, guarantees, statements.
46
+- `inventory` — warehouses, stock movement/counting/cost.
47
+- `assets` — fixed assets and depreciation.
48
+- `hr_payroll` — employees, employment contracts, leave, payroll and employee accruals.
49
+- `office_automation` — secretariat registries, correspondence, scan/attachments, archive/search foundations.
50
+- `requests_workflow` — admin-defined request types/fields and request submission foundation.
51
+- `group_consolidation` — existing group/intercompany management controls; statutory consolidation remains a roadmap item.
52
+- `analytics` — reporting/management surfaces.
53
+
54
+### Planned, not sold/exposed as operational yet
55
+- `crm` — lead/opportunity/activity/service lifecycle.
56
+- `transport` — fleet, driver, vehicle request/dispatch/trip/fuel/maintenance linkage.
57
+- `manufacturing` — BOM/MRP/work orders/production costing.
58
+- `maintenance` — equipment/work order/preventive maintenance.
59
+
60
+The license schema already knows these future keys so commercial packaging can evolve without another entitlement redesign, but the admin UI disables unimplemented modules to prevent selling fake capability.
61
+
62
+## License model
63
+`licenses.modules text[]` is independent of plan duration and `max_companies`.
64
+
65
+- `['full_suite']` means all modules, including future modules when released.
66
+- Otherwise the array contains explicit module keys.
67
+- Existing licenses were grandfathered to `full_suite` because they previously had no module boundary; this avoids silently removing already purchased/used functionality.
68
+- New module enforcement occurs in Postgres RLS and the atomic sync RPC. Hiding a rail button is only UX, never the security boundary.
69
+- Admin module changes use `admin_set_license_modules`; the function rechecks the server-side admin role and validates module keys.
70
+
71
+## Office automation domain contract
72
+### Secretariat registry (`officeRegistries`)
73
+`id, companyId, code, title, prefix, nextNumber, active, createdAt`.
74
+
75
+Each registry is an independent numbering gateway. Registration is performed by `office_register_correspondence` inside one database transaction with `FOR UPDATE`; two sessions cannot legitimately consume the same counter value. A unique index on owner + registry + register number is the second collision guard.
76
+
77
+### Correspondence (`correspondence`)
78
+- identity: `id`, `companyId`, `registryId`, `registerNumber`.
79
+- kind: `incoming | outgoing | internal`.
80
+- external metadata: external number/date, sender/recipient.
81
+- content: subject, body, tags (next UI slice).
82
+- controls: priority, confidentiality, due date, status.
83
+- OCR-ready: `ocrStatus`, `ocrText`; **no OCR accuracy claim until a real engine is connected and tested on Persian scans**.
84
+- lifecycle: draft → registered → circulation/follow-up → closed. The first slice implements draft and atomic registration; shared circulation waits for tenant RBAC.
85
+
86
+### Attachments (`correspondenceAttachments`)
87
+Binary content is not stored inside JSON records. Files use a private Supabase Storage bucket `office-attachments`, maximum 20 MB each, PDF/JPEG/PNG/TIFF. Object paths begin with the authenticated UID. Storage RLS requires both object ownership and the `office_automation` entitlement. Record metadata stores correspondence id, private storage path, original filename, MIME type, size and timestamp.
88
+
89
+### Referrals and audit
90
+Collections are reserved now (`correspondenceReferrals`, `correspondenceAudit`) but shared-user referral is not exposed until organization membership and server-side member permissions exist.
91
+
92
+## Configurable requests
93
+`requestTypes` stores an admin-defined schema (`fields[]`) instead of hard-coding “vehicle request” or “stationery request”. The first UI supports text/number/date/long-text field definitions and required flags. `requests` stores the chosen type, values, number and status. `requestActions` is reserved for approval/reject/return/delegate history once member RBAC exists.
94
+
95
+Recommended packaged templates after the workflow engine is complete:
96
+- vehicle/transport request → transport dispatch;
97
+- stationery/office supplies → procurement/inventory issue;
98
+- leave/overtime/mission → HR/payroll;
99
+- purchase request → procurement/budget approval;
100
+- payment request → treasury/accounting;
101
+- IT/service request → service desk/maintenance;
102
+- contract/legal review → contracting/legal;
103
+- visitor/access request → facilities/security.
104
+
105
+## Multi-user RBAC target (next high-risk slice)
106
+Do not overload `profiles.role` (`user/admin`) for organization permissions. Introduce explicit tenant structures:
107
+
108
+1. `organizations` / legal tenant.
109
+2. `organization_members` mapping auth users to tenant + employment/position identity.
110
+3. `module_roles` such as module-admin, manager, operator, viewer.
111
+4. `member_module_permissions` with capabilities: `read`, `create`, `edit`, `delete`, `approve`, `register`, `refer`, `archive`, `configure`.
112
+5. row scope: own / unit / branch / company / all organization.
113
+6. confidentiality clearance independent from generic read permission.
114
+7. immutable action/audit ledger for permission changes, registration, referral, approval and document access where required.
115
+
116
+Examples:
117
+- Accounting user: accounting entitlement + `read/write` accounting role; no office module.
118
+- Office ordinary user: office entitlement + draft/read own inbox; cannot allocate registry numbers.
119
+- Secretariat operator: `register`, scan/attachment correction and archive metadata; no global module configuration.
120
+- Office module admin: configure registries/templates/routing and see module audit according to tenant policy.
121
+- Approver/manager: read/approve/refer within assigned scope; cannot silently alter registered history.
122
+
123
+## Entry experience
124
+After authentication Finora derives the purchased module list from the server license. When multiple modules are available, a workspace launcher is shown. The primary rail is also filtered to entitled modules. A user can switch workspaces without a second login. This is the product-level equivalent of a unified organizational desk while preserving module boundaries.
125
+
126
+## Security invariants
127
+1. UI visibility never grants or denies data access by itself.
128
+2. RLS blocks unentitled collections on SELECT/INSERT/UPDATE/DELETE.
129
+3. `finora_sync_records` rejects mixed upsert/delete payloads containing an unentitled collection.
130
+4. Office files are private and owner/module restricted.
131
+5. Registration numbers are allocated atomically server-side.
132
+6. Module license and member permission remain independent.
133
+7. Registered correspondence must gain immutable registration-history/audit guards before shared multi-user editing is enabled.
134
+8. No “module manager” or “secretariat shared inbox” claim before tenant membership/RBAC RLS passes positive and negative tests.
135
+
136
+## Delivery roadmap
137
+### Slice A — implemented in this checkpoint
138
+Server module entitlements; admin module picker; module launcher; office/request collections; private scan bucket; secretariat registry; draft/atomic registered correspondence; attachment upload/download; archive metadata search; configurable request type/fields and request submission.
139
+
140
+### Slice B — tenant + permissions
141
+Organization/membership migration, row ownership conversion strategy, module roles/capabilities, unit/branch scopes, secretariat operator and module-admin roles, shared inbox and referral, permission audit.
142
+
143
+### Slice C — mature office automation
144
+Letter templates/Word-like editor, signatures/approval, referral chains, read receipts, deadlines/reminders, reply/related-letter graph, archive folders/classification, OCR service + Persian quality benchmark, full-text/OCR search, ECE/API/email gateway adapters, meeting/task integration.
145
+
146
+### Slice D — workflow/BPMS-lite
147
+Versioned request schemas, visual step definitions, conditions, parallel/sequential approvals, SLA/escalation, delegation/substitution, form versioning, audit, cross-module actions.
148
+
149
+### Slice E — logistics/operations
150
+Transport/fleet/dispatch/fuel/maintenance, procurement request-to-order, office supplies issue, service desk, CRM and manufacturing/maintenance only as complete vertical products with accounting/permissions/reporting integration.
151
+
152
+## Acceptance criteria for Slice A
153
+- Production `licenses.modules` exists and old licenses remain functional through explicit `full_suite` grandfathering.
154
+- An explicit module subset is enforced in RLS and atomic sync, not only the UI.
155
+- Admin can assign full suite or implemented module subset independently of duration/company capacity.
156
+- Office and Requests appear only when licensed.
157
+- Secretariat registry can be created; registered correspondence gets a server-allocated unique number.
158
+- Scan files use private Storage with owner + module RLS.
159
+- Request type builder can add fields and create a request from the resulting schema.
160
+- Existing accounting/domain/Real-DOM gates remain green.
js/bootstrap.js
+2
-1
@@ -1 +1,2 @@
1
-window.addEventListener('DOMContentLoaded',()=>{initAuthSystem();});
1
+function finoraLoadScript(src){return new Promise((resolve,reject)=>{const s=document.createElement('script');s.src=src;s.onload=resolve;s.onerror=()=>reject(new Error('Failed to load '+src));document.head.appendChild(s)})}
2
+window.addEventListener('DOMContentLoaded',async()=>{try{await finoraLoadScript('js/platform-modules.js?v=20260930-platform-v1');await finoraLoadScript('js/office-automation.js?v=20260930-office-v1')}catch(e){console.error('Finora platform extension load failed',e)}initAuthSystem();});
js/office-automation.js
new
+44
@@ -0,0 +1,44 @@
1
+/* Finora office automation + configurable requests MVP. No multi-user delegation is claimed until tenant RBAC exists. */
2
+(function(){
3
+function mine(k){return (datastore[k]||[]).filter(x=>x.ownerUserId===currentUser?.id)}
4
+function oid(p){return p+'_'+Date.now().toString(36)+'_'+Math.random().toString(36).slice(2,7)}
5
+function oesc(v){return typeof esc==='function'?esc(v):String(v??'')}
6
+function nowIso(){return new Date().toISOString()}
7
+function ensureViews(){const root=document.querySelector('.main-surface');if(!root)return;[['view-office','office'],['view-requests','requests']].forEach(([id,kind])=>{if(document.getElementById(id))return;const s=document.createElement('section');s.id=id;s.className='view-pane';s.dataset.finoraPlatform=kind;root.appendChild(s)})}
8
+function companyId(){try{return getMySettings().default_company_id||getMyCompanies()[0]?.id||''}catch(_){return ''}}
9
+function directionLabel(v){return ({incoming:'وارده',outgoing:'صادره',internal:'داخلی'})[v]||v}
10
+function statusLabel(v){return ({draft:'پیشنویس',registered:'ثبتشده',submitted:'ارسالشده',closed:'مختومه'})[v]||v}
11
+function registryOptions(){return mine('officeRegistries').map(x=>'<option value="'+oesc(x.id)+'">'+oesc(x.title)+' · '+oesc(x.prefix||'بدون پیشوند')+'</option>').join('')}
12
+function officeHeader(title,sub){return '<div class="af-head"><div><h1>'+title+'</h1><p>'+sub+'</p></div><div><button class="btn btn-secondary btn-inline" onclick="showModuleLauncher(true)">تغییر فضای کاری</button></div></div>'}
13
+function correspondenceRows(rows){return rows.length?rows.map(x=>'<tr><td><strong>'+oesc(x.registerNumber||'—')+'</strong><small style="display:block;color:var(--text-muted)">'+directionLabel(x.direction)+'</small></td><td>'+oesc(x.subject||'—')+'</td><td>'+oesc(x.counterparty||'—')+'</td><td>'+oesc(x.externalNumber||'—')+'</td><td>'+oesc(x.priority||'عادی')+' / '+oesc(x.confidentiality||'عادی')+'</td><td>'+statusLabel(x.status)+'</td><td><button class="btn btn-secondary btn-inline" onclick="officeOpenRecord(\''+oesc(x.id)+'\')">مشاهده</button></td></tr>').join(''):'<tr><td colspan="7" class="af-empty">مکاتبهای ثبت نشده است.</td></tr>'}
14
+window.officeRender=function(task='inbox'){
15
+ ensureViews();window.FINORA_OFFICE_TASK=task;const r=document.getElementById('view-office');if(!r)return;const regs=mine('officeRegistries'),letters=mine('correspondence').slice().sort((a,b)=>String(b.registeredAt||b.createdAt||'').localeCompare(String(a.registeredAt||a.createdAt||''))),atts=mine('correspondenceAttachments');
16
+ if(task==='registries')r.innerHTML=officeHeader('دفاتر دبیرخانه و شمارهگذاری','هر دفتر شمارنده مستقل دارد؛ شماره ثبت قطعی روی سرور و بهصورت اتمیک تخصیص مییابد.')+'<div class="card"><div class="form-row"><div class="form-group"><label>کد دفتر</label><input id="office-reg-code" class="form-control" placeholder="CENTRAL"></div><div class="form-group"><label>عنوان دفتر</label><input id="office-reg-title" class="form-control" placeholder="دبیرخانه مرکزی"></div><div class="form-group"><label>پیشوند شماره</label><input id="office-reg-prefix" class="form-control" placeholder="د/م"></div><div class="form-group"><label>شماره بعدی</label><input id="office-reg-next" type="number" min="1" value="1" class="form-control"></div></div><button class="btn btn-primary" onclick="officeSaveRegistry()">ثبت دفتر</button></div><div class="card"><div class="table-responsive"><table><thead><tr><th>کد</th><th>عنوان</th><th>پیشوند</th><th>شماره بعدی</th></tr></thead><tbody>'+ (regs.map(x=>'<tr><td>'+oesc(x.code)+'</td><td>'+oesc(x.title)+'</td><td>'+oesc(x.prefix||'—')+'</td><td>'+oesc(x.nextNumber||1)+'</td></tr>').join('')||'<tr><td colspan="4" class="af-empty">دفتر دبیرخانهای تعریف نشده است.</td></tr>')+'</tbody></table></div></div>';
17
+ else if(task==='new')r.innerHTML=officeHeader('ثبت و ایجاد نامه','نامه وارده، صادره یا داخلی را با فراداده، متن و فایل اسکن ثبت کنید.')+'<div class="card"><div class="form-row"><div class="form-group"><label>نوع مکاتبه</label><select id="office-direction" class="form-control"><option value="incoming">وارده</option><option value="outgoing">صادره</option><option value="internal">داخلی</option></select></div><div class="form-group"><label>دفتر دبیرخانه</label><select id="office-registry" class="form-control"><option value="">— انتخاب دفتر —</option>'+registryOptions()+'</select></div><div class="form-group"><label>شماره نامه طرف مقابل</label><input id="office-external-no" class="form-control"></div><div class="form-group"><label>تاریخ نامه طرف مقابل</label><input id="office-external-date" class="form-control" placeholder="1405/07/08"></div></div><div class="form-row"><div class="form-group" style="grid-column:span 2"><label>موضوع</label><input id="office-subject" class="form-control" maxlength="240"></div><div class="form-group"><label>فرستنده / گیرنده</label><input id="office-party" class="form-control" maxlength="160"></div><div class="form-group"><label>مهلت پیگیری</label><input id="office-due" class="form-control" placeholder="1405/07/15"></div></div><div class="form-row"><div class="form-group"><label>اولویت</label><select id="office-priority" class="form-control"><option>عادی</option><option>فوری</option><option>آنی</option></select></div><div class="form-group"><label>طبقهبندی</label><select id="office-conf" class="form-control"><option>عادی</option><option>محرمانه</option><option>خیلی محرمانه</option></select></div><div class="form-group" style="grid-column:span 2"><label>اسکن / پیوست (PDF/JPG/PNG/TIFF، حداکثر ۲۰MB هر فایل)</label><input id="office-files" type="file" multiple accept="application/pdf,image/jpeg,image/png,image/tiff" class="form-control"></div></div><div class="form-group"><label>متن / شرح نامه</label><textarea id="office-body" class="form-control" rows="6"></textarea></div><div style="display:flex;gap:8px;flex-wrap:wrap"><button class="btn btn-secondary" onclick="officeSaveDraft()">ذخیره پیشنویس</button><button class="btn btn-primary" onclick="officeRegister()">ثبت قطعی و شمارهدهی</button></div><p class="af-hint">OCR-ready: متن استخراجشده و وضعیت OCR در مدل داده پیشبینی شده، اما موتور OCR واقعی هنوز متصل و اعتبارسنجی نشده است.</p></div>';
18
+ else if(task==='attachments')r.innerHTML=officeHeader('پیوستها و اسکن','فایلهای نامه در فضای خصوصی ذخیره میشوند و دسترسی آنها تابع لایسنس اتوماسیون است.')+'<div class="card"><div class="table-responsive"><table><thead><tr><th>نامه</th><th>نام فایل</th><th>نوع</th><th>حجم</th><th>عملیات</th></tr></thead><tbody>'+(atts.map(a=>{const l=letters.find(x=>x.id===a.correspondenceId);return '<tr><td>'+oesc(l?.registerNumber||l?.subject||a.correspondenceId)+'</td><td>'+oesc(a.fileName)+'</td><td>'+oesc(a.mimeType)+'</td><td>'+Math.ceil(Number(a.size||0)/1024).toLocaleString('fa-IR')+' KB</td><td><button class="btn btn-secondary btn-inline" onclick="officeDownloadAttachment(\''+oesc(a.id)+'\')">دریافت</button></td></tr>'}).join('')||'<tr><td colspan="5" class="af-empty">پیوستی ثبت نشده است.</td></tr>')+'</tbody></table></div></div>';
19
+ else {const archive=task==='archive';r.innerHTML=officeHeader(archive?'جستوجو و آرشیو مکاتبات':'کارتابل مکاتبات',archive?'جستوجوی فرادادهای نامهها؛ OCR واقعی پس از اتصال موتور جستوجوی متن اسکن را تکمیل میکند.':'نمای مکاتبات ثبتشده و وضعیت پیگیری.')+'<div class="card"><div class="form-row"><div class="form-group" style="grid-column:span 3"><label>جستوجو</label><input id="office-search" class="form-control" placeholder="شماره، موضوع، طرف مکاتبه یا شماره بیرونی" oninput="officeFilterTable()"></div><div class="form-group"><label>نوع</label><select id="office-direction-filter" class="form-control" onchange="officeFilterTable()"><option value="">همه</option><option value="incoming">وارده</option><option value="outgoing">صادره</option><option value="internal">داخلی</option></select></div></div><div class="table-responsive"><table><thead><tr><th>ثبت</th><th>موضوع</th><th>طرف مکاتبه</th><th>شماره بیرونی</th><th>اولویت/طبقه</th><th>وضعیت</th><th></th></tr></thead><tbody id="office-letter-body">'+correspondenceRows(letters)+'</tbody></table></div></div>'}
20
+};
21
+window.officeSaveRegistry=function(){if(!requireWrite())return;const code=String(document.getElementById('office-reg-code')?.value||'').trim().toUpperCase(),title=String(document.getElementById('office-reg-title')?.value||'').trim(),prefix=String(document.getElementById('office-reg-prefix')?.value||'').trim(),nextNumber=Math.max(1,Number(document.getElementById('office-reg-next')?.value||1));if(!code||!title)return alert('کد و عنوان دفتر الزامی است.');if(mine('officeRegistries').some(x=>String(x.code).toUpperCase()===code))return alert('کد دفتر تکراری است.');datastore.officeRegistries.push({id:oid('OREG'),ownerUserId:currentUser.id,companyId:companyId(),code,title,prefix,nextNumber,active:true,createdAt:nowIso()});saveDatastore();officeRender('registries')};
22
+function formPayload(id,status){return {id,ownerUserId:currentUser.id,companyId:companyId(),direction:document.getElementById('office-direction')?.value||'incoming',registryId:document.getElementById('office-registry')?.value||'',externalNumber:String(document.getElementById('office-external-no')?.value||'').trim(),externalDate:String(document.getElementById('office-external-date')?.value||'').trim(),subject:String(document.getElementById('office-subject')?.value||'').trim(),counterparty:String(document.getElementById('office-party')?.value||'').trim(),dueDate:String(document.getElementById('office-due')?.value||'').trim(),priority:document.getElementById('office-priority')?.value||'عادی',confidentiality:document.getElementById('office-conf')?.value||'عادی',body:String(document.getElementById('office-body')?.value||'').trim(),status,ocrStatus:'not_requested',ocrText:'',createdAt:nowIso()}}
23
+async function uploadSelected(correspondenceId){const files=[...(document.getElementById('office-files')?.files||[])];for(const file of files){if(file.size>20971520)throw new Error('حجم فایل '+file.name+' بیش از ۲۰MB است.');const ext=(file.name.split('.').pop()||'bin').replace(/[^A-Za-z0-9]/g,'').toLowerCase(),path=currentUser.id+'/'+correspondenceId+'/'+oid('F')+(ext?'.'+ext:'');const {error}=await sb.storage.from('office-attachments').upload(path,file,{upsert:false,contentType:file.type||undefined});if(error)throw error;datastore.correspondenceAttachments.push({id:oid('ATT'),ownerUserId:currentUser.id,companyId:companyId(),correspondenceId,storagePath:path,fileName:file.name,mimeType:file.type||'',size:file.size,createdAt:nowIso()})}if(files.length)saveDatastore()}
24
+window.officeSaveDraft=async function(){if(!requireWrite())return;const id=oid('COR'),p=formPayload(id,'draft');if(!p.subject)return alert('موضوع نامه الزامی است.');datastore.correspondence.push(p);saveDatastore();try{await uploadSelected(id);alert('پیشنویس و پیوستها ثبت شد.');officeRender('inbox')}catch(e){console.error(e);alert('پیشنویس ذخیره شد اما بارگذاری یک پیوست ناموفق بود: '+(e.message||e))}};
25
+window.officeRegister=async function(){if(!requireWrite())return;const id=oid('COR'),p=formPayload(id,'draft');if(!p.subject||!p.registryId)return alert('موضوع و دفتر دبیرخانه برای ثبت قطعی الزامی است.');try{const payload=Object.assign({},p);delete payload.id;delete payload.ownerUserId;const {data,error}=await sb.rpc('office_register_correspondence',{p_id:id,p_registry_id:p.registryId,p_payload:payload});if(error)throw error;await pullAll();try{await uploadSelected(id)}catch(fileErr){console.error(fileErr);alert('نامه با شماره '+data+' ثبت شد، اما بارگذاری یک پیوست ناموفق بود: '+(fileErr.message||fileErr));officeRender('inbox');return}alert('نامه با شماره '+data+' ثبت شد.');officeRender('inbox')}catch(e){console.error(e);alert('ثبت قطعی نامه انجام نشد: '+(e.message||e))}};
26
+window.officeDownloadAttachment=async function(id){const a=mine('correspondenceAttachments').find(x=>x.id===id);if(!a)return;const {data,error}=await sb.storage.from('office-attachments').download(a.storagePath);if(error)return alert('دریافت فایل ناموفق بود: '+error.message);const url=URL.createObjectURL(data),link=document.createElement('a');link.href=url;link.download=a.fileName||'attachment';document.body.appendChild(link);link.click();link.remove();setTimeout(()=>URL.revokeObjectURL(url),1000)};
27
+window.officeFilterTable=function(){const q=String(document.getElementById('office-search')?.value||'').trim().toLowerCase(),d=document.getElementById('office-direction-filter')?.value||'',rows=mine('correspondence').filter(x=>(!d||x.direction===d)&&(!q||[x.registerNumber,x.subject,x.counterparty,x.externalNumber,x.body,x.ocrText].some(v=>String(v||'').toLowerCase().includes(q))));const b=document.getElementById('office-letter-body');if(b)b.innerHTML=correspondenceRows(rows)};
28
+window.officeOpenRecord=function(id){const x=mine('correspondence').find(r=>r.id===id);if(!x)return;const a=mine('correspondenceAttachments').filter(z=>z.correspondenceId===id);alert('شماره ثبت: '+(x.registerNumber||'—')+'\nنوع: '+directionLabel(x.direction)+'\nموضوع: '+(x.subject||'—')+'\nطرف مکاتبه: '+(x.counterparty||'—')+'\nپیوست: '+a.length+' فایل\n\n'+(x.body||''))};
29
+
30
+let requestFields=[];
31
+function requestTypeOptions(){return mine('requestTypes').filter(x=>x.active!==false).map(x=>'<option value="'+oesc(x.id)+'">'+oesc(x.title)+'</option>').join('')}
32
+function renderFieldBuilder(){const b=document.getElementById('request-field-builder');if(!b)return;b.innerHTML=requestFields.map((f,i)=>'<div class="form-row" style="align-items:end"><div class="form-group" style="grid-column:span 2"><label>عنوان فیلد</label><input class="form-control" value="'+oesc(f.label)+'" oninput="requestFields['+i+'].label=this.value"></div><div class="form-group"><label>نوع</label><select class="form-control" onchange="requestFields['+i+'].type=this.value"><option value="text" '+(f.type==='text'?'selected':'')+'>متن</option><option value="number" '+(f.type==='number'?'selected':'')+'>عدد</option><option value="date" '+(f.type==='date'?'selected':'')+'>تاریخ</option><option value="textarea" '+(f.type==='textarea'?'selected':'')+'>متن بلند</option><option value="select" '+(f.type==='select'?'selected':'')+'>انتخابی</option></select></div><div class="form-group"><label><input type="checkbox" '+(f.required?'checked':'')+' onchange="requestFields['+i+'].required=this.checked"> الزامی</label><button class="btn btn-danger btn-inline" onclick="removeRequestField('+i+')">حذف</button></div></div>').join('')||'<div class="af-empty">هنوز فیلدی اضافه نشده است.</div>'}
33
+window.requestsRender=function(task='mine'){ensureViews();window.FINORA_REQUEST_TASK=task;const r=document.getElementById('view-requests');if(!r)return;const types=mine('requestTypes'),reqs=mine('requests').slice().sort((a,b)=>String(b.createdAt||'').localeCompare(String(a.createdAt||'')));
34
+ if(task==='types'){requestFields=[];r.innerHTML=officeHeader('انواع درخواست و فرمساز','مدیر سامانه میتواند نوع درخواست و فیلدهای آن را بدون تغییر کد تعریف کند. گردش چندکاربره و سطوح تأیید پس از tenant/RBAC سروری فعال میشود.')+'<div class="card"><div class="form-row"><div class="form-group"><label>کد</label><input id="request-type-code" class="form-control" placeholder="VEHICLE"></div><div class="form-group" style="grid-column:span 2"><label>عنوان</label><input id="request-type-title" class="form-control" placeholder="درخواست خودرو"></div><div class="form-group"><label>دسته</label><input id="request-type-category" class="form-control" placeholder="خدمات اداری"></div></div><div id="request-field-builder"></div><div style="display:flex;gap:8px"><button class="btn btn-secondary" onclick="addRequestField()">+ افزودن فیلد</button><button class="btn btn-primary" onclick="saveRequestType()">ثبت نوع درخواست</button></div></div><div class="card"><div class="table-responsive"><table><thead><tr><th>کد</th><th>عنوان</th><th>دسته</th><th>فیلدها</th></tr></thead><tbody>'+(types.map(x=>'<tr><td>'+oesc(x.code)+'</td><td>'+oesc(x.title)+'</td><td>'+oesc(x.category||'—')+'</td><td>'+Number(x.fields?.length||0).toLocaleString('fa-IR')+'</td></tr>').join('')||'<tr><td colspan="4" class="af-empty">نوع درخواستی تعریف نشده است.</td></tr>')+'</tbody></table></div></div>';renderFieldBuilder()}
35
+ else if(task==='new'){r.innerHTML=officeHeader('درخواست جدید','نوع درخواست را انتخاب کنید؛ فرم بر اساس فیلدهای تعریفشده ساخته میشود.')+'<div class="card"><div class="form-group"><label>نوع درخواست</label><select id="request-type-select" class="form-control" onchange="renderDynamicRequestForm()"><option value="">— انتخاب —</option>'+requestTypeOptions()+'</select></div><div id="dynamic-request-fields"></div><button class="btn btn-primary" onclick="submitDynamicRequest()">ثبت درخواست</button></div>'}
36
+ else r.innerHTML=officeHeader('درخواستهای من','درخواستهای ثبتشده و وضعیت جاری آنها.')+'<div class="card"><div class="table-responsive"><table><thead><tr><th>شماره</th><th>نوع</th><th>تاریخ</th><th>وضعیت</th><th>خلاصه</th></tr></thead><tbody>'+(reqs.map(x=>{const t=types.find(z=>z.id===x.requestTypeId);return '<tr><td>'+oesc(x.number)+'</td><td>'+oesc(t?.title||'—')+'</td><td>'+oesc(x.createdAt?.slice(0,10)||'—')+'</td><td>'+statusLabel(x.status)+'</td><td>'+oesc(Object.values(x.values||{}).slice(0,2).join(' · '))+'</td></tr>'}).join('')||'<tr><td colspan="5" class="af-empty">درخواستی ثبت نشده است.</td></tr>')+'</tbody></table></div></div>'};
37
+window.addRequestField=function(){requestFields.push({key:'field_'+(requestFields.length+1),label:'',type:'text',required:false});renderFieldBuilder()};window.removeRequestField=function(i){requestFields.splice(i,1);renderFieldBuilder()};
38
+window.saveRequestType=function(){if(!requireWrite())return;const code=String(document.getElementById('request-type-code')?.value||'').trim().toUpperCase(),title=String(document.getElementById('request-type-title')?.value||'').trim(),category=String(document.getElementById('request-type-category')?.value||'').trim(),fields=requestFields.map((f,i)=>({key:'f'+(i+1),label:String(f.label||'').trim(),type:f.type,required:!!f.required})).filter(f=>f.label);if(!code||!title)return alert('کد و عنوان الزامی است.');if(mine('requestTypes').some(x=>String(x.code).toUpperCase()===code))return alert('کد نوع درخواست تکراری است.');datastore.requestTypes.push({id:oid('RT'),ownerUserId:currentUser.id,companyId:companyId(),code,title,category,fields,workflow:{mode:'single_owner',steps:[]},active:true,createdAt:nowIso()});saveDatastore();requestsRender('types')};
39
+window.renderDynamicRequestForm=function(){const id=document.getElementById('request-type-select')?.value,t=mine('requestTypes').find(x=>x.id===id),b=document.getElementById('dynamic-request-fields');if(!b)return;b.innerHTML=t?(t.fields||[]).map(f=>'<div class="form-group"><label>'+oesc(f.label)+(f.required?' *':'')+'</label>'+(f.type==='textarea'?'<textarea class="form-control request-dyn" data-key="'+oesc(f.key)+'" data-required="'+(f.required?'1':'0')+'"></textarea>':'<input class="form-control request-dyn" data-key="'+oesc(f.key)+'" data-required="'+(f.required?'1':'0')+'" type="'+(f.type==='number'?'number':'text')+'">')+'</div>').join(''):''};
40
+window.submitDynamicRequest=function(){if(!requireWrite())return;const requestTypeId=document.getElementById('request-type-select')?.value,t=mine('requestTypes').find(x=>x.id===requestTypeId);if(!t)return alert('نوع درخواست را انتخاب کنید.');const values={};for(const el of document.querySelectorAll('.request-dyn')){const v=String(el.value||'').trim();if(el.dataset.required==='1'&&!v)return alert('فیلدهای الزامی را تکمیل کنید.');values[el.dataset.key]=v}const seq=mine('requests').length+1,number='REQ-'+new Date().getFullYear()+'-'+String(seq).padStart(5,'0');datastore.requests.push({id:oid('REQ'),ownerUserId:currentUser.id,companyId:companyId(),requestTypeId,number,values,status:'submitted',createdAt:nowIso(),submittedAt:nowIso()});saveDatastore();alert('درخواست '+number+' ثبت شد.');requestsRender('mine')};
41
+
42
+ensureViews();
43
+if(typeof navigateShell==='function'){const baseNav=navigateShell;navigateShell=function(moduleKey,viewId,task='',rerender=true){const out=baseNav(moduleKey,viewId,task,rerender);if(out===false)return false;if(viewId==='view-office')officeRender(task||'inbox');if(viewId==='view-requests')requestsRender(task||'mine');return out}}
44
+})();
\ No newline at end of file
js/platform-modules.js
new
+86
@@ -0,0 +1,86 @@
1
+/* Finora modular platform foundation: commercial entitlements, module launcher and admin picker. */
2
+(function(){
3
+const MODULE_CATALOG={
4
+ core:{title:'هسته فینورا',icon:'⌂',implemented:true},accounting:{title:'حسابداری',icon:'▦',implemented:true},commerce:{title:'بازرگانی',icon:'⇄',implemented:true},treasury:{title:'خزانهداری',icon:'◈',implemented:true},contracting:{title:'پیمانها',icon:'▧',implemented:true},inventory:{title:'انبار',icon:'▦',implemented:true},assets:{title:'دارایی ثابت',icon:'◆',implemented:true},hr_payroll:{title:'منابع انسانی و حقوق',icon:'♙',implemented:true},office_automation:{title:'اتوماسیون اداری',icon:'✉',implemented:true},requests_workflow:{title:'درخواستها و فرایندها',icon:'✓',implemented:true},group_consolidation:{title:'گروه و بینشرکتی',icon:'◎',implemented:true},analytics:{title:'گزارش و تحلیل',icon:'▥',implemented:true},crm:{title:'CRM و فروش',icon:'◇',implemented:false},transport:{title:'حملونقل و ناوگان',icon:'⌁',implemented:false},manufacturing:{title:'تولید و MRP',icon:'⚙',implemented:false},maintenance:{title:'نگهداری و تعمیرات',icon:'⌘',implemented:false}
5
+};
6
+window.FINORA_MODULE_CATALOG=MODULE_CATALOG;
7
+const newColls=['officeRegistries','correspondence','correspondenceAttachments','correspondenceReferrals','correspondenceAudit','requestTypes','requests','requestActions'];
8
+if(typeof COLLS!=='undefined')newColls.forEach(k=>{if(!COLLS.includes(k))COLLS.push(k)});
9
+if(typeof datastore!=='undefined')newColls.forEach(k=>{if(!Array.isArray(datastore[k]))datastore[k]=[]});
10
+
11
+if(typeof buildUserFromRows==='function'){
12
+ const baseBuild=buildUserFromRows;
13
+ buildUserFromRows=function(profile,lic){const u=baseBuild(profile,lic);u.modules=Array.isArray(lic?.modules)&&lic.modules.length?lic.modules.slice():['full_suite'];return u};
14
+}
15
+function licensed(key){if(key==='core')return true;if(!currentUser)return false;const mods=Array.isArray(currentUser.modules)&¤tUser.modules.length?currentUser.modules:['full_suite'];return mods.includes('full_suite')||mods.includes(key)}
16
+window.hasLicensedModule=licensed;
17
+function shellEntitlement(moduleKey,task=''){
18
+ if(['dashboard','settings'].includes(moduleKey))return 'core';
19
+ if(moduleKey==='accounting')return 'accounting';if(moduleKey==='commerce')return 'commerce';if(moduleKey==='treasury')return 'treasury';if(moduleKey==='projects')return 'contracting';if(moduleKey==='inventory')return 'inventory';if(moduleKey==='assets')return 'assets';if(moduleKey==='office')return 'office_automation';if(moduleKey==='requests')return 'requests_workflow';if(moduleKey==='reports')return licensed('analytics')?'analytics':'accounting';
20
+ if(moduleKey==='enterprise'){
21
+ if(['employees','contracts','leave','payroll','benefits'].includes(task))return 'hr_payroll';
22
+ if(['treasury','pettyops'].includes(task))return 'treasury';
23
+ if(task==='group')return 'group_consolidation';
24
+ return 'accounting';
25
+ }
26
+ return 'core';
27
+}
28
+function canModule(moduleKey,task=''){if(moduleKey==='enterprise'&&!task)return ['hr_payroll','treasury','group_consolidation','accounting'].some(licensed);if(moduleKey==='reports'&&!task)return licensed('analytics')||licensed('accounting');return licensed(shellEntitlement(moduleKey,task))}
29
+window.canAccessFinoraModule=canModule;
30
+
31
+function registerShellModules(){
32
+ if(typeof FINORA_MODULES==='undefined')return;
33
+ if(!FINORA_MODULES.office)FINORA_MODULES.office={title:'اتوماسیون اداری',context:'دبیرخانه، مکاتبات، اسکن و بایگانی',groups:[{title:'دبیرخانه',items:[['کارتابل مکاتبات','view-office','✉','','inbox'],['ثبت نامه','view-office','+','','new'],['دفاتر و شمارهگذاری','view-office','▤','','registries']]},{title:'بایگانی و کنترل',items:[['جستوجو و آرشیو','view-office','⌕','','archive'],['پیوستها و اسکن','view-office','▣','','attachments']]}]};
34
+ if(!FINORA_MODULES.requests)FINORA_MODULES.requests={title:'درخواستها',context:'فرمساز و گردش درخواستهای سازمانی',groups:[{title:'کار من',items:[['درخواست جدید','view-requests','+','','new'],['درخواستهای من','view-requests','▤','','mine']]},{title:'راهاندازی',items:[['انواع درخواست و فرمساز','view-requests','⚙','','types']]}]};
35
+ if(typeof FINORA_VIEW_HOME!=='undefined'){FINORA_VIEW_HOME['view-office']='office';FINORA_VIEW_HOME['view-requests']='requests'}
36
+ if(typeof FINORA_COMMANDS!=='undefined'){
37
+ [['office',FINORA_MODULES.office],['requests',FINORA_MODULES.requests]].forEach(([module,m])=>m.groups.forEach(g=>g.items.forEach(i=>{if(!FINORA_COMMANDS.some(x=>x.module===module&&x.view===i[1]&&x.task===(i[4]||'')))FINORA_COMMANDS.push({module,moduleTitle:m.title,groupTitle:g.title,title:i[0],view:i[1],icon:i[2],guard:i[3]||'',task:i[4]||''})})));
38
+ }
39
+}
40
+function injectRail(){const rail=document.getElementById('module-rail');if(!rail)return;const before=rail.querySelector('[data-module="reports"]');[['office','view-office','✉','اتوماسیون','inbox'],['requests','view-requests','✓','درخواستها','new']].forEach(([m,v,ic,label,task])=>{if(rail.querySelector('[data-module="'+m+'"]'))return;const b=document.createElement('button');b.className='module-tab';b.dataset.module=m;b.dataset.view=v;b.title=label;b.innerHTML='<span>'+ic+'</span><b>'+label+'</b>';b.onclick=()=>openModule(m,v,task);rail.insertBefore(b,before||null)})}
41
+function applyLicensedUI(){injectRail();document.querySelectorAll('.module-tab').forEach(b=>{b.style.display=canModule(b.dataset.module||'core','')?'':'none'});const q=document.getElementById('quick-create-menu');if(q)q.querySelectorAll('[data-finora-license-gated]').forEach(x=>x.remove())}
42
+window.applyLicensedModuleUI=applyLicensedUI;
43
+
44
+registerShellModules();
45
+if(typeof canShowShellCommand==='function'){
46
+ const baseCan=canShowShellCommand;
47
+ canShowShellCommand=function(cmd){if(!baseCan(cmd))return false;if(cmd&&cmd.module)return canModule(cmd.module,cmd.task||'');return true};
48
+}
49
+if(typeof renderModulePanel==='function'){
50
+ const basePanel=renderModulePanel;
51
+ renderModulePanel=function(moduleKey,activeView,activeTask=''){if(!canModule(moduleKey,activeTask||'')){showModuleLauncher(true);return}basePanel(moduleKey,activeView,activeTask);const box=document.getElementById('module-panel-links');if(box)box.querySelectorAll('.module-link').forEach(btn=>{const task=btn.dataset.task||'',view=btn.dataset.view||'';const cmd=typeof FINORA_COMMANDS!=='undefined'?FINORA_COMMANDS.find(x=>x.module===moduleKey&&x.view===view&&x.task===task):null;if(cmd&&!canModule(moduleKey,task))btn.remove()})};
52
+}
53
+if(typeof openModule==='function'){
54
+ const baseOpen=openModule;
55
+ openModule=function(moduleKey,defaultView,defaultTask=''){if(!canModule(moduleKey,defaultTask||'')){alert('این ماژول در لایسنس فعلی فعال نیست.');return showModuleLauncher(true)}return baseOpen(moduleKey,defaultView,defaultTask)};
56
+}
57
+if(typeof navigateShell==='function'){
58
+ const baseNav=navigateShell;
59
+ navigateShell=function(moduleKey,viewId,task='',rerender=true){if(!canModule(moduleKey,task||'')){alert('دسترسی این ماژول در لایسنس فعلی فعال نیست.');return false}return baseNav(moduleKey,viewId,task,rerender)};
60
+}
61
+if(typeof refreshAllSurfaces==='function'){
62
+ const baseRefresh=refreshAllSurfaces;
63
+ refreshAllSurfaces=function(){const r=baseRefresh();applyLicensedUI();if(document.getElementById('view-office')?.classList.contains('active')&&typeof officeRender==='function')officeRender(window.FINORA_OFFICE_TASK||'inbox');if(document.getElementById('view-requests')?.classList.contains('active')&&typeof requestsRender==='function')requestsRender(window.FINORA_REQUEST_TASK||'mine');return r};
64
+}
65
+
66
+function launcherModules(){const list=[['accounting','accounting','view-accounting-foundation','accounts'],['commerce','commerce','view-invoices',''],['treasury','treasury','view-payments',''],['contracting','projects','view-contracting',''],['inventory','inventory','view-inventory','stock'],['assets','assets','view-assets','asset-register'],['hr_payroll','enterprise','view-enterprise','employees'],['office_automation','office','view-office','inbox'],['requests_workflow','requests','view-requests','new'],['group_consolidation','enterprise','view-enterprise','group'],['analytics','reports','view-reports','']];return list.filter(x=>licensed(x[0]))}
67
+function ensureLauncher(){let el=document.getElementById('finora-module-launcher');if(el)return el;el=document.createElement('div');el.id='finora-module-launcher';el.className='modal-backdrop';el.innerHTML='<div class="modal-card" style="max-width:860px"><div style="display:flex;justify-content:space-between;gap:12px;align-items:center"><div><h3 style="font-size:20px">ورود به فضای کاری</h3><p style="color:var(--text-muted);font-size:12px;margin-top:5px">فقط ماژولهای فعال در لایسنس شما نمایش داده میشوند.</p></div><button class="btn btn-secondary btn-inline" onclick="closeModuleLauncher()">ادامه در داشبورد</button></div><div id="finora-launcher-grid" style="display:grid;grid-template-columns:repeat(auto-fit,minmax(180px,1fr));gap:12px;margin-top:18px"></div></div>';document.body.appendChild(el);return el}
68
+function showModuleLauncher(force=false){if(!currentUser)return;const choices=launcherModules();if(!force&&choices.length<=1)return;const el=ensureLauncher(),grid=document.getElementById('finora-launcher-grid');grid.innerHTML=choices.map(x=>{const c=MODULE_CATALOG[x[0]];return '<button class="card" style="text-align:right;cursor:pointer;border:1px solid var(--border);padding:16px" onclick="enterLicensedWorkspace(\''+x[1]+'\',\''+x[2]+'\',\''+x[3]+'\')"><div style="font-size:24px">'+c.icon+'</div><strong style="display:block;margin-top:8px">'+c.title+'</strong><small style="color:var(--text-muted)">ورود به ماژول</small></button>'}).join('');el.classList.add('active')}
69
+window.showModuleLauncher=showModuleLauncher;
70
+window.closeModuleLauncher=()=>document.getElementById('finora-module-launcher')?.classList.remove('active');
71
+window.enterLicensedWorkspace=(m,v,t)=>{closeModuleLauncher();navigateShell(m,v,t||'')};
72
+
73
+function ensureLicensePicker(){const modal=document.querySelector('#modal-admin-license-edit .modal-card');if(!modal||document.getElementById('modal-license-modules'))return;const actions=modal.querySelector('div[style*="margin-top:16px"]');const box=document.createElement('div');box.id='modal-license-modules';box.className='form-group';box.innerHTML='<label>ماژولهای فعال لایسنس</label><div id="license-module-grid" style="display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:7px;margin-top:8px"></div><small style="color:var(--text-muted)">«کامل» همه ماژولهای فعلی و آینده را باز میکند. ماژولهای آتی تا زمان عملیاتیشدن قابل فروش نیستند.</small>';modal.insertBefore(box,actions||null)}
74
+function renderLicensePicker(uid){ensureLicensePicker();const u=typeof adminUsersCache!=='undefined'?adminUsersCache.find(x=>x.id===uid):null,mods=Array.isArray(u?.lic?.modules)&&u.lic.modules.length?u.lic.modules:['full_suite'],grid=document.getElementById('license-module-grid');if(!grid)return;grid.innerHTML='<label style="grid-column:1/-1"><input type="checkbox" value="full_suite" '+(mods.includes('full_suite')?'checked':'')+' onchange="toggleFullSuiteModules(this)"> <strong>لایسنس کامل ERP</strong></label>'+Object.entries(MODULE_CATALOG).filter(([k,v])=>k!=='core').map(([k,v])=>'<label style="opacity:'+(v.implemented?1:.5)+'"><input class="license-module-check" type="checkbox" value="'+k+'" '+(mods.includes('full_suite')||mods.includes(k)?'checked':'')+' '+(v.implemented?'':'disabled')+'> '+v.title+(v.implemented?'':' — آتی')+'</label>').join('');toggleFullSuiteModules(grid.querySelector('input[value="full_suite"]'),true)}
75
+window.toggleFullSuiteModules=function(el,keep){document.querySelectorAll('.license-module-check').forEach(x=>{if(el?.checked){x.checked=true;x.disabled=true}else{x.disabled=!MODULE_CATALOG[x.value]?.implemented;if(!keep&&MODULE_CATALOG[x.value]?.implemented)x.checked=false}})};
76
+if(typeof openLicenseEditModal==='function'){const baseOpenLicense=openLicenseEditModal;openLicenseEditModal=function(uid){baseOpenLicense(uid);renderLicensePicker(uid)}}
77
+if(typeof applyLicenseDurationChange==='function'){
78
+ applyLicenseDurationChange=async function(){const uid=document.getElementById('modal-license-target-username').value,plan=document.getElementById('modal-license-duration-select').value,u=adminUsersCache.find(x=>x.id===uid),ready=!!(u?.lic&&Object.prototype.hasOwnProperty.call(u.lic,'max_companies')),cap=Math.max(1,Math.min(1000,Number(document.getElementById('modal-license-company-limit')?.value||1))),full=document.querySelector('#license-module-grid input[value="full_suite"]')?.checked,mods=full?['full_suite']:[...document.querySelectorAll('.license-module-check:checked:not(:disabled)')].map(x=>x.value);if(!mods.length)return alert('حداقل یک ماژول عملیاتی را انتخاب کنید.');closeLicenseEditModal();let ok=await adminRpc('admin_set_license',{target:uid,new_plan:plan,new_status:'active'},'');if(!ok)return false;if(ready){ok=await adminRpc('admin_set_company_limit',{target:uid,new_max_companies:cap},'');if(!ok)return false}ok=await adminRpc('admin_set_license_modules',{target:uid,new_modules:mods},'لایسنس، ظرفیت و ماژولهای کاربر اعمال شد.');if(ok&¤tUser?.id===uid){currentUser=await fetchCurrentUser({id:uid});await pullAll();refreshAllSurfaces()}return ok};
79
+}
80
+if(typeof enterApp==='function'){
81
+ const baseEnter=enterApp;
82
+ enterApp=async function(authUser){await baseEnter(authUser);if(!currentUser)return;applyLicensedUI();setTimeout(()=>{if(!document.getElementById('modal-user-onboarding')?.classList.contains('active'))showModuleLauncher(false)},50)};
83
+}
84
+window.addEventListener('finora:onboarding-complete',()=>showModuleLauncher(false));
85
+applyLicensedUI();
86
+})();
\ No newline at end of file
scripts/platform-office-check.mjs
new
+17
@@ -0,0 +1,17 @@
1
+import fs from 'node:fs';
2
+const read=p=>fs.readFileSync(p,'utf8');
3
+const platform=read('js/platform-modules.js'),office=read('js/office-automation.js'),m1=read('supabase/migrations/20260930025546_modular_entitlements_office_automation_foundation.sql'),m2=read('supabase/migrations/20260930025647_office_secretariat_atomic_registration.sql'),doc=read('docs/FINORA_MODULAR_ERP_OFFICE_AUTOMATION_V1.md');
4
+const checks=[
5
+ ['full-suite entitlement',m1.includes("'full_suite'")&&m1.includes('admin_set_license_modules')],
6
+ ['server collection entitlement',m1.includes('private.has_collection_entitlement(collection)')&&m1.includes("raise exception 'module entitlement required'")],
7
+ ['office private storage',m1.includes("'office-attachments'")&&m1.includes('finora_office_files_insert')&&m1.includes("private.has_module_entitlement('office_automation')")],
8
+ ['atomic registry allocation',m2.includes('for update')&&m2.includes('ux_finora_correspondence_registry_number')&&m2.includes('office_register_correspondence')],
9
+ ['module launcher',platform.includes('finora-module-launcher')&&platform.includes('hasLicensedModule')&&platform.includes('admin_set_license_modules')],
10
+ ['future modules disabled',platform.includes("transport:{title:'حملونقل و ناوگان'")&&platform.includes('implemented:false')],
11
+ ['office scan upload',office.includes("sb.storage.from('office-attachments').upload")&&office.includes('officeRegister')],
12
+ ['configurable request fields',office.includes('requestFields')&&office.includes('saveRequestType')&&office.includes('submitDynamicRequest')],
13
+ ['rbac boundary documented',doc.includes('Effective access = customer/module entitlement')&&doc.includes('Multi-user RBAC target')]
14
+];
15
+const failed=checks.filter(x=>!x[1]);
16
+if(failed.length){console.error('Platform/office checks failed:',failed.map(x=>x[0]).join(', '));process.exit(1)}
17
+console.log('Platform/office foundation checks PASS:',checks.map(x=>x[0]).join(' | '));
scripts/platform-office.spec.js
new
+32
@@ -0,0 +1,32 @@
1
+const {test,expect}=require('@playwright/test');
2
+
3
+test('modular launcher, office and request builder render from licensed modules',async({page})=>{
4
+ const errs=[];page.on('pageerror',e=>errs.push(String(e)));
5
+ await page.goto('http://127.0.0.1:4173/index.html',{waitUntil:'domcontentloaded'});
6
+ await page.waitForFunction(()=>window.FINORA_MODULE_CATALOG&&typeof window.officeRender==='function'&&typeof window.requestsRender==='function');
7
+ await page.evaluate(()=>{
8
+ currentUser={id:'platform-smoke',email:'platform@example.test',role:'admin',modules:['office_automation','requests_workflow'],subscription:{type:'lifetime',status:'active',endDate:'2099-01-01'}};
9
+ ['officeRegistries','correspondence','correspondenceAttachments','correspondenceReferrals','correspondenceAudit','requestTypes','requests','requestActions'].forEach(k=>datastore[k]=[]);
10
+ applyLicensedModuleUI();
11
+ });
12
+ await expect(page.locator('[data-module="office"]')).toBeVisible();
13
+ await expect(page.locator('[data-module="requests"]')).toBeVisible();
14
+ await expect(page.locator('[data-module="accounting"]')).toBeHidden();
15
+ await expect(page.locator('[data-module="settings"]')).toBeVisible();
16
+ expect(await page.evaluate(()=>hasLicensedModule('office_automation'))).toBe(true);
17
+ expect(await page.evaluate(()=>hasLicensedModule('accounting'))).toBe(false);
18
+ await page.evaluate(()=>{switchView('view-office');officeRender('registries')});
19
+ await expect(page.locator('#view-office')).toContainText('دفاتر دبیرخانه و شمارهگذاری');
20
+ await expect(page.locator('#view-office')).toContainText('اتمیک');
21
+ await page.evaluate(()=>{switchView('view-office');officeRender('new')});
22
+ await expect(page.locator('#office-files')).toHaveAttribute('accept',/application\/pdf/);
23
+ await expect(page.locator('#view-office')).toContainText('OCR-ready');
24
+ await page.evaluate(()=>{switchView('view-requests');requestsRender('types');addRequestField()});
25
+ await expect(page.locator('#request-field-builder input')).toHaveCount(1);
26
+ await expect(page.locator('#view-requests')).toContainText('فرمساز');
27
+ await page.evaluate(()=>{adminUsersCache=[{id:'platform-smoke',email:'platform@example.test',role:'admin',lic:{plan:'lifetime',status:'active',starts_at:'2026-01-01',ends_at:'2099-01-01',max_companies:1,modules:['office_automation','requests_workflow']}}];openLicenseEditModal('platform-smoke')});
28
+ await expect(page.locator('#modal-license-modules')).toContainText('لایسنس کامل ERP');
29
+ await expect(page.locator('#license-module-grid input[value="transport"]')).toBeDisabled();
30
+ await expect(page.locator('#license-module-grid input[value="office_automation"]')).toBeChecked();
31
+ expect(errs.filter(x=>!x.includes('ResizeObserver'))).toEqual([]);
32
+});
supabase/migrations/20260930025546_modular_entitlements_office_automation_foundation.sql
new
+161
@@ -0,0 +1,161 @@
1
+create schema if not exists private;
2
+revoke all on schema private from public, anon;
3
+grant usage on schema private to authenticated;
4
+
5
+alter table public.licenses
6
+ add column if not exists modules text[] not null default array['full_suite']::text[];
7
+
8
+create or replace function private.is_valid_finora_module(module_key text)
9
+returns boolean
10
+language sql immutable security invoker set search_path = '' as $$
11
+ select module_key = any(array[
12
+ 'full_suite','core','accounting','commerce','treasury','contracting','inventory','assets',
13
+ 'hr_payroll','office_automation','requests_workflow','crm','transport','manufacturing',
14
+ 'maintenance','group_consolidation','analytics'
15
+ ]::text[])
16
+$$;
17
+
18
+create or replace function private.has_module_entitlement(module_key text)
19
+returns boolean
20
+language sql stable security definer set search_path = '' as $$
21
+ select case
22
+ when module_key = 'core' then true
23
+ else exists (
24
+ select 1 from public.licenses l
25
+ where l.user_id = (select auth.uid())
26
+ and l.status in ('trial','active')
27
+ and (l.plan = 'lifetime' or l.ends_at >= (now() at time zone 'Asia/Tehran')::date)
28
+ and ('full_suite' = any(l.modules) or module_key = any(l.modules))
29
+ )
30
+ end
31
+$$;
32
+
33
+create or replace function private.collection_module(collection_key text)
34
+returns text
35
+language sql immutable security invoker set search_path = '' as $$
36
+ select case
37
+ when collection_key = any(array['companies','settings','importBatches','integrationConnections','integrationOutbox','phase5Audit','enterpriseAudit']::text[]) then 'core'
38
+ when collection_key = any(array['fiscalYears','accounts','dimensionTypes','dimensionValues','accountDimensionRules','branches','postingProfiles','journalVouchers','journalLines','journalLineDimensions','currencies','exchangeRates','costCenters','expenses','complianceRules','budgets','costDrivers','costAllocations']::text[]) then 'accounting'
39
+ when collection_key = any(array['contacts','products','invoices','purchases']::text[]) then 'commerce'
40
+ when collection_key = any(array['cheques','payments','cashboxes','pettyCashFunds','pettyCashTransactions']::text[]) then 'treasury'
41
+ when collection_key = any(array['projects','projectLinks','contracts','contractAmendments','contractParties','contractDeductions','guarantees','guaranteeEvents','contractStatements','phase4Audit']::text[]) then 'contracting'
42
+ when collection_key = any(array['warehouses','stockMovements','inventoryCounts']::text[]) then 'inventory'
43
+ when collection_key = any(array['fixedAssets','assetDepreciations']::text[]) then 'assets'
44
+ when collection_key = any(array['employees','employmentContracts','employeeLeave','payrollRuns','payrollLines','employeeBenefitAccruals']::text[]) then 'hr_payroll'
45
+ when collection_key = 'intercompanyTransactions' then 'group_consolidation'
46
+ when collection_key = any(array['officeRegistries','correspondence','correspondenceAttachments','correspondenceReferrals','correspondenceAudit']::text[]) then 'office_automation'
47
+ when collection_key = any(array['requestTypes','requests','requestActions']::text[]) then 'requests_workflow'
48
+ else null
49
+ end
50
+$$;
51
+
52
+create or replace function private.has_collection_entitlement(collection_key text)
53
+returns boolean
54
+language sql stable security invoker set search_path = '' as $$
55
+ select coalesce(private.has_module_entitlement(private.collection_module(collection_key)), false)
56
+$$;
57
+
58
+revoke all on function private.is_valid_finora_module(text) from public, anon;
59
+revoke all on function private.has_module_entitlement(text) from public, anon;
60
+revoke all on function private.collection_module(text) from public, anon;
61
+revoke all on function private.has_collection_entitlement(text) from public, anon;
62
+grant execute on function private.is_valid_finora_module(text) to authenticated;
63
+grant execute on function private.has_module_entitlement(text) to authenticated;
64
+grant execute on function private.collection_module(text) to authenticated;
65
+grant execute on function private.has_collection_entitlement(text) to authenticated;
66
+
67
+create or replace function public.admin_set_license_modules(target uuid, new_modules text[])
68
+returns void
69
+language plpgsql
70
+security definer
71
+set search_path = ''
72
+as $$
73
+declare normalized text[];
74
+begin
75
+ if not public.is_admin() then raise exception 'forbidden' using errcode = '42501'; end if;
76
+ if new_modules is null or cardinality(new_modules)=0 then raise exception 'at least one module is required'; end if;
77
+ if exists (select 1 from unnest(new_modules) m where not private.is_valid_finora_module(m)) then
78
+ raise exception 'invalid module entitlement';
79
+ end if;
80
+ if 'full_suite' = any(new_modules) then normalized := array['full_suite']::text[];
81
+ else select array_agg(distinct m order by m) into normalized from unnest(new_modules) m;
82
+ end if;
83
+ update public.licenses set modules=normalized, updated_at=now() where user_id=target;
84
+ if not found then raise exception 'user not found'; end if;
85
+end
86
+$$;
87
+revoke all on function public.admin_set_license_modules(uuid,text[]) from public, anon;
88
+grant execute on function public.admin_set_license_modules(uuid,text[]) to authenticated;
89
+
90
+alter table public.records drop constraint if exists records_collection_check;
91
+alter table public.records add constraint records_collection_check check (collection = any(array[
92
+ 'companies','contacts','products','invoices','cheques','expenses','settings','purchases','payments',
93
+ 'fiscalYears','accounts','dimensionTypes','dimensionValues','accountDimensionRules','branches','projects','projectLinks','postingProfiles',
94
+ 'journalVouchers','journalLines','journalLineDimensions','contracts','contractAmendments','contractParties','contractDeductions','guarantees','guaranteeEvents','contractStatements','phase4Audit',
95
+ 'warehouses','stockMovements','inventoryCounts','fixedAssets','assetDepreciations','currencies','exchangeRates','costCenters','importBatches','integrationConnections','integrationOutbox','phase5Audit',
96
+ 'employees','employmentContracts','employeeLeave','cashboxes','pettyCashFunds','complianceRules','payrollRuns','payrollLines','employeeBenefitAccruals','pettyCashTransactions','budgets','costDrivers','costAllocations','intercompanyTransactions','enterpriseAudit',
97
+ 'officeRegistries','correspondence','correspondenceAttachments','correspondenceReferrals','correspondenceAudit','requestTypes','requests','requestActions'
98
+]::text[]));
99
+
100
+-- Module entitlement is enforced at the data boundary, not only in the UI.
101
+drop policy if exists records_select on public.records;
102
+drop policy if exists records_insert on public.records;
103
+drop policy if exists records_update on public.records;
104
+drop policy if exists records_delete on public.records;
105
+create policy records_select on public.records for select to authenticated
106
+ using (owner_id=(select auth.uid()) and private.has_collection_entitlement(collection));
107
+create policy records_insert on public.records for insert to authenticated
108
+ with check (owner_id=(select auth.uid()) and public.has_active_license() and private.has_collection_entitlement(collection));
109
+create policy records_update on public.records for update to authenticated
110
+ using (owner_id=(select auth.uid()) and public.has_active_license() and private.has_collection_entitlement(collection))
111
+ with check (owner_id=(select auth.uid()) and public.has_active_license() and private.has_collection_entitlement(collection));
112
+create policy records_delete on public.records for delete to authenticated
113
+ using (owner_id=(select auth.uid()) and public.has_active_license() and private.has_collection_entitlement(collection));
114
+
115
+create or replace function public.finora_sync_records(p_upserts jsonb default '[]'::jsonb, p_deletes jsonb default '[]'::jsonb)
116
+returns void
117
+language plpgsql
118
+security invoker
119
+set search_path = public
120
+as $$
121
+begin
122
+ if auth.uid() is null then raise exception 'authentication required'; end if;
123
+ if not public.has_active_license() then raise exception 'active license required'; end if;
124
+ if exists (
125
+ select 1 from jsonb_to_recordset(coalesce(p_upserts,'[]'::jsonb)) as x(collection text,id text,data jsonb)
126
+ where not private.has_collection_entitlement(x.collection)
127
+ ) or exists (
128
+ select 1 from jsonb_to_recordset(coalesce(p_deletes,'[]'::jsonb)) as d(collection text,id text)
129
+ where not private.has_collection_entitlement(d.collection)
130
+ ) then raise exception 'module entitlement required' using errcode='42501'; end if;
131
+
132
+ insert into public.records(owner_id, collection, id, data)
133
+ select auth.uid(), x.collection, x.id, x.data
134
+ from jsonb_to_recordset(coalesce(p_upserts,'[]'::jsonb)) as x(collection text,id text,data jsonb)
135
+ on conflict (owner_id,collection,id) do update set data=excluded.data;
136
+
137
+ delete from public.records r
138
+ using jsonb_to_recordset(coalesce(p_deletes,'[]'::jsonb)) as d(collection text,id text)
139
+ where r.owner_id=auth.uid() and r.collection=d.collection and r.id=d.id;
140
+end $$;
141
+revoke all on function public.finora_sync_records(jsonb,jsonb) from public, anon;
142
+grant execute on function public.finora_sync_records(jsonb,jsonb) to authenticated;
143
+
144
+-- Private office-document bucket. Object operations remain through Storage API; SQL only defines the bucket and RLS policies.
145
+insert into storage.buckets(id,name,public,file_size_limit,allowed_mime_types)
146
+values ('office-attachments','office-attachments',false,20971520,array['application/pdf','image/jpeg','image/png','image/tiff']::text[])
147
+on conflict (id) do update set public=false,file_size_limit=excluded.file_size_limit,allowed_mime_types=excluded.allowed_mime_types;
148
+
149
+drop policy if exists finora_office_files_select on storage.objects;
150
+drop policy if exists finora_office_files_insert on storage.objects;
151
+drop policy if exists finora_office_files_update on storage.objects;
152
+drop policy if exists finora_office_files_delete on storage.objects;
153
+create policy finora_office_files_select on storage.objects for select to authenticated
154
+using (bucket_id='office-attachments' and owner_id=(select auth.uid()::text) and private.has_module_entitlement('office_automation'));
155
+create policy finora_office_files_insert on storage.objects for insert to authenticated
156
+with check (bucket_id='office-attachments' and (storage.foldername(name))[1]=(select auth.uid()::text) and private.has_module_entitlement('office_automation') and public.has_active_license());
157
+create policy finora_office_files_update on storage.objects for update to authenticated
158
+using (bucket_id='office-attachments' and owner_id=(select auth.uid()::text) and private.has_module_entitlement('office_automation') and public.has_active_license())
159
+with check (bucket_id='office-attachments' and owner_id=(select auth.uid()::text) and private.has_module_entitlement('office_automation') and public.has_active_license());
160
+create policy finora_office_files_delete on storage.objects for delete to authenticated
161
+using (bucket_id='office-attachments' and owner_id=(select auth.uid()::text) and private.has_module_entitlement('office_automation') and public.has_active_license());
\ No newline at end of file
supabase/migrations/20260930025647_office_secretariat_atomic_registration.sql
new
+57
@@ -0,0 +1,57 @@
1
+create unique index if not exists ux_finora_correspondence_registry_number
2
+on public.records(owner_id,(data->>'registryId'),(data->>'registerNumber'))
3
+where collection='correspondence' and coalesce(data->>'registerNumber','')<>'';
4
+
5
+create or replace function public.office_register_correspondence(p_id text, p_registry_id text, p_payload jsonb)
6
+returns text
7
+language plpgsql
8
+security invoker
9
+set search_path = public
10
+as $$
11
+declare
12
+ registry_row public.records%rowtype;
13
+ next_no integer;
14
+ prefix text;
15
+ assigned text;
16
+begin
17
+ if auth.uid() is null then raise exception 'authentication required'; end if;
18
+ if not public.has_active_license() or not private.has_module_entitlement('office_automation') then
19
+ raise exception 'office automation entitlement required' using errcode='42501';
20
+ end if;
21
+ if p_id is null or p_id !~ '^[A-Za-z0-9_-]{1,64}$' then raise exception 'invalid correspondence id'; end if;
22
+ if p_registry_id is null or p_registry_id !~ '^[A-Za-z0-9_-]{1,64}$' then raise exception 'invalid registry id'; end if;
23
+ if p_payload is null or jsonb_typeof(p_payload) <> 'object' then raise exception 'invalid payload'; end if;
24
+
25
+ select * into registry_row
26
+ from public.records
27
+ where owner_id=auth.uid() and collection='officeRegistries' and id=p_registry_id
28
+ for update;
29
+ if not found then raise exception 'registry not found'; end if;
30
+
31
+ next_no := greatest(1,coalesce(nullif(registry_row.data->>'nextNumber','')::integer,1));
32
+ prefix := trim(coalesce(registry_row.data->>'prefix',''));
33
+ assigned := case when prefix='' then next_no::text else prefix||'-'||next_no::text end;
34
+
35
+ update public.records
36
+ set data=jsonb_set(registry_row.data,'{nextNumber}',to_jsonb(next_no+1),true)
37
+ where owner_id=auth.uid() and collection='officeRegistries' and id=p_registry_id;
38
+
39
+ insert into public.records(owner_id,collection,id,data)
40
+ values(auth.uid(),'correspondence',p_id,
41
+ p_payload || jsonb_build_object(
42
+ 'registryId',p_registry_id,
43
+ 'registerNumber',assigned,
44
+ 'status','registered',
45
+ 'registeredAt',now()
46
+ ))
47
+ on conflict(owner_id,collection,id) do update
48
+ set data = case
49
+ when public.records.data->>'status'='registered' then public.records.data
50
+ else excluded.data
51
+ end;
52
+
53
+ return assigned;
54
+end
55
+$$;
56
+revoke all on function public.office_register_correspondence(text,text,jsonb) from public, anon;
57
+grant execute on function public.office_register_correspondence(text,text,jsonb) to authenticated;
\ No newline at end of file