# Workspace Type / Subscription Schema Design Review

Status: Active architecture planning source  
Introduced: v412  
Scope: workspace type model, account class model, plan visibility, trial policy fields, registration workflow state, owned interface / invited portal ownership, broker load-distribution usage limits, internal load-board access, billing-gate overrides, and Super Admin audit model  
Product UI changed in v412: No  
Prisma schema changed in v412: No

## Purpose

This document decides the schema direction before Prisma is changed. It converts the v409 role-workspace plan and v410 subscription/trial plan into a practical model that can support Super Admin, registration, subscriptions, entitlements, owned driver interfaces, invited portals, broker load distribution, internal load-board access, billing gates, Stripe handoff, and audit history.

The key principle is simple: **a login is not always a paid workspace**. Dispatch Spot must distinguish between paid workspaces, owned interfaces, invited portals, platform layers, and internal operations before subscription enforcement is made live.

## v412 decision summary

1. `Organization` should become the durable workspace/tenant record and should store `workspaceType` and `accountClass`.
2. Paid customer workspaces should use `accountClass = PAID_WORKSPACE` and should normally have a `WorkspaceSubscription`.
3. Driver interfaces should not be separate paid workspaces by default. They should remain users/interfaces owned by the workspace they drive for.
4. Small shipper/customer portals and carrier-response portals should usually be invited access owned by a paid workspace, not separate subscriptions.
5. Large shipper accounts may later become paid workspaces, but that should be an explicit workspace type/product decision.
6. Plan visibility should be stored by workspace type so a broker does not see dispatcher/fleet-only plans and a driver interface does not see paid workspace plans.
7. Trial policy should be centralized and Super Admin-configurable, but every paid workspace should still get a subscription record from creation.
8. Registration should produce a tracked registration workflow record before workspace/subscription creation becomes fully automated.
9. Broker load distribution needs dedicated usage limits, send history, opt-out/suppression handling, and Super Admin abuse monitoring before live high-volume sending.
10. Internal load-board access should be modeled as a platform service controlled by workspace type, plan, verification, billing state, and Super Admin rules.
11. Billing gate overrides must be explicit, reasoned, time-bound where possible, and audited.
12. Super Admin changes to plan, trial, workspace type, account class, billing gate, entitlement, provider availability, and access state must create audit events.

## Exact workspace type model

Recommended enum:

```prisma
WorkspaceType {
  DISPATCHER
  COMPANY_FLEET
  CARRIER_OWNER_OPERATOR
  FREIGHT_BROKER
  SHIPPER
  INTERNAL_OPERATIONS
}
```

Meaning:

| Workspace type | Paid by default? | Notes |
| --- | --- | --- |
| `DISPATCHER` | Yes | Dispatch service workspace. Current maturity benchmark. |
| `COMPANY_FLEET` | Yes | Fleet/company workspace managing trucks, drivers, documents, revenue, and costs. |
| `CARRIER_OWNER_OPERATOR` | Yes when independent | Simplified carrier/owner-operator workspace. |
| `FREIGHT_BROKER` | Yes | Brokerage workspace for shippers, loads, carriers, tenders, load distribution, and margins. |
| `SHIPPER` | Optional/later | Large shipper workspace. Small customers can remain invited portals. |
| `INTERNAL_OPERATIONS` | Internal only | Dispatch Spot internal operations/customer success workspace. |

Driver should **not** be a workspace type. Driver is an owned user/interface role under an organization.

Carrier response portal should **not** be a workspace type by default. It should be invited portal access tied to a load, carrier contact, or broker workspace.

## Exact account class model

Recommended enum:

```prisma
WorkspaceAccountClass {
  PAID_WORKSPACE
  OWNED_INTERFACE
  INVITED_PORTAL
  PLATFORM_LAYER
  INTERNAL
}
```

How to use it:

| Account class | Use case | Subscription expectation |
| --- | --- | --- |
| `PAID_WORKSPACE` | Dispatcher, fleet, independent carrier/owner-operator, broker, large shipper | Requires trial, active subscription, comp, manual, enterprise, or internal billing state. |
| `OWNED_INTERFACE` | Driver interface, road-only user experience, staff sub-interface | No independent subscription; belongs to owning workspace. |
| `INVITED_PORTAL` | Shipper/customer portal, carrier response portal, document-upload portal | No independent subscription by default; access governed by inviting workspace. |
| `PLATFORM_LAYER` | Internal load board or shared marketplace service if modeled as a tenant-like record | Access controlled by platform policy, plan, add-ons, verification, and abuse rules. |
| `INTERNAL` | Dispatch Spot internal operations | Internal/test/comp state only. |

Recommended initial storage: add `accountClass` to `Organization`, but only use `PAID_WORKSPACE` and `INTERNAL` on actual organizations at first. Owned interfaces and invited portals should be represented through user/access records, not fake organizations, unless a later design requires a tenant-like portal organization.

## Organization schema direction

Future Prisma direction, not implemented in v412:

```prisma
model Organization {
  workspaceType WorkspaceType?
  accountClass  WorkspaceAccountClass @default(PAID_WORKSPACE)
  onboardingStatus WorkspaceOnboardingStatus @default(SETUP_NEEDED)
  registrationSourceId String?
  billingGateState WorkspaceBillingGateState @default(EVALUATING)
  billingGateReason String?
  billingGateUpdatedAt DateTime?
  // existing fields remain
}
```

Recommended indexes:

```prisma
@@index([workspaceType])
@@index([accountClass])
@@index([isActive, workspaceType])
```

Design note: `workspaceType` may be nullable during migration so existing organizations can be classified safely by Super Admin before hard enforcement.

## Plan visibility by workspace type

Short-term approach: extend `SubscriptionPlan` with visibility and trial fields.

Recommended future fields:

```prisma
model SubscriptionPlan {
  planFamily                 SubscriptionPlanFamily?
  visibleWorkspaceTypesJson  Json?
  isPublic                   Boolean @default(false)
  isTrialEligible            Boolean @default(true)
  isInternal                 Boolean @default(false)
  requiresBillingMethodForTrial Boolean @default(false)
  sortOrder                  Int @default(100)
  // existing fields remain
}
```

Recommended enum:

```prisma
SubscriptionPlanFamily {
  DISPATCHER
  FLEET
  OWNER_OPERATOR
  BROKER
  SHIPPER
  INTERNAL
  ENTERPRISE
}
```

Rules:

- Registration only shows public, live plans visible for the selected workspace type.
- Super Admin can assign hidden/internal/custom plans.
- Drivers and invited portals do not see plan selection by default.
- Broker plans should carry load-distribution and load-board limits.
- Fleet/company plans should carry truck, driver, route/weather, compliance, and accounting entitlements.
- Dispatcher plans should carry trucks/carriers served, CORI, phone, notifications, and dispatch operations limits.

Long-term approach: if JSON becomes too limiting, introduce `SubscriptionPlanWorkspaceVisibility` as a normalized join table.

## Trial policy fields

Recommended policy model:

```prisma
model WorkspaceTrialPolicy {
  id                         String @id @default(uuid())
  name                       String
  workspaceType              WorkspaceType?
  planFamily                 SubscriptionPlanFamily?
  defaultTrialDays           Int @default(14)
  maxTrialExtensions         Int @default(1)
  maxExtensionDays           Int @default(14)
  requiresBillingMethod      Boolean @default(false)
  allowHighCostFeatures      Boolean @default(false)
  isDefault                  Boolean @default(false)
  isActive                   Boolean @default(true)
  createdAt                  DateTime @default(now())
  updatedAt                  DateTime @updatedAt
}
```

Rules:

- Initial default trial remains 14 days.
- Trial belongs to the workspace subscription, not to the first user.
- Super Admin can later configure trial length by workspace type or plan family.
- Trial extensions must be audited.
- High-cost features stay limited unless the plan/policy/Super Admin explicitly allows them.

## Registration workflow state

Recommended enum:

```prisma
WorkspaceRegistrationStatus {
  STARTED
  ACCOUNT_CREATED
  WORKSPACE_TYPE_SELECTED
  WORKSPACE_DETAILS_ENTERED
  PLAN_SELECTED
  WORKSPACE_CREATED
  TRIAL_SUBSCRIPTION_CREATED
  STRIPE_CUSTOMER_PREPARED
  CHECKOUT_STARTED
  COMPLETED
  ABANDONED
  NEEDS_REVIEW
}
```

Recommended model:

```prisma
model WorkspaceRegistrationIntent {
  id                     String @id @default(uuid())
  userId                 String?
  email                  String
  workspaceName          String?
  workspaceType          WorkspaceType?
  selectedPlanId         String?
  status                 WorkspaceRegistrationStatus @default(STARTED)
  organizationId         String?
  stripeCustomerId       String?
  checkoutSessionId      String?
  trialEndsAt            DateTime?
  metadataJson           Json?
  errorNote              String?
  createdAt              DateTime @default(now())
  updatedAt              DateTime @updatedAt
}
```

Rules:

- Registration must be recoverable if the user leaves before workspace creation or Stripe checkout.
- The app should not create paid workspace data before the registration flow has enough required information.
- Super Admin should be able to see incomplete, failed, or needs-review registrations.
- This model should not store raw payment details. Stripe handles payment collection.

## Owned interface and invited portal ownership model

Recommended invitation enums:

```prisma
WorkspaceAccessInviteType {
  DRIVER_INTERFACE
  CUSTOMER_PORTAL
  SHIPPER_PORTAL
  CARRIER_RESPONSE_PORTAL
  STAFF_USER
}

WorkspaceAccessInviteStatus {
  PENDING
  ACCEPTED
  EXPIRED
  REVOKED
  DECLINED
}
```

Recommended table:

```prisma
model WorkspaceAccessInvite {
  id                 String @id @default(uuid())
  organizationId     String
  invitedByUserId    String?
  inviteType         WorkspaceAccessInviteType
  email              String
  status             WorkspaceAccessInviteStatus @default(PENDING)
  linkedUserId       String?
  linkedDriverId     String?
  linkedLoadId       String?
  permissionsJson    Json?
  expiresAt          DateTime?
  acceptedAt         DateTime?
  revokedAt          DateTime?
  createdAt          DateTime @default(now())
  updatedAt          DateTime @updatedAt
}
```

Rules:

- Driver interface access is owned by the organization and can be linked to an existing `Driver` record.
- Customer/shipper portals are limited to shipments/records explicitly shared with them.
- Carrier response portals should be limited to the relevant load offer, response, documents, and award/decline status.
- Invited portal users do not see internal notes, margin, provider settings, workspace billing, or unrelated records.
- The owning workspace plan controls how many invited users/portals are allowed.

## Broker load-distribution usage limits

Freight Broker Workspace needs separate records for carrier contacts, suppression, distribution batches, recipients, and response events before live scale.

Recommended future models:

```prisma
model BrokerCarrierContact {
  id              String @id @default(uuid())
  organizationId  String
  carrierName     String
  contactName     String?
  email           String?
  phone           String?
  mcNumber        String?
  dotNumber       String?
  relationshipStatus String @default("ACTIVE")
  optedOutAt      DateTime?
  suppressionReason String?
  createdAt       DateTime @default(now())
  updatedAt       DateTime @updatedAt
}

model BrokerLoadDistributionBatch {
  id              String @id @default(uuid())
  organizationId  String
  loadId          String
  channel         String
  status          String @default("DRAFT")
  recipientCount  Int @default(0)
  sentCount       Int @default(0)
  failedCount     Int @default(0)
  suppressedCount Int @default(0)
  provider        String?
  providerMessageId String?
  createdByUserId String?
  approvedByUserId String?
  approvedAt      DateTime?
  sentAt          DateTime?
  metadataJson    Json?
  createdAt       DateTime @default(now())
  updatedAt       DateTime @updatedAt
}

model BrokerLoadDistributionRecipient {
  id              String @id @default(uuid())
  batchId         String
  carrierContactId String?
  email           String
  status          String @default("PENDING")
  responseStatus  String?
  respondedAt     DateTime?
  failureReason   String?
  createdAt       DateTime @default(now())
}
```

