Allow optional payment recording on admin grant/extend subscriptions.
Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
parent
a44eee78b7
commit
9f10bc161d
|
|
@ -40,7 +40,7 @@ Admins manage learner access without Chapa/ArifPay checkout via **one** apply en
|
|||
|
||||
| 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 |
|
||||
| **Grant or extend** | `POST /api/v1/admin/users/:user_id/subscriptions/extend` | `subscriptions.admin_extend` | `201` grant / `200` extend | Body: `{ "plan_id", "record_payment?" }`. No active sub in plan category → **grant**. Active sub in that category → **extend** by one period of the selected plan. `record_payment` defaults to `true` |
|
||||
| **Cancel** | `POST /api/v1/admin/subscriptions/:id/cancel` | `subscriptions.admin_cancel` | `200` | Cancel subscription by ID |
|
||||
|
||||
| Supporting read | Endpoint | Permission |
|
||||
|
|
@ -53,8 +53,10 @@ Admins manage learner access without Chapa/ArifPay checkout via **one** apply en
|
|||
|
||||
| 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 |
|
||||
| **Grant** + `record_payment: true` (default) | Creates new `ACTIVE` row | `SUCCESS` at **plan price**, method `ADMIN_GRANT` | `201` — Subscription granted successfully |
|
||||
| **Grant** + `record_payment: false` | Creates new `ACTIVE` row | **No** payments row | `201` — Subscription granted successfully (no payment recorded) |
|
||||
| **Extend** + `record_payment: true` (default) | Updates `expires_at`, sets `ACTIVE`, may update `plan_id` to selected plan | `SUCCESS` at **plan price**, method `ADMIN_EXTEND` | `200` — Subscription extended successfully |
|
||||
| **Extend** + `record_payment: false` | Same subscription update | **No** payments row | `200` — Subscription extended successfully (no payment recorded) |
|
||||
| **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.
|
||||
|
|
@ -70,17 +72,21 @@ sequenceDiagram
|
|||
participant DB as Postgres
|
||||
participant Notif as Learner notifications
|
||||
|
||||
Admin->>API: POST /admin/users/{user_id}/subscriptions/extend { plan_id }
|
||||
Admin->>API: POST /admin/users/{user_id}/subscriptions/extend { plan_id, record_payment? }
|
||||
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)
|
||||
opt record_payment true (default)
|
||||
API->>DB: INSERT payments (ADMIN_GRANT, plan.price, SUCCESS)
|
||||
end
|
||||
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)
|
||||
opt record_payment true (default)
|
||||
API->>DB: INSERT payments (ADMIN_EXTEND, plan.price, SUCCESS)
|
||||
end
|
||||
API->>DB: Activity SUBSCRIPTION_EXTENDED
|
||||
API-->>Admin: 200 extended
|
||||
end
|
||||
|
|
@ -191,15 +197,17 @@ Display helpers from `GET .../users/:user_id/subscriptions`:
|
|||
|
||||
| Action | Payment effect |
|
||||
|--------|----------------|
|
||||
| Grant | New row: `status=SUCCESS`, `amount=<plan.price>`, `payment_method=ADMIN_GRANT`, linked `subscription_id` / `plan_id` |
|
||||
| Extend | New row: `status=SUCCESS`, `amount=<plan.price>`, `payment_method=ADMIN_EXTEND` |
|
||||
| Grant with `record_payment: true` (default) | New row: `status=SUCCESS`, `amount=<plan.price>`, `payment_method=ADMIN_GRANT`, linked `subscription_id` / `plan_id` |
|
||||
| Grant with `record_payment: false` | No payments row |
|
||||
| Extend with `record_payment: true` (default) | New row: `status=SUCCESS`, `amount=<plan.price>`, `payment_method=ADMIN_EXTEND` |
|
||||
| Extend with `record_payment: false` | No payments row |
|
||||
| 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.
|
||||
When a payment is recorded, 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. Complimentary grants/extends (`record_payment: false`) do **not** affect revenue.
|
||||
|
||||
### 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`.
|
||||
Admin grant/extend `SUCCESS` payments **count toward revenue** (same as gateway payments). Complimentary apply (`record_payment: false`) does not. Subscription **status counts** still reflect cancel/extend/grant via `user_subscriptions`.
|
||||
|
||||
### Learner notification
|
||||
|
||||
|
|
@ -209,8 +217,8 @@ On **successful grant**, the API may send a learn-package subscribed notificatio
|
|||
|
||||
| Action | `action` | `resource_type` | Notes |
|
||||
|--------|----------|-----------------|-------|
|
||||
| Grant | `SUBSCRIPTION_CREATED` | `SUBSCRIPTION` | Metadata includes `created: true` |
|
||||
| Extend | `SUBSCRIPTION_EXTENDED` | `SUBSCRIPTION` | Metadata includes `created: false` |
|
||||
| Grant | `SUBSCRIPTION_CREATED` | `SUBSCRIPTION` | Metadata includes `created: true`, `record_payment`, `payment_recorded` |
|
||||
| Extend | `SUBSCRIPTION_EXTENDED` | `SUBSCRIPTION` | Metadata includes `created: false`, `record_payment`, `payment_recorded` |
|
||||
| Cancel | `SUBSCRIPTION_CANCELLED` | `SUBSCRIPTION` | Same action as learner cancel |
|
||||
|
||||
Ensure the activity-logs UI can display `SUBSCRIPTION_EXTENDED` (label e.g. "Subscription extended").
|
||||
|
|
@ -305,24 +313,31 @@ Content-Type: application/json
|
|||
|---------------|------|----------|-------|
|
||||
| `user_id` (path) | int | Yes | Existing learner |
|
||||
| `plan_id` (body) | int64 | Yes | `min=1`; plan must exist |
|
||||
| `record_payment` (body) | bool | No | Default `true`. When `true`, insert SUCCESS payment at plan price. When `false`, grant/extend with no payments row |
|
||||
|
||||
```json
|
||||
{ "plan_id": 3 }
|
||||
{ "plan_id": 3, "record_payment": true }
|
||||
```
|
||||
|
||||
```json
|
||||
{ "plan_id": 3, "record_payment": false }
|
||||
```
|
||||
|
||||
### 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 |
|
||||
| No active subscription in plan's category | **Grant** — create row; payment `ADMIN_GRANT` only if `record_payment` is true |
|
||||
| Active subscription in plan's category | **Extend** — add one period of selected plan; payment `ADMIN_EXTEND` only if `record_payment` is true; update `plan_id` if different |
|
||||
|
||||
### Success
|
||||
|
||||
| Case | Status | Message |
|
||||
|------|--------|---------|
|
||||
| Grant | `201 Created` | `Subscription granted successfully` |
|
||||
| Extend | `200 OK` | `Subscription extended successfully` |
|
||||
| Grant + payment | `201 Created` | `Subscription granted successfully` |
|
||||
| Grant without payment | `201 Created` | `Subscription granted successfully (no payment recorded)` |
|
||||
| Extend + payment | `200 OK` | `Subscription extended successfully` |
|
||||
| Extend without payment | `200 OK` | `Subscription extended successfully (no payment recorded)` |
|
||||
|
||||
### Common failures
|
||||
|
||||
|
|
@ -361,7 +376,8 @@ After cancel, call the unified extend endpoint again with a `plan_id` to grant a
|
|||
| 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 |
|
||||
| Body `{ plan_id, record_payment? }` | Custom date, note, or `renew_one_period` fields |
|
||||
| Explicit **Record payment** vs **No payment** choice | Always forcing a plan-price payment |
|
||||
| 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 |
|
||||
|
|
@ -394,6 +410,8 @@ function filterPlans(plans: SubscriptionPlan[], query: string): SubscriptionPlan
|
|||
```ts
|
||||
export interface AdminApplySubscriptionBody {
|
||||
plan_id: number;
|
||||
/** Default true when omitted. false = complimentary grant/extend (no payments row). */
|
||||
record_payment?: boolean;
|
||||
}
|
||||
|
||||
export interface SubscriptionRes {
|
||||
|
|
@ -416,7 +434,8 @@ const base = process.env.NEXT_PUBLIC_API_BASE_URL; // .../api/v1
|
|||
async function adminApplySubscription(
|
||||
token: string,
|
||||
userId: number,
|
||||
planId: number
|
||||
planId: number,
|
||||
recordPayment = true
|
||||
): Promise<{ status: number; data: SubscriptionRes; message: string }> {
|
||||
const res = await fetch(`${base}/admin/users/${userId}/subscriptions/extend`, {
|
||||
method: "POST",
|
||||
|
|
@ -424,7 +443,10 @@ async function adminApplySubscription(
|
|||
Authorization: `Bearer ${token}`,
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify({ plan_id: planId } satisfies AdminApplySubscriptionBody),
|
||||
body: JSON.stringify({
|
||||
plan_id: planId,
|
||||
record_payment: recordPayment,
|
||||
} satisfies AdminApplySubscriptionBody),
|
||||
});
|
||||
const json = await res.json();
|
||||
if (!res.ok) {
|
||||
|
|
@ -458,7 +480,7 @@ Use `status === 201` (or message containing "granted") to distinguish grant vs e
|
|||
|
||||
| Action | Confirm button | Notes |
|
||||
|--------|----------------|-------|
|
||||
| Grant / extend | Confirm | Mention plan price; wording grant vs extend from `active_by_category` |
|
||||
| Grant / extend | Confirm | Choose **Record payment** (plan price) or **No payment**; wording grant vs extend from `active_by_category` |
|
||||
| Cancel | Confirm cancel | Destructive |
|
||||
|
||||
---
|
||||
|
|
@ -466,7 +488,8 @@ Use `status === 201` (or message containing "granted") to distinguish grant vs e
|
|||
## Integration checklist
|
||||
|
||||
- [ ] Single apply button gated on `subscriptions.admin_extend`
|
||||
- [ ] `POST /admin/users/:user_id/subscriptions/extend` with `{ plan_id }` only
|
||||
- [ ] `POST /admin/users/:user_id/subscriptions/extend` with `{ plan_id, record_payment? }`
|
||||
- [ ] UI choice: record plan-price payment vs complimentary (no payment)
|
||||
- [ ] 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`
|
||||
|
|
@ -477,8 +500,10 @@ Use `status === 201` (or message containing "granted") to distinguish grant vs e
|
|||
|
||||
## Testing checklist
|
||||
|
||||
- [ ] No active in category → `201`, `ADMIN_GRANT`, amount = plan.price
|
||||
- [ ] Active in category → `200`, `ADMIN_EXTEND`, expiry moved by plan period
|
||||
- [ ] No active in category + `record_payment: true` → `201`, `ADMIN_GRANT`, amount = plan.price
|
||||
- [ ] No active in category + `record_payment: false` → `201`, no new payments row
|
||||
- [ ] Active in category + `record_payment: true` → `200`, `ADMIN_EXTEND`, expiry moved by plan period
|
||||
- [ ] Active in category + `record_payment: false` → `200`, no new payments row
|
||||
- [ ] Different plan same category → extend updates `plan_id`
|
||||
- [ ] Non-learner → `400`
|
||||
- [ ] Cancel preserves SUCCESS payments
|
||||
|
|
@ -490,12 +515,14 @@ Use `status === 201` (or message containing "granted") to distinguish grant vs e
|
|||
|
||||
| Method | Path | Permission | Body |
|
||||
|--------|------|------------|------|
|
||||
| `POST` | `/api/v1/admin/users/:user_id/subscriptions/extend` | `subscriptions.admin_extend` | `{ "plan_id": <id> }` |
|
||||
| `POST` | `/api/v1/admin/users/:user_id/subscriptions/extend` | `subscriptions.admin_extend` | `{ "plan_id": <id>, "record_payment"?: true\|false }` |
|
||||
| `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 |
|
||||
| Outcome | HTTP | Payment |
|
||||
|---------|------|---------|
|
||||
| Grant + `record_payment: true` | `201` | `ADMIN_GRANT` @ plan price |
|
||||
| Grant + `record_payment: false` | `201` | none |
|
||||
| Extend + `record_payment: true` | `200` | `ADMIN_EXTEND` @ plan price |
|
||||
| Extend + `record_payment: false` | `200` | none |
|
||||
|
|
|
|||
|
|
@ -180,10 +180,19 @@ type AdminExtendSubscriptionInput struct {
|
|||
RenewOnePeriod bool
|
||||
}
|
||||
|
||||
// AdminApplySubscriptionInput is the unified admin grant-or-extend request.
|
||||
type AdminApplySubscriptionInput struct {
|
||||
PlanID int64
|
||||
// RecordPayment when true creates a SUCCESS payment at the plan price.
|
||||
// When false, access is granted/extended with no payments row.
|
||||
RecordPayment 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
|
||||
Subscription *UserSubscription
|
||||
Created bool // true when a new subscription row was granted
|
||||
PaymentRecorded bool // true when a SUCCESS admin payment was inserted
|
||||
}
|
||||
|
||||
// LifetimeSubscriptionExpiresAt is stored for one-time (non-expiring) subscription plans.
|
||||
|
|
|
|||
|
|
@ -155,15 +155,23 @@ func (s *Service) AdminGrantSubscription(ctx context.Context, userID, planID int
|
|||
return nil, ErrAlreadySubscribed
|
||||
}
|
||||
|
||||
return s.createAdminGrantedSubscription(ctx, userID, plan, newExpiresAt, note)
|
||||
sub, _, err := s.createAdminGrantedSubscription(ctx, userID, plan, newExpiresAt, note, true)
|
||||
return sub, err
|
||||
}
|
||||
|
||||
func (s *Service) createAdminGrantedSubscription(ctx context.Context, userID int64, plan *domain.SubscriptionPlan, newExpiresAt *time.Time, note *string) (*domain.UserSubscription, error) {
|
||||
func (s *Service) createAdminGrantedSubscription(
|
||||
ctx context.Context,
|
||||
userID int64,
|
||||
plan *domain.SubscriptionPlan,
|
||||
newExpiresAt *time.Time,
|
||||
note *string,
|
||||
recordPayment bool,
|
||||
) (*domain.UserSubscription, bool, error) {
|
||||
startsAt := time.Now()
|
||||
expiresAt := domain.CalculateSubscriptionExpiresAt(startsAt, plan.IsLifetime, plan.DurationValue, plan.DurationUnit)
|
||||
if newExpiresAt != nil {
|
||||
if newExpiresAt.Before(time.Now()) {
|
||||
return nil, ErrExtendExpiresInPast
|
||||
return nil, false, ErrExtendExpiresInPast
|
||||
}
|
||||
expiresAt = newExpiresAt.UTC()
|
||||
}
|
||||
|
|
@ -182,20 +190,30 @@ func (s *Service) createAdminGrantedSubscription(ctx context.Context, userID int
|
|||
|
||||
sub, err := s.store.CreateUserSubscription(ctx, input)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
return nil, false, err
|
||||
}
|
||||
if err := s.recordAdminPayment(ctx, sub, plan, method, note); err != nil {
|
||||
return nil, err
|
||||
paymentRecorded := false
|
||||
if recordPayment {
|
||||
recorded, err := s.recordAdminPayment(ctx, sub, plan, method, note)
|
||||
if err != nil {
|
||||
return nil, false, err
|
||||
}
|
||||
paymentRecorded = recorded
|
||||
}
|
||||
s.invalidateActiveSubscriptionCache(userID)
|
||||
return s.GetSubscriptionByID(ctx, sub.ID)
|
||||
updated, err := s.GetSubscriptionByID(ctx, sub.ID)
|
||||
if err != nil {
|
||||
return nil, paymentRecorded, err
|
||||
}
|
||||
return updated, paymentRecorded, nil
|
||||
}
|
||||
|
||||
// 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)
|
||||
// When input.RecordPayment is true, a SUCCESS payment at the plan price is recorded.
|
||||
func (s *Service) AdminApplySubscription(ctx context.Context, userID int64, input domain.AdminApplySubscriptionInput) (*domain.AdminApplySubscriptionResult, error) {
|
||||
plan, err := s.store.GetSubscriptionPlanByID(ctx, input.PlanID)
|
||||
if err != nil {
|
||||
return nil, ErrPlanNotFound
|
||||
}
|
||||
|
|
@ -218,11 +236,15 @@ func (s *Service) AdminApplySubscription(ctx context.Context, userID, planID int
|
|||
}
|
||||
|
||||
if existing == nil {
|
||||
sub, err := s.createAdminGrantedSubscription(ctx, userID, plan, nil, nil)
|
||||
sub, paymentRecorded, err := s.createAdminGrantedSubscription(ctx, userID, plan, nil, nil, input.RecordPayment)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &domain.AdminApplySubscriptionResult{Subscription: sub, Created: true}, nil
|
||||
return &domain.AdminApplySubscriptionResult{
|
||||
Subscription: sub,
|
||||
Created: true,
|
||||
PaymentRecorded: paymentRecorded,
|
||||
}, nil
|
||||
}
|
||||
|
||||
baseTime := existing.ExpiresAt
|
||||
|
|
@ -242,12 +264,21 @@ func (s *Service) AdminApplySubscription(ctx context.Context, userID, planID int
|
|||
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
|
||||
paymentRecorded := false
|
||||
if input.RecordPayment {
|
||||
note := fmt.Sprintf("admin extend to %s", updated.ExpiresAt.UTC().Format(time.RFC3339))
|
||||
recorded, err := s.recordAdminPayment(ctx, updated, plan, "ADMIN_EXTEND", ¬e)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
paymentRecorded = recorded
|
||||
}
|
||||
s.invalidateActiveSubscriptionCache(userID)
|
||||
return &domain.AdminApplySubscriptionResult{Subscription: updated, Created: false}, nil
|
||||
return &domain.AdminApplySubscriptionResult{
|
||||
Subscription: updated,
|
||||
Created: false,
|
||||
PaymentRecorded: paymentRecorded,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (s *Service) GetSubscriptionByID(ctx context.Context, id int64) (*domain.UserSubscription, error) {
|
||||
|
|
@ -401,16 +432,16 @@ func (s *Service) AdminExtendSubscription(ctx context.Context, subscriptionID in
|
|||
return nil, ErrPlanNotFound
|
||||
}
|
||||
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 {
|
||||
if _, err := s.recordAdminPayment(ctx, updated, plan, "ADMIN_EXTEND", ¬e); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
s.invalidateActiveSubscriptionCache(updated.UserID)
|
||||
return updated, nil
|
||||
}
|
||||
|
||||
func (s *Service) recordAdminPayment(ctx context.Context, sub *domain.UserSubscription, plan *domain.SubscriptionPlan, method string, note *string) error {
|
||||
func (s *Service) recordAdminPayment(ctx context.Context, sub *domain.UserSubscription, plan *domain.SubscriptionPlan, method string, note *string) (bool, error) {
|
||||
if s.payments == nil {
|
||||
return nil
|
||||
return false, nil
|
||||
}
|
||||
currency := plan.Currency
|
||||
if currency == "" {
|
||||
|
|
@ -428,9 +459,9 @@ func (s *Service) recordAdminPayment(ctx context.Context, sub *domain.UserSubscr
|
|||
TransactionID: note,
|
||||
})
|
||||
if err != nil {
|
||||
return fmt.Errorf("create admin payment (%s): %w", method, err)
|
||||
return false, fmt.Errorf("create admin payment (%s): %w", method, err)
|
||||
}
|
||||
return nil
|
||||
return true, nil
|
||||
}
|
||||
|
||||
func (s *Service) resolveAdminExtendExpiry(ctx context.Context, sub *domain.UserSubscription, input domain.AdminExtendSubscriptionInput) (time.Time, error) {
|
||||
|
|
|
|||
|
|
@ -14,11 +14,20 @@ import (
|
|||
|
||||
type adminApplySubscriptionReq struct {
|
||||
PlanID int64 `json:"plan_id" validate:"required,min=1"`
|
||||
// RecordPayment when omitted defaults to true (record SUCCESS payment at plan price).
|
||||
RecordPayment *bool `json:"record_payment"`
|
||||
}
|
||||
|
||||
func (r adminApplySubscriptionReq) recordPaymentOrDefault() bool {
|
||||
if r.RecordPayment == nil {
|
||||
return true
|
||||
}
|
||||
return *r.RecordPayment
|
||||
}
|
||||
|
||||
// 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.
|
||||
// @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). Optionally records a SUCCESS payment at the plan price (record_payment, default true).
|
||||
// @Tags subscriptions
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
|
|
@ -82,41 +91,61 @@ func (h *Handler) AdminExtendOrGrantUserSubscription(c *fiber.Ctx) error {
|
|||
})
|
||||
}
|
||||
|
||||
result, err := h.subscriptionsSvc.AdminApplySubscription(c.Context(), targetID, req.PlanID)
|
||||
recordPayment := req.recordPaymentOrDefault()
|
||||
result, err := h.subscriptionsSvc.AdminApplySubscription(c.Context(), targetID, domain.AdminApplySubscriptionInput{
|
||||
PlanID: req.PlanID,
|
||||
RecordPayment: recordPayment,
|
||||
})
|
||||
if err != nil {
|
||||
return h.mapAdminSubscriptionMutationError(c, err, "Failed to apply subscription")
|
||||
}
|
||||
sub := result.Subscription
|
||||
|
||||
meta, _ := json.Marshal(map[string]interface{}{
|
||||
"subscription_id": sub.ID,
|
||||
"user_id": targetID,
|
||||
"plan_id": req.PlanID,
|
||||
"plan_category": plan.Category,
|
||||
"expires_at": sub.ExpiresAt,
|
||||
"created": result.Created,
|
||||
"subscription_id": sub.ID,
|
||||
"user_id": targetID,
|
||||
"plan_id": req.PlanID,
|
||||
"plan_category": plan.Category,
|
||||
"expires_at": sub.ExpiresAt,
|
||||
"created": result.Created,
|
||||
"record_payment": recordPayment,
|
||||
"payment_recorded": result.PaymentRecorded,
|
||||
})
|
||||
|
||||
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)
|
||||
grantMsg := fmt.Sprintf("Admin granted plan %d to user %d (subscription ID: %d)", req.PlanID, targetID, sub.ID)
|
||||
if !result.PaymentRecorded {
|
||||
grantMsg += " without payment"
|
||||
}
|
||||
h.recordActivity(c, domain.ActionSubscriptionCreated, domain.ResourceSubscription, &sub.ID, grantMsg, meta)
|
||||
|
||||
msg := "Subscription granted successfully"
|
||||
if !result.PaymentRecorded {
|
||||
msg = "Subscription granted successfully (no payment recorded)"
|
||||
}
|
||||
return c.Status(fiber.StatusCreated).JSON(domain.Response{
|
||||
Message: "Subscription granted successfully",
|
||||
Message: msg,
|
||||
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)
|
||||
extendMsg := fmt.Sprintf("Admin extended subscription ID: %d (user %d) to %s", sub.ID, targetID, sub.ExpiresAt.Format(time.RFC3339))
|
||||
if !result.PaymentRecorded {
|
||||
extendMsg += " without payment"
|
||||
}
|
||||
h.recordActivity(c, domain.ActionSubscriptionExtended, domain.ResourceSubscription, &sub.ID, extendMsg, meta)
|
||||
|
||||
msg := "Subscription extended successfully"
|
||||
if !result.PaymentRecorded {
|
||||
msg = "Subscription extended successfully (no payment recorded)"
|
||||
}
|
||||
return c.JSON(domain.Response{
|
||||
Message: "Subscription extended successfully",
|
||||
Message: msg,
|
||||
Data: subscriptionToRes(sub),
|
||||
Success: true,
|
||||
StatusCode: fiber.StatusOK,
|
||||
|
|
|
|||
Loading…
Reference in New Issue
Block a user