# SaaS Platform Foundation

## Scope
FieldOps Cloud is now shaped as a SaaS platform for trade businesses: sole traders, plumbers, electricians, HVAC teams, property maintenance companies, and multi-crew contractors.

This implementation adds the safe commercial foundation:

- Tenant workspaces for each trade company.
- Starter, Growth, and Scale plan catalog.
- Seat, job, AI credit, and storage limits.
- Subscription and usage views.
- Platform-owner global pricing controls for plan prices, trial periods, discounts, supported currencies, and operating regions.
- Platform admin panel for SaaS operators to monitor tenants, revenue, trials, billing risk, integration health, incidents, security follow-ups, and audit events.
- Platform-admin tenant support sessions with a controlled "Log in as the Tenant" action and a return path to the original platform-admin session.
- Platform invoicing ledger for tenant contracts, billed-to-date totals, remaining contract value, next automatic invoice amounts, and manual billing overrides.
- Platform accounting connection controls for the site admin's own accounting system.
- Billing provider readiness controls that keep manual billing as the default and block live payment collection until provider configuration is complete.
- Tenant invitations, feature flags, billing event, and usage-counter schema.
- RBAC permissions for workspace and billing management.
- Guest pricing page and in-app workspace/subscription navigation.

## New Routes
- `/pricing`: public SaaS pricing page.
- `/workspace`: tenant workspace, onboarding, usage, and trade segment view.
- `/subscription`: plan catalog, current plan, and billing readiness view.
- `/platform-admin`: platform-owner SaaS operations panel.
- `POST /platform-admin/tenants/login`: start a platform-admin support session as the selected tenant admin.
- `/platform-admin/tenants/return`: restore the original platform-admin session after tenant support.
- `POST /platform-admin/billing/override`: save or clear a platform-admin manual invoice override for a tenant contract.
- `POST /platform-admin/accounting/connect`: link the platform billing entity to a supported accounting provider in demo mode.
- `POST /api/billing/stripe/webhook`: signed billing webhook endpoint for provider event intake and idempotency.
- `/settings/pricing`: platform-owner global pricing, trial, discount, currency, tax-display, and region configuration.
- `/demo/platform-admin`: local demo shortcut to enter the platform-admin role.
- `/demo/company-admin`: local demo shortcut to return to the tenant company-admin role.

## Database Contracts
- `tenants`: trade company workspace record.
- `subscription_plans`: commercial plan metadata.
- `tenant_subscriptions`: tenant plan, billing provider, status, and period/trial dates.
- `tenant_usage_counters`: metered usage by tenant and billing period.
- `tenant_invitations`: hashed invitation tokens for team onboarding.
- `tenant_feature_flags`: tenant-level plan or override feature access.
- `billing_events`: non-sensitive provider event audit trail using payload hashes.
- `platform_billing_overrides`: manual platform billing override action, amount, reason, actor, and timestamp.
- Future `platform_billing_contracts`: tenant contract terms, billing cycle, currency, contract dates, and commercial overrides.
- Future `platform_accounting_connections`: platform-owner accounting provider, external organisation id, sync mode, encrypted tokens, and audit metadata.
- Future `platform_pricing_settings`: global plan metadata, default currency, enabled ISO-4217 currencies, trial days, discount rules, operating regions, and tax-display behavior.
- Future `platform_price_points`: per-plan, per-currency price records with provider price ids and audit metadata.

All customer, job, quote, invoice, accounting, import, export, and audit tables continue to include `tenant_id`. Future repository work must keep tenant-scoped lookups as a hard rule.

## Global Pricing Controls
The demo now stores platform pricing settings in session so the owner/admin can preview the operating model without a live database migration. The intended production version should move this to platform-level database tables with audit logs.

Supported settings:

- Default billing currency and enabled international currencies.
- Operating regions and tax-display behavior: exclusive, inclusive, or not collected.
- Global trial days.
- Global discount percentage, label, and optional expiry date.
- Monthly price matrix for each plan and currency.
- Public pricing and tenant subscription pages render prices from the same catalog.

## Platform Admin Panel
The platform admin panel is the SaaS operator cockpit. It is separate from tenant workspace administration and should eventually be restricted to internal platform roles only.

Current demo coverage:

- Tenant overview table with workspace, owner, region, plan, subscription status, usage, MRR, and risk.
- SaaS metrics: tenants, active subscriptions, trials, MRR, ARR, churn risk, and open incidents.
- Billing health: provider readiness, webhook status, failed payments, past-due invoices, trial conversion follow-ups, currency, and tax mode.
- Integration health for accounting, calendars, LLM controls, and billing webhooks.
- Incident and follow-up queue.
- Demo audit trail and security checklist.
- Quick links to pricing, subscription, accounting, calendar, LLM, and reports.
- Tenant support access: select a tenant and use "Log in as the Tenant" to view/edit the tenant workspace as an owner/admin while preserving platform-admin return context.
- Platform invoicing: tenant name, monthly or annual package, contract value, billed so far, remaining to bill, next invoice amount/date, and override status.
- Manual billing override: override the next invoice amount, pause automatic invoicing, or resume automatic invoicing with an audit reason.
- Platform accounting link: choose Xero, QuickBooks Online, Sage, Zoho Books, MYOB, FreeAgent, Reckon, FreshBooks, Wave, or other supported providers for platform tenant-invoice sync readiness.

Production requirements:

- Move tenant and billing metrics to database-backed repositories.
- Persist billing overrides and platform accounting connection state in database tables with immutable audit rows.
- Require internal support/admin role checks and audit every tenant lookup.
- Add immutable audit logs for billing, support impersonation, tenant status changes, and global pricing changes.
- Do not expose secrets, raw webhook payloads, card data, OAuth tokens, or customer private notes.
- Keep high-risk platform-admin actions read-only until provider webhooks, tenant isolation, and durable audit trails are fully verified.

## Billing Direction
Live payment capture is intentionally not enabled by default. Gate 5 implemented the truthful billing foundation:

- Manual platform billing is the default provider state.
- Platform billing overrides and billing provider events have a database-backed repository in production mode.
- The platform-admin billing health card shows provider readiness, webhook signing state, price mapping state, and live-collection state.
- `billing_events` stores non-sensitive provider event metadata and payload hashes only.
- `POST /api/billing/stripe/webhook` verifies Stripe-style signatures, rejects stale or invalid signatures, requires tenant metadata, and handles replay idempotency.

The recommended live production implementation remains:

- Stripe Billing subscriptions with Checkout Sessions in subscription mode.
- Stripe Prices for plan billing objects.
- One provider price id per plan, currency, and billing interval.
- Stripe Customer Portal for tenant self-service plan and payment method changes.
- Webhook signature validation before any billing state mutation.
- Idempotent billing event processing keyed by provider event id and payload hash.
- No secrets, raw webhook payloads, card data, or OAuth tokens in logs.

The current code is billing-foundation work only. Live collection still requires operator-supplied Stripe credentials, webhook secret, provider price IDs, approval, and subscription-state mutation tests.

## Security Requirements
- Require `manage_tenant` for workspace administration.
- Require `manage_billing` for subscription and billing surfaces.
- Require `manage_platform_pricing` for global platform pricing changes.
- Require `view_platform_admin` for the platform operator panel.
- Require `impersonate_tenants` before starting tenant support sessions.
- Require `manage_platform_billing` before applying billing overrides or linking platform accounting.
- Require `manage_platform_admin` before any future tenant suspension, plan override, or destructive support action.
- Store original platform-admin session context server-side and expose a clear return path during tenant support sessions.
- Store invitation and API tokens only as hashes.
- Store future provider tokens encrypted with an environment-managed key.
- Never store platform accounting access tokens, refresh tokens, OAuth codes, card data, or provider secrets in plain session state.
- Scope every repository query by authenticated tenant id.
- Record non-sensitive audit logs for plan, user, billing, and integration changes.
- Never trust client-side plan or usage values for enforcement.
- Do not let tenant admins change global prices; use a platform role and audit each change.

## Next Build Steps
1. Add tenant-aware repository methods across all live database-backed modules.
2. Add tenant creation, invite acceptance, and role assignment flows.
3. Add plan enforcement at service boundaries before creating users, jobs, AI requests, uploads, and exports.
4. Persist global pricing settings and per-currency price points in database tables with audit logs.
5. Add Stripe Checkout Session and Customer Portal endpoints after Stripe test credentials are available.
6. Connect verified webhook events to subscription-state changes only after live provider configuration and release approval.
7. Add admin/internal support tools for tenant status, billing incident review, and audit trails.
