---
title: "Plans & Entitlements"
description: "Learn how Vuesion configures workspace features with plans, overrides, and effective entitlements, and how to add and enforce a new feature."
canonical_url: "https://www.vuesion.dev/docs/core-concepts/plans-and-entitlements"
---

> Index of every page on this site: [llms.txt](https://www.vuesion.dev/llms.txt)

# Plans & Entitlements

Most products eventually offer different configurations to different customers.

One workspace may invite three members, another twenty. One receives community support, another a dedicated contact.

Vuesion models this with plans and entitlements.

A plan defines the product configuration available to a workspace:

```text
Free
├── maxMembers = 3
└── supportLevel = COMMUNITY

Pro
├── maxMembers = 20
└── supportLevel = PRIORITY
```

Every workspace is assigned one plan. A workspace may additionally receive feature-specific overrides.

Application behavior never asks which plan a workspace has. It asks what the workspace is entitled to.

## The central rule

Product code depends on features, not on plan names or keys.

Instead of checking the plan:

```ts
// Don't do this
if (plan.key === 'pro') {
  // ...
}
```

Vuesion resolves the **effective entitlement** of a workspace and makes decisions based on it:

```text
effective plan          (subscription, trial or assigned plan)
            │
            ▼
       PlanFeature
            │
            ▼
WorkspaceFeatureOverride
            │
            ▼
  effective entitlement
            │
            ▼
 policy / application behavior
```

This keeps plans pure business configuration. Plans can be renamed, replaced, or reconfigured without touching product code.

## Architecture

```text
Feature Catalog          (code)
            │
            ▼
        Feature               (database projection)
            │
            ▼
   Plan ── PlanFeature
            │
            ▼
      WorkspacePlan ── Subscription, WorkspaceTrial
            │
            ▼
WorkspaceFeatureOverride
            │
            ▼
   Entitlement Service
            │
            ▼
 Policies / Product API
            │
            ▼
       Product UI
```

- **Feature Catalog**: the code-defined source of truth for feature keys, feature types, and ENUM values.
- **Feature**: the database table that persists the Feature Catalog for relational references. It is not an admin-managed catalog.
- **Plan**: a named product configuration. Plans are database-owned business configuration managed by Platform Admins.
- **PlanFeature**: configures the value of one feature for one plan.
- **PlanPrice**: one purchasable billing option of a plan. It does not affect entitlements (see [Plan prices](https://www.vuesion.dev/docs/core-concepts/billing-and-subscriptions#plan-prices)).
- **WorkspacePlan**: assigns exactly one plan to a workspace. It is not a billing subscription.
- **Subscription**: the local projection of a provider subscription. While a workspace has a current subscription, it decides the workspace plan (see [Subscriptions](https://www.vuesion.dev/docs/core-concepts/billing-and-subscriptions#subscriptions)).
- **WorkspaceTrial**: a time-limited trial of a plan for one workspace. While it is active, the workspace has the entitlements of the trial plan (see [trialDays](#trialdays)).
- **WorkspaceFeatureOverride**: replaces the plan value of one feature for one specific workspace.
- **Entitlement Service**: resolves the effective feature values of a workspace.
- **Policies**: use effective entitlements wherever a feature needs authoritative backend enforcement.

The relevant code lives in:

```text
src/shared/domain/feature/feature-catalog.ts               Feature Catalog
src/server/domain/feature/                                 feature synchronization
src/server/domain/plan/                                    plans, default plan, bootstrap
src/server/domain/plan-feature/                            plan feature values
src/server/domain/plan-price/                              plan prices
src/server/domain/subscription/                            subscriptions, plan synchronization and emails
src/server/domain/workspace-plan/                          plan assignment, effective plan changes
src/server/domain/workspace-trial/                         plan trials and their emails
src/server/domain/workspace-feature-override/              workspace overrides
src/server/domain/entitlement/use-entitlement-service.ts   effective entitlements
```

## Feature types

Every feature has one of three types.

### BOOLEAN

A capability that is granted or not.

```text
apiKeys = true
```

The default catalog currently contains no BOOLEAN feature, but the type is fully supported. The guide below adds one as an example.

### NUMBER

A numeric limit, such as the maximum number of workspace members:

```text
maxMembers = 3
```

A NUMBER value is either a finite, non-negative integer or explicitly unlimited. `0` is a valid finite value.

Unlimited is not encoded as a magic number such as `-1` or `Infinity`. It is a separate state:

```ts [Entitlement.ts]
export type NumberEntitlement = { value: number; unlimited: false } | { value: null; unlimited: true };
```

### ENUM

One value out of a fixed set defined in the Feature Catalog:

```text
supportLevel = COMMUNITY
```

The current support levels are `COMMUNITY`, `EMAIL`, `PRIORITY`, and `DEDICATED`.

## Feature Catalog

Features are defined in code:

```ts [feature-catalog.ts]
export const SupportLevel = {
  COMMUNITY: 'COMMUNITY',
  EMAIL: 'EMAIL',
  PRIORITY: 'PRIORITY',
  DEDICATED: 'DEDICATED',
} as const;

export const Feature = {
  MAX_MEMBERS: 'maxMembers',
  SUPPORT_LEVEL: 'supportLevel',
} as const;

export const FeatureCatalog = {
  [Feature.MAX_MEMBERS]: {
    type: FeatureType.NUMBER,
  },
  [Feature.SUPPORT_LEVEL]: {
    type: FeatureType.ENUM,
    values: Object.values(SupportLevel),
  },
} as const;
```

The catalog defines:

- The stable technical key of every feature
- The type of every feature
- The allowed values of ENUM features

Application code refers to features through the catalog, for example `Feature.MAX_MEMBERS`, instead of using string literals.

Platform Admins cannot create features. A feature only makes sense if the application understands it, and only code can provide that understanding.

The catalog is still persisted in the `Feature` table:

```text
Code      → defines what the application understands
Database  → provides persisted identities and foreign keys
```

`PlanFeature` and `WorkspaceFeatureOverride` reference `Feature` rows, so the database can enforce relational integrity.

## Feature synchronization

The seed (`prisma/seed.ts`) initializes the plan and entitlement data in two steps:

```text
sync Feature Catalog
        │
        ▼
bootstrap initial plan if necessary
```

Run it after applying migrations, locally and on every deployment:

```bash
npm run db:migrate-deploy
npm run db:seed
```

Feature synchronization:

- Creates missing `Feature` rows
- Is safe to run repeatedly
- Verifies the type of existing `Feature` rows against the catalog
- Fails with a clear error when a persisted type differs from the catalog
- Never deletes `Feature` rows that are no longer part of the catalog

Changing the type of an existing feature is therefore not a normal deployment operation. See **Changing a feature type** below.

## Initial plan bootstrap

A fresh installation must be able to create workspaces immediately.

If no plan exists at all, the seed creates the initial plan:

```text
name: Free
key: free
active: true
default: true

maxMembers: 3
supportLevel: COMMUNITY
```

The plan and its plan features are created in one transaction.

**Free is bootstrap data, not a permanent system plan.**

Once at least one plan exists, the seed never creates or modifies plans again. As a result:

- Admin changes to the plan are preserved
- A deleted Free plan is not recreated
- Free has no special runtime behavior
- Application code must never depend on `key === 'free'`

## Plans

A plan has the following properties.

### key

The stable technical identifier of the plan. It is set on creation and cannot be changed.

The key identifies the plan in administration. It must not be used for feature checks.

### name

The human-facing name of the plan. Several plans may share the same display name if the product owner chooses so, for example when a newer edition of a plan replaces an older one.

### isActive

`isActive` means: **this plan may be newly assigned.**

It does not mean that workspaces lose their entitlements. Workspaces already assigned to an inactive plan keep it and continue to resolve its features normally.

### isDefault

`isDefault` means: **new workspaces are automatically assigned to this plan.**

It does not affect existing workspaces. `isDefault` is not an editable setting of a plan. It is changed only through the explicit default plan operation described below.

### trialDays

`trialDays` means: **a workspace can trial this plan for this many days.** `null` means the plan cannot be trialed.

The value must be a positive integer. The default plan never has a trial. Each trial stores its end date when it starts, so later changes to `trialDays` do not affect running trials. Active trials change the [effective plan](#effective-entitlements).

#### Configuring trials

Platform Admins set `trialDays` in the plan form of the administration, when creating and editing a plan (`trialDays` in `POST /api/admin/plans` and `PATCH /api/admin/plans/:id`, or `usePlanService().createPlan()` and `updatePlan()` on the server). Leave the field empty for a plan that cannot be trialed. To ship trials as initial data, set `trialDays` in the seed or the demo fixture; the demo fixture gives Pro and Business 14 days.

The default plan cannot have a trial: setting `trialDays` on it returns `409`, the form shows a note instead of the field, and a plan loses its `trialDays` when it becomes the default. Changing `trialDays` never affects trials that have already started. Trials need no other configuration, but the [`workspace-trial-expiry` task](#trial-expiry-task) must be registered.

#### Starting a trial

The workspace owner starts a trial from the Plan & Billing section of the workspace settings with the trial button next to the plan. The workspace then receives the entitlements of the trial plan immediately and keeps its assigned plan.

`POST /api/workspaces/:id/billing/trial` accepts a `planId`. It requires the same permission as a checkout (`canManageWorkspaceBilling`) and succeeds only if all of these are true:

- The plan exists and is active, has `trialDays`, and is not the default plan.
- The workspace is assigned to the default plan and has no current subscription.
- The workspace has no `ACTIVE` trial.
- The user has never started a trial for this plan, in any workspace and with any status, including trials of deleted workspaces. A trial for another plan, such as a newer version of a deactivated plan, is allowed.

The rules are implemented once, in `useWorkspaceTrialService().getTrialIneligibilities()`. The billing response (`canStartTrial` per plan) and the start use it; the UI does not repeat them. A violated rule returns `409` with `data.code`, an unknown plan returns `404`.

The start locks the workspace and the plan in one transaction, so concurrent requests create exactly one trial, and deleting a plan cannot race a trial start. Starting a checkout during a trial remains possible.

#### Trial lifecycle

Every trial ends with exactly one status:

<table>
<thead>
  <tr>
    <th>
      Status
    </th>
    
    <th>
      Set when
    </th>
  </tr>
</thead>

<tbody>
  <tr>
    <td>
      <code>
        EXPIRED
      </code>
    </td>
    
    <td>
      <code>
        endsAt
      </code>
      
       has passed. <code>
        endedAt
      </code>
      
       is <code>
        endsAt
      </code>
      
      .
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        CONVERTED
      </code>
    </td>
    
    <td>
      The workspace gets an active paid subscription during the trial, whether for the trial plan or another.
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        CANCELED
      </code>
    </td>
    
    <td>
      A Platform Admin assigns a plan to the workspace during the trial or ends the trial.
    </td>
  </tr>
</tbody>
</table>

- **Expiry**: the hourly `workspace-trial-expiry` task expires all `ACTIVE` trials past their `endsAt`, each in its own transaction, and logs failures. Starting a trial and synchronizing a subscription that grants a paid plan also expire the ended trial of the workspace first, so they do not wait for the task.
- **Conversion**: the subscription synchronization (webhook, reconciliation, demo checkout) converts the active trial. A trial past its end is expired instead. A subscription that ends later does not make the converted trial effective again.
- **Admin assignment**: assigning a plan ends the active trial, so the assigned plan takes effect immediately. A workspace with a current subscription still rejects the assignment.

#### Trial expiry task

The `workspace-trial-expiry` task expires ended trials and sends the trial reminders. It must be registered in `nitro.scheduledTasks` of your `nuxt.config.ts`, as Vuesion does hourly together with `subscription-reconciliation`:

```ts [nuxt.config.ts]
scheduledTasks: {
  '0 * * * *': ['subscription-reconciliation', 'workspace-trial-expiry'],
},
```

Without it, a trial still stops granting entitlements at `endsAt`, because the end is evaluated at read time. But its status stays `ACTIVE`, no reminder is sent, and the expired email is only sent when a trial start or the synchronization of a paid subscription expires it. See **Development → Configuration → Scheduled tasks** for the requirements of the schedule, and run the task manually in development with `/_nitro/tasks/workspace-trial-expiry`.

#### Administering trials

On the workspace detail page in the administration, Platform Admins see the active trial of the workspace: trial plan (also if it was deactivated), start, end and the user who started it. The workspace list marks workspaces with an active trial. Without an active trial, nothing about trials is shown.

- **Extend**: `PATCH /api/admin/workspaces/:id/trial/extend` with `endsAt` sets a later end. Only active trials can be extended, and the new end must be later than the current one, otherwise the request returns `409` with `data.code` `TRIAL_NOT_ACTIVE` or `TRIAL_END_NOT_LATER`. If the new end is more than 3 days away, `reminderSentAt` is cleared so the [reminder](#trial-emails) is sent again. Extending does not change the effective plan.
- **End**: `PATCH /api/admin/workspaces/:id/trial/end` cancels the active trial with the same cancellation as an admin plan assignment (`CANCELED`, reason `TRIAL_CANCELED`). The assigned plan takes effect immediately. A trial that is not active returns `409` with `TRIAL_NOT_ACTIVE`.

Both run in the workspace lock and check the rules again inside it. Platform Admins cannot start trials, and there is no trial history in the administration.

#### Trial emails

All current owners of the workspace receive these emails in their own language, with a link to the Plan & Billing section (`/workspaces/:id/settings#plan-and-billing`, which opens the section by URL):

<table>
<thead>
  <tr>
    <th>
      Email
    </th>
    
    <th>
      Sent
    </th>
    
    <th>
      Contains
    </th>
  </tr>
</thead>

<tbody>
  <tr>
    <td>
      Reminder
    </td>
    
    <td>
      By the hourly <code>
        workspace-trial-expiry
      </code>
      
       task, within the last 3 days
    </td>
    
    <td>
      Trial plan, end date in the recipient's locale and time zone
    </td>
  </tr>
  
  <tr>
    <td>
      Expired
    </td>
    
    <td>
      When the trial expires, whether by the task, a trial start or a sync
    </td>
    
    <td>
      Trial plan, the plan the workspace is now on
    </td>
  </tr>
</tbody>
</table>

- The reminder is sent only for trials longer than 3 days and **at most once per trial end**: `WorkspaceTrial.reminderSentAt` is set within the workspace lock before the email is sent. A failed send is logged and not retried. Extending a trial clears it, so the new end gets a reminder.
- The expired email is a consequence of `TRIAL_EXPIRED` (see [Effective plan changes](#effective-plan-changes)), so every expiry path sends it.
- Start, conversion and cancellation send no email, and there is no in-app banner: the billing section shows the active trial and its end date.
- The locale comes from the user settings of the recipient, `en-US` without settings. Seeded demo users receive no emails (see **Development → Configuration → Emails**).

#### Subscription emails

All current owners of the workspace receive these emails in their own language, with a link to the Plan & Billing section. They follow the status transition of the subscription, not the effective plan change, so a trial that converts to a subscription of the same plan is still confirmed:

<table>
<thead>
  <tr>
    <th>
      Email
    </th>
    
    <th>
      Sent
    </th>
    
    <th>
      Contains
    </th>
  </tr>
</thead>

<tbody>
  <tr>
    <td>
      Active
    </td>
    
    <td>
      A subscription becomes <code>
        ACTIVE
      </code>
      
       or <code>
        PAST_DUE
      </code>
      
       from another status or none, or its plan changes while it stays paid
    </td>
    
    <td>
      Workspace, subscribed plan
    </td>
  </tr>
  
  <tr>
    <td>
      Ended
    </td>
    
    <td>
      A subscription leaves <code>
        ACTIVE
      </code>
      
       or <code>
        PAST_DUE
      </code>
      
       for <code>
        UNPAID
      </code>
      
      , <code>
        PAUSED
      </code>
      
       or <code>
        EXPIRED
      </code>
      
      , whether cancelled, expired or unpaid
    </td>
    
    <td>
      Workspace, previous plan, plan it is now on
    </td>
  </tr>
</tbody>
</table>

- The previous state is read within the workspace lock, so webhook retries and reconciliation runs of an unchanged state send nothing. Changes of `cancelAtPeriodEnd`, the period, the billing interval of the same plan and moves between `ACTIVE` and `PAST_DUE` send nothing either.
- Admin plan changes send no email.
- The billing provider sends payment receipts, renewal reminders and dunning emails for unpaid subscriptions. Vuesion does not duplicate them and only informs about the plan of the workspace. See **Development → Configuration → Emails** for all emails of the application.

## Default plan management

Platform Admins can make an active plan the default:

```text
Free  = default
Pro   = active

Set Pro as default

Free  = ordinary plan
Pro   = default
```

The switch is atomic. There is always exactly one active default plan, never none and never two.

- Only active plans can become the default.
- The current default cannot be deactivated or deleted. Make another plan the default first.
- Setting the current default again succeeds without changes.
- A plan loses its `trialDays` when it becomes the default.

Changing the default does not migrate existing workspaces:

```text
Workspace A → Free

change default to Pro

Workspace A → Free
new Workspace B → Pro
```

Use **Set as default** on the plan detail page in the administration, or `usePlanService().setDefaultPlan(planId)` on the server.

## Editing a plan

Editing a plan changes the configured entitlements of every workspace currently assigned to it.

```text
Pro.maxMembers = 20

changed to

Pro.maxMembers = 10
```

All workspaces on Pro now resolve `maxMembers = 10`.

Plans are not versioned. This is intended behavior.

If existing customers should keep an old product configuration, create another plan instead of editing the existing one:

```text
name: Pro
key: pro-2026

name: Pro
key: pro-2027
```

Existing workspaces stay on the old plan, while new workspaces are assigned to the new one, for example by making it the default.

## WorkspacePlan

Every workspace is assigned exactly one plan:

```text
Workspace → WorkspacePlan → Plan
```

When a workspace is created, it receives the current active default plan. Creating the workspace and its plan assignment happens atomically, so a workspace never exists without a plan.

If no active default plan or more than one exists, workspace creation fails with a clear error instead of guessing.

**WorkspacePlan represents the assignment of a product configuration, not payment state.**

It deliberately contains no provider, subscription ID, price, currency, billing interval, quantity, or seat billing state.

## Workspace feature overrides

An override replaces the plan value of one feature for one specific workspace.

```text
Pro
maxMembers = 20

Acme workspace override
maxMembers = 50

Effective:
maxMembers = 50
```

Overrides use replacement semantics. They never add to, multiply, or merge with the plan value.

An override survives a plan change:

```text
Workspace
Plan = Pro
maxMembers override = 50

change plan → Business

maxMembers override remains 50
```

An override may also configure a feature that the plan does not configure.

Removing the override deletes it, and the workspace falls back to the plan value, if the plan configures one.

## Effective entitlements

The Entitlement Service resolves the effective entitlements of a workspace:

```ts
const entitlements = await useEntitlementService().getWorkspaceEntitlements(workspaceId);
```

First, the effective plan of the workspace is resolved in this order:

1. The plan of an active paid subscription (`ACTIVE` or `PAST_DUE`), which billing assigns as the WorkspacePlan
2. The plan of an active trial
3. The assigned WorkspacePlan

A trial is active while its status is `ACTIVE` and its `endsAt` lies in the future. `endsAt` is evaluated at read time, so a trial past its end is ignored even if its status is still `ACTIVE`. A workspace has at most one `ACTIVE` trial.

### Effective plan changes

An effective plan change is a write that changes the result of this resolution for an existing workspace, in either direction: a subscription synchronization (webhook, reconciliation, cancellation, price change, demo checkout), a manual plan assignment by a Platform Admin, the start of a trial, or the end of a trial (expiry, conversion, cancellation). A trial expires without a write at its `endsAt`, so the expiry handles that change. Writes that leave the effective plan unchanged, such as a webhook retry or the conversion of a trial into a subscription of the same plan, are not changes. The first plan assignment of a new workspace is not a change either.

All of these paths call `handleEffectivePlanChange` in `src/server/domain/workspace-plan/handle-effective-plan-change.ts` with the previous and the new effective plan and a reason, within the transaction and the workspace lock of their write. Consequences of a plan change belong in this function, not in the paths.

Consequences that must happen within the transaction are done in `handleEffectivePlanChange`. Consequences that must wait for the commit, such as emails, are returned from it as `PostCommitConsequence` (`{ name, run }`) and added by reason:

```ts [handle-effective-plan-change.ts]
if (change.reason === 'TRIAL_EXPIRED') {
  consequences.push({ name: `trial-expired-email:${workspaceId}`, run: () => sendEmails(workspaceId) });
}
```

Paths run their transaction with `runInTransactionWithConsequences` from `post-commit-consequences.ts`, which requires the callback to return `{ result, consequences }`. The consequences run after the commit and are discarded on a rollback. A failing consequence is logged, never fails the caller, is not retried, and is not an Incident. Consequences read the data they need when they run, so they see the state after the commit.

The features of the effective plan then follow a single precedence rule:

```text
PlanFeature
            │
            ▼
WorkspaceFeatureOverride   (replaces the plan value if present)
            │
            ▼
     effective value
```

The result only contains configured features:

```ts [Entitlement.ts]
export type EntitlementValue = boolean | string | NumberEntitlement;

export type WorkspaceEntitlements = Partial<Record<FeatureKey, EntitlementValue>>;
```

BOOLEAN features resolve to `boolean`, ENUM features to their value as `string`, and NUMBER features to a `NumberEntitlement`.

The resolver is a read-only service. It does not invent defaults, create plan assignments, repair configuration, fall back to Free, or change any data.

It fails with a clear server error when the stored data is inconsistent:

- The workspace has no plan assigned.
- A stored feature is not part of the catalog.
- A stored feature type differs from the catalog.
- A stored value is invalid for its feature type.

## Missing features

The system intentionally preserves the difference between these states:

```text
apiKeys = false          configured, not granted
apiKeys missing          not configured
```

```text
maxMembers = 0           no members allowed
maxMembers unlimited     no limit
maxMembers missing       not configured
```

Do not treat a missing value as `false` or unlimited unless your product explicitly defines that behavior for the feature.

The member limit, for example, treats a missing `maxMembers` entitlement as a configuration error: inviting members fails until a plan or override configures the feature.

## Feature vs. policy

Entitlements and policies answer different questions.

An **entitlement** describes what a workspace is entitled to:

```text
Does this workspace have API keys?
How many members may it have?
What support level does it receive?
```

A **policy** decides whether a concrete operation is allowed right now. It may combine several inputs:

- User authorization, such as the workspace role
- Entitlements
- Domain state

For example, *"Can this user invite another member to this workspace?"* depends on:

```text
the user's workspace role
+
the maxMembers entitlement
+
the current members and pending invitations
```

```text
Entitlements describe product capability.
Policies and domain logic enforce it.
```

See **Authorization** for how policies work in general.

## Backend enforcement

```text
Frontend entitlement checks improve the user experience.

Backend policies enforce product rules.
```

`maxMembers` is the real example in Vuesion.

Member slots are counted as:

```text
used slots
=
current members
+
active pending invitations
```

An active invitation reserves a member slot. Expired invitations do not.

The effective `maxMembers` entitlement is enforced when:

- Inviting a member
- Resending an invitation
- Accepting an invitation

Resending an expired invitation reserves a slot again, so it checks members plus active pending invitations. Resending an active invitation only checks the current members, because the invitation already holds its slot; it succeeds exactly when the invitation could be accepted now.

Accepting an invitation turns its reserved slot into a membership, so it only checks the current members against the limit.

The rule itself is a policy in `workspace.policy.ts`:

```ts [workspace.policy.ts]
export const canAddWorkspaceMember = (maxMembersEntitlement: NumberEntitlement, usedSlots: number) => {
  return maxMembersEntitlement.unlimited || usedSlots < maxMembersEntitlement.value;
};
```

If no slot is available, the API responds with `403 The workspace has reached its member limit.` and the error data `{ code: 'WORKSPACE_MEMBER_LIMIT' }`. The invitation page uses the code to tell the invitee that the workspace has no free seat and that they should contact the workspace owner.

### Over-limit policy

```text
Existing things stay.
New things are blocked.
Nothing is removed automatically.
```

A workspace can exceed a limit after a downgrade, a trial or subscription ending, a lowered plan value or a changed override. The state is derived from the effective entitlements at read time; nothing is stored or enforced when the limit changes.

For `maxMembers`:

<table>
<thead>
  <tr>
    <th>
      Operation
    </th>
    
    <th>
      Above the limit
    </th>
  </tr>
</thead>

<tbody>
  <tr>
    <td>
      Existing members
    </td>
    
    <td>
      Keep access and roles
    </td>
  </tr>
  
  <tr>
    <td>
      Pending invitations
    </td>
    
    <td>
      Stay valid
    </td>
  </tr>
  
  <tr>
    <td>
      Creating an invitation
    </td>
    
    <td>
      Blocked
    </td>
  </tr>
  
  <tr>
    <td>
      Resending an expired invitation
    </td>
    
    <td>
      Blocked until a slot is free
    </td>
  </tr>
  
  <tr>
    <td>
      Resending an active invitation
    </td>
    
    <td>
      Blocked only when it could not be accepted
    </td>
  </tr>
  
  <tr>
    <td>
      Accepting an invitation
    </td>
    
    <td>
      Blocked only while the current members alone have reached the limit
    </td>
  </tr>
  
  <tr>
    <td>
      Removing members, revoking invitations
    </td>
    
    <td>
      Always possible
    </td>
  </tr>
</tbody>
</table>

The member slots in workspace settings show a dedicated over-limit state when used slots exceed the limit. Users who manage billing see the plans action, others are asked to contact the workspace owner.

Developers who add a new limit follow the same policy: block only operations that add new usage, never remove or change existing data when a limit drops, and always allow operations that free capacity.

### Capacity limits and concurrency

Member limit enforcement is safe against concurrent requests. Capacity-changing operations of the same workspace run one after another inside a database transaction, so simultaneous invitations cannot exceed the effective limit.

This is why the member limit is evaluated in the workspace invitation service rather than in the controller: the check and the write must happen atomically.

If a future entitlement represents a hard capacity limit, enforce the check and the mutation atomically on the backend as well.

## Frontend usage

The product frontend reads the effective entitlements of a workspace through a scoped API:

```text
GET /api/workspaces/:id/entitlements
```

The endpoint:

- Requires access to the workspace
- Returns the same effective values as the Entitlement Service
- Is read-only

The product UI therefore does not need to know which plan a workspace has or whether a value comes from an override.

On the client, `useWorkspaceActions()` provides `fetchWorkspaceEntitlements(workspaceId)` and `currentWorkspaceEntitlements`.

The workspace settings use them to show member slot usage and to disable the invite action when the limit is reached. The backend still enforces the limit, for example when the displayed state is outdated.

## Platform administration

Platform Admins configure plans and workspaces in the **Platform** section of the sidebar:

```text
Platform
├── Plans
└── Workspaces
```

**Plans** (`/admin/plans`)

- Create plans
- Edit plan names
- Activate and deactivate plans
- Configure plan features
- Configure plan prices
- Configure the trial days of a plan
- Set an active plan as default
- Delete plans when allowed

**Workspaces** (`/admin/workspaces`)

- Search existing workspaces by name or ID
- See the assigned plan
- Assign another active plan, unless the workspace has a current subscription (this ends an active trial)
- See, extend and end the active trial (see [Administering trials](#administering-trials))
- Configure workspace feature overrides

The workspace administration manages plan configuration and trials only. Workspace profiles, members, and invitations remain managed in the workspace itself.

The feature controls in both screens are generated from the Feature Catalog, so a new feature needs no feature-specific admin UI.

### Platform Admin security

Platform administration is authorized by `User.isAdmin`.

It is separate from the workspace roles `OWNER`, `ADMIN`, and `MEMBER`. A workspace owner or admin is not a Platform Admin.

All `/api/admin/...` endpoints are protected on the server with `getAdminServerSession(event)`, which returns `401` without a session and `403` for users who are not Platform Admins.

Hiding the sidebar section and redirecting the admin pages only improve the user experience. They are not the security boundary.

Promote a user to Platform Admin directly in the database, for example:

```sql
UPDATE "User" SET "isAdmin" = true WHERE "email" = 'admin@example.com';
```

## Deactivating and deleting plans

- The current default plan cannot be deactivated.
- The current default plan cannot be deleted.
- A plan assigned to workspaces cannot be deleted. Deactivate it instead.
- An inactive plan may remain assigned to existing workspaces, which continue to resolve it normally.
- A plan with prices cannot be deleted. Delete its prices first, or deactivate the plan instead.
- A plan with an active trial cannot be deleted. Deactivate it instead.

Deleting a plan also deletes its plan features and its inactive trials. Deleting a workspace deletes its plan assignment, overrides, and expired subscriptions, and keeps its trials without the workspace reference; a workspace with a current subscription cannot be deleted.

## Removing a feature

Removing a feature from the catalog is more than deleting a constant.

Existing `PlanFeature` and `WorkspaceFeatureOverride` rows may still reference the feature. The resolver intentionally fails when stored configuration contains a feature the application no longer understands, so every workspace with such a row would fail to resolve its entitlements.

Remove a feature in this order:

```text
1. Stop using the feature in product behavior.
2. Delete or migrate its PlanFeature and WorkspaceFeatureOverride rows.
3. Remove the feature from the catalog and its labels.
4. Deploy.
```

Step 2 can be a migration created with `npm run db:migrate-create` that deletes the rows and optionally the `Feature` row itself. If your deployment applies migrations before the new code serves requests, as recommended above, steps 2 to 4 can ship in the same deployment.

The `Feature` row is not deleted automatically. A leftover row is harmless: the administration ignores features that are not part of the catalog.

## Changing a feature type

Do not change the type of an existing feature key, for example from NUMBER to BOOLEAN or from ENUM to NUMBER.

Feature synchronization detects the type mismatch and fails, and existing values could not be interpreted with the new type anyway.

If the meaning of a feature fundamentally changes, prefer:

- A new feature key, removing the old feature as described above, or
- A migration that explicitly converts the stored values and the `Feature` row

Adding a value to an ENUM feature is not a type change and needs no migration. Removing an ENUM value that is still stored makes resolution fail, just like removing a feature.

## Adding a new feature

This guide adds a BOOLEAN feature `apiKeys` that controls whether a workspace may create API keys.

`apiKeys` is an example. It is not part of Vuesion.

### Step 1: Add the feature to the catalog

Add the key and its definition to `src/shared/domain/feature/feature-catalog.ts`:

```ts [feature-catalog.ts]
export const Feature = {
  MAX_MEMBERS: 'maxMembers',
  SUPPORT_LEVEL: 'supportLevel',
  API_KEYS: 'apiKeys',
} as const;

export const FeatureCatalog = {
  // ...
  [Feature.API_KEYS]: {
    type: FeatureType.BOOLEAN,
  },
} as const;
```

Add the feature label to `getFeatureTranslations` in `src/shared/enums/translation-maps.ts`. ENUM features also need labels for their values in `getFeatureEnumValueTranslations`; for other types, add an empty object:

```ts [translation-maps.ts]
export const getFeatureTranslations = (t: any): Record<FeatureKey, string> => {
  return {
    // ...
    apiKeys: t('Feature.apiKeys' /* API keys */),
  };
};

export const getFeatureEnumValueTranslations = (t: any): Record<FeatureKey, Record<string, string>> => {
  return {
    // ...
    apiKeys: {},
  };
};
```

Type checking reports a missing entry in both maps. Then extract and translate the new messages as described in **Internationalization**:

```bash
npm run extract-i18n-messages
```

Update the expected features in `feature-catalog.spec.ts`.

The next `npm run db:seed` creates the `Feature` row. The test database is seeded automatically.

### Step 2: Configure plans

Once the feature is synchronized, Platform Admins configure it on the plan detail pages:

```text
Free
apiKeys = false

Pro
apiKeys = true
```

Individual workspaces can receive an override in the workspace administration.

No admin UI changes are necessary. The feature controls are generated from the catalog.

### Step 3: Decide what the feature controls

Adding a feature to the catalog enforces nothing.

Decide what the feature means and which operations it protects. For `apiKeys`:

- `true` allows creating API keys.
- `false` does not.
- A missing value means the plan does not grant API keys. This is a deliberate product decision for this feature.

Then identify the authoritative backend operation, here: creating an API key.

### Step 4: Enforce it on the backend

Express the rule as a policy of the domain:

```ts [api-key.policy.ts]
import { Feature } from '#shared/domain/feature/feature-catalog';
import type { WorkspaceEntitlements } from '#shared/types/domain/Entitlement';

export const canUseApiKeys = (entitlements: WorkspaceEntitlements) => {
  return entitlements[Feature.API_KEYS] === true;
};
```

Evaluate it in the controller next to the role-based policy, before calling the service:

```ts
const workspace = await useWorkspaceService().getWorkspaceDetails(body.workspaceId, session.user.id);

if (!workspace) {
  throw NotFoundError('Workspace not found');
}

assertHasAccess(canUpdateWorkspace(workspace));

const entitlements = await useEntitlementService().getWorkspaceEntitlements(workspace.id);

if (!canUseApiKeys(entitlements)) {
  throw ForbiddenError('API keys are not included in the plan of this workspace.');
}

return createApiKey(/* ... */);
```

The decision flows from the workspace through its effective entitlement to the backend decision. It never inspects the plan.

### Step 5: Add frontend UX if needed

If the product UI should react proactively, load the effective entitlements where they are needed:

```ts
const { currentWorkspaceEntitlements, fetchWorkspaceEntitlements } = useWorkspaceActions();

await fetchWorkspaceEntitlements(workspaceId.value);

const hasApiKeys = computed(() => currentWorkspaceEntitlements.value?.apiKeys === true);
```

Use the result to show, hide, or disable the relevant UI and to explain why an action is unavailable.

This step is optional. Frontend checks only improve the user experience. The backend remains authoritative.

### Step 6: Test the behavior

The generic entitlement infrastructure is already tested. Focus on the business behavior of the new feature:

- The catalog definition, in `feature-catalog.spec.ts`
- The protected backend operation with the feature granted, not granted, and not configured
- A workspace override changing the outcome, if overrides matter for the feature
- The frontend UX, if you added any

Assign the configuration in server tests through plans and overrides, for example with `usePlanFeatureService().upsertPlanFeature(planId, Feature.API_KEYS, { booleanValue: true })` on a plan created for the test.

### NUMBER features

A capacity feature like `maxMembers` differs from a BOOLEAN capability in two ways.

It has more meaningful states:

```text
finite 3     three allowed
finite 0     none allowed
unlimited    no limit
missing      not configured
```

Check `unlimited` explicitly before comparing `value`.

It also needs enforcement around every operation that consumes capacity, and the check and the mutation must happen atomically, as described in **Capacity limits and concurrency**.

## Adding a plan

Features are defined in code, because only code can give them meaning. Plans and prices are database data, because they are business configuration:

```text
Feature Catalog    code       a deployment adds or removes features
Plan, PlanFeature  database   Platform Admins or the seed configure them
PlanPrice          database   Platform Admins or the seed configure them
```

A new plan therefore needs no code change. As a Platform Admin, in **Platform → Plans**:

1. Create the plan with a `key` and a `name`.
2. Configure its features. Features that are not configured stay missing (see [Missing features](#missing-features)).
3. Add one price per billing interval with the External ID of the provider price (see [Plan prices](https://www.vuesion.dev/docs/core-concepts/billing-and-subscriptions#plan-prices)).
4. Optionally set `trialDays` so that workspaces can trial the plan (see [trialDays](#trialdays)).
5. Optionally make the plan the default for new workspaces. The default plan cannot have a trial.

The plan is offered in **Plan & Billing** as soon as it is active and has at least one active price. Platform Admins can also assign any active plan, with or without prices, to a workspace without a current subscription.

On the server, the same operations are available through `usePlanService()`, `usePlanFeatureService()`, and `usePlanPriceService()`. To ship plans as initial data of your product, add them to the seed instead (see **Development → Configuration → Customize the seed**).

Plan prices, subscriptions and the billing provider are described in [Billing & Subscriptions](https://www.vuesion.dev/docs/core-concepts/billing-and-subscriptions).

## What is intentionally not part of the system

Plans & Entitlements and billing do not model:

- More than one billing provider per installation
- Quantity or seat-based billing
- Provider trials as a separate state; Lemon Squeezy trials (`on_trial`) and Stripe trials (`trialing`) count as `ACTIVE`. Vuesion's own plan trials are independent of the billing provider, see [trialDays](#trialdays)
- Invoices, payments, and taxes, which stay in the billing provider
- Usage metering or credits
- Reusable add-ons
- Plan versioning

None of these are required to use the system. Workspace feature overrides already support custom configurations for individual workspaces.

## Why this architecture?

Checking plan names spreads business configuration through the codebase. Every pricing change then becomes a code change.

Vuesion separates the two:

- Code defines which features exist and enforces what they mean.
- Plans and overrides configure which workspace receives which value.
- A single service resolves the effective value.
- Backend policies enforce product rules, while the frontend only improves the experience.

The result is a small, explicit system that lets product configuration change without changing product behavior.

## Next steps

Continue with **Billing & Subscriptions** to learn how plan prices, subscriptions and the billing provider assign plans to workspaces.

## Sitemap

See the full [sitemap](https://www.vuesion.dev/sitemap.md) for all pages.
