# FMS --- Finance Management System

## Master Development Specification

**Version:** 1.0 \| **Status:** Approved architecture baseline \|
**Model:** Multi-tenant SaaS

------------------------------------------------------------------------

# 1. Executive Summary

FMS is one SaaS platform with two distinct financial products:

-   **Individual FMS:** personal income, expenses, accounts, transfers,
    budgets, savings, loans, liabilities and cash-flow tracking.
-   **Organisation FMS:** organisation finance operations, double-entry
    bookkeeping, accounting, budgets, approvals, payments, receipts,
    ledgers and financial statements.

The platform has four functional areas:

1.  **Public CMS:** marketing website, features, pricing, manuals, FAQs,
    registration and login entry points.
2.  **Individual FMS:** personal financial management application.
3.  **Organisation FMS:** accounting and financial management
    application.
4.  **Super Admin:** platform-wide registration, organisation, user,
    staff, role, plan, feature, subscription, payment, CMS and support
    administration.

All areas run in **one Laravel application and one shared MySQL
database**. Customer financial data is isolated by workspace. The
architecture is a modular monolith, not microservices.

## 1.1 Approved product decisions

  -----------------------------------------------------------------------
  Area                                Decision
  ----------------------------------- -----------------------------------
  Product                             Individual and Organisation in one
                                      SaaS platform

  Public website                      CMS with Features, Manual, Pricing,
                                      Registration and Login

  Individual registration             Automatic activation after email
                                      verification

  Organisation registration           Mandatory Super Admin approval

  Organisation ownership              One Owner plus configurable
                                      administrators

  Subscription catalogue              Separate Individual and
                                      Organisation plans

  Payments                            Online payment gateway only

  Feature access                      Automatically determined by
                                      subscription plan

  Staff access                        Super Admin has platform-wide
                                      access

  Hosting                             One Laravel application and shared
                                      MySQL

  Architecture                        Modular monolith

  Frontend                            Blade, Livewire and Tailwind CSS

  Organisation accounting             Full double-entry bookkeeping

  Personal accounting                 Simplified transaction/account
                                      movement experience
  -----------------------------------------------------------------------

## 1.2 Core principles

-   One public brand and primary domain.
-   Separate Individual, Organisation and Admin layouts, routes and
    navigation.
-   One customer identity may participate in multiple workspaces.
-   Workspace is the financial data ownership boundary.
-   Every workspace-owned financial record is tenant-scoped.
-   Organisation postings are balanced and immutable after posting.
-   Subscription entitlements and user permissions are separate.
-   Payment activation relies on verified gateway events, not browser
    redirects.
-   Sensitive administrative and financial actions are audited.
-   Responsive mobile and desktop experience.

------------------------------------------------------------------------

# 2. Product Areas and URL Structure

Use one primary domain initially, e.g. `https://fms.example.com`.
Replace the example domain at deployment.

## 2.1 Public CMS routes

  Route                    Purpose
  ------------------------ -----------------------------
  `/`                      Homepage
  `/features`              Product features
  `/individual`            Individual product page
  `/organisation`          Organisation product page
  `/pricing`               Separate product pricing
  `/manual`                User documentation
  `/manual/individual`     Individual guide
  `/manual/organisation`   Organisation guide
  `/faq`                   FAQs
  `/about`                 About FMS
  `/contact`               Contact form
  `/terms`                 Terms
  `/privacy`               Privacy policy
  `/register`              Registration type selection
  `/login`                 Login type selection

## 2.2 Registration and login routes

  Route                      Purpose
  -------------------------- ---------------------------
  `/register/individual`     Individual registration
  `/register/organisation`   Organisation registration
  `/email/verify`            Verification notice
  `/login/individual`        Individual login page
  `/login/organisation`      Organisation login page
  `/admin/login`             Platform staff login

## 2.3 Application routes

  Prefix              Application
  ------------------- --------------------
  `/individual/*`     Individual FMS
  `/organisation/*`   Organisation FMS
  `/admin/*`          Super Admin portal

Dashboard routes:

-   `/individual/dashboard`
-   `/organisation/dashboard`
-   `/admin/dashboard`

The selected login type is a requested destination, not proof of access.
Validate the user's workspace membership and permissions on every
request.

------------------------------------------------------------------------

# 3. Identity, Users and Roles

## 3.1 Customer identity

Use one `users` table for Individual users and Organisation members. A
person may own a Personal workspace, own an Organisation workspace, or
be a member of multiple organisations with different roles.

Registration type determines the initial workspace created; it does not
permanently restrict the user's identity.

## 3.2 Platform administrators

Use a separate `admin_users` authentication model/provider for platform
staff. Platform staff are not ordinary customer workspace members.

Suggested platform roles:

-   Platform Owner
-   Super Admin
-   Platform Admin
-   Registration Officer
-   Accounts Officer
-   Subscription Manager
-   Support Staff
-   CMS Manager
-   Read-only Auditor

Super Admin has platform-wide access as approved. Sensitive access must
still be audited. Protect the Platform Owner role against ordinary
assignment or removal.

