From 0e0203ab373611e3f16b665d2c96c25bc3bc1bf8 Mon Sep 17 00:00:00 2001 From: Yared Yemane Date: Fri, 10 Jul 2026 04:25:11 -0700 Subject: [PATCH] feat: unify admin grant/extend and record plan-price payments Use one user-scoped extend endpoint that grants or renews by plan_id, charge admin payments at plan price for revenue, and refresh the admin panel integration guide. Co-authored-by: Cursor --- db/query/analytics.sql | 12 +- db/query/subscriptions.sql | 5 +- ...t-extend-cancel-admin-panel-integration.md | 768 +++++------------- gen/db/analytics.sql.go | 12 +- gen/db/subscriptions.sql.go | 8 +- internal/domain/payment.go | 3 +- internal/domain/subscriptions.go | 10 +- internal/ports/subscriptions.go | 2 +- internal/repository/subscriptions.go | 3 +- internal/services/rbac/seeds.go | 5 +- internal/services/subscriptions/service.go | 75 +- .../handlers/admin_subscription_handler.go | 134 +-- internal/web_server/routes.go | 3 +- 13 files changed, 317 insertions(+), 723 deletions(-) diff --git a/db/query/analytics.sql b/db/query/analytics.sql index c6b40909..cd6e3a33 100644 --- a/db/query/analytics.sql +++ b/db/query/analytics.sql @@ -183,7 +183,6 @@ SELECT FROM payments p JOIN subscription_plans sp ON sp.id = p.plan_id WHERE p.status = 'SUCCESS' - AND COALESCE(p.payment_method, '') NOT IN ('ADMIN_GRANT', 'ADMIN_EXTEND') AND (sqlc.narg('range_start')::timestamptz IS NULL OR COALESCE(p.paid_at, p.created_at) >= sqlc.narg('range_start')::timestamptz) AND (sqlc.narg('range_end')::timestamptz IS NULL OR COALESCE(p.paid_at, p.created_at) < sqlc.narg('range_end')::timestamptz) GROUP BY sp.name, sp.currency @@ -208,8 +207,6 @@ ORDER BY d.date; -- Payment Analytics -- ===================== --- Complimentary admin grant/extend rows stay in payments for audit but are --- excluded from revenue and payment-volume analytics (amount is always 0). -- name: AnalyticsPaymentsSummary :one SELECT COALESCE(SUM(p.amount) FILTER (WHERE p.status = 'SUCCESS'), 0)::float8 AS total_revenue, @@ -217,8 +214,7 @@ SELECT COUNT(*)::bigint AS total_payments, COUNT(*) FILTER (WHERE p.status = 'SUCCESS')::bigint AS successful_payments FROM payments p -WHERE COALESCE(p.payment_method, '') NOT IN ('ADMIN_GRANT', 'ADMIN_EXTEND') - AND (sqlc.narg('range_start')::timestamptz IS NULL OR COALESCE(p.paid_at, p.created_at) >= sqlc.narg('range_start')::timestamptz) +WHERE (sqlc.narg('range_start')::timestamptz IS NULL OR COALESCE(p.paid_at, p.created_at) >= sqlc.narg('range_start')::timestamptz) AND (sqlc.narg('range_end')::timestamptz IS NULL OR COALESCE(p.paid_at, p.created_at) < sqlc.narg('range_end')::timestamptz); -- name: AnalyticsPaymentsByStatus :many @@ -227,8 +223,7 @@ SELECT COUNT(*)::bigint AS count, COALESCE(SUM(p.amount), 0)::float8 AS total_amount FROM payments p -WHERE COALESCE(p.payment_method, '') NOT IN ('ADMIN_GRANT', 'ADMIN_EXTEND') - AND (sqlc.narg('range_start')::timestamptz IS NULL OR COALESCE(p.paid_at, p.created_at) >= sqlc.narg('range_start')::timestamptz) +WHERE (sqlc.narg('range_start')::timestamptz IS NULL OR COALESCE(p.paid_at, p.created_at) >= sqlc.narg('range_start')::timestamptz) AND (sqlc.narg('range_end')::timestamptz IS NULL OR COALESCE(p.paid_at, p.created_at) < sqlc.narg('range_end')::timestamptz) GROUP BY p.status ORDER BY count DESC; @@ -240,7 +235,6 @@ SELECT COALESCE(SUM(p.amount), 0)::float8 AS total_amount FROM payments p WHERE p.status = 'SUCCESS' - AND COALESCE(p.payment_method, '') NOT IN ('ADMIN_GRANT', 'ADMIN_EXTEND') AND (sqlc.narg('range_start')::timestamptz IS NULL OR COALESCE(p.paid_at, p.created_at) >= sqlc.narg('range_start')::timestamptz) AND (sqlc.narg('range_end')::timestamptz IS NULL OR COALESCE(p.paid_at, p.created_at) < sqlc.narg('range_end')::timestamptz) GROUP BY p.payment_method @@ -257,7 +251,6 @@ FROM generate_series( ) AS d(date) LEFT JOIN payments p ON COALESCE(p.paid_at, p.created_at)::date = d.date AND p.status = 'SUCCESS' - AND COALESCE(p.payment_method, '') NOT IN ('ADMIN_GRANT', 'ADMIN_EXTEND') AND (sqlc.narg('range_start')::timestamptz IS NULL OR COALESCE(p.paid_at, p.created_at) >= sqlc.narg('range_start')::timestamptz) AND (sqlc.narg('range_end')::timestamptz IS NULL OR COALESCE(p.paid_at, p.created_at) < sqlc.narg('range_end')::timestamptz) GROUP BY d.date @@ -280,7 +273,6 @@ by_month_currency AS ( SUM(p.amount)::float8 AS total_revenue FROM payments p WHERE p.status = 'SUCCESS' - AND COALESCE(p.payment_method, '') NOT IN ('ADMIN_GRANT', 'ADMIN_EXTEND') AND EXTRACT(YEAR FROM COALESCE(p.paid_at, p.created_at) AT TIME ZONE 'UTC')::int = sqlc.arg('report_year')::int GROUP BY 1, 2 ) diff --git a/db/query/subscriptions.sql b/db/query/subscriptions.sql index 79a867d4..10a870b5 100644 --- a/db/query/subscriptions.sql +++ b/db/query/subscriptions.sql @@ -256,11 +256,12 @@ WHERE id = $2; -- name: AdminExtendUserSubscription :exec UPDATE user_subscriptions SET - expires_at = $1, + plan_id = $1, + expires_at = $2, status = 'ACTIVE', cancelled_at = NULL, updated_at = CURRENT_TIMESTAMP -WHERE id = $2; +WHERE id = $3; -- name: ListUserSubscriptionsAdmin :many SELECT diff --git a/docs/admin-subscription-grant-extend-cancel-admin-panel-integration.md b/docs/admin-subscription-grant-extend-cancel-admin-panel-integration.md index caf9569b..e0399e2f 100644 --- a/docs/admin-subscription-grant-extend-cancel-admin-panel-integration.md +++ b/docs/admin-subscription-grant-extend-cancel-admin-panel-integration.md @@ -1,15 +1,15 @@ -# Admin Subscription Grant / Extend / Cancel — Admin Panel Integration Guide +# 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. +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, or a global subscriptions management screen that needs complimentary access controls. +**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 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. +> **Not for learner self-service.** Learners cancel via `POST /api/v1/subscriptions/:id/cancel` (`subscriptions.cancel`). Admin cancel uses `subscriptions.admin_cancel`. --- @@ -22,43 +22,42 @@ This guide documents how to integrate **admin-managed learner subscriptions** in 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) +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 can manage learner access without going through Chapa/ArifPay checkout. +Admins manage learner access without Chapa/ArifPay checkout via **one** apply endpoint plus cancel. -| 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 | +| 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 (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 | +| 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 each action does (summary) +### What the unified action does -| 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 | +| 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. --- @@ -71,28 +70,26 @@ sequenceDiagram 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 + 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 - 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 + API->>DB: CANCEL open payments + API->>DB: Activity SUBSCRIPTION_CANCELLED + API-->>Admin: 200 cancelled ``` ### Where to place these actions in the product @@ -101,112 +98,79 @@ Primary surface: **Learner user detail → Subscriptions / Billing** tab, which `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. +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 -All three mutation endpoints require: - ```http Authorization: Bearer ``` | Permission key | Seeded name | Required for | |----------------|-------------|--------------| -| `subscriptions.admin_grant` | Grant User Subscription (Admin) | Grant | -| `subscriptions.admin_extend` | Extend User Subscription (Admin) | Extend | +| `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 before/after mutations | +| `subscriptions.get_by_user` | (existing) | Load user subscription details | -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. +Seeded on the **ADMIN** role. Custom roles need these assigned explicitly. | UI control | Permission | |------------|------------| -| “Grant subscription” | `subscriptions.admin_grant` | -| “Extend” / “Renew one period” | `subscriptions.admin_extend` | -| “Cancel subscription” | `subscriptions.admin_cancel` | +| "Grant / extend" (plan picker) | `subscriptions.admin_extend` | +| "Cancel subscription" | `subscriptions.admin_cancel` | -> **Do not** reuse learner permission `subscriptions.cancel` for admin cancel UI. +> **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 (grant only) +### Target users -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” | +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) -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. +**Unified behavior for a selected `plan_id`:** -To change access while an active sub exists in that category: **extend** that row, or **cancel** it first, then grant. +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). -### 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`. +There is **no** `409` conflict for "already subscribed" on this endpoint — that case becomes an extend. ### Extend base time -For relative modes (`duration_*` or `renew_one_period`): +When extending: -- 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**. +- 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**. -### 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. +Duration comes from the **selected** plan's `duration_value` / `duration_unit` (DUOLINGO → 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. +Inactive plans may be selected (`active_only=false` on the plans list). ### 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. +- 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”) | +| `ACTIVE` | Active (access also requires `expires_at` in the future for "currently active") | | `EXPIRED` | Past expiry | | `CANCELLED` | Admin or learner cancelled | @@ -227,15 +191,15 @@ Display helpers from `GET .../users/:user_id/subscriptions`: | 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` | +| 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 as “Complimentary / Admin” in the UI (amount `0`). +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 -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`. +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 @@ -245,24 +209,11 @@ On **successful grant**, the API may send a learn-package subscribed notificatio | 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 | +| 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 | -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”). +Ensure the activity-logs UI can display `SUBSCRIPTION_EXTENDED` (label e.g. "Subscription extended"). --- @@ -283,18 +234,15 @@ 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", + "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, @@ -305,19 +253,12 @@ Returned by grant / extend / cancel: } ``` -| 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" + "message": "Failed to apply subscription", + "error": "Target user is not a learner account" } ``` @@ -334,330 +275,126 @@ Authorization: Bearer **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. +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 grant picker +### List plans for 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 +## API reference — Grant or extend (unified) ### Request ```http -POST /api/v1/admin/users/{user_id}/subscriptions +POST /api/v1/admin/users/{user_id}/subscriptions/extend Authorization: Bearer Content-Type: application/json ``` -**Path** +**Permission:** `subscriptions.admin_extend` -| 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** +| 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, - "new_expires_at": "2026-12-31T23:59:59Z", - "note": "Promo through end of year" -} +{ "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 -- **Status:** `201 Created` -- **Message:** `Subscription granted successfully` -- **Data:** `subscriptionRes` (see above) +| 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, expiry in the past | +| `400` | Invalid user id, validation, not a learner, plan not found | | `404` | User not found | -| `409` | Already has active subscription in that plan’s category | -| `403` | Missing `subscriptions.admin_grant` | +| `403` | Missing `subscriptions.admin_extend` | | `500` | Unexpected server/DB error | --- -## API reference — Extend - -### Request - -```http -POST /api/v1/admin/subscriptions/{id}/extend -Authorization: Bearer -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 ``` -No body. +**Permission:** `subscriptions.admin_cancel` — no body. -**Path** - -| Param | Type | Rules | -|-------|------|-------| -| `id` | int | Positive subscription ID | - -### Example - -```http -POST /api/v1/admin/subscriptions/42/cancel -Authorization: Bearer -``` - -### Success - -- **Status:** `200 OK` -- **Message:** `Subscription cancelled successfully` -- **Data:** `subscriptionRes` with `status: "CANCELLED"` - -### Common failures - -| Status | When | -|--------|------| -| `400` | Invalid id | +| Status | Meaning | +|--------|---------| +| `200` | Cancelled; data is `subscriptionRes` with `status: "CANCELLED"` | | `404` | Subscription not found | -| `403` | Missing `subscriptions.admin_cancel` | -| `500` | Unexpected error (including failure cancelling open payments) | +| `403` | Missing permission | -### 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`). +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) + ); +} ``` -┌─────────────────────────────────────────────────────────────┐ -│ 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 AdminApplySubscriptionBody { + plan_id: number; +} export interface SubscriptionRes { id: number; @@ -666,218 +403,86 @@ export interface SubscriptionRes { plan_name?: string; starts_at: string; expires_at: string; - status: SubscriptionStatus | string; - payment_reference?: string; + status: 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 -} +const base = process.env.NEXT_PUBLIC_API_BASE_URL; // .../api/v1 -/** 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 { - 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( +async function adminApplySubscription( token: string, userId: number, - body: AdminGrantSubscriptionBody -): Promise { - const res = await fetch(`${base}/admin/users/${userId}/subscriptions`, { + 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(body), + body: JSON.stringify({ plan_id: planId } satisfies AdminApplySubscriptionBody), }); 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 { - 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 { - 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): 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" - ); + 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 | `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 | +| 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 | -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. +> `409` is **not** expected from the unified apply endpoint (active category → extend). --- ## 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” +| Action | Confirm button | Notes | +|--------|----------------|-------| +| Grant / extend | Confirm | Mention plan price; wording grant vs extend from `active_by_category` | +| Cancel | Confirm cancel | Destructive | --- ## 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`) +- [ ] 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 -### 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 +- [ ] 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 --- @@ -885,19 +490,12 @@ Suggested success toasts: | 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/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` | — | — | +| `GET` | `/api/v1/subscription-plans?active_only=false` | — | Client-side search | -| 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` | +| Outcome | HTTP | Payment method | +|---------|------|----------------| +| Grant | `201` | `ADMIN_GRANT` @ plan price | +| Extend | `200` | `ADMIN_EXTEND` @ plan price | diff --git a/gen/db/analytics.sql.go b/gen/db/analytics.sql.go index d5b0328e..2bef34af 100644 --- a/gen/db/analytics.sql.go +++ b/gen/db/analytics.sql.go @@ -384,7 +384,6 @@ SELECT COALESCE(SUM(p.amount), 0)::float8 AS total_amount FROM payments p WHERE p.status = 'SUCCESS' - AND COALESCE(p.payment_method, '') NOT IN ('ADMIN_GRANT', 'ADMIN_EXTEND') AND ($1::timestamptz IS NULL OR COALESCE(p.paid_at, p.created_at) >= $1::timestamptz) AND ($2::timestamptz IS NULL OR COALESCE(p.paid_at, p.created_at) < $2::timestamptz) GROUP BY p.payment_method @@ -428,8 +427,7 @@ SELECT COUNT(*)::bigint AS count, COALESCE(SUM(p.amount), 0)::float8 AS total_amount FROM payments p -WHERE COALESCE(p.payment_method, '') NOT IN ('ADMIN_GRANT', 'ADMIN_EXTEND') - AND ($1::timestamptz IS NULL OR COALESCE(p.paid_at, p.created_at) >= $1::timestamptz) +WHERE ($1::timestamptz IS NULL OR COALESCE(p.paid_at, p.created_at) >= $1::timestamptz) AND ($2::timestamptz IS NULL OR COALESCE(p.paid_at, p.created_at) < $2::timestamptz) GROUP BY p.status ORDER BY count DESC @@ -474,8 +472,7 @@ SELECT COUNT(*)::bigint AS total_payments, COUNT(*) FILTER (WHERE p.status = 'SUCCESS')::bigint AS successful_payments FROM payments p -WHERE COALESCE(p.payment_method, '') NOT IN ('ADMIN_GRANT', 'ADMIN_EXTEND') - AND ($1::timestamptz IS NULL OR COALESCE(p.paid_at, p.created_at) >= $1::timestamptz) +WHERE ($1::timestamptz IS NULL OR COALESCE(p.paid_at, p.created_at) >= $1::timestamptz) AND ($2::timestamptz IS NULL OR COALESCE(p.paid_at, p.created_at) < $2::timestamptz) ` @@ -494,8 +491,6 @@ type AnalyticsPaymentsSummaryRow struct { // ===================== // Payment Analytics // ===================== -// Complimentary admin grant/extend rows stay in payments for audit but are -// excluded from revenue and payment-volume analytics (amount is always 0). func (q *Queries) AnalyticsPaymentsSummary(ctx context.Context, arg AnalyticsPaymentsSummaryParams) (AnalyticsPaymentsSummaryRow, error) { row := q.db.QueryRow(ctx, AnalyticsPaymentsSummary, arg.RangeStart, arg.RangeEnd) var i AnalyticsPaymentsSummaryRow @@ -636,7 +631,6 @@ SELECT FROM payments p JOIN subscription_plans sp ON sp.id = p.plan_id WHERE p.status = 'SUCCESS' - AND COALESCE(p.payment_method, '') NOT IN ('ADMIN_GRANT', 'ADMIN_EXTEND') AND ($1::timestamptz IS NULL OR COALESCE(p.paid_at, p.created_at) >= $1::timestamptz) AND ($2::timestamptz IS NULL OR COALESCE(p.paid_at, p.created_at) < $2::timestamptz) GROUP BY sp.name, sp.currency @@ -691,7 +685,6 @@ FROM generate_series( ) AS d(date) LEFT JOIN payments p ON COALESCE(p.paid_at, p.created_at)::date = d.date AND p.status = 'SUCCESS' - AND COALESCE(p.payment_method, '') NOT IN ('ADMIN_GRANT', 'ADMIN_EXTEND') AND ($3::timestamptz IS NULL OR COALESCE(p.paid_at, p.created_at) >= $3::timestamptz) AND ($4::timestamptz IS NULL OR COALESCE(p.paid_at, p.created_at) < $4::timestamptz) GROUP BY d.date @@ -751,7 +744,6 @@ by_month_currency AS ( SUM(p.amount)::float8 AS total_revenue FROM payments p WHERE p.status = 'SUCCESS' - AND COALESCE(p.payment_method, '') NOT IN ('ADMIN_GRANT', 'ADMIN_EXTEND') AND EXTRACT(YEAR FROM COALESCE(p.paid_at, p.created_at) AT TIME ZONE 'UTC')::int = $1::int GROUP BY 1, 2 ) diff --git a/gen/db/subscriptions.sql.go b/gen/db/subscriptions.sql.go index 2fbb0704..41003826 100644 --- a/gen/db/subscriptions.sql.go +++ b/gen/db/subscriptions.sql.go @@ -14,20 +14,22 @@ import ( const AdminExtendUserSubscription = `-- name: AdminExtendUserSubscription :exec UPDATE user_subscriptions SET - expires_at = $1, + plan_id = $1, + expires_at = $2, status = 'ACTIVE', cancelled_at = NULL, updated_at = CURRENT_TIMESTAMP -WHERE id = $2 +WHERE id = $3 ` type AdminExtendUserSubscriptionParams struct { + PlanID int64 `json:"plan_id"` ExpiresAt pgtype.Timestamptz `json:"expires_at"` ID int64 `json:"id"` } func (q *Queries) AdminExtendUserSubscription(ctx context.Context, arg AdminExtendUserSubscriptionParams) error { - _, err := q.db.Exec(ctx, AdminExtendUserSubscription, arg.ExpiresAt, arg.ID) + _, err := q.db.Exec(ctx, AdminExtendUserSubscription, arg.PlanID, arg.ExpiresAt, arg.ID) return err } diff --git a/internal/domain/payment.go b/internal/domain/payment.go index 57fc91e4..3f2e70a5 100644 --- a/internal/domain/payment.go +++ b/internal/domain/payment.go @@ -81,7 +81,8 @@ type CreatePaymentInput struct { ExpiresAt *time.Time } -// CreateAdminPaymentInput records a complimentary / admin-panel payment row. +// CreateAdminPaymentInput records an admin-panel payment as SUCCESS at the plan price +// (treated as charged for revenue/analytics; no gateway checkout). type CreateAdminPaymentInput struct { UserID int64 PlanID *int64 diff --git a/internal/domain/subscriptions.go b/internal/domain/subscriptions.go index 52e1d9a0..e9c7553c 100644 --- a/internal/domain/subscriptions.go +++ b/internal/domain/subscriptions.go @@ -155,8 +155,8 @@ type CreateUserSubscriptionInput struct { AutoRenew *bool } -// AdminExtendSubscriptionInput extends a learner subscription from the admin panel. -// Provide exactly one of: NewExpiresAt, DurationValue+DurationUnit, or RenewOnePeriod. +// AdminExtendSubscriptionInput is kept for API completeness; the admin panel +// unified endpoint only sends plan_id and renews one period of that plan. type AdminExtendSubscriptionInput struct { NewExpiresAt *time.Time DurationValue *int32 @@ -164,6 +164,12 @@ type AdminExtendSubscriptionInput struct { RenewOnePeriod bool } +// AdminApplySubscriptionResult is the outcome of the unified grant-or-extend admin API. +type AdminApplySubscriptionResult struct { + Subscription *UserSubscription + Created bool // true when a new subscription row was granted +} + // LifetimeSubscriptionExpiresAt is stored for one-time (non-expiring) DUOLINGO subscriptions. var LifetimeSubscriptionExpiresAt = time.Date(9999, 12, 31, 23, 59, 59, 0, time.UTC) diff --git a/internal/ports/subscriptions.go b/internal/ports/subscriptions.go index 941c8201..a3aae7f5 100644 --- a/internal/ports/subscriptions.go +++ b/internal/ports/subscriptions.go @@ -29,7 +29,7 @@ type SubscriptionStore interface { UpdateSubscriptionStatus(ctx context.Context, id int64, status string) error UpdateAutoRenew(ctx context.Context, id int64, autoRenew bool) error ExtendSubscription(ctx context.Context, id int64, newExpiresAt time.Time) error - AdminExtendUserSubscription(ctx context.Context, id int64, newExpiresAt time.Time) error + AdminExtendUserSubscription(ctx context.Context, id, planID int64, newExpiresAt time.Time) error ListUserSubscriptionsAdmin(ctx context.Context, filter domain.UserSubscriptionAdminFilter) (domain.UserSubscriptionAdminPage, error) ListLearnEnglishSubscriptionsExpiringInSevenDays(ctx context.Context) ([]domain.SubscriptionExpiryReminder, error) } diff --git a/internal/repository/subscriptions.go b/internal/repository/subscriptions.go index 91b6b5bd..58695eef 100644 --- a/internal/repository/subscriptions.go +++ b/internal/repository/subscriptions.go @@ -270,8 +270,9 @@ func (s *Store) ExtendSubscription(ctx context.Context, id int64, newExpiresAt t }) } -func (s *Store) AdminExtendUserSubscription(ctx context.Context, id int64, newExpiresAt time.Time) error { +func (s *Store) AdminExtendUserSubscription(ctx context.Context, id, planID int64, newExpiresAt time.Time) error { return s.queries.AdminExtendUserSubscription(ctx, dbgen.AdminExtendUserSubscriptionParams{ + PlanID: planID, ExpiresAt: toPgTimestamptz(newExpiresAt), ID: id, }) diff --git a/internal/services/rbac/seeds.go b/internal/services/rbac/seeds.go index ee5503fe..49b39e2a 100644 --- a/internal/services/rbac/seeds.go +++ b/internal/services/rbac/seeds.go @@ -169,8 +169,7 @@ var AllPermissions = []domain.PermissionSeed{ {Key: "subscriptions.status", Name: "Check Subscription Status", Description: "Check subscription status", GroupName: "Subscriptions"}, {Key: "subscriptions.cancel", Name: "Cancel Subscription", Description: "Cancel own subscription", GroupName: "Subscriptions"}, {Key: "subscriptions.admin_cancel", Name: "Cancel User Subscription (Admin)", Description: "Cancel any learner subscription from the admin panel", GroupName: "Subscriptions"}, - {Key: "subscriptions.admin_extend", Name: "Extend User Subscription (Admin)", Description: "Extend any learner subscription from the admin panel", GroupName: "Subscriptions"}, - {Key: "subscriptions.admin_grant", Name: "Grant User Subscription (Admin)", Description: "Assign a subscription plan to a learner from the admin panel", GroupName: "Subscriptions"}, + {Key: "subscriptions.admin_extend", Name: "Grant or Extend User Subscription (Admin)", Description: "Grant a plan to a learner or extend their active subscription in that category from the admin panel", GroupName: "Subscriptions"}, {Key: "subscriptions.set_auto_renew", Name: "Set Auto Renew", Description: "Set auto-renew on subscription", GroupName: "Subscriptions"}, // Payments @@ -458,7 +457,7 @@ var DefaultRolePermissions = map[string][]string{ // Subscriptions & Payments (full access) "subscription_plans.create", "subscription_plans.update", "subscription_plans.delete", "subscriptions.create", "subscriptions.checkout", "subscriptions.get_mine", "subscriptions.get_by_user", "subscriptions.export", "subscriptions.history", - "subscriptions.status", "subscriptions.cancel", "subscriptions.admin_cancel", "subscriptions.admin_extend", "subscriptions.admin_grant", "subscriptions.set_auto_renew", + "subscriptions.status", "subscriptions.cancel", "subscriptions.admin_cancel", "subscriptions.admin_extend", "subscriptions.set_auto_renew", "payments.initiate", "payments.verify", "payments.list_mine", "payments.get", "payments.cancel", "payments.direct_initiate", "payments.direct_verify_otp", "payments.list_all", "payments.export", diff --git a/internal/services/subscriptions/service.go b/internal/services/subscriptions/service.go index 1e3725f4..ee4cd312 100644 --- a/internal/services/subscriptions/service.go +++ b/internal/services/subscriptions/service.go @@ -97,8 +97,8 @@ func (s *Service) Subscribe(ctx context.Context, userID, planID int64, paymentRe return s.store.CreateUserSubscription(ctx, input) } -// AdminGrantSubscription assigns a plan to a learner without payment (admin panel). -// Optional newExpiresAt overrides the plan-derived expiry. Inactive plans are allowed. +// AdminGrantSubscription assigns a plan to a learner (admin panel). +// Prefer AdminApplySubscription for the unified grant-or-extend flow. func (s *Service) AdminGrantSubscription(ctx context.Context, userID, planID int64, newExpiresAt *time.Time, note *string) (*domain.UserSubscription, error) { plan, err := s.store.GetSubscriptionPlanByID(ctx, planID) if err != nil { @@ -113,6 +113,10 @@ func (s *Service) AdminGrantSubscription(ctx context.Context, userID, planID int return nil, ErrAlreadySubscribed } + return s.createAdminGrantedSubscription(ctx, userID, plan, newExpiresAt, note) +} + +func (s *Service) createAdminGrantedSubscription(ctx context.Context, userID int64, plan *domain.SubscriptionPlan, newExpiresAt *time.Time, note *string) (*domain.UserSubscription, error) { startsAt := time.Now() expiresAt := domain.CalculateSubscriptionExpiresAt(startsAt, plan.Category, plan.DurationValue, plan.DurationUnit) if newExpiresAt != nil { @@ -125,7 +129,7 @@ func (s *Service) AdminGrantSubscription(ctx context.Context, userID, planID int method := "ADMIN_GRANT" input := domain.CreateUserSubscriptionInput{ UserID: userID, - PlanID: planID, + PlanID: plan.ID, StartsAt: &startsAt, ExpiresAt: expiresAt, Status: strPtr(string(domain.SubscriptionStatusActive)), @@ -144,6 +148,64 @@ func (s *Service) AdminGrantSubscription(ctx context.Context, userID, planID int return s.GetSubscriptionByID(ctx, sub.ID) } +// AdminApplySubscription grants a plan when the learner has no active subscription +// in that plan's category, or extends (and may switch plan within the category) +// the active subscription by one period of the selected plan. +func (s *Service) AdminApplySubscription(ctx context.Context, userID, planID int64) (*domain.AdminApplySubscriptionResult, error) { + plan, err := s.store.GetSubscriptionPlanByID(ctx, planID) + if err != nil { + return nil, ErrPlanNotFound + } + + active, err := s.store.ListActiveSubscriptionsByUserID(ctx, userID) + if err != nil { + return nil, err + } + + var existing *domain.UserSubscription + for i := range active { + cat := "" + if active[i].PlanCategory != nil { + cat = *active[i].PlanCategory + } + if cat == plan.Category { + existing = &active[i] + break + } + } + + if existing == nil { + sub, err := s.createAdminGrantedSubscription(ctx, userID, plan, nil, nil) + if err != nil { + return nil, err + } + return &domain.AdminApplySubscriptionResult{Subscription: sub, Created: true}, nil + } + + baseTime := existing.ExpiresAt + if baseTime.Before(time.Now()) { + baseTime = time.Now() + } + newExpiry := domain.CalculateSubscriptionExpiresAt(baseTime, plan.Category, plan.DurationValue, plan.DurationUnit) + if newExpiry.Before(time.Now()) { + return nil, ErrExtendExpiresInPast + } + + if err := s.store.AdminExtendUserSubscription(ctx, existing.ID, plan.ID, newExpiry); err != nil { + return nil, err + } + + updated, err := s.GetSubscriptionByID(ctx, existing.ID) + if err != nil { + return nil, err + } + note := fmt.Sprintf("admin extend to %s", updated.ExpiresAt.UTC().Format(time.RFC3339)) + if err := s.recordAdminPayment(ctx, updated, plan, "ADMIN_EXTEND", ¬e); err != nil { + return nil, err + } + return &domain.AdminApplySubscriptionResult{Subscription: updated, Created: false}, nil +} + func (s *Service) GetSubscriptionByID(ctx context.Context, id int64) (*domain.UserSubscription, error) { sub, err := s.store.GetUserSubscriptionByID(ctx, id) if err != nil { @@ -224,7 +286,8 @@ func (s *Service) AdminCancelSubscription(ctx context.Context, subscriptionID in return s.GetSubscriptionByID(ctx, subscriptionID) } -// AdminExtendSubscription extends (and reactivates) any learner subscription (admin panel). +// AdminExtendSubscription extends (and reactivates) any learner subscription by ID (admin panel). +// Prefer AdminApplySubscription for the unified user+plan flow. func (s *Service) AdminExtendSubscription(ctx context.Context, subscriptionID int64, input domain.AdminExtendSubscriptionInput) (*domain.UserSubscription, error) { sub, err := s.GetSubscriptionByID(ctx, subscriptionID) if err != nil { @@ -239,7 +302,7 @@ func (s *Service) AdminExtendSubscription(ctx context.Context, subscriptionID in return nil, ErrExtendExpiresInPast } - if err := s.store.AdminExtendUserSubscription(ctx, subscriptionID, newExpiry); err != nil { + if err := s.store.AdminExtendUserSubscription(ctx, subscriptionID, sub.PlanID, newExpiry); err != nil { return nil, err } @@ -272,7 +335,7 @@ func (s *Service) recordAdminPayment(ctx context.Context, sub *domain.UserSubscr UserID: sub.UserID, PlanID: &planID, SubscriptionID: sub.ID, - Amount: 0, + Amount: plan.Price, Currency: currency, PaymentMethod: method, Nonce: fmt.Sprintf("admin-%s-%s", method, helpers.GenerateID()), diff --git a/internal/web_server/handlers/admin_subscription_handler.go b/internal/web_server/handlers/admin_subscription_handler.go index 416f7ac3..78f0ee4f 100644 --- a/internal/web_server/handlers/admin_subscription_handler.go +++ b/internal/web_server/handlers/admin_subscription_handler.go @@ -12,35 +12,26 @@ import ( "github.com/gofiber/fiber/v2" ) -type adminExtendSubscriptionReq struct { - NewExpiresAt *time.Time `json:"new_expires_at"` - DurationValue *int32 `json:"duration_value" validate:"omitempty,min=1"` - DurationUnit *string `json:"duration_unit" validate:"omitempty,oneof=DAY WEEK MONTH YEAR"` - RenewOnePeriod bool `json:"renew_one_period"` +type adminApplySubscriptionReq struct { + PlanID int64 `json:"plan_id" validate:"required,min=1"` } -type adminGrantSubscriptionReq struct { - PlanID int64 `json:"plan_id" validate:"required,min=1"` - NewExpiresAt *time.Time `json:"new_expires_at"` - Note *string `json:"note" validate:"omitempty,max=255"` -} - -// AdminGrantUserSubscription godoc -// @Summary Grant a subscription plan to a learner (admin) -// @Description Creates an active subscription for the target learner from a selected plan (no payment). Fails if the user already has an active subscription in that plan category. +// AdminExtendOrGrantUserSubscription godoc +// @Summary Grant or extend a learner subscription (admin) +// @Description Unified admin action: if the learner has no active subscription in the plan's category, creates one (grant). If they already have an active subscription in that category, extends it by one period of the selected plan (and switches plan_id when different). Records a SUCCESS payment at the plan price. // @Tags subscriptions // @Accept json // @Produce json // @Security Bearer // @Param user_id path int true "Target learner user ID" -// @Param body body adminGrantSubscriptionReq true "Grant payload" +// @Param body body adminApplySubscriptionReq true "Plan to grant or extend" +// @Success 200 {object} domain.Response // @Success 201 {object} domain.Response // @Failure 400 {object} domain.ErrorResponse // @Failure 404 {object} domain.ErrorResponse -// @Failure 409 {object} domain.ErrorResponse // @Failure 500 {object} domain.ErrorResponse -// @Router /api/v1/admin/users/{user_id}/subscriptions [post] -func (h *Handler) AdminGrantUserSubscription(c *fiber.Ctx) error { +// @Router /api/v1/admin/users/{user_id}/subscriptions/extend [post] +func (h *Handler) AdminExtendOrGrantUserSubscription(c *fiber.Ctx) error { targetID, err := parseAdminTargetUserID(c) if err != nil { return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{ @@ -64,12 +55,12 @@ func (h *Handler) AdminGrantUserSubscription(c *fiber.Ctx) error { } if !user.Role.IsCustomerLearnerRole() { return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{ - Message: "Failed to grant subscription", + Message: "Failed to apply subscription", Error: "Target user is not a learner account", }) } - var req adminGrantSubscriptionReq + var req adminApplySubscriptionReq if err := c.BodyParser(&req); err != nil { return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{ Message: "Invalid request body", @@ -86,19 +77,16 @@ func (h *Handler) AdminGrantUserSubscription(c *fiber.Ctx) error { plan, err := h.subscriptionsSvc.GetPlanByID(c.Context(), req.PlanID) if err != nil { return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{ - Message: "Failed to grant subscription", + Message: "Failed to apply subscription", Error: "Subscription plan not found", }) } - sub, err := h.subscriptionsSvc.AdminGrantSubscription(c.Context(), targetID, req.PlanID, req.NewExpiresAt, req.Note) + result, err := h.subscriptionsSvc.AdminApplySubscription(c.Context(), targetID, req.PlanID) if err != nil { - return h.mapAdminSubscriptionMutationError(c, err, "Failed to grant subscription") - } - - if h.learnerNotifSvc != nil { - h.learnerNotifSvc.MaybeNotifyLearnPackageSubscribed(targetID, plan.Category, plan.Name, sub.ExpiresAt) + return h.mapAdminSubscriptionMutationError(c, err, "Failed to apply subscription") } + sub := result.Subscription meta, _ := json.Marshal(map[string]interface{}{ "subscription_id": sub.ID, @@ -106,16 +94,32 @@ func (h *Handler) AdminGrantUserSubscription(c *fiber.Ctx) error { "plan_id": req.PlanID, "plan_category": plan.Category, "expires_at": sub.ExpiresAt, - "note": req.Note, + "created": result.Created, }) - h.recordActivity(c, domain.ActionSubscriptionCreated, domain.ResourceSubscription, &sub.ID, - fmt.Sprintf("Admin granted plan %d to user %d (subscription ID: %d)", req.PlanID, targetID, sub.ID), meta) - return c.Status(fiber.StatusCreated).JSON(domain.Response{ - Message: "Subscription granted successfully", + if result.Created { + if h.learnerNotifSvc != nil { + h.learnerNotifSvc.MaybeNotifyLearnPackageSubscribed(targetID, plan.Category, plan.Name, sub.ExpiresAt) + } + h.recordActivity(c, domain.ActionSubscriptionCreated, domain.ResourceSubscription, &sub.ID, + fmt.Sprintf("Admin granted plan %d to user %d (subscription ID: %d)", req.PlanID, targetID, sub.ID), meta) + + return c.Status(fiber.StatusCreated).JSON(domain.Response{ + Message: "Subscription granted successfully", + Data: subscriptionToRes(sub), + Success: true, + StatusCode: fiber.StatusCreated, + }) + } + + h.recordActivity(c, domain.ActionSubscriptionExtended, domain.ResourceSubscription, &sub.ID, + fmt.Sprintf("Admin extended subscription ID: %d (user %d) to %s", sub.ID, targetID, sub.ExpiresAt.Format(time.RFC3339)), meta) + + return c.JSON(domain.Response{ + Message: "Subscription extended successfully", Data: subscriptionToRes(sub), Success: true, - StatusCode: fiber.StatusCreated, + StatusCode: fiber.StatusOK, }) } @@ -161,70 +165,6 @@ func (h *Handler) AdminCancelUserSubscription(c *fiber.Ctx) error { }) } -// AdminExtendUserSubscription godoc -// @Summary Extend a learner subscription (admin) -// @Description Extends expiry and reactivates the subscription. Provide exactly one of: new_expires_at, duration_value+duration_unit, or renew_one_period=true. -// @Tags subscriptions -// @Accept json -// @Produce json -// @Security Bearer -// @Param id path int true "Subscription ID" -// @Param body body adminExtendSubscriptionReq true "Extend payload" -// @Success 200 {object} domain.Response -// @Failure 400 {object} domain.ErrorResponse -// @Failure 404 {object} domain.ErrorResponse -// @Failure 500 {object} domain.ErrorResponse -// @Router /api/v1/admin/subscriptions/{id}/extend [post] -func (h *Handler) AdminExtendUserSubscription(c *fiber.Ctx) error { - id, err := strconv.ParseInt(c.Params("id"), 10, 64) - if err != nil || id <= 0 { - return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{ - Message: "Invalid subscription ID", - Error: "subscription ID must be a valid positive integer", - }) - } - - var req adminExtendSubscriptionReq - if err := c.BodyParser(&req); err != nil { - return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{ - Message: "Invalid request body", - Error: err.Error(), - }) - } - if valErrs, ok := h.validator.Validate(c, req); !ok { - return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{ - Message: "Validation failed", - Error: firstValidationError(valErrs), - }) - } - - sub, err := h.subscriptionsSvc.AdminExtendSubscription(c.Context(), id, domain.AdminExtendSubscriptionInput{ - NewExpiresAt: req.NewExpiresAt, - DurationValue: req.DurationValue, - DurationUnit: req.DurationUnit, - RenewOnePeriod: req.RenewOnePeriod, - }) - if err != nil { - return h.mapAdminSubscriptionMutationError(c, err, "Failed to extend subscription") - } - - meta, _ := json.Marshal(map[string]interface{}{ - "subscription_id": id, - "user_id": sub.UserID, - "plan_id": sub.PlanID, - "expires_at": sub.ExpiresAt, - }) - h.recordActivity(c, domain.ActionSubscriptionExtended, domain.ResourceSubscription, &id, - fmt.Sprintf("Admin extended subscription ID: %d (user %d) to %s", id, sub.UserID, sub.ExpiresAt.Format(time.RFC3339)), meta) - - return c.JSON(domain.Response{ - Message: "Subscription extended successfully", - Data: subscriptionToRes(sub), - Success: true, - StatusCode: fiber.StatusOK, - }) -} - func (h *Handler) mapAdminSubscriptionMutationError(c *fiber.Ctx, err error, message string) error { switch { case errors.Is(err, subscriptionsvc.ErrSubscriptionNotFound): diff --git a/internal/web_server/routes.go b/internal/web_server/routes.go index 110ffd73..0480ab81 100644 --- a/internal/web_server/routes.go +++ b/internal/web_server/routes.go @@ -364,12 +364,11 @@ func (a *App) initAppRoutes() { groupV1.Get("/admin/users/deletion-requests", a.authMiddleware, a.RequirePermission("users.deletion_requests.list"), h.ListAccountDeletionRequests) groupV1.Get("/admin/subscriptions/export", a.authMiddleware, a.RequirePermission("subscriptions.export"), h.ExportUserSubscriptionsCSV) groupV1.Post("/admin/subscriptions/:id/cancel", a.authMiddleware, a.RequirePermission("subscriptions.admin_cancel"), h.AdminCancelUserSubscription) - groupV1.Post("/admin/subscriptions/:id/extend", a.authMiddleware, a.RequirePermission("subscriptions.admin_extend"), h.AdminExtendUserSubscription) groupV1.Get("/admin/users/:user_id/lms-learning-activity", a.authMiddleware, a.RequirePermission("progress.get_any_user"), h.AdminGetUserLMSLearningActivity) groupV1.Get("/admin/users/:user_id/recent-activity", a.authMiddleware, a.RequirePermission("progress.get_any_user"), h.AdminGetUserRecentActivity) groupV1.Get("/admin/users/:user_id/learning-activity", a.authMiddleware, a.RequirePermission("progress.get_any_user"), h.AdminGetUserLearningActivityDetails) groupV1.Get("/admin/users/:user_id/subscriptions", a.authMiddleware, a.RequirePermission("subscriptions.get_by_user"), h.AdminGetUserSubscriptions) - groupV1.Post("/admin/users/:user_id/subscriptions", a.authMiddleware, a.RequirePermission("subscriptions.admin_grant"), h.AdminGrantUserSubscription) + groupV1.Post("/admin/users/:user_id/subscriptions/extend", a.authMiddleware, a.RequirePermission("subscriptions.admin_extend"), h.AdminExtendOrGrantUserSubscription) groupV1.Get("/users/summary", a.authMiddleware, a.RequirePermission("users.summary"), h.GetUserSummary) groupV1.Put("/user", a.authMiddleware, a.RequirePermission("users.update_self"), h.UpdateUser) groupV1.Patch("/user/status", a.authMiddleware, a.RequirePermission("users.update_status"), h.UpdateUserStatus)