# טיוטה: סביבת Admin

> טיוטת PR #69 — לא מוזגה. מקור: docs/company-admin-workspace.md · 34bdd4e · 2026-11-21.

Implementation date: 21 November 2026. Source branch: `admin/company-workspace-20261121`, stacked on `security/development-identity-20261121`.

## Scope

This release adds the company workspace to the existing Admin surface. It includes the central dashboard, B2C/B2B subscription segmentation, RevOps, email, separate WhatsApp service/sales channels, customers, subscriptions, tenant memberships, billing obligations and energy transactions. The product, native mobile application, marketing pages and approved visual assets retain their existing implementations.

No additional Supabase project, paid branch, plan upgrade, mailbox or WhatsApp account is created by this source change. The database additions target the existing project when live Admin is activated. The preview uses synthetic fixtures and cannot read company data or send messages.

The energy-read migration (`20261121143921_company_admin_energy_read.sql`) and RevOps-ledger migration (`20261121145421_company_admin_revops_ledger.sql`) are source changes tested against an isolated local database. They have **not been applied to the live database** as part of this work. Local migration replay and a deployed synthetic preview do not activate live company data.

## Modules

| Module        | Working behavior                                                                                                                                      | Live source                                                                                           |
| ------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------- |
| Dashboard     | Current account/subscription/membership totals, paid-obligation collection trend, attention queue, recent billing records                             | Existing fixed-column company queries                                                                 |
| B2C/B2B       | B2C = Personal + Family; B2B = Business + Enterprise; four-tier active subscription breakdown                                                         | `ev1_subscriptions.plan_code`, status `active`; trialing excluded                                     |
| RevOps        | Monthly MRR bridge, growth, ARR, seven audience/tier scopes, customer counts/churn, ARPA, CAC, gross-profit-adjusted LTV and LTV:CAC, history and CSV | Automatic subscription change ledger plus explicit cost coverage                                      |
| Email         | Inbox search, thread view, local draft composer, status/filter controls                                                                               | Provider adapter and company mailbox authorization still required                                     |
| WhatsApp      | Independently scoped customer-service and sales workspaces                                                                                            | Provider ingestion/delivery adapters and two verified business number/channel mappings still required |
| Customers     | Search, status/plan filters, pagination, details and current-page CSV                                                                                 | Existing tenant accounts                                                                              |
| Subscriptions | Status/plan filters and subscription details                                                                                                          | Existing billing subscriptions                                                                        |
| Users         | Account memberships and role/status information                                                                                                       | Existing tenant memberships; not a distinct-person metric                                             |
| Transactions  | Separate billing/collection and charging/fueling ledgers, date filters, details and CSV                                                               | Existing billing records and unified energy evidence                                                  |

Family members and organization employees do not inflate the subscription count. The active-subscription KPI is distinct from the number of accounts contributing MRR under the documented recurring-service policy. Gross collections are not presented as recognized revenue or MRR. Supplier-imported energy evidence remains explicitly unverified.

## Automatic RevOps calculation

The additive migration captures subscription financial changes and actual subscription-payment evidence inside the existing database transaction. It preserves a baseline when installed and records changes after that point. Generic historical audit events do not contain sufficient old/new financial values, so periods before coverage are never reconstructed from guesses.

The read endpoint obtains a bounded, consistent source snapshot and calculates the report. Reading a report does not create events, alter subscriptions, collect money, send messages or write cost records. Calendar months use `Asia/Jerusalem`.

The current raw-source limits are **5,000 subscription rows, 5,000 retained account records and 10,000 subscription events**. These limits cover the full stored source inventory, including inactive subscriptions and the entire retained event history; they are not limits for only the selected report month, and selecting a new month does not reset them. A source that exceeds its bound is explicitly marked incomplete and its array is omitted, rather than silently truncated. Current MRR can remain available from an independently complete current subscription snapshot; historical movements and dependent metrics require complete replayable history. Growth beyond these limits requires a separately reviewed aggregation/checkpoint design that preserves completeness and replay guarantees.

Monthly recurring amounts exclude VAT and normalize annual contracts by twelve. The bridge reconciles in exact twelfths of a minor currency unit before display rounding. Tier migrations use transfer entries so an existing customer changing plans does not become a new company customer. New, expansion, contraction, churn, reactivation and unknown-history activations remain distinct.

CAC requires a completed month, complete attributable acquisition costs and verified first-time paying accounts. A service-only, idempotent cost-import contract supports monthly source snapshots and revisions; an adapter to the company's actual marketing/accounting systems must supply those records. Missing costs are not zero costs.