## 3.3 Organisation roles

Suggested configurable workspace roles:

-   Owner
-   Organisation Administrator
-   Accountant
-   Finance Officer
-   Approver
-   Department Head
-   Viewer

Do not hardcode permissions solely by role name.

------------------------------------------------------------------------

# 4. Public CMS Requirements

The public homepage explains the two products and provides clear calls
to action:

-   Register
-   Login
-   Explore Individual FMS
-   Explore Organisation FMS
-   Features
-   Pricing
-   User Manual

Authorized CMS staff can manage:

-   Homepage sections and product pages.
-   Features and pricing page content.
-   FAQs and manuals.
-   Announcements.
-   About and contact pages.
-   Terms and privacy policy.
-   SEO title, description and slug.
-   Draft/published status and publication dates.

CMS content must be sanitized and permission-controlled. Actual plan
prices and feature entitlements must come from subscription data, not
conflicting static CMS text.

Acceptance criteria:

-   Public pages are accessible without login.
-   Individual and Organisation product pages are distinct.
-   Registration and login selection are reachable from public
    navigation.
-   CMS staff cannot access customer accounting data by virtue of CMS
    permissions.

------------------------------------------------------------------------

# 5. Registration and Approval Requirements

## 5.1 Individual registration

Route: `/register/individual`

Suggested fields:

-   Full name.
-   Email.
-   Mobile, if enabled.
-   Country.
-   Password and confirmation.
-   Terms and privacy acceptance.

Workflow:

1.  Validate fields and email uniqueness.
2.  Create unverified customer user.
3.  Send signed email verification link.
4.  Verify email.
5.  Create exactly one Personal workspace.
6.  Create Owner workspace membership.
7.  Create default accounts/categories where appropriate.
8.  Assign the default Individual plan or free entitlement.
9.  Redirect to Individual dashboard.

Individual activation is automatic after email verification. No Super
Admin approval is required. Registration completion must be idempotent
to prevent duplicate workspaces.

## 5.2 Organisation registration

Route: `/register/organisation`

Applicant fields:

-   Contact person's name.
-   Email and mobile.
-   Password.
-   Country.

Organisation fields:

-   Legal/registered name.
-   Organisation type.
-   Registration/identification number, where applicable.
-   Official email and phone.
-   Address.
-   Website, optional.
-   Supporting documents, if required for that organisation type.

Organisation types may include company, educational institution, school,
college/university, partnership, sole proprietorship, trust/society/NGO
and other.

Workflow:

1.  Applicant submits registration.
2.  Verify email.
3.  Create or associate customer user.
4.  Create registration request with `pending_review` status.
5.  Do not grant Organisation application access.
6.  Notify authorized registration staff.
7.  Admin reviews application and documents.
8.  Admin approves, rejects or requests information.
9.  On approval, create Organisation workspace and organisation profile.
10. Create Owner membership for applicant.
11. Set subscription state to pending plan/payment or assign an
    explicitly configured free plan.
12. Enable Organisation application access only when approval and
    required subscription entitlement conditions are satisfied.

Approval and payment are separate states. An approved organisation is
not automatically a paid subscriber.

## 5.3 Registration statuses

-   `email_verification_pending`
-   `pending_review`
-   `information_requested`
-   `resubmitted`
-   `approved`
-   `rejected`
-   `withdrawn`

Maintain immutable approval history. Every decision records admin,
action, previous/new status, timestamp and remarks.

Repeated approval actions must not create duplicate workspaces.

------------------------------------------------------------------------

# 6. Individual FMS Requirements

Modules:

1.  Dashboard.
2.  Accounts.
3.  Income.
4.  Expenses.
5.  Transfers.
6.  Categories.
7.  Budgets.
8.  Recurring transactions.
9.  Savings goals.
10. Loans and EMIs.
11. Credit cards.
12. Assets and liabilities.
13. Reports.
14. Attachments.
15. Profile/settings.
16. Subscription and billing.

Account types may include bank, cash, wallet, credit card, loan and
investment accounts.

Transaction types:

-   Income.
-   Expense.
-   Transfer.
-   Refund.
-   Credit-card purchase.
-   Credit-card repayment.
-   Loan disbursement.
-   Loan repayment.
-   Controlled opening balance adjustment.

A transfer between the user's own accounts is not income or expense. A
credit-card purchase records expense and increases card liability.
Repayment reduces bank balance and card liability without recording the
expense twice.

Dashboard:

-   Available cash/bank balance.
-   Account balances.
-   Monthly income and expenses.
-   Savings.
-   Budget utilization.
-   Category-wise spending.
-   Upcoming bills/EMIs.
-   Recent transactions.

Mobile transaction entry:

1.  Select Income, Expense or Transfer.
2.  Select category where applicable.
3.  Enter amount.
4.  Select account.
5.  Select date.
6.  Add note/receipt optionally.
7.  Save.

The Individual user should not need to understand debit and credit.

------------------------------------------------------------------------

# 7. Organisation FMS Requirements

Modules:

1.  Organisation profile.
2.  Branches and departments.
3.  Cost centres.
4.  Financial years.
5.  Chart of Accounts.
6.  Opening balances.
7.  Income vouchers.
8.  Expense vouchers.
9.  Payment vouchers.
10. Receipt vouchers.
11. Journal vouchers.
12. Transfers.
13. Vendors/customers/contacts.
14. General Ledger.
15. Trial Balance.
16. Budget management.
17. Approval workflows.
18. Bank reconciliation.
19. Receivables and payables.
20. Fixed assets and depreciation.
21. Financial statements.
22. Attachments and audit history.
23. Subscription and billing.

## 7.1 Transaction states

Normal workflow:

`Draft → Pending Approval → Approved → Posted`

Other states: Rejected, Cancelled before posting, Reversed.

Approval is configurable by workflow and permission. Posting must be
atomic.

## 7.2 Double-entry bookkeeping

Every posted journal must satisfy:

`Total Debit = Total Credit`

Example: stationery expense paid from bank for ₹5,000.

  Ledger                 Debit   Credit
  -------------------- ------- --------
  Stationery Expense     5,000        0
  Bank Account               0    5,000
  Total                  5,000    5,000

Support assets, liabilities, equity/funds, income, expenses,
parent/child accounts, account codes, normal balances, opening balances,
period closing, reversals, trial balance, general ledger and configured
financial statements.

## 7.3 Posting rules

-   Debit and credit amounts are non-negative.
-   Journal has valid debit and credit lines.
-   Posted journal is balanced.
-   All accounts belong to the same workspace.
-   Posting is wrapped in a database transaction.
-   Use row locking/concurrency control where required.
-   Use idempotency keys to prevent duplicate posting.
-   Posted journals cannot be silently edited or deleted.
-   Corrections use reversal and replacement entries.
-   Closed periods reject ordinary postings.
-   Backdated adjustments require permission and audit history.

## 7.4 Budget management

Support annual/monthly budgets, department/branch/cost-centre
allocations, revisions, budget-vs-actual reports and approved
commitments. Define whether utilization counts posted expenditure only
or posted expenditure plus approved commitments.

------------------------------------------------------------------------

# 8. Super Admin Portal

Route prefix: `/admin`. Use a separate platform-admin authentication
guard/provider.

## 8.1 Dashboard

Show live database-derived indicators:

-   Total customer users.
-   Individual registrations.
-   Organisation registrations.
-   Pending approvals.
-   Approved organisations.
-   Active subscriptions.
-   Expired subscriptions.
-   Failed payments.
-   Successful payments.
-   Revenue summaries.
-   Active platform staff.
-   Support ticket counts.

## 8.2 Admin modules

  -----------------------------------------------------------------------
  Module                              Functions
  ----------------------------------- -----------------------------------
  Dashboard                           Platform overview and analytics

  Registrations                       Individual and Organisation
                                      records; review applications

  Users                               Search, profile, status and
                                      workspace memberships

  Organisations                       Profile, Owner, admins,
                                      subscription and status

  Plans                               Separate Individual and
                                      Organisation plans

  Features                            Feature catalogue and plan mapping

  Subscriptions                       Active, pending, expired, cancelled

  Payments                            Successful, failed, invoices,
                                      refunds

  Staff                               Add, edit and deactivate platform
                                      staff

  Roles & Permissions                 Configure staff RBAC

  CMS                                 Pages, pricing content, manuals,
                                      FAQs

  Support                             Tickets and customer queries

  Reports                             Revenue, registration and
                                      subscription reports

  Settings                            Email, payment gateway, security
                                      and system settings

  Audit                               Platform-wide administrative
                                      activity
  -----------------------------------------------------------------------

## 8.3 Registration management

Admin can review organisation applications, inspect documents, approve,
reject with reason, request more information, review resubmissions and
view complete decision history.

Individual registration is automatically activated after email
verification. Admin may manage or suspend accounts under platform policy
but does not approve each normal Individual registration.

## 8.4 Organisation management

Admin can view organisation details, Owner, administrators, workspace
status, subscription, entitlements, usage and registration history.
Suspension/reactivation must be audited.

## 8.5 Staff RBAC

Example platform permission identifiers:

-   `admin.dashboard.view`
-   `admin.users.view`
-   `admin.users.suspend`
-   `admin.organisations.view`
-   `admin.registrations.review`
-   `admin.registrations.approve`
-   `admin.registrations.reject`
-   `admin.plans.manage`
-   `admin.features.manage`
-   `admin.subscriptions.view`
-   `admin.payments.view`
-   `admin.refunds.manage`
-   `admin.staff.manage`
-   `admin.roles.manage`
-   `admin.cms.manage`
-   `admin.audit.view`
-   `admin.settings.manage`

Super Admin has all platform permissions as approved. Staff permissions
must be checked server-side.

------------------------------------------------------------------------

# 9. Subscription Plans and Feature Entitlements

## 9.1 Separate catalogues

Use one `subscription_plans` table with `product_type` equal to
`individual` or `organisation`, and separate Admin screens/catalogue
filters.

Illustrative Individual plans: Free, Basic, Premium, Pro.

Illustrative Organisation plans: Starter, Professional, Enterprise.

Prices and limits are configurable; do not hardcode them.

Plan fields:

-   Name, slug, product type, description.
-   Price and currency.
-   Billing interval and interval count.
-   Trial days.
-   Active/public flags.
-   Sort order.
-   Version.
-   Feature entitlements and limits.

## 9.2 Feature catalogue

Examples:

-   Income management.
-   Expense management.
-   Multiple accounts.
-   Budget management.
-   Recurring transactions.
-   Advanced reports.
-   General ledger.
-   Trial balance.
-   Approval workflow.
-   Bank reconciliation.
-   Multiple users.
-   Multiple branches.
-   Asset management.
-   Export functionality.

Support boolean and numeric entitlements, e.g. `enabled=true`,
`max_users=10`, `max_branches=3`, `storage_gb=10`.

## 9.3 Entitlement rules

The plan determines what the workspace has purchased. Workspace RBAC
determines which members can use those features.

Every restricted feature must be checked server-side. Hiding a menu item
is not sufficient.

Flow:

1.  User selects plan.
2.  Create pending subscription/order.
3.  Initiate payment.
4.  Verify gateway event.
5.  Record payment once.
6.  Activate subscription.
7.  Resolve plan entitlements.
8.  Enable features/limits.
9.  Record subscription history.

Plan changes must not rewrite historical invoices or purchased terms.
Store plan versions or snapshot price and entitlement terms in the
subscription/invoice.

## 9.4 Subscription states

-   `pending_payment`
-   `trialing`
-   `active`
-   `past_due`
-   `expired`
-   `cancelled`
-   `suspended`

On expiry, preserve historical financial data. Restrict new operations
according to policy and offer a read-only/renewal experience where
appropriate.

------------------------------------------------------------------------

# 10. Online Payment Gateway

Only online gateway collection is in scope. Manual bank-transfer
verification is excluded.

Potential providers: Razorpay, Cashfree and PayU.

Build a provider-independent payment service interface.

Payment flow:

1.  Select plan.
2.  Create pending subscription.
3.  Create gateway order.
4.  Complete checkout.
5.  Receive signed webhook.
6.  Verify signature and provider status.
7.  Validate amount, currency, order and workspace.
8.  Record payment idempotently.
9.  Activate subscription.
10. Generate invoice.
11. Enable entitlements.

Requirements:

-   Verify webhook signatures.
-   Store provider event IDs.
-   Prevent duplicate event processing.
-   Validate amount and currency.
-   Store gateway order/payment references.
-   Record failed/pending attempts.
-   Support retry.
-   Support refunds where provider/policy permits.
-   Keep invoice and payment history.
-   Never store raw card data.
-   Keep secrets outside source control.
-   Reconcile gateway settlement records operationally.

A browser success redirect is not authoritative payment proof.

------------------------------------------------------------------------

# 11. Database Design

## 11.1 Conventions

-   MySQL 8+, InnoDB, `utf8mb4`.
-   ULID/UUID public identifiers.
-   Foreign keys where practical.
-   `DECIMAL(19,4)` for money, with explicit currency precision rules.
-   Currency code stored with monetary records where multi-currency is
    supported.
-   UTC timestamps and workspace timezone for display.
-   Index workspace, status, date, foreign keys and search fields.
-   No floating-point money.
-   Do not soft-delete posted journals or immutable payment records.
-   Shared database with strict workspace isolation in Version 1.

## 11.2 Identity tables

### `users`

`id`, `name`, `email`, `email_verified_at`, `mobile`,
`mobile_verified_at`, `password`, `status`, `last_login_at`, timestamps.

### `personal_profiles`

`id`, `user_id`, `country`, `preferred_currency`, `timezone`,
`profile_photo_path`, timestamps. Collect optional personal fields only
when necessary.

### `admin_users`

`id`, `name`, `email`, `password`, `status`, `mfa_enabled`,
`last_login_at`, timestamps.

## 11.3 Workspace and organisation tables

### `workspaces`

`id`, `name`, `type` (`individual`, `organisation`), `owner_user_id`,
`status`, `default_currency`, `timezone`, timestamps.

### `workspace_members`

`id`, `workspace_id`, `user_id`, `status`, `joined_at`, timestamps.
Unique `(workspace_id,user_id)`.

### `organisations`

`id`, `workspace_id`, `legal_name`, `display_name`, `organisation_type`,
`registration_number`, optional tax identifier, official email, phone,
website, address, country, timestamps.

### `registration_requests`

`id`, `user_id`, `product_type`, organisation details as applicable,
`submitted_data` JSON snapshot, `status`, `submitted_at`, `reviewed_at`,
timestamps.

### `registration_documents`

`id`, `registration_request_id`, private file path, original filename,
MIME type, size, document type, uploaded timestamp.

