# Admin Subscription Grant / Extend / Cancel — Admin Panel Integration Guide This guide documents how to integrate **admin-managed learner subscriptions** into the Yimaru admin panel: a **unified grant-or-extend** action (pick a plan), and **cancel**. **Use this guide when:** building or updating the learner profile "Subscriptions / Billing" section. **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 via `POST /api/v1/subscriptions/:id/cancel` (`subscriptions.cancel`). Admin cancel uses `subscriptions.admin_cancel`. --- ## 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 or extend (unified)](#api-reference--grant-or-extend-unified) 9. [API reference — Cancel](#api-reference--cancel) 10. [Recommended admin UI](#recommended-admin-ui) 11. [TypeScript types & API client](#typescript-types--api-client) 12. [Error handling](#error-handling) 13. [UX copy & confirmations](#ux-copy--confirmations) 14. [Integration checklist](#integration-checklist) 15. [Testing checklist](#testing-checklist) 16. [Quick reference](#quick-reference) --- ## Feature overview Admins manage learner access without Chapa/ArifPay checkout via **one** apply endpoint plus cancel. | Action | Endpoint | Permission | HTTP | Behavior | |--------|----------|------------|------|----------| | **Grant or extend** | `POST /api/v1/admin/users/:user_id/subscriptions/extend` | `subscriptions.admin_extend` | `201` grant / `200` extend | Body: `{ "plan_id" }`. No active sub in plan category → **grant**. Active sub in that category → **extend** by one period of the selected plan | | **Cancel** | `POST /api/v1/admin/subscriptions/:id/cancel` | `subscriptions.admin_cancel` | `200` | Cancel subscription by ID | | Supporting read | Endpoint | Permission | |-----------------|----------|------------| | User subscription details | `GET /api/v1/admin/users/:user_id/subscriptions` | `subscriptions.get_by_user` | | List plans (picker) | `GET /api/v1/subscription-plans` | Public; use `active_only=false` if needed | | Export subscriptions CSV | `GET /api/v1/admin/subscriptions/export` | `subscriptions.export` | ### What the unified action does | Case | Subscription | Payment | HTTP / message | |------|--------------|---------|----------------| | **Grant** (no active in category) | Creates new `ACTIVE` row | `SUCCESS` at **plan price**, method `ADMIN_GRANT` | `201` — Subscription granted successfully | | **Extend** (active in category) | Updates `expires_at`, sets `ACTIVE`, may update `plan_id` to selected plan | `SUCCESS` at **plan price**, method `ADMIN_EXTEND` | `200` — Subscription extended successfully | | **Cancel** | `CANCELLED`, `auto_renew=false` | Cancels open (non-`SUCCESS`) payments only | `200` | > **Removed endpoints:** `POST /admin/users/:user_id/subscriptions` (old grant) and `POST /admin/subscriptions/:id/extend` (old extend-by-id). Use the unified route above. Permission `subscriptions.admin_grant` is no longer seeded. --- ## 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 Admin->>API: POST /admin/users/{user_id}/subscriptions/extend { plan_id } API->>DB: Validate learner + plan alt No active sub in plan category API->>DB: INSERT user_subscriptions (ACTIVE) API->>DB: INSERT payments (ADMIN_GRANT, plan.price, SUCCESS) API->>Notif: MaybeNotifyLearnPackageSubscribed API->>DB: Activity SUBSCRIPTION_CREATED API-->>Admin: 201 granted else Active sub in category API->>DB: UPDATE plan_id, expires_at (+1 plan period), ACTIVE API->>DB: INSERT payments (ADMIN_EXTEND, plan.price, SUCCESS) API->>DB: Activity SUBSCRIPTION_EXTENDED API-->>Admin: 200 extended end Admin->>API: POST /admin/subscriptions/{id}/cancel API->>DB: UPDATE subscription CANCELLED API->>DB: CANCEL open payments API->>DB: Activity SUBSCRIPTION_CANCELLED API-->>Admin: 200 cancelled ``` ### 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 — cancel by subscription `id`; grant/extend still goes through the user-scoped unified endpoint (needs `user_id` + `plan_id`). --- ## Authentication & permissions ```http Authorization: Bearer ``` | Permission key | Seeded name | Required for | |----------------|-------------|--------------| | `subscriptions.admin_extend` | Grant or Extend User Subscription (Admin) | Unified grant-or-extend | | `subscriptions.admin_cancel` | Cancel User Subscription (Admin) | Cancel | | `subscriptions.get_by_user` | (existing) | Load user subscription details | Seeded on the **ADMIN** role. Custom roles need these assigned explicitly. | UI control | Permission | |------------|------------| | "Grant / extend" (plan picker) | `subscriptions.admin_extend` | | "Cancel subscription" | `subscriptions.admin_cancel` | > **Do not** reuse learner `subscriptions.cancel` for admin cancel. **`subscriptions.admin_grant` is removed** from seeds — use `admin_extend` only. --- ## Concepts & business rules ### Target users Unified apply is allowed only for **learner** accounts (`STUDENT`, `OPEN_LEARNER`). Others → `400` "Target user is not a learner account". ### Categories (one active subscription per category) | Category | Typical product | |----------|-----------------| | `LEARN_ENGLISH` | LMS / Learn English | | `IELTS` | Exam prep IELTS | | `DUOLINGO` | Exam prep Duolingo (lifetime-style expiry) | **Unified behavior for a selected `plan_id`:** 1. If the learner has **no** active subscription in that plan's category → **grant** (create). 2. If they **do** have an active subscription in that category → **extend** that row by one period of the **selected** plan (updates `plan_id` when a different plan in the same category is chosen). There is **no** `409` conflict for "already subscribed" on this endpoint — that case becomes an extend. ### Extend base time When extending: - If current `expires_at` is still in the future → add one plan period onto that expiry. - If already past → add one plan period from **now**. Duration comes from the **selected** plan's `duration_value` / `duration_unit` (DUOLINGO → lifetime sentinel). ### Inactive plans Inactive plans may be selected (`active_only=false` on the plans list). ### Cancel behavior - Works on any subscription ID. - Sets `CANCELLED`, `cancelled_at`, `auto_renew = false`. - Preserves prior `SUCCESS` payments 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=`, `payment_method=ADMIN_GRANT`, linked `subscription_id` / `plan_id` | | Extend | New row: `status=SUCCESS`, `amount=`, `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 like other successful payments (plan price + method `ADMIN_GRANT` / `ADMIN_EXTEND`). No gateway checkout runs; the row is recorded as if the plan amount was charged. ### Analytics dashboard Admin grant/extend `SUCCESS` payments **count toward revenue** (same as gateway payments). Subscription **status counts** also reflect cancel/extend/grant via `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` | Metadata includes `created: true` | | Extend | `SUBSCRIPTION_EXTENDED` | `SUBSCRIPTION` | Metadata includes `created: false` | | Cancel | `SUBSCRIPTION_CANCELLED` | `SUBSCRIPTION` | Same action as learner cancel | 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`) ```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_method": "ADMIN_GRANT", "auto_renew": false, "duration_value": 3, "duration_unit": "MONTH", "price": 1500, "currency": "ETB", "created_at": "2026-07-10T10:00:00Z" } ``` ### Error ```json { "message": "Failed to apply subscription", "error": "Target user is not a learner account" } ``` --- ## Supporting APIs ### Load user billing context ```http GET /api/v1/admin/users/{user_id}/subscriptions Authorization: Bearer ``` **Permission:** `subscriptions.get_by_user` Use this: 1. Before apply — show which categories are already active (`active_by_category`); picking a plan in an active category will **extend**, not fail. 2. After any mutation — refresh the tab. 3. Use `subscription.id` for **cancel** only. ### List plans for picker ```http GET /api/v1/subscription-plans?active_only=false ``` --- ## API reference — Grant or extend (unified) ### Request ```http POST /api/v1/admin/users/{user_id}/subscriptions/extend Authorization: Bearer Content-Type: application/json ``` **Permission:** `subscriptions.admin_extend` | Param / field | Type | Required | Rules | |---------------|------|----------|-------| | `user_id` (path) | int | Yes | Existing learner | | `plan_id` (body) | int64 | Yes | `min=1`; plan must exist | ```json { "plan_id": 3 } ``` ### Server decision | Condition | Result | |-----------|--------| | No active subscription in plan's category | **Grant** — create row, payment `ADMIN_GRANT` | | Active subscription in plan's category | **Extend** — add one period of selected plan, payment `ADMIN_EXTEND`, update `plan_id` if different | ### Success | Case | Status | Message | |------|--------|---------| | Grant | `201 Created` | `Subscription granted successfully` | | Extend | `200 OK` | `Subscription extended successfully` | ### Common failures | Status | When | |--------|------| | `400` | Invalid user id, validation, not a learner, plan not found | | `404` | User not found | | `403` | Missing `subscriptions.admin_extend` | | `500` | Unexpected server/DB error | --- ## API reference — Cancel ```http POST /api/v1/admin/subscriptions/{id}/cancel Authorization: Bearer ``` **Permission:** `subscriptions.admin_cancel` — no body. | Status | Meaning | |--------|---------| | `200` | Cancelled; data is `subscriptionRes` with `status: "CANCELLED"` | | `404` | Subscription not found | | `403` | Missing permission | After cancel, call the unified extend endpoint again with a `plan_id` to grant a new subscription in that category. --- ## Recommended admin UI ### UI principles | Do | Do not | |----|--------| | One **Grant / extend** flow with searchable plan picker | Separate grant vs extend APIs | | Body always `{ plan_id }` | Custom date, note, or `renew_one_period` fields | | Confirm in a separate **Are you sure?** modal | Call API from the picker screen | | Client-side plan search | Server-side plan search | | Show plan price in confirm (recorded as charged) | Assume amount is 0 | ### Learner profile — Subscriptions tab - Button: **Grant / extend plan** (permission `admin_extend`) - Per active row: **Cancel** only (renew/change plan uses the same Grant / extend flow) - Hint: if category already active, confirm copy says **extend**; otherwise **grant** ### Client-side plan search ```ts function filterPlans(plans: SubscriptionPlan[], query: string): SubscriptionPlan[] { const q = query.trim().toLowerCase(); if (!q) return plans; return plans.filter((p) => [p.name, p.category, p.currency, String(p.price), `${p.duration_value} ${p.duration_unit}`] .join(" ") .toLowerCase() .includes(q) ); } ``` --- ## TypeScript types & API client ```ts export interface AdminApplySubscriptionBody { plan_id: number; } export interface SubscriptionRes { id: number; user_id: number; plan_id: number; plan_name?: string; starts_at: string; expires_at: string; status: string; payment_method?: string; auto_renew: boolean; price?: number; currency?: string; created_at: string; } const base = process.env.NEXT_PUBLIC_API_BASE_URL; // .../api/v1 async function adminApplySubscription( token: string, userId: number, planId: number ): Promise<{ status: number; data: SubscriptionRes; message: string }> { const res = await fetch(`${base}/admin/users/${userId}/subscriptions/extend`, { method: "POST", headers: { Authorization: `Bearer ${token}`, "Content-Type": "application/json", }, body: JSON.stringify({ plan_id: planId } satisfies AdminApplySubscriptionBody), }); const json = await res.json(); if (!res.ok) { throw Object.assign(new Error(json.message ?? "Apply failed"), { status: res.status, body: json, }); } return { status: res.status, data: json.data, message: json.message }; } ``` Use `status === 201` (or message containing "granted") to distinguish grant vs extend in the UI if needed. --- ## Error handling | HTTP | Cause | UI | |------|-------|-----| | `400` | Validation / not learner / plan missing | Show in confirm modal | | `404` | User missing | Close; toast | | `403` | Missing `admin_extend` / `admin_cancel` | Hide controls | | `500` | Server | Retry | > `409` is **not** expected from the unified apply endpoint (active category → extend). --- ## UX copy & confirmations | Action | Confirm button | Notes | |--------|----------------|-------| | Grant / extend | Confirm | Mention plan price; wording grant vs extend from `active_by_category` | | Cancel | Confirm cancel | Destructive | --- ## Integration checklist - [ ] Single apply button gated on `subscriptions.admin_extend` - [ ] `POST /admin/users/:user_id/subscriptions/extend` with `{ plan_id }` only - [ ] Client-side plan search; Are you sure? modal before API - [ ] Handle `201` vs `200` for grant vs extend messaging - [ ] Cancel via `POST /admin/subscriptions/:id/cancel` + `admin_cancel` - [ ] Do **not** call removed grant/extend-by-id routes - [ ] Refetch user subscriptions after success --- ## Testing checklist - [ ] No active in category → `201`, `ADMIN_GRANT`, amount = plan.price - [ ] Active in category → `200`, `ADMIN_EXTEND`, expiry moved by plan period - [ ] Different plan same category → extend updates `plan_id` - [ ] Non-learner → `400` - [ ] Cancel preserves SUCCESS payments - [ ] Old routes `POST .../subscriptions` and `POST .../subscriptions/:id/extend` → not found --- ## Quick reference | Method | Path | Permission | Body | |--------|------|------------|------| | `POST` | `/api/v1/admin/users/:user_id/subscriptions/extend` | `subscriptions.admin_extend` | `{ "plan_id": }` | | `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` | — | Client-side search | | Outcome | HTTP | Payment method | |---------|------|----------------| | Grant | `201` | `ADMIN_GRANT` @ plan price | | Extend | `200` | `ADMIN_EXTEND` @ plan price |