RezinaLMS-BackEnd/docs/admin-subscription-grant-extend-cancel-admin-panel-integration.md
Yared Yemane 615c5f733f docs: add admin subscription grant/extend/cancel integration guide
Document admin panel APIs, permissions, side effects, and UI patterns for complimentary learner subscription management.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-10 02:38:26 -07:00

904 lines
30 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# Admin Subscription Grant / Extend / Cancel — Admin Panel Integration Guide
This guide documents how to integrate **admin-managed learner subscriptions** into the Yimaru admin panel: **grant** a plan to a learner, **extend** (and reactivate) an existing subscription, and **cancel** any learner subscription.
**Use this guide when:** building or updating the learner profile “Subscriptions / Billing” section, or a global subscriptions management screen that needs complimentary access controls.
**Related:**
- [CSV Export — Admin Panel Integration](./csv-export-admin-panel-integration.md) (subscriptions export)
- [Activity Logs — Admin Panel Integration](./activity-logs-admin-panel-integration.md) (audit trail for these actions)
> **Not for learner self-service.** Learners cancel their own subscription via `POST /api/v1/subscriptions/:id/cancel` (`subscriptions.cancel`). Admin cancel uses a different route and permission (`subscriptions.admin_cancel`). Do not mix them.
---
## Table of contents
1. [Feature overview](#feature-overview)
2. [Architecture & end-to-end flows](#architecture--end-to-end-flows)
3. [Authentication & permissions](#authentication--permissions)
4. [Concepts & business rules](#concepts--business-rules)
5. [Side effects (payments, analytics, notifications, activity logs)](#side-effects-payments-analytics-notifications-activity-logs)
6. [Response envelopes](#response-envelopes)
7. [Supporting APIs](#supporting-apis)
8. [API reference — Grant](#api-reference--grant)
9. [API reference — Extend](#api-reference--extend)
10. [API reference — Cancel](#api-reference--cancel)
11. [Recommended admin UI](#recommended-admin-ui)
12. [TypeScript types & API client](#typescript-types--api-client)
13. [Error handling](#error-handling)
14. [UX copy & confirmations](#ux-copy--confirmations)
15. [Integration checklist](#integration-checklist)
16. [Testing checklist](#testing-checklist)
17. [Quick reference](#quick-reference)
---
## Feature overview
Admins can manage learner access without going through Chapa/ArifPay checkout.
| Action | Endpoint | Permission | HTTP | Typical use |
|--------|----------|------------|------|-------------|
| **Grant** | `POST /api/v1/admin/users/:user_id/subscriptions` | `subscriptions.admin_grant` | `201` | Give a plan to a learner who has no active sub in that category |
| **Extend** | `POST /api/v1/admin/subscriptions/:id/extend` | `subscriptions.admin_extend` | `200` | Push expiry forward and/or reactivate a cancelled/expired row |
| **Cancel** | `POST /api/v1/admin/subscriptions/:id/cancel` | `subscriptions.admin_cancel` | `200` | Immediately cancel any learner subscription by ID |
| Supporting read | Endpoint | Permission |
|-----------------|----------|------------|
| User subscription details (history + payments) | `GET /api/v1/admin/users/:user_id/subscriptions` | `subscriptions.get_by_user` |
| List plans (for grant picker) | `GET /api/v1/subscription-plans` | Public (no permission key); use `active_only=false` if granting inactive plans |
| Get one plan | `GET /api/v1/subscription-plans/:id` | Public |
| Export subscriptions CSV | `GET /api/v1/admin/subscriptions/export` | `subscriptions.export` |
### What each action does (summary)
| Action | Subscription row | Payment row | Plan change? |
|--------|------------------|-------------|--------------|
| **Grant** | Creates new `ACTIVE` row | Inserts `SUCCESS` audit payment, amount `0`, method `ADMIN_GRANT` | Yes — admin picks `plan_id` |
| **Extend** | Updates `expires_at`, sets `ACTIVE`, clears `cancelled_at` | Inserts `SUCCESS` audit payment, amount `0`, method `ADMIN_EXTEND` | **No** — keeps existing plan |
| **Cancel** | Sets `CANCELLED`, `cancelled_at`, `auto_renew=false` | Cancels only **open** (non-`SUCCESS`) payments for that subscription | No |
---
## Architecture & end-to-end flows
```mermaid
sequenceDiagram
participant Admin as Admin panel
participant API as Yimaru API
participant DB as Postgres
participant Notif as Learner notifications
Note over Admin,Notif: Grant
Admin->>API: POST /admin/users/{user_id}/subscriptions { plan_id, ... }
API->>DB: Validate learner + plan; no active sub in category
API->>DB: INSERT user_subscriptions (ACTIVE)
API->>DB: INSERT payments (ADMIN_GRANT, amount 0, SUCCESS)
API->>Notif: MaybeNotifyLearnPackageSubscribed (best-effort)
API->>DB: Activity log SUBSCRIPTION_CREATED
API-->>Admin: 201 subscription
Note over Admin,DB: Extend
Admin->>API: POST /admin/subscriptions/{id}/extend { one mode }
API->>DB: Resolve new expiry; UPDATE expires_at + ACTIVE
API->>DB: INSERT payments (ADMIN_EXTEND, amount 0, SUCCESS)
API->>DB: Activity log SUBSCRIPTION_EXTENDED
API-->>Admin: 200 subscription
Note over Admin,DB: Cancel
Admin->>API: POST /admin/subscriptions/{id}/cancel
API->>DB: UPDATE subscription CANCELLED
API->>DB: CANCEL open (non-SUCCESS) payments for subscription_id
API->>DB: Activity log SUBSCRIPTION_CANCELLED
API-->>Admin: 200 subscription
```
### Where to place these actions in the product
Primary surface: **Learner user detail → Subscriptions / Billing** tab, which already loads:
`GET /api/v1/admin/users/:user_id/subscriptions`
Secondary surface (optional): global subscriptions list/export page — cancel/extend by subscription `id` without opening the user first.
---
## Authentication & permissions
All three mutation endpoints require:
```http
Authorization: Bearer <team_access_token>
```
| Permission key | Seeded name | Required for |
|----------------|-------------|--------------|
| `subscriptions.admin_grant` | Grant User Subscription (Admin) | Grant |
| `subscriptions.admin_extend` | Extend User Subscription (Admin) | Extend |
| `subscriptions.admin_cancel` | Cancel User Subscription (Admin) | Cancel |
| `subscriptions.get_by_user` | (existing) | Load user subscription details before/after mutations |
These keys are seeded on the **ADMIN** role. Custom roles need them assigned explicitly in RBAC.
### UI gating
Hide or disable buttons when the logged-in team member lacks the permission (from the session/permissions payload). Always handle `403` from the API as a fallback.
| UI control | Permission |
|------------|------------|
| “Grant subscription” | `subscriptions.admin_grant` |
| “Extend” / “Renew one period” | `subscriptions.admin_extend` |
| “Cancel subscription” | `subscriptions.admin_cancel` |
> **Do not** reuse learner permission `subscriptions.cancel` for admin cancel UI.
---
## Concepts & business rules
### Target users (grant only)
Grant is allowed only for **learner** accounts:
| Role | Grant allowed? |
|------|----------------|
| `STUDENT` | Yes |
| `OPEN_LEARNER` | Yes |
| Team / admin / instructor / support | No → `400` “Target user is not a learner account” |
### Categories (one active subscription per category)
Plans belong to exactly one category:
| Category | Typical product |
|----------|-----------------|
| `LEARN_ENGLISH` | LMS / Learn English |
| `IELTS` | Exam prep IELTS |
| `DUOLINGO` | Exam prep Duolingo (lifetime-style expiry) |
**Grant fails with `409`** if the learner already has an **active** subscription in the **same category** as the selected plan. They may still hold active subs in other categories.
To change access while an active sub exists in that category: **extend** that row, or **cancel** it first, then grant.
### Extend does not change the plan
Extend only changes expiry (and reactivates). There is **no** `plan_id` on the extend body. To move a learner to a different plan: cancel (or wait until inactive), then grant the new plan.
### Exactly one extend mode
The extend body must include **exactly one** of:
1. `new_expires_at` — absolute timestamp (must be in the future)
2. `duration_value` **and** `duration_unit` together — add duration from a base time
3. `renew_one_period: true` — add one period using the **current plan’s** `duration_value` / `duration_unit`
Sending zero modes, two modes, or only one of `duration_value` / `duration_unit` → `400` with `ErrInvalidExtendInput`.
### Extend base time
For relative modes (`duration_*` or `renew_one_period`):
- If current `expires_at` is **still in the future**, duration is added to that expiry (stacking time).
- If already **expired**, duration is added from **now**.
### DUOLINGO / lifetime plans
`DUOLINGO` category uses a far-future lifetime expiry when calculating from plan duration. Prefer absolute `new_expires_at` only when you intentionally need a custom end date; `renew_one_period` on a lifetime plan will again resolve to the lifetime sentinel.
### Inactive plans
Grant **allows inactive plans** (admin complimentary access). For the plan picker:
- Use `GET /api/v1/subscription-plans?active_only=false` if you need inactive plans.
- Default list (`active_only=true` or omitted) returns active plans only — fine for most grants.
### Cancel behavior
- Works on **any** subscription ID (no ownership check against the admin).
- Sets status `CANCELLED`, stamps `cancelled_at`, forces `auto_renew = false`.
- Does **not** delete the row; history remains on `GET .../subscriptions`.
- Paid (`SUCCESS`) payment history is **preserved** for revenue analytics.
### Status values you will see
| Status | Meaning |
|--------|---------|
| `PENDING` | Checkout not completed |
| `ACTIVE` | Active (access also requires `expires_at` in the future for “currently active”) |
| `EXPIRED` | Past expiry |
| `CANCELLED` | Admin or learner cancelled |
Display helpers from `GET .../users/:user_id/subscriptions`:
| Field | Meaning |
|-------|---------|
| `display_status` | `ACTIVE` \| `PENDING` \| `Unsubscribed` (list-style summary) |
| `has_active_subscription` | Any currently active sub |
| `active_by_category` | Map of category → bool |
| `is_currently_active` | Per-row: `status === 'ACTIVE' && expires_at > now` |
---
## Side effects (payments, analytics, notifications, activity logs)
### Payments table
| Action | Payment effect |
|--------|----------------|
| Grant | New row: `status=SUCCESS`, `amount=0`, `payment_method=ADMIN_GRANT`, linked `subscription_id` / `plan_id` |
| Extend | New row: `status=SUCCESS`, `amount=0`, `payment_method=ADMIN_EXTEND` |
| Cancel | Open payments for that `subscription_id` → `CANCELLED` (**not** prior `SUCCESS` paid rows) |
These admin rows appear in the user’s payment list on `GET /admin/users/:user_id/subscriptions` (`payments[]`). Show them as “Complimentary / Admin” in the UI (amount `0`).
### Analytics dashboard
Revenue / payment-volume analytics **exclude** `ADMIN_GRANT` and `ADMIN_EXTEND` so $0 audit rows do not inflate success counts or depress average order value. Subscription **status counts** still reflect cancel/extend/grant because they read `user_subscriptions`.
### Learner notification
On **successful grant**, the API may send a learn-package subscribed notification (`MaybeNotifyLearnPackageSubscribed`). Treat as best-effort; do not block the UI on it.
### Activity logs
| Action | `action` | `resource_type` | Notes |
|--------|----------|-----------------|-------|
| Grant | `SUBSCRIPTION_CREATED` | `SUBSCRIPTION` | Same action as learner subscribe; metadata includes admin grant fields |
| Extend | `SUBSCRIPTION_EXTENDED` | `SUBSCRIPTION` | Admin-only action string |
| Cancel | `SUBSCRIPTION_CANCELLED` | `SUBSCRIPTION` | Same action as learner cancel |
Example metadata (grant):
```json
{
"subscription_id": 42,
"user_id": 1001,
"plan_id": 3,
"plan_category": "LEARN_ENGLISH",
"expires_at": "2026-10-10T10:00:00Z",
"note": "Comp for support ticket #123"
}
```
Ensure the activity-logs UI can display `SUBSCRIPTION_EXTENDED` (label e.g. “Subscription extended”).
---
## Response envelopes
### Success
```json
{
"message": "Subscription granted successfully",
"data": { "...subscription..." },
"success": true,
"status_code": 201
}
```
Grant uses `201`; extend and cancel use `200`.
### Mutation `data` shape (`subscriptionRes`)
Returned by grant / extend / cancel:
```json
{
"id": 42,
"user_id": 1001,
"plan_id": 3,
"plan_name": "Learn English — 3 Months",
"starts_at": "2026-07-10T10:00:00Z",
"expires_at": "2026-10-10T10:00:00Z",
"status": "ACTIVE",
"payment_reference": "Comp for support ticket #123",
"payment_method": "ADMIN_GRANT",
"auto_renew": false,
"duration_value": 3,
"duration_unit": "MONTH",
"price": 1500,
"currency": "ETB",
"created_at": "2026-07-10T10:00:00Z"
}
```
| Field | Notes |
|-------|--------|
| `payment_method` | `ADMIN_GRANT` after grant; unchanged plan method on extend response may still show prior method on the subscription row — extend audit is on the **payments** table as `ADMIN_EXTEND` |
| `payment_reference` | Grant `note` is stored here when provided |
| `auto_renew` | Grant always creates with `false` |
| Timestamps | ISO-8601 strings |
### Error
```json
{
"message": "Failed to grant subscription",
"error": "user already has an active subscription for this category"
}
```
---
## Supporting APIs
### Load user billing context
```http
GET /api/v1/admin/users/{user_id}/subscriptions
Authorization: Bearer <token>
```
**Permission:** `subscriptions.get_by_user`
**Success `data`:** `AdminUserSubscriptionDetails`
```ts
{
user_id: number;
display_status: string; // ACTIVE | PENDING | Unsubscribed
has_active_subscription: boolean;
active_by_category: {
LEARN_ENGLISH: boolean;
IELTS: boolean;
DUOLINGO: boolean;
};
active_subscriptions: AdminUserSubscriptionRecord[];
subscriptions: AdminUserSubscriptionRecord[]; // full history
payments: AdminUserSubscriptionPayment[];
}
```
Use this:
1. Before grant — disable categories that are already active in `active_by_category`.
2. After any mutation — refresh the tab so history and payments update.
3. To obtain `subscription.id` for extend/cancel.
### List plans for grant picker
```http
GET /api/v1/subscription-plans?active_only=false
```
| Query | Default | Use |
|-------|---------|-----|
| `active_only` | `true` if omitted behaves as active-only when query is `"true"` | Pass `false` to include inactive plans for complimentary grants |
Plan object:
```ts
{
id: number;
name: string;
description?: string;
category: "LEARN_ENGLISH" | "IELTS" | "DUOLINGO";
duration_value: number;
duration_unit: "DAY" | "WEEK" | "MONTH" | "YEAR";
price: number;
currency: string;
is_active: boolean;
created_at: string;
}
```
---
## API reference — Grant
### Request
```http
POST /api/v1/admin/users/{user_id}/subscriptions
Authorization: Bearer <token>
Content-Type: application/json
```
**Path**
| Param | Type | Rules |
|-------|------|-------|
| `user_id` | int | Positive integer; must be an existing learner |
**Body**
| Field | Type | Required | Rules |
|-------|------|----------|-------|
| `plan_id` | int64 | **Yes** | `min=1`; plan must exist |
| `new_expires_at` | string (RFC3339) \| null | No | If set, must be **in the future**; overrides plan-derived expiry |
| `note` | string \| null | No | Max **255** chars; stored as subscription `payment_reference` |
**Default expiry** (when `new_expires_at` omitted): computed from plan `duration_value` / `duration_unit` and category (DUOLINGO → lifetime sentinel).
### Examples
**Grant using plan duration**
```http
POST /api/v1/admin/users/1001/subscriptions
Content-Type: application/json
{
"plan_id": 3,
"note": "Comp for support ticket #123"
}
```
**Grant with explicit end date**
```json
{
"plan_id": 3,
"new_expires_at": "2026-12-31T23:59:59Z",
"note": "Promo through end of year"
}
```
### Success
- **Status:** `201 Created`
- **Message:** `Subscription granted successfully`
- **Data:** `subscriptionRes` (see above)
### Common failures
| Status | When |
|--------|------|
| `400` | Invalid `user_id`, validation, not a learner, plan not found, expiry in the past |
| `404` | User not found |
| `409` | Already has active subscription in that plan’s category |
| `403` | Missing `subscriptions.admin_grant` |
| `500` | Unexpected server/DB error |
---
## API reference — Extend
### Request
```http
POST /api/v1/admin/subscriptions/{id}/extend
Authorization: Bearer <token>
Content-Type: application/json
```
**Path**
| Param | Type | Rules |
|-------|------|-------|
| `id` | int | Positive subscription ID (`user_subscriptions.id`) |
**Body — choose exactly one mode**
| Mode | Fields | Behavior |
|------|--------|----------|
| Absolute | `new_expires_at` | Set expiry to this timestamp (must be future) |
| Custom duration | `duration_value` + `duration_unit` | Add duration from base time (see [Extend base time](#extend-base-time)) |
| Renew one period | `renew_one_period: true` | Add one period from the **existing plan** |
| Field | Type | Rules |
|-------|------|-------|
| `new_expires_at` | RFC3339 datetime | Optional |
| `duration_value` | int32 | Optional; `min=1` when used |
| `duration_unit` | string | Optional; one of `DAY`, `WEEK`, `MONTH`, `YEAR` |
| `renew_one_period` | bool | Optional; default `false` |
### Examples
**Renew one plan period (recommended default button)**
```json
{
"renew_one_period": true
}
```
**Add 2 months**
```json
{
"duration_value": 2,
"duration_unit": "MONTH"
}
```
**Set absolute expiry**
```json
{
"new_expires_at": "2027-01-15T00:00:00Z"
}
```
### Invalid bodies (all → `400`)
```json
{}
```
```json
{ "renew_one_period": true, "new_expires_at": "2027-01-01T00:00:00Z" }
```
```json
{ "duration_value": 2 }
```
```json
{ "duration_unit": "MONTH" }
```
```json
{ "new_expires_at": "2020-01-01T00:00:00Z" }
```
### Success
- **Status:** `200 OK`
- **Message:** `Subscription extended successfully`
- **Data:** updated `subscriptionRes` with new `expires_at` and `status: "ACTIVE"`
### Common failures
| Status | When |
|--------|------|
| `400` | Invalid id, invalid/ambiguous body, expiry resolves in the past, plan missing for renew |
| `404` | Subscription not found |
| `403` | Missing `subscriptions.admin_extend` |
| `500` | Unexpected error |
---
## API reference — Cancel
### Request
```http
POST /api/v1/admin/subscriptions/{id}/cancel
Authorization: Bearer <token>
```
No body.
**Path**
| Param | Type | Rules |
|-------|------|-------|
| `id` | int | Positive subscription ID |
### Example
```http
POST /api/v1/admin/subscriptions/42/cancel
Authorization: Bearer <token>
```
### Success
- **Status:** `200 OK`
- **Message:** `Subscription cancelled successfully`
- **Data:** `subscriptionRes` with `status: "CANCELLED"`
### Common failures
| Status | When |
|--------|------|
| `400` | Invalid id |
| `404` | Subscription not found |
| `403` | Missing `subscriptions.admin_cancel` |
| `500` | Unexpected error (including failure cancelling open payments) |
### After cancel
- Learner loses access for that category once the row is no longer active.
- You may **grant** a new plan in that category, or **extend** the same row later (extend reactivates and clears `cancelled_at`).
---
## Recommended admin UI
### Learner profile — Subscriptions tab
```
┌─────────────────────────────────────────────────────────────┐
│ Subscriptions [ Grant subscription ]│
│ Status: ACTIVE · LEARN_ENGLISH ✓ IELTS ✗ DUOLINGO ✗ │
├─────────────────────────────────────────────────────────────┤
│ Active │
│ #42 Learn English — 3 Months · ACTIVE · expires Oct 10 │
│ [ Extend ] [ Cancel ] │
├─────────────────────────────────────────────────────────────┤
│ History │
│ #40 … CANCELLED … │
│ #38 … EXPIRED … │
├─────────────────────────────────────────────────────────────┤
│ Payments │
│ ADMIN_GRANT 0 ETB SUCCESS │
│ chapa 1500 ETB SUCCESS │
└─────────────────────────────────────────────────────────────┘
```
### Grant modal
1. Load plans (`active_only=false` if needed).
2. Group or filter by `category`.
3. Disable / warn categories where `active_by_category[category] === true`.
4. Fields:
- Plan (required)
- Optional “Custom end date” → maps to `new_expires_at`
- Optional note (max 255)
5. On success: toast + refetch `GET .../subscriptions`.
### Extend modal
Offer three clear choices (mutually exclusive in the form):
| UI option | Payload |
|-----------|---------|
| “Renew one period” (default) | `{ renew_one_period: true }` |
| “Add duration” | `{ duration_value, duration_unit }` |
| “Set end date” | `{ new_expires_at }` |
Show current plan name, current `expires_at`, and preview of the new end date when possible (client-side estimate is OK; trust API response as source of truth).
### Cancel confirmation
Require an explicit confirm dialog:
> Cancel subscription **#42** ({plan_name}) for this learner? They will lose access for **{category}** immediately. Paid payment history is kept.
---
## TypeScript types & API client
```ts
export type DurationUnit = "DAY" | "WEEK" | "MONTH" | "YEAR";
export type PlanCategory = "LEARN_ENGLISH" | "IELTS" | "DUOLINGO";
export type SubscriptionStatus = "PENDING" | "ACTIVE" | "EXPIRED" | "CANCELLED";
export interface SubscriptionRes {
id: number;
user_id: number;
plan_id: number;
plan_name?: string;
starts_at: string;
expires_at: string;
status: SubscriptionStatus | string;
payment_reference?: string;
payment_method?: string;
auto_renew: boolean;
duration_value?: number;
duration_unit?: DurationUnit | string;
price?: number;
currency?: string;
created_at: string;
}
export interface AdminGrantSubscriptionBody {
plan_id: number;
new_expires_at?: string; // ISO-8601
note?: string; // max 255
}
/** Exactly one mode must be set. */
export type AdminExtendSubscriptionBody =
| { new_expires_at: string; duration_value?: never; duration_unit?: never; renew_one_period?: false }
| {
duration_value: number;
duration_unit: DurationUnit;
new_expires_at?: never;
renew_one_period?: false;
}
| {
renew_one_period: true;
new_expires_at?: never;
duration_value?: never;
duration_unit?: never;
};
export interface ApiSuccess<T> {
message: string;
data: T;
success?: boolean;
status_code?: number;
}
export interface ApiError {
message: string;
error?: string;
}
```
### Client helpers (fetch)
```ts
const base = process.env.NEXT_PUBLIC_API_BASE_URL; // e.g. https://api.example.com/api/v1
async function adminGrantSubscription(
token: string,
userId: number,
body: AdminGrantSubscriptionBody
): Promise<SubscriptionRes> {
const res = await fetch(`${base}/admin/users/${userId}/subscriptions`, {
method: "POST",
headers: {
Authorization: `Bearer ${token}`,
"Content-Type": "application/json",
},
body: JSON.stringify(body),
});
const json = await res.json();
if (!res.ok) throw Object.assign(new Error(json.message ?? "Grant failed"), { status: res.status, body: json });
return json.data as SubscriptionRes;
}
async function adminExtendSubscription(
token: string,
subscriptionId: number,
body: AdminExtendSubscriptionBody
): Promise<SubscriptionRes> {
const res = await fetch(`${base}/admin/subscriptions/${subscriptionId}/extend`, {
method: "POST",
headers: {
Authorization: `Bearer ${token}`,
"Content-Type": "application/json",
},
body: JSON.stringify(body),
});
const json = await res.json();
if (!res.ok) throw Object.assign(new Error(json.message ?? "Extend failed"), { status: res.status, body: json });
return json.data as SubscriptionRes;
}
async function adminCancelSubscription(
token: string,
subscriptionId: number
): Promise<SubscriptionRes> {
const res = await fetch(`${base}/admin/subscriptions/${subscriptionId}/cancel`, {
method: "POST",
headers: { Authorization: `Bearer ${token}` },
});
const json = await res.json();
if (!res.ok) throw Object.assign(new Error(json.message ?? "Cancel failed"), { status: res.status, body: json });
return json.data as SubscriptionRes;
}
```
### Client-side extend mode guard
```ts
export function assertSingleExtendMode(body: Record<string, unknown>): void {
const hasAbsolute = body.new_expires_at != null && body.new_expires_at !== "";
const hasDuration =
body.duration_value != null &&
body.duration_unit != null &&
String(body.duration_unit).length > 0;
const hasRenew = body.renew_one_period === true;
const modes = [hasAbsolute, hasDuration, hasRenew].filter(Boolean).length;
if (modes !== 1) {
throw new Error(
"Provide exactly one of new_expires_at, duration_value+duration_unit, or renew_one_period"
);
}
}
```
---
## Error handling
| HTTP | `message` (typical) | `error` (typical) | UI suggestion |
|------|---------------------|-------------------|---------------|
| `400` | Failed to grant/extend/cancel… | Validation / not a learner / invalid extend input / expiry in past / plan not found | Inline form error; fix fields |
| `404` | … | User not found / Subscription not found | Toast; navigate away or refresh list |
| `409` | Failed to grant subscription | user already has an active subscription for this category | Prompt to extend existing or cancel first |
| `403` | Forbidden (middleware) | — | Hide controls; show “no permission” |
| `500` | Failed to … | server detail | Generic retry toast |
Always prefer showing API `error` (when present) under the form; use `message` as the toast title.
### Grant conflict flow
On `409`:
1. Refetch `GET /admin/users/:user_id/subscriptions`.
2. Highlight the active subscription in that category.
3. Offer **Extend** on that row instead of grant.
---
## UX copy & confirmations
| Action | Primary button | Confirm? |
|--------|----------------|----------|
| Grant | “Grant subscription” | Optional confirm if note empty: “Grant {plan} to {user} with no payment?” |
| Extend | “Extend access” | Soft confirm showing old → new expiry when known |
| Cancel | “Cancel subscription” | **Required** destructive confirm |
Suggested success toasts:
- Grant: “Subscription granted”
- Extend: “Subscription extended to {expires_at}”
- Cancel: “Subscription cancelled”
---
## Integration checklist
- [ ] Gate Grant / Extend / Cancel on `subscriptions.admin_grant` / `admin_extend` / `admin_cancel`
- [ ] Load context via `GET /admin/users/:user_id/subscriptions` (`subscriptions.get_by_user`)
- [ ] Plan picker uses `GET /subscription-plans` (include inactive if product needs it)
- [ ] Block grant UI for categories already active (`active_by_category`)
- [ ] Extend form enforces exactly one mode; default = `renew_one_period`
- [ ] Cancel uses **admin** route, not learner `POST /subscriptions/:id/cancel`
- [ ] After each mutation, refetch user subscription details
- [ ] Show `ADMIN_GRANT` / `ADMIN_EXTEND` payments as complimentary (0 amount)
- [ ] Activity log labels include `SUBSCRIPTION_EXTENDED`
- [ ] Note field capped at 255 characters in the UI
- [ ] Handle `409` on grant with extend/cancel guidance
- [ ] Only show Grant for learner roles (`STUDENT`, `OPEN_LEARNER`)
---
## Testing checklist
### Grant
- [ ] Grant active `LEARN_ENGLISH` plan → `201`, status `ACTIVE`, payment `ADMIN_GRANT` amount `0`
- [ ] Second grant same category while active → `409`
- [ ] Grant different category while first active → `201`
- [ ] Grant to non-learner team user → `400`
- [ ] Grant unknown user → `404`
- [ ] Grant with past `new_expires_at` → `400`
- [ ] Grant with `note` longer than 255 → `400` validation
- [ ] Grant inactive plan by id → succeeds (if product allows)
- [ ] Without permission → `403`
### Extend
- [ ] `renew_one_period: true` on active sub → expiry moves forward by plan duration
- [ ] Extend expired/cancelled sub → status becomes `ACTIVE`, `cancelled_at` cleared
- [ ] Absolute `new_expires_at` in future → accepted
- [ ] Empty body / two modes / partial duration → `400`
- [ ] Unknown subscription id → `404`
- [ ] Payment row `ADMIN_EXTEND` amount `0` appears on user details
### Cancel
- [ ] Cancel active → `CANCELLED`, access lost for category
- [ ] Open `PENDING` payments for that sub become `CANCELLED`
- [ ] Prior paid `SUCCESS` payments remain `SUCCESS`
- [ ] After cancel, grant same category succeeds
- [ ] Extend after cancel reactivates same row
### Analytics / audit
- [ ] Dashboard revenue unchanged by grant/extend $0 rows
- [ ] Activity log shows create / extend / cancel actions for the admin actor
---
## Quick reference
| Method | Path | Permission | Body |
|--------|------|------------|------|
| `POST` | `/api/v1/admin/users/:user_id/subscriptions` | `subscriptions.admin_grant` | `{ plan_id, new_expires_at?, note? }` |
| `POST` | `/api/v1/admin/subscriptions/:id/extend` | `subscriptions.admin_extend` | Exactly one extend mode |
| `POST` | `/api/v1/admin/subscriptions/:id/cancel` | `subscriptions.admin_cancel` | _(none)_ |
| `GET` | `/api/v1/admin/users/:user_id/subscriptions` | `subscriptions.get_by_user` | — |
| `GET` | `/api/v1/subscription-plans?active_only=false` | — | — |
| Extend mode | JSON |
|-------------|------|
| Renew one period | `{ "renew_one_period": true }` |
| Add duration | `{ "duration_value": 2, "duration_unit": "MONTH" }` |
| Absolute date | `{ "new_expires_at": "2027-01-15T00:00:00Z" }` |
| Duration units | `DAY` \| `WEEK` \| `MONTH` \| `YEAR` |
| Categories | `LEARN_ENGLISH` \| `IELTS` \| `DUOLINGO` |
| Admin payment methods | `ADMIN_GRANT` \| `ADMIN_EXTEND` (amount `0`, excluded from revenue analytics) |
| Activity actions | `SUBSCRIPTION_CREATED` \| `SUBSCRIPTION_EXTENDED` \| `SUBSCRIPTION_CANCELLED` |