### `registration_approvals`

`id`, `registration_request_id`, `admin_user_id`, action, previous
status, new status, remarks, timestamp.

### `workspace_invitations`

`id`, `workspace_id`, email, invited_by, token hash, expiry, accepted
timestamp, status.

## 11.4 Workspace RBAC

-   `roles`
-   `permissions`
-   `role_permissions`
-   `member_roles`

Platform RBAC is separate:

-   `admin_roles`
-   `admin_permissions`
-   `admin_role_permissions`
-   `admin_user_roles`

Do not mix customer workspace permissions and platform staff
permissions.

## 11.5 Subscription tables

### `subscription_plans`

`id`, `product_type`, `name`, `slug`, `description`, `price`,
`currency`, `billing_interval`, `billing_interval_count`, `trial_days`,
`is_active`, `is_public`, `version`, timestamps.

### `features`

`id`, `key`, `name`, `description`, `value_type`, `product_type`,
`is_active`.

### `plan_features`

`id`, `plan_id`, `feature_id`, `value` JSON/typed value. Unique
`(plan_id,feature_id)`.

### `subscriptions`

`id`, `workspace_id`, `plan_id`, `status`, `starts_at`, `ends_at`,
`trial_ends_at`, `cancelled_at`, `price_snapshot`, `currency`,
`plan_version_snapshot`, timestamps.

### `subscription_history`

`id`, `subscription_id`, event, old/new values, actor type/id,
timestamp.

### `workspace_feature_overrides`

`id`, `workspace_id`, `feature_id`, value, reason, starts/ends,
created_by, timestamp. Use only for authorized exceptions; default
access remains plan-based.

## 11.6 Payment tables

### `payment_gateways`

`id`, provider, display name, active status, secure configuration
reference, timestamps. Do not store plaintext secrets in ordinary rows.

### `payment_orders`

`id`, `workspace_id`, `subscription_id`, provider, provider order ID,
amount, currency, status, idempotency key, timestamps.

### `payments`

`id`, `workspace_id`, `payment_order_id`, provider payment ID, amount,
currency, status, paid_at, provider payload reference, timestamps.

### `payment_webhook_events`

`id`, provider, provider event ID, event type, signature verified,
processing status, payload reference, processed_at, created_at. Unique
provider event ID per provider.

### `subscription_invoices`

`id`, `workspace_id`, `subscription_id`, invoice number, amount, tax
amount, total, currency, status, issued_at, due_at, created_at.

### `refunds`

`id`, `payment_id`, provider refund ID, amount, reason, status,
processed_at, created_at.

## 11.7 Financial tables

### `financial_years`

`id`, `workspace_id`, name, start/end dates, status, closed_at,
closed_by.

### `branches`

`id`, `workspace_id`, name, code, address, status.

### `departments`

`id`, `workspace_id`, `branch_id`, name, code, status.

### `cost_centres`

`id`, `workspace_id`, name, code, status.

### `accounts`

`id`, `workspace_id`, `parent_id`, code, name, account_type,
normal_balance, is_control_account, is_active, timestamps.

### `categories`

`id`, `workspace_id`, `parent_id`, name, type (`income`, `expense`),
is_active.

Categories are user-facing classifications, not a replacement for the
Chart of Accounts.

### `transactions`

`id`, `workspace_id`, transaction number, type, transaction date,
status, description, created_by, approved_by, posted_at, timestamps.

### `journal_entries`

`id`, `workspace_id`, `financial_year_id`, `transaction_id`, journal
number/date, status, description, posted_at, posted_by, created_at.

### `journal_lines`

`id`, `journal_entry_id`, `account_id`, optional branch/department/cost
centre, description, debit, credit, currency, created_at.

Journal entries and journal lines are the canonical Organisation
accounting records. Do not create a duplicate debit/credit table.

### `personal_account_movements`

`id`, `workspace_id`, `transaction_id`, `account_id`, movement type,
amount, currency, effective date, created_at.

### `transaction_attachments`

`id`, `transaction_id`, private file path, original filename, MIME type,
size, uploaded_by, created_at.

### `transaction_reversals`

`id`, original transaction ID, reversal transaction ID, reason,
created_by, created_at.

## 11.8 Other financial extension tables

-   `budgets`
-   `budget_lines`
-   `budget_revisions`
-   `recurring_transactions`
-   `recurring_transaction_runs`
-   `savings_goals`
-   `savings_contributions`
-   `contacts`
-   `payment_methods`
-   `approval_workflows`
-   `approval_steps`
-   `approval_requests`
-   `approval_actions`
-   `bank_statements`
-   `bank_statement_lines`
-   `bank_reconciliations`
-   `bank_reconciliation_matches`
-   `assets`
-   `asset_depreciations`
-   `loans`
-   `loan_installments`
-   `receivables`
-   `payables`

Implement extension tables when their module enters development; do not
create unused structures without defined requirements.

## 11.9 CMS, support and audit tables