The preview's synthetic historical events and costs do not establish live coverage. The live baseline starts when the migration is actually installed, and genuine cost sources must be connected and reconciled before cost-dependent metrics can be available.

LTV is explicitly a model: selected-period ARPA multiplied by the prior six completed months' revenue-weighted gross margin, divided by the average monthly customer churn over those six months. Missing history, incomplete costs and zero churn return an unavailable metric with its reason. The model is not a guaranteed lifetime revenue forecast. Definitions and calculation policy are documented in [admin-revops-metrics.md](/draft-admin-revops).

## Access and connection boundaries

Live company Admin requires an explicit staff grant, the configured Admin identity issuer/origin, a current verified session and fresh MFA. Customer tenant administrators do not receive company access. CEO/operations can read the operational modules; the accountant can read the dashboard, subscriptions, transactions and RevOps, without access to the contact/user/communications directories.

All Admin data endpoints are fixed read routes, private/no-store and denied on the product and website surfaces. No public endpoint accepts arbitrary SQL, a table name or a client-supplied staff identity. See [admin-access.md](/draft-admin-access).

The communication modules currently provide disconnected UI and provider data contracts. No live mailbox or WhatsApp provider adapter is activated; provider ingestion/delivery, account authorization and channel mappings still need to be completed. Drafts and example thread status changes remain in browser component memory and disappear on navigation/reload. Sending stays disabled. See [admin-communications.md](/draft-admin-communications) for the provider-specific integration contract.

## Preview and verification

Generate the self-contained preview from the actual React components:

```sh
node scripts/build-admin-preview.mjs
```

`docs/previews/company-admin.html` contains synthetic data, the existing brand assets/tokens and the actual Admin components. Its content security policy disables outbound network connections. `company-admin-mobile.html` is an isolated responsive review harness that embeds the same UI at selectable mobile widths; it is not a product route.

The branch contains dedicated unit tests, real PostgreSQL regression scripts and `playwright.admin.config.ts` for desktop/mobile UI and closed-API checks. CI has an additive `admin-browser` job and runs the database regressions. Validation outcomes and any environment blockers are recorded in the pull request rather than inferred from test discovery.

### Confirmed verification checkpoint

Final local verification completed on 21 November 2026:

| Check                                           | Confirmed result                                                                                         |
| ----------------------------------------------- | -------------------------------------------------------------------------------------------------------- |
| Repository unit suite                           | 1,011 tests passed across 74 files                                                                       |
| Optimized Admin build and TypeScript            | Passed with `APP_SURFACE=admin`; all 20 static pages generated                                           |
| Scoped ESLint                                   | Passed across the Admin implementation, routes, surface boundaries and regression scripts                |
| RevOps calculation engine                       | 45 unit tests passed                                                                                     |
| RevOps PostgreSQL                               | 15 grouped checks passed, including two-session claim/cancel concurrency and qualifying payment evidence |
| Energy PostgreSQL                               | 28 grouped checks passed                                                                                 |
| Existing billing foundation                     | 8 grouped checks passed                                                                                  |
| Existing billing safety                         | 11 grouped checks passed                                                                                 |
| Admin HTTP authorization and surface boundaries | 2 tests passed, one per configured project, including `/api/admin/revops`; no browser fixture required   |
| Admin Playwright discovery                      | 36 definitions listed: 34 browser UI cases and the 2 HTTP cases above                                    |

The full desktop/mobile Playwright UI suite did **not** execute locally: Chromium failed before UI execution with `socket() failed: Operation not permitted`. Discovery is not a UI pass. Manual cloud-browser review passed for the actual bundled React UI: desktop dashboard and cohort totals; RevOps scope changes (four/two/one tier rows), current and last full month; separate WhatsApp service/sales threads and disabled sends; company email thread; 390px responsive dashboard and RevOps without document horizontal overflow; hidden mobile navigation, open/close, Escape and focus restoration. This is Chrome with a responsive iframe harness, not an iPhone/Safari device test. Screenshots are checked in under `docs/previews/`. Later GitHub CI results are recorded separately in the pull request. The local PostgreSQL checks use the isolated test database and do not demonstrate that the live database has been migrated.

## Live activation dependencies

1. Review and promote the stacked identity/Admin source through the existing release process.
2. Apply the additive energy-read and RevOps-ledger migrations to the existing database after review. Establish and record the true historical coverage start.
3. Configure verified company staff identities and the existing database connection using the Admin boundary documented above.
4. Complete the live provider adapters, authorize the company mailbox provider and bind the two WhatsApp business numbers to their separate channels.
5. Connect the actual marketing/accounting cost source to the idempotent import contract and validate monthly coverage before displaying CAC/LTV as available.

Committing this implementation does not perform these live-account or production-data actions.