Usage limits should be entitlements, not hard-coded page logic:

- carrier list size;
- email recipients per batch;
- email sends per month;
- external load-board postings per month;
- internal load-board postings per month;
- featured postings;
- carrier responses retained;
- SendGrid-like provider access;
- abuse/complaint thresholds.

Rules:

- Broker load blasts require review/approval before sending.
- Suppression/opt-out must be honored.
- Bounce/failure/complaint handling must be visible to Workspace Admin and Super Admin in plain language.
- Raw provider diagnostics and API keys remain hidden.
- Super Admin must see volume, failed sends, abuse risk, provider cost, and billing impact.

## Internal load-board access rules

The internal load board is a platform layer. It should not be built as a single broker page.

Recommended access controls:

- workspace type;
- plan;
- subscription status;
- verification/trust state;
- posting entitlement;
- search entitlement;
- response entitlement;
- billing status;
- abuse flags;
- Super Admin override.

Rules:

- Freight brokers may post when verified and entitled.
- Carriers, owner-operators, fleets, and dispatchers may search/respond when entitled.
- Shippers may request freight or post only if a later shipper product supports it.
- Super Admin must be able to pause, remove, flag, or review postings.
- Marketplace abuse controls must exist before public network effects are expanded.

## Billing gate override rules

Billing gates decide whether a workspace can use plan-limited and provider-cost features.

Recommended enum:

```prisma
WorkspaceBillingGateState {
  EVALUATING
  ALLOW
  WARN
  RESTRICT_HIGH_COST
  READ_ONLY
  SUSPENDED
  INTERNAL_ALLOW
}
```

Recommended explicit override model:

```prisma
model WorkspaceBillingGateOverride {
  id                String @id @default(uuid())
  organizationId    String
  workspaceSubscriptionId String?
  state             WorkspaceBillingGateState
  reason            String
  startsAt          DateTime @default(now())
  expiresAt         DateTime?
  createdByUserId   String?
  revokedByUserId   String?
  revokedAt         DateTime?
  metadataJson      Json?
  createdAt         DateTime @default(now())
  updatedAt         DateTime @updatedAt
}
```

Rules:

- Overrides must not be silent.
- Every override needs a human-readable reason.
- Temporary overrides should expire.
- Revoked overrides should be preserved, not deleted.
- Work surfaces should show simple messages; Super Admin should see the detailed reason, actor, and timing.
- Billing status gates must be centralized through a shared entitlement/access service, not scattered across page components.

## Super Admin audit model

Recommended generic audit table:

```prisma
model PlatformAdminAuditEvent {
  id              String @id @default(uuid())
  actorUserId     String?
  organizationId  String?
  entityType      String
  entityId        String?
  action          String
  beforeJson      Json?
  afterJson       Json?
  reason          String?
  visibleSummary  String?
  ipAddress       String?
  userAgent       String?
  createdAt       DateTime @default(now())
}
```

Audit required for:

- workspace type changes;
- account class changes;
- plan assignment;
- trial extension/cancel/comp;
- billing gate override;
- subscription suspension/reactivation;
- entitlement override;
- phone-number assignment override;
- provider availability override;
- broker distribution limit override;
- internal load-board pause/removal/flag actions;
- workspace deletion/recovery decisions.

Rules:

- Audit records should preserve before/after state when practical.
- Browser-facing audit summaries should be plain and safe.
- Secrets, raw API keys, raw auth headers, and provider tokens must never be written into audit `beforeJson` or `afterJson`.

## Recommended entitlement model direction

Existing plan booleans and JSON are useful for early builds, but live billing will need clearer capabilities.

Recommended future staged approach:

1. Keep current `SubscriptionPlan` fields while adding workspace type visibility and plan family.
2. Add centralized entitlement calculation service.
3. Add `WorkspaceUsageCounter` or `WorkspaceUsageEvent` for countable usage.
4. Normalize entitlements only after repeated JSON rules become hard to maintain.

Potential usage counter:

```prisma
model WorkspaceUsageCounter {
  id              String @id @default(uuid())
  organizationId  String
  usageKey        String
  periodKey       String
  usedCount       Int @default(0)
  limitCount      Int?
  metadataJson    Json?
  updatedAt       DateTime @updatedAt

  @@unique([organizationId, usageKey, periodKey])
}
```

Example usage keys:

- `broker.email_recipients.monthly`;
- `broker.load_board_posts.monthly`;
- `phone.sms_segments.monthly`;
- `phone.call_minutes.monthly`;
- `cori.actions.monthly`;
- `routing.weather_checks.monthly`;
- `documents.storage_mb`;
- `internal_load_board.responses.monthly`.

## Recommended schema implementation order

v412 does **not** change Prisma. When approved, schema work should be staged in this order:

### Phase 1 — Core workspace/subscription identity

- Add `WorkspaceType` enum.
- Add `WorkspaceAccountClass` enum.
- Add nullable `Organization.workspaceType`.
- Add `Organization.accountClass` defaulting to `PAID_WORKSPACE`.
- Add plan family / plan visibility fields to `SubscriptionPlan`.
- Add simple `PlatformAdminAuditEvent`.

### Phase 2 — Trial and registration workflow

- Add `WorkspaceTrialPolicy`.
- Add `WorkspaceRegistrationIntent`.
- Add registration state fields and Super Admin visibility.

### Phase 3 — Owned interfaces and invited portals

- Add `WorkspaceAccessInvite`.
- Add limited portal/access permission JSON first.
- Strengthen driver interface ownership and invited customer/carrier portal boundaries.

### Phase 4 — Usage limits and billing gates

- Add `WorkspaceUsageCounter` or `WorkspaceUsageEvent`.
- Add `WorkspaceBillingGateOverride`.
- Centralize entitlement/billing gate checks.

### Phase 5 — Broker distribution and internal load board

- Add broker carrier contact/distribution/suppression models.
- Add internal load-board posting/response/award models.
- Add Super Admin abuse/trust visibility and usage billing hooks.

## What must not happen next

- Do not change sign-up UI until workspace type, public plan visibility, and trial behavior are represented or safely staged.
- Do not make drivers independent paid workspaces by default.
- Do not use inferred workspace type as a hard entitlement gate.
- Do not build broker email blasts without suppression, usage limits, approval, and audit planning.
- Do not build internal load-board posting without Super Admin policy and abuse controls.
- Do not scatter billing checks across many pages.
- Do not expose Stripe, Twilio, SendGrid-like, SMTP, maps, weather, AI, or load-board provider secrets in browser-facing pages.

## Next recommended build

Proceed with the first safe Prisma schema foundation only after this design is approved:

- workspace type enum;
- account class enum;
- nullable organization fields;
- plan family and public/visibility fields;
- initial Super Admin audit table;
- no registration UI changes yet.


## v413 implementation note

The Phase 1 schema foundation from this design review is now implemented. The new durable fields/models are:

- `WorkspaceType`;
- `WorkspaceAccountClass`;
- nullable `Organization.workspaceType`;
- nullable `Organization.accountClass`;
- `SubscriptionPlanFamily`;
- `SubscriptionPlanVisibility`;
- `SubscriptionPlan.planFamily`;
- `SubscriptionPlan.planVisibility`;
- `SubscriptionPlan.visibleWorkspaceTypesJson`;
- `SuperAdminAuditEvent`.

This is a foundation only. Do not use these fields as hard entitlement gates until Super Admin classification workflow, registration flow, plan visibility enforcement, billing gates, and audit-backed override behavior are explicitly designed and built.

## v414 update — guarded classification workflow

v414 adds the first Super Admin workflow for applying the v413 stored classification fields to existing workspaces.

The workflow allows Super Admin to set `Organization.workspaceType` and `Organization.accountClass` together, or clear both for continued review. Each change writes a `SuperAdminAuditEvent` with before and after values.

This is intentionally not an enforcement build. Registration UI, public plan selection, Stripe handoff, trial creation, billing gates, plan visibility enforcement, broker load distribution limits, owned driver interface records, invited portal records, and internal load-board access rules remain future phases.