-   `cms_pages`
-   `cms_faqs`
-   `cms_manuals`
-   `cms_announcements`
-   `support_tickets`
-   `support_ticket_messages`
-   `notifications`
-   `system_settings`
-   `audit_logs`
-   `admin_audit_logs`

Audit records should be append-only at application level and protected
from ordinary deletion.

------------------------------------------------------------------------

# 12. Database Integrity and Tenant Isolation

Every workspace-owned record must be scoped by `workspace_id`, directly
or through a validated parent relationship.

Required safeguards:

1.  Validate workspace membership on every customer request.
2.  Establish workspace context in middleware.
3.  Use scoped Eloquent queries and policies.
4.  Use composite foreign keys where practical to prevent
    cross-workspace relationships.
5.  Never trust a client-supplied workspace ID without authorization.
6.  Journal lines cannot reference accounts from another workspace.
7.  Attachments cannot be accessed across workspaces.
8.  Queued jobs and exports preserve workspace context.
9.  Cache keys include workspace identity.
10. Automated tests attempt cross-tenant access across every major
    module.

Some rules, such as total journal balancing across multiple rows,
require transactional application validation and may be supplemented by
carefully designed database triggers. Ordinary CHECK constraints cannot
enforce every cross-row accounting invariant.

------------------------------------------------------------------------

# 13. Laravel Architecture

## 13.1 Suggested structure

``` text
app/
├── Core/
│   ├── Authentication/
│   ├── Workspace/
│   ├── Accounting/
│   ├── Transactions/
│   ├── Entitlements/
│   ├── Subscription/
│   ├── Audit/
│   └── Notifications/
├── Modules/
│   ├── CMS/
│   ├── Individual/
│   ├── Organisation/
│   ├── SuperAdmin/
│   ├── Registration/
│   ├── Plans/
│   ├── Features/
│   ├── Payment/
│   ├── Staff/
│   ├── Approvals/
│   ├── Budget/
│   ├── Banking/
│   ├── Assets/
│   ├── Reports/
│   └── Support/
├── Http/
│   ├── Controllers/
│   ├── Middleware/
│   └── Requests/
├── Policies/
├── Services/
├── Jobs/
├── Events/
├── Listeners/
└── Providers/

resources/views/
├── cms/
├── auth/
│   ├── individual/
│   ├── organisation/
│   └── admin/
├── individual/
├── organisation/
└── admin/

routes/
├── web.php
├── individual.php
├── organisation.php
└── admin.php
```

## 13.2 Architectural rules

-   Controllers coordinate HTTP requests, not accounting calculations.
-   Livewire components call application services.
-   Form Requests validate incoming data.
-   Policies authorize actions.
-   Middleware establishes user and workspace context.
-   Services implement use cases.
-   Domain services implement financial rules.
-   Events/jobs handle asynchronous side effects.
-   Web and API controllers reuse application services.
-   Database transactions wrap posting and payment activation.

## 13.3 Important services

  Service                       Responsibility
  ----------------------------- -------------------------------
  RegistrationService           Registration workflows
  EmailVerificationService      Verification and activation
  OrganisationApprovalService   Review and workspace creation
  WorkspaceService              Workspace lifecycle
  WorkspaceAccessService        Membership and tenant access
  EntitlementService            Plan features and limits
  SubscriptionService           Subscription lifecycle
  PaymentService                Provider-independent payments
  WebhookVerificationService    Gateway event verification
  TransactionService            Transaction lifecycle
  OrganisationPostingService    Double-entry posting
  PersonalPostingService        Personal movements
  JournalService                Journals and reversals
  AccountBalanceService         Balance calculation
  BudgetService                 Budget calculation
  ApprovalService               Organisation approvals
  ReportService                 Financial reports
  AuditService                  Audit recording

Use separate `OrganisationPostingService` and `PersonalPostingService`
behind a common application-level transaction interface.

------------------------------------------------------------------------

# 14. Authentication and Authorization

Use separate customer and platform-admin authentication providers.

Customer routes: - Individual. - Organisation.

Platform routes: - Admin.

Authentication checks alone are insufficient. Each request must check:

1.  Authenticated identity.
2.  Requested product type.
3.  Workspace membership.
4.  Workspace status.
5.  Subscription entitlement.
6.  User role permission.
7.  Record workspace ownership.
8.  Financial period and transaction state.

Individual and Organisation login pages can authenticate the same
customer identity, but must validate the destination workspace type.

MFA is strongly recommended for platform administrators.

------------------------------------------------------------------------

# 15. Responsive UI Requirements

## Desktop

-   Sidebar navigation.
-   Top bar and workspace identity/switcher.
-   Dashboard cards.
-   Searchable/filterable tables.
-   Detailed accounting forms.
-   Report and export controls.

## Mobile

-   Responsive navigation/bottom navigation.
-   Quick income/expense entry.
-   Camera receipt upload.
-   Search and filters.
-   Card-based transaction lists.
-   Touch-friendly forms.
-   Mobile-friendly login and registration.
-   PWA capability in a later phase.

Separate layouts and navigation for Individual, Organisation and Admin.

------------------------------------------------------------------------

# 16. Reports and Exports

## Individual

-   Daily transactions.
-   Monthly income and expense.
-   Account statement.
-   Category-wise expenses.
-   Budget vs actual.
-   Cash-flow summary.
-   Savings progress.
-   Loan/EMI schedule.
-   Credit-card statement summary.

## Organisation

-   Cash book.
-   Bank book.
-   General Ledger.
-   Trial Balance.
-   Income and Expenditure.
-   Profit and Loss, where applicable.
-   Balance Sheet.
-   Cash Flow Statement.
-   Budget vs Actual.
-   Department/branch expenditure.
-   Receivables and payables.
-   Bank reconciliation.
-   Fixed asset register.
-   Depreciation schedule.

Formal statements require appropriate accounting policy, opening
balances, accrual adjustments, classification and closing procedures. A
simple cash/bank movement report is not a formal cash flow statement.

Exports: PDF, Excel and CSV. Large exports should use queues and private
temporary storage.

------------------------------------------------------------------------

# 17. Notifications and Email

Notify users about:

-   Email verification.
-   Organisation registration received.
-   Organisation approval/rejection.
-   Additional information requested.
-   Organisation invitation.
-   Payment success/failure.
-   Invoice generated.
-   Renewal reminder.
-   Subscription expiry.
-   Payment retry.
-   Support ticket updates.
-   Platform announcements.

Use queued delivery and prevent duplicate notifications for repeated
webhook events.

------------------------------------------------------------------------

# 18. Security, Privacy and Audit

Security requirements:

-   HTTPS.
-   Secure password hashing.
-   CSRF protection.
-   Rate limiting.
-   Secure session and cookie configuration.
-   Email verification.
-   MFA for platform administrators.
-   Encryption of sensitive fields.
-   Private document storage.
-   Authorized downloads.
-   Signed payment webhook validation.
-   Input validation and output escaping.
-   Protection against IDOR and cross-tenant access.
-   Dependency updates.
-   Automated backup and restore tests.

The approved Super Admin access policy allows platform-wide access. For
sensitive customer data, record admin identity, workspace, target
record/module, reason, action, timestamp and relevant before/after
values.

Impersonation, if implemented, must be visibly indicated, time-limited
and audited. It must not bypass accounting immutability.

Audit events include login/security, registration decisions, suspension,
role changes, subscription/plan changes, payments/refunds, financial
posting/reversals, year closing, sensitive document access and platform
settings changes.

------------------------------------------------------------------------

# 19. Non-Functional Requirements

  -----------------------------------------------------------------------
  Area                                Requirement
  ----------------------------------- -----------------------------------
  Performance                         Target normal dashboard response
                                      within 2--3 seconds under defined
                                      test load

  Availability                        Initial target 99.5%, subject to
                                      hosting and operations

  Scalability                         Support growth in users and
                                      workspaces

  Isolation                           Strict workspace data separation

  Recovery                            Automated backups and tested
                                      restoration

  Auditability                        Traceable financial and
                                      administrative actions

  Accessibility                       Keyboard and screen-reader-aware
                                      forms

  Compatibility                       Current major desktop and mobile
                                      browsers

  Responsive design                   Mobile, tablet and desktop

  Maintainability                     Modular code and automated tests

  Reliability                         Idempotent posting and payment
                                      operations

  Integrity                           Balanced journals and valid
                                      relationships
  -----------------------------------------------------------------------

Validate targets through load, security and recovery testing.

------------------------------------------------------------------------

# 20. Testing and Acceptance Criteria

## Registration

-   Individual cannot access dashboard before email verification.
-   Verified Individual creates exactly one Personal workspace.
-   Organisation applicant cannot access Organisation app before
    approval.
-   Approval creates exactly one Organisation workspace and Owner
    membership.
-   Repeated approval cannot duplicate workspace.
-   Rejected applicant cannot access Organisation app.
-   Information request can be resubmitted and reviewed.

## Subscription and payment

-   Individual cannot purchase Organisation plan.
-   Organisation cannot purchase Individual plan.
-   Failed payment does not activate paid entitlement.
-   Valid signed webhook activates subscription once.
-   Duplicate webhook does not duplicate payment/activation.
-   Expiry changes access according to policy.
-   Historical invoices remain unchanged after plan edits.

## Tenant isolation

-   URL manipulation cannot expose another workspace.
-   Attachments are workspace-scoped.
-   API validates membership and permission.
-   Queued reports preserve workspace scope.
-   Cache does not leak data across workspaces.

## Accounting

-   Every posted journal balances.
-   Unbalanced journal rejected.
-   Cross-workspace journal line rejected.
-   Duplicate posting prevented.
-   Posted journal cannot be edited.
-   Reversal preserves original history.
-   Closed period rejects ordinary postings.
-   Transfers do not duplicate income/expense.
-   Credit-card repayment does not duplicate expense.

## Admin and RBAC

-   Platform staff cannot log in through customer login.
-   Customer cannot log in through Admin login.
-   Staff permissions checked server-side.
-   Registration Officer cannot manage plans unless granted.
-   CMS Manager cannot access financial records by default.
-   Super Admin activity is logged.

------------------------------------------------------------------------

# 21. Development Roadmap

Complete each milestone's acceptance tests before proceeding.

  -----------------------------------------------------------------------
  Phase                               Deliverables
  ----------------------------------- -----------------------------------
  1\. Foundation                      Laravel, MySQL, environment, base
                                      UI, logging, tests, deployment
                                      pipeline

  2\. Public CMS                      Homepage, product pages, features,
                                      pricing, manuals, FAQs, CMS admin

  3\. Identity and Registration       Customer registration, email
                                      verification, Individual and
                                      Organisation workflows

  4\. Workspace Isolation             Workspaces, memberships,
                                      middleware, policies, tenant tests

  5\. Super Admin                     Separate login, dashboard, staff
                                      RBAC, registration approval,
                                      organisation management

  6\. Plans and Features              Separate plan catalogues, feature
                                      catalogue, entitlement resolver,
                                      limits

  7\. Payments                        Gateway integration, signed
                                      webhooks, idempotency,
                                      subscriptions, invoices

  8\. Shared Financial Core           Accounts, categories, transactions,
                                      attachments, balance services,
                                      audit

  9\. Individual FMS                  Dashboard, income, expenses,
                                      transfers, budgets, savings,
                                      reports

  10\. Organisation Accounting        Chart of Accounts, years, journals,
                                      ledger, trial balance, reversals

  11\. Organisation Operations        Vouchers, contacts, approvals,
                                      budgets, cash flow,
                                      receivables/payables

  12\. Advanced Accounting            Reconciliation, assets,
                                      depreciation, statements, year
                                      closing

  13\. Production Readiness           Security/load tests, backups,
                                      monitoring, queues, PWA,
                                      documentation, deployment
  -----------------------------------------------------------------------

------------------------------------------------------------------------

# 22. Deployment Architecture

Initial deployment:

-   One Laravel application.
-   One MySQL database.
-   One primary domain.
-   Separate route groups and layouts.
-   Private file storage.
-   Queue worker for email, reports and webhook side effects.
-   Scheduler for reminders, renewals and recurring transactions.
-   Redis optional initially; recommended as load requires.
-   Automated backups and restore tests.
-   HTTPS.

Production components:

1.  Web server and PHP runtime.
2.  Laravel application.
3.  MySQL.
4.  Queue worker.
5.  Scheduler.
6.  Private file storage.
7.  Email provider.
8.  Payment gateway.
9.  Monitoring and backup service.

Keep secrets outside source control.

------------------------------------------------------------------------

# 23. Decisions to Finalize During Detailed Design

These do not change the approved architecture, but require explicit
policy decisions before their modules are implemented:

1.  Whether a Free plan exists for each product.
2.  Whether an approved Organisation application expires if it does not
    subscribe within a defined period.
3.  Grace period and read-only policy after expiry.
4.  Immediate or next-cycle downgrade.
5.  Refund and cancellation policy.
6.  Whether mobile verification is mandatory.
7.  Required documents by organisation type.
8.  Whether Individual users can create multiple Personal workspaces.
9.  Multi-currency scope for Version 1.
10. Whether GST/TDS compliance is included or deferred.
11. Organisation accounting basis and statement formats.
12. Approval thresholds and multi-level workflows.

Do not silently invent these policies in code. Record them as versioned
decisions or approved configuration.

------------------------------------------------------------------------

# 24. Definition of Done

A module is complete only when:

-   Functional requirements are implemented.
-   Desktop and mobile UI work.
-   Authorization is enforced server-side.
-   Workspace isolation is tested.
-   Validation and error handling are implemented.
-   Required audit events are recorded.
-   Unit and feature tests pass.
-   Relevant user documentation exists.
-   No critical security or data-integrity defect remains.
-   Acceptance criteria are demonstrated.

------------------------------------------------------------------------

# 25. Final Product Definition

**Public CMS:** product information, features, pricing, manuals,
registration and login.

**Individual FMS:** personal income, expenses, accounts, transfers,
budgets, savings, loans and reports.

**Organisation FMS:** organisation finance, double-entry bookkeeping,
General Ledger, Trial Balance, vouchers, budgets, approvals,
reconciliation and financial statements.

**Super Admin:** registration approvals, users, organisations, plans,
features, subscriptions, payments, staff RBAC, CMS, support, audit and
platform settings.

**Technical foundation:** one Laravel application, one shared MySQL
database, workspace-level tenant isolation, modular monolith,
Blade/Livewire/Tailwind, provider-independent payment integration and
responsive web application.

Implementation order:

`CMS → Identity and Registration → Workspace Isolation → Super Admin → Plans and Payments → Shared Financial Core → Individual FMS → Organisation FMS → Advanced Accounting → Production`

This document is the master development baseline. Changes to approved
business rules must be recorded as versioned changes to this
specification.
