From 9f04706fb962df2061a9e0d0599ada3cea1847d6 Mon Sep 17 00:00:00 2001 From: Yared Yemane Date: Fri, 10 Jul 2026 02:33:29 -0700 Subject: [PATCH] feat: add admin grant, extend, and cancel for learner subscriptions Record complimentary admin payment rows for audit, cancel only open payments so paid revenue stays intact, and exclude ADMIN_GRANT/ADMIN_EXTEND from revenue analytics. Co-authored-by: Cursor --- cmd/main.go | 2 +- db/query/analytics.sql | 12 +- db/query/payments.sql | 37 +++ db/query/subscriptions.sql | 9 + gen/db/analytics.sql.go | 12 +- gen/db/payments.sql.go | 91 ++++++ gen/db/subscriptions.sql.go | 20 ++ internal/domain/activity_log.go | 1 + internal/domain/payment.go | 12 + internal/domain/subscriptions.go | 9 + internal/ports/payment.go | 2 + internal/ports/subscriptions.go | 1 + internal/repository/payments.go | 21 ++ internal/repository/subscriptions.go | 7 + internal/services/rbac/seeds.go | 7 +- internal/services/subscriptions/service.go | 185 +++++++++++- .../handlers/admin_subscription_handler.go | 271 ++++++++++++++++++ internal/web_server/routes.go | 3 + 18 files changed, 692 insertions(+), 10 deletions(-) create mode 100644 internal/web_server/handlers/admin_subscription_handler.go diff --git a/cmd/main.go b/cmd/main.go index e8697d1b..0a0b3c6b 100644 --- a/cmd/main.go +++ b/cmd/main.go @@ -309,7 +309,7 @@ func main() { practiceContentSvc := practicecontentservice.NewService(store, store, store, store, store) // Subscriptions service - subscriptionsSvc := subscriptions.NewService(store) + subscriptionsSvc := subscriptions.NewService(store, store) // ArifPay service (direct/legacy payment flows) arifpaySvc := arifpay.NewArifpayService( diff --git a/db/query/analytics.sql b/db/query/analytics.sql index cd6e3a33..c6b40909 100644 --- a/db/query/analytics.sql +++ b/db/query/analytics.sql @@ -183,6 +183,7 @@ 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 @@ -207,6 +208,8 @@ 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, @@ -214,7 +217,8 @@ SELECT COUNT(*)::bigint AS total_payments, COUNT(*) FILTER (WHERE p.status = 'SUCCESS')::bigint AS successful_payments FROM payments p -WHERE (sqlc.narg('range_start')::timestamptz IS NULL OR COALESCE(p.paid_at, p.created_at) >= sqlc.narg('range_start')::timestamptz) +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) AND (sqlc.narg('range_end')::timestamptz IS NULL OR COALESCE(p.paid_at, p.created_at) < sqlc.narg('range_end')::timestamptz); -- name: AnalyticsPaymentsByStatus :many @@ -223,7 +227,8 @@ SELECT COUNT(*)::bigint AS count, COALESCE(SUM(p.amount), 0)::float8 AS total_amount FROM payments p -WHERE (sqlc.narg('range_start')::timestamptz IS NULL OR COALESCE(p.paid_at, p.created_at) >= sqlc.narg('range_start')::timestamptz) +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) 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; @@ -235,6 +240,7 @@ 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 @@ -251,6 +257,7 @@ 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 @@ -273,6 +280,7 @@ 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/payments.sql b/db/query/payments.sql index edf53554..2d7e2c32 100644 --- a/db/query/payments.sql +++ b/db/query/payments.sql @@ -78,6 +78,43 @@ SET updated_at = CURRENT_TIMESTAMP WHERE id = $2; +-- name: CreateAdminPayment :one +INSERT INTO payments ( + user_id, + plan_id, + subscription_id, + transaction_id, + nonce, + amount, + currency, + payment_method, + status, + paid_at +) +VALUES ( + $1, + $2, + $3, + $4, + $5, + $6, + $7, + $8, + 'SUCCESS', + CURRENT_TIMESTAMP +) +RETURNING *; + +-- Cancel open (non-settled) payments for a subscription. SUCCESS rows are left +-- intact so historical revenue analytics are not erased on admin cancel. +-- name: CancelPaymentsBySubscriptionID :execrows +UPDATE payments +SET + status = 'CANCELLED', + updated_at = CURRENT_TIMESTAMP +WHERE subscription_id = $1 + AND status NOT IN ('CANCELLED', 'EXPIRED', 'FAILED', 'SUCCESS'); + -- name: GetExpiredPendingPayments :many SELECT * FROM payments WHERE status = 'PENDING' diff --git a/db/query/subscriptions.sql b/db/query/subscriptions.sql index 22be381b..79a867d4 100644 --- a/db/query/subscriptions.sql +++ b/db/query/subscriptions.sql @@ -253,6 +253,15 @@ SET updated_at = CURRENT_TIMESTAMP WHERE id = $2; +-- name: AdminExtendUserSubscription :exec +UPDATE user_subscriptions +SET + expires_at = $1, + status = 'ACTIVE', + cancelled_at = NULL, + updated_at = CURRENT_TIMESTAMP +WHERE id = $2; + -- name: ListUserSubscriptionsAdmin :many SELECT COUNT(*) OVER () AS total_count, diff --git a/gen/db/analytics.sql.go b/gen/db/analytics.sql.go index 2bef34af..d5b0328e 100644 --- a/gen/db/analytics.sql.go +++ b/gen/db/analytics.sql.go @@ -384,6 +384,7 @@ 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 @@ -427,7 +428,8 @@ SELECT COUNT(*)::bigint AS count, COALESCE(SUM(p.amount), 0)::float8 AS total_amount FROM payments p -WHERE ($1::timestamptz IS NULL OR COALESCE(p.paid_at, p.created_at) >= $1::timestamptz) +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) AND ($2::timestamptz IS NULL OR COALESCE(p.paid_at, p.created_at) < $2::timestamptz) GROUP BY p.status ORDER BY count DESC @@ -472,7 +474,8 @@ SELECT COUNT(*)::bigint AS total_payments, COUNT(*) FILTER (WHERE p.status = 'SUCCESS')::bigint AS successful_payments FROM payments p -WHERE ($1::timestamptz IS NULL OR COALESCE(p.paid_at, p.created_at) >= $1::timestamptz) +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) AND ($2::timestamptz IS NULL OR COALESCE(p.paid_at, p.created_at) < $2::timestamptz) ` @@ -491,6 +494,8 @@ 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 @@ -631,6 +636,7 @@ 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 @@ -685,6 +691,7 @@ 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 @@ -744,6 +751,7 @@ 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/payments.sql.go b/gen/db/payments.sql.go index f036fac2..4b194120 100644 --- a/gen/db/payments.sql.go +++ b/gen/db/payments.sql.go @@ -11,6 +11,25 @@ import ( "github.com/jackc/pgx/v5/pgtype" ) +const CancelPaymentsBySubscriptionID = `-- name: CancelPaymentsBySubscriptionID :execrows +UPDATE payments +SET + status = 'CANCELLED', + updated_at = CURRENT_TIMESTAMP +WHERE subscription_id = $1 + AND status NOT IN ('CANCELLED', 'EXPIRED', 'FAILED', 'SUCCESS') +` + +// Cancel open (non-settled) payments for a subscription. SUCCESS rows are left +// intact so historical revenue analytics are not erased on admin cancel. +func (q *Queries) CancelPaymentsBySubscriptionID(ctx context.Context, subscriptionID pgtype.Int8) (int64, error) { + result, err := q.db.Exec(ctx, CancelPaymentsBySubscriptionID, subscriptionID) + if err != nil { + return 0, err + } + return result.RowsAffected(), nil +} + const CountPaymentsAdmin = `-- name: CountPaymentsAdmin :one SELECT COUNT(*)::bigint AS total FROM payments p @@ -89,6 +108,78 @@ func (q *Queries) CountUserPayments(ctx context.Context, userID int64) (int64, e return count, err } +const CreateAdminPayment = `-- name: CreateAdminPayment :one +INSERT INTO payments ( + user_id, + plan_id, + subscription_id, + transaction_id, + nonce, + amount, + currency, + payment_method, + status, + paid_at +) +VALUES ( + $1, + $2, + $3, + $4, + $5, + $6, + $7, + $8, + 'SUCCESS', + CURRENT_TIMESTAMP +) +RETURNING id, user_id, plan_id, subscription_id, session_id, transaction_id, nonce, amount, currency, payment_method, status, payment_url, paid_at, expires_at, created_at, updated_at +` + +type CreateAdminPaymentParams struct { + UserID int64 `json:"user_id"` + PlanID pgtype.Int8 `json:"plan_id"` + SubscriptionID pgtype.Int8 `json:"subscription_id"` + TransactionID pgtype.Text `json:"transaction_id"` + Nonce string `json:"nonce"` + Amount pgtype.Numeric `json:"amount"` + Currency string `json:"currency"` + PaymentMethod pgtype.Text `json:"payment_method"` +} + +func (q *Queries) CreateAdminPayment(ctx context.Context, arg CreateAdminPaymentParams) (Payment, error) { + row := q.db.QueryRow(ctx, CreateAdminPayment, + arg.UserID, + arg.PlanID, + arg.SubscriptionID, + arg.TransactionID, + arg.Nonce, + arg.Amount, + arg.Currency, + arg.PaymentMethod, + ) + var i Payment + err := row.Scan( + &i.ID, + &i.UserID, + &i.PlanID, + &i.SubscriptionID, + &i.SessionID, + &i.TransactionID, + &i.Nonce, + &i.Amount, + &i.Currency, + &i.PaymentMethod, + &i.Status, + &i.PaymentUrl, + &i.PaidAt, + &i.ExpiresAt, + &i.CreatedAt, + &i.UpdatedAt, + ) + return i, err +} + const CreatePayment = `-- name: CreatePayment :one INSERT INTO payments ( diff --git a/gen/db/subscriptions.sql.go b/gen/db/subscriptions.sql.go index 4af286d0..2fbb0704 100644 --- a/gen/db/subscriptions.sql.go +++ b/gen/db/subscriptions.sql.go @@ -11,6 +11,26 @@ import ( "github.com/jackc/pgx/v5/pgtype" ) +const AdminExtendUserSubscription = `-- name: AdminExtendUserSubscription :exec +UPDATE user_subscriptions +SET + expires_at = $1, + status = 'ACTIVE', + cancelled_at = NULL, + updated_at = CURRENT_TIMESTAMP +WHERE id = $2 +` + +type AdminExtendUserSubscriptionParams struct { + 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) + return err +} + const CancelUserSubscription = `-- name: CancelUserSubscription :exec UPDATE user_subscriptions SET diff --git a/internal/domain/activity_log.go b/internal/domain/activity_log.go index 23995955..7c88ab5f 100644 --- a/internal/domain/activity_log.go +++ b/internal/domain/activity_log.go @@ -107,6 +107,7 @@ const ( ActionRatingDeleted ActivityAction = "RATING_DELETED" ActionSubscriptionCreated ActivityAction = "SUBSCRIPTION_CREATED" ActionSubscriptionCancelled ActivityAction = "SUBSCRIPTION_CANCELLED" + ActionSubscriptionExtended ActivityAction = "SUBSCRIPTION_EXTENDED" ActionSubscriptionAutoRenewUpdated ActivityAction = "SUBSCRIPTION_AUTO_RENEW_UPDATED" ActionPaymentInitiated ActivityAction = "PAYMENT_INITIATED" ActionPaymentVerified ActivityAction = "PAYMENT_VERIFIED" diff --git a/internal/domain/payment.go b/internal/domain/payment.go index 034ee3fb..57fc91e4 100644 --- a/internal/domain/payment.go +++ b/internal/domain/payment.go @@ -81,6 +81,18 @@ type CreatePaymentInput struct { ExpiresAt *time.Time } +// CreateAdminPaymentInput records a complimentary / admin-panel payment row. +type CreateAdminPaymentInput struct { + UserID int64 + PlanID *int64 + SubscriptionID int64 + Amount float64 + Currency string + PaymentMethod string + Nonce string + TransactionID *string +} + type PaymentProvider string const ( diff --git a/internal/domain/subscriptions.go b/internal/domain/subscriptions.go index 2ab202d0..52e1d9a0 100644 --- a/internal/domain/subscriptions.go +++ b/internal/domain/subscriptions.go @@ -155,6 +155,15 @@ type CreateUserSubscriptionInput struct { AutoRenew *bool } +// AdminExtendSubscriptionInput extends a learner subscription from the admin panel. +// Provide exactly one of: NewExpiresAt, DurationValue+DurationUnit, or RenewOnePeriod. +type AdminExtendSubscriptionInput struct { + NewExpiresAt *time.Time + DurationValue *int32 + DurationUnit *string + RenewOnePeriod bool +} + // 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/payment.go b/internal/ports/payment.go index c2bc0614..fc942d74 100644 --- a/internal/ports/payment.go +++ b/internal/ports/payment.go @@ -7,6 +7,7 @@ import ( type PaymentStore interface { CreatePayment(ctx context.Context, input domain.CreatePaymentInput) (*domain.Payment, error) + CreateAdminPayment(ctx context.Context, input domain.CreateAdminPaymentInput) (*domain.Payment, error) GetPaymentByID(ctx context.Context, id int64) (*domain.Payment, error) GetPaymentBySessionID(ctx context.Context, sessionID string) (*domain.Payment, error) GetPaymentByNonce(ctx context.Context, nonce string) (*domain.Payment, error) @@ -18,6 +19,7 @@ type PaymentStore interface { UpdatePaymentStatusByNonce(ctx context.Context, nonce, status, transactionID, paymentMethod string) error UpdatePaymentSessionID(ctx context.Context, id int64, sessionID, paymentURL string) error LinkPaymentToSubscription(ctx context.Context, paymentID, subscriptionID int64) error + CancelPaymentsBySubscriptionID(ctx context.Context, subscriptionID int64) (int64, error) GetExpiredPendingPayments(ctx context.Context) ([]domain.Payment, error) ExpirePayment(ctx context.Context, id int64) error ExpireStalePendingPayments(ctx context.Context) (int64, error) diff --git a/internal/ports/subscriptions.go b/internal/ports/subscriptions.go index c410f926..941c8201 100644 --- a/internal/ports/subscriptions.go +++ b/internal/ports/subscriptions.go @@ -29,6 +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 ListUserSubscriptionsAdmin(ctx context.Context, filter domain.UserSubscriptionAdminFilter) (domain.UserSubscriptionAdminPage, error) ListLearnEnglishSubscriptionsExpiringInSevenDays(ctx context.Context) ([]domain.SubscriptionExpiryReminder, error) } diff --git a/internal/repository/payments.go b/internal/repository/payments.go index 0c7c3a93..5235510c 100644 --- a/internal/repository/payments.go +++ b/internal/repository/payments.go @@ -29,6 +29,27 @@ func (s *Store) CreatePayment(ctx context.Context, input domain.CreatePaymentInp return paymentToDomain(payment), nil } +func (s *Store) CreateAdminPayment(ctx context.Context, input domain.CreateAdminPaymentInput) (*domain.Payment, error) { + payment, err := s.queries.CreateAdminPayment(ctx, dbgen.CreateAdminPaymentParams{ + UserID: input.UserID, + PlanID: int64PtrToPgInt8(input.PlanID), + SubscriptionID: pgtype.Int8{Int64: input.SubscriptionID, Valid: true}, + TransactionID: toPgText(input.TransactionID), + Nonce: input.Nonce, + Amount: toPgNumeric(input.Amount), + Currency: input.Currency, + PaymentMethod: toPgText(&input.PaymentMethod), + }) + if err != nil { + return nil, err + } + return paymentToDomain(payment), nil +} + +func (s *Store) CancelPaymentsBySubscriptionID(ctx context.Context, subscriptionID int64) (int64, error) { + return s.queries.CancelPaymentsBySubscriptionID(ctx, pgtype.Int8{Int64: subscriptionID, Valid: true}) +} + func (s *Store) GetPaymentByID(ctx context.Context, id int64) (*domain.Payment, error) { payment, err := s.queries.GetPaymentByID(ctx, id) if err != nil { diff --git a/internal/repository/subscriptions.go b/internal/repository/subscriptions.go index 1b3f9cd3..91b6b5bd 100644 --- a/internal/repository/subscriptions.go +++ b/internal/repository/subscriptions.go @@ -270,6 +270,13 @@ func (s *Store) ExtendSubscription(ctx context.Context, id int64, newExpiresAt t }) } +func (s *Store) AdminExtendUserSubscription(ctx context.Context, id int64, newExpiresAt time.Time) error { + return s.queries.AdminExtendUserSubscription(ctx, dbgen.AdminExtendUserSubscriptionParams{ + ExpiresAt: toPgTimestamptz(newExpiresAt), + ID: id, + }) +} + func (s *Store) ListUserSubscriptionsAdmin(ctx context.Context, filter domain.UserSubscriptionAdminFilter) (domain.UserSubscriptionAdminPage, error) { rows, err := s.queries.ListUserSubscriptionsAdmin(ctx, dbgen.ListUserSubscriptionsAdminParams{ UserID: int64PtrToPgInt8(filter.UserID), diff --git a/internal/services/rbac/seeds.go b/internal/services/rbac/seeds.go index 157625de..ee5503fe 100644 --- a/internal/services/rbac/seeds.go +++ b/internal/services/rbac/seeds.go @@ -167,7 +167,10 @@ var AllPermissions = []domain.PermissionSeed{ {Key: "subscriptions.export", Name: "Export Subscriptions", Description: "Export user subscriptions as CSV (admin)", GroupName: "Subscriptions"}, {Key: "subscriptions.history", Name: "Subscription History", Description: "Get subscription history", GroupName: "Subscriptions"}, {Key: "subscriptions.status", Name: "Check Subscription Status", Description: "Check subscription status", GroupName: "Subscriptions"}, - {Key: "subscriptions.cancel", Name: "Cancel Subscription", Description: "Cancel a subscription", 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.set_auto_renew", Name: "Set Auto Renew", Description: "Set auto-renew on subscription", GroupName: "Subscriptions"}, // Payments @@ -455,7 +458,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.set_auto_renew", + "subscriptions.status", "subscriptions.cancel", "subscriptions.admin_cancel", "subscriptions.admin_extend", "subscriptions.admin_grant", "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 5bb2c0f6..1e3725f4 100644 --- a/internal/services/subscriptions/service.go +++ b/internal/services/subscriptions/service.go @@ -2,9 +2,11 @@ package subscriptions import ( "Yimaru-Backend/internal/domain" + "Yimaru-Backend/internal/pkgs/helpers" "Yimaru-Backend/internal/ports" "context" "errors" + "fmt" "time" "github.com/jackc/pgx/v5" @@ -16,14 +18,18 @@ var ( ErrSubscriptionNotOwned = errors.New("subscription does not belong to this user") ErrAlreadySubscribed = errors.New("user already has an active subscription for this category") ErrInvalidPlan = errors.New("invalid subscription plan") + ErrInvalidExtendInput = errors.New("provide exactly one of new_expires_at, duration_value+duration_unit, or renew_one_period") + ErrExtendExpiresInPast = errors.New("new expiry must be in the future") + ErrNotALearner = errors.New("target user is not a learner account") ) type Service struct { - store ports.SubscriptionStore + store ports.SubscriptionStore + payments ports.PaymentStore } -func NewService(store ports.SubscriptionStore) *Service { - return &Service{store: store} +func NewService(store ports.SubscriptionStore, payments ports.PaymentStore) *Service { + return &Service{store: store, payments: payments} } // ===================== @@ -91,6 +97,53 @@ 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. +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 { + return nil, ErrPlanNotFound + } + + hasActive, err := s.store.HasActiveSubscriptionByCategory(ctx, userID, plan.Category) + if err != nil { + return nil, err + } + if hasActive { + return nil, ErrAlreadySubscribed + } + + startsAt := time.Now() + expiresAt := domain.CalculateSubscriptionExpiresAt(startsAt, plan.Category, plan.DurationValue, plan.DurationUnit) + if newExpiresAt != nil { + if newExpiresAt.Before(time.Now()) { + return nil, ErrExtendExpiresInPast + } + expiresAt = newExpiresAt.UTC() + } + + method := "ADMIN_GRANT" + input := domain.CreateUserSubscriptionInput{ + UserID: userID, + PlanID: planID, + StartsAt: &startsAt, + ExpiresAt: expiresAt, + Status: strPtr(string(domain.SubscriptionStatusActive)), + PaymentReference: note, + PaymentMethod: &method, + AutoRenew: boolPtr(false), + } + + sub, err := s.store.CreateUserSubscription(ctx, input) + if err != nil { + return nil, err + } + if err := s.recordAdminPayment(ctx, sub, plan, method, note); err != nil { + return nil, err + } + return s.GetSubscriptionByID(ctx, sub.ID) +} + func (s *Service) GetSubscriptionByID(ctx context.Context, id int64) (*domain.UserSubscription, error) { sub, err := s.store.GetUserSubscriptionByID(ctx, id) if err != nil { @@ -155,6 +208,132 @@ func (s *Service) CancelSubscriptionForUser(ctx context.Context, subscriptionID, return s.store.CancelUserSubscription(ctx, subscriptionID) } +// AdminCancelSubscription cancels any learner subscription (admin panel). +func (s *Service) AdminCancelSubscription(ctx context.Context, subscriptionID int64) (*domain.UserSubscription, error) { + if _, err := s.GetSubscriptionByID(ctx, subscriptionID); err != nil { + return nil, err + } + if err := s.store.CancelUserSubscription(ctx, subscriptionID); err != nil { + return nil, err + } + if s.payments != nil { + if _, err := s.payments.CancelPaymentsBySubscriptionID(ctx, subscriptionID); err != nil { + return nil, fmt.Errorf("cancel linked payments: %w", err) + } + } + return s.GetSubscriptionByID(ctx, subscriptionID) +} + +// AdminExtendSubscription extends (and reactivates) any learner subscription (admin panel). +func (s *Service) AdminExtendSubscription(ctx context.Context, subscriptionID int64, input domain.AdminExtendSubscriptionInput) (*domain.UserSubscription, error) { + sub, err := s.GetSubscriptionByID(ctx, subscriptionID) + if err != nil { + return nil, err + } + + newExpiry, err := s.resolveAdminExtendExpiry(ctx, sub, input) + if err != nil { + return nil, err + } + if newExpiry.Before(time.Now()) { + return nil, ErrExtendExpiresInPast + } + + if err := s.store.AdminExtendUserSubscription(ctx, subscriptionID, newExpiry); err != nil { + return nil, err + } + + updated, err := s.GetSubscriptionByID(ctx, subscriptionID) + if err != nil { + return nil, err + } + + plan, planErr := s.store.GetSubscriptionPlanByID(ctx, updated.PlanID) + if planErr != nil { + 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 { + return nil, err + } + return updated, nil +} + +func (s *Service) recordAdminPayment(ctx context.Context, sub *domain.UserSubscription, plan *domain.SubscriptionPlan, method string, note *string) error { + if s.payments == nil { + return nil + } + currency := plan.Currency + if currency == "" { + currency = "ETB" + } + planID := plan.ID + _, err := s.payments.CreateAdminPayment(ctx, domain.CreateAdminPaymentInput{ + UserID: sub.UserID, + PlanID: &planID, + SubscriptionID: sub.ID, + Amount: 0, + Currency: currency, + PaymentMethod: method, + Nonce: fmt.Sprintf("admin-%s-%s", method, helpers.GenerateID()), + TransactionID: note, + }) + if err != nil { + return fmt.Errorf("create admin payment (%s): %w", method, err) + } + return nil +} + +func (s *Service) resolveAdminExtendExpiry(ctx context.Context, sub *domain.UserSubscription, input domain.AdminExtendSubscriptionInput) (time.Time, error) { + hasAbsolute := input.NewExpiresAt != nil + durationUnitSet := input.DurationUnit != nil && *input.DurationUnit != "" + durationComplete := input.DurationValue != nil && durationUnitSet + durationPartial := (input.DurationValue != nil) != durationUnitSet + if durationPartial { + return time.Time{}, ErrInvalidExtendInput + } + + modes := 0 + if hasAbsolute { + modes++ + } + if durationComplete { + modes++ + } + if input.RenewOnePeriod { + modes++ + } + if modes != 1 { + return time.Time{}, ErrInvalidExtendInput + } + + if hasAbsolute { + return input.NewExpiresAt.UTC(), nil + } + + baseTime := sub.ExpiresAt + if baseTime.Before(time.Now()) { + baseTime = time.Now() + } + + if input.RenewOnePeriod { + plan, err := s.store.GetSubscriptionPlanByID(ctx, sub.PlanID) + if err != nil { + return time.Time{}, ErrPlanNotFound + } + category := plan.Category + if sub.PlanCategory != nil && *sub.PlanCategory != "" { + category = *sub.PlanCategory + } + return domain.CalculateSubscriptionExpiresAt(baseTime, category, plan.DurationValue, plan.DurationUnit), nil + } + + if *input.DurationValue < 1 { + return time.Time{}, ErrInvalidExtendInput + } + return domain.CalculateExpiryDate(baseTime, *input.DurationValue, *input.DurationUnit), nil +} + // SetAutoRenewForUser updates auto-renew only if the subscription belongs to userID. func (s *Service) SetAutoRenewForUser(ctx context.Context, subscriptionID, userID int64, autoRenew bool) error { if err := s.subscriptionOwnedBy(ctx, subscriptionID, userID); err != nil { diff --git a/internal/web_server/handlers/admin_subscription_handler.go b/internal/web_server/handlers/admin_subscription_handler.go new file mode 100644 index 00000000..416f7ac3 --- /dev/null +++ b/internal/web_server/handlers/admin_subscription_handler.go @@ -0,0 +1,271 @@ +package handlers + +import ( + "Yimaru-Backend/internal/domain" + subscriptionsvc "Yimaru-Backend/internal/services/subscriptions" + "encoding/json" + "errors" + "fmt" + "strconv" + "time" + + "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 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. +// @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" +// @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 { + targetID, err := parseAdminTargetUserID(c) + if err != nil { + return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{ + Message: "Invalid user ID", + Error: "user ID must be a valid positive integer", + }) + } + + user, err := h.userSvc.GetUserByID(c.Context(), targetID) + if err != nil { + if errors.Is(err, domain.ErrUserNotFound) { + return c.Status(fiber.StatusNotFound).JSON(domain.ErrorResponse{ + Message: "User not found", + Error: err.Error(), + }) + } + return c.Status(fiber.StatusInternalServerError).JSON(domain.ErrorResponse{ + Message: "Failed to load user", + Error: err.Error(), + }) + } + if !user.Role.IsCustomerLearnerRole() { + return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{ + Message: "Failed to grant subscription", + Error: "Target user is not a learner account", + }) + } + + var req adminGrantSubscriptionReq + 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), + }) + } + + 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", + Error: "Subscription plan not found", + }) + } + + sub, err := h.subscriptionsSvc.AdminGrantSubscription(c.Context(), targetID, req.PlanID, req.NewExpiresAt, req.Note) + 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) + } + + 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, + "note": req.Note, + }) + 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, + }) +} + +// AdminCancelUserSubscription godoc +// @Summary Cancel a learner subscription (admin) +// @Description Cancels any user_subscriptions row by ID. Does not require ownership by the caller. +// @Tags subscriptions +// @Produce json +// @Security Bearer +// @Param id path int true "Subscription ID" +// @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}/cancel [post] +func (h *Handler) AdminCancelUserSubscription(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", + }) + } + + sub, err := h.subscriptionsSvc.AdminCancelSubscription(c.Context(), id) + if err != nil { + return h.mapAdminSubscriptionMutationError(c, err, "Failed to cancel subscription") + } + + meta, _ := json.Marshal(map[string]interface{}{ + "subscription_id": id, + "user_id": sub.UserID, + "plan_id": sub.PlanID, + }) + h.recordActivity(c, domain.ActionSubscriptionCancelled, domain.ResourceSubscription, &id, + fmt.Sprintf("Admin cancelled subscription ID: %d (user %d)", id, sub.UserID), meta) + + return c.JSON(domain.Response{ + Message: "Subscription cancelled successfully", + Data: subscriptionToRes(sub), + Success: true, + StatusCode: fiber.StatusOK, + }) +} + +// 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): + return c.Status(fiber.StatusNotFound).JSON(domain.ErrorResponse{ + Message: message, + Error: "Subscription not found", + }) + case errors.Is(err, subscriptionsvc.ErrAlreadySubscribed): + return c.Status(fiber.StatusConflict).JSON(domain.ErrorResponse{ + Message: message, + Error: err.Error(), + }) + case errors.Is(err, subscriptionsvc.ErrInvalidPlan): + return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{ + Message: message, + Error: err.Error(), + }) + case errors.Is(err, subscriptionsvc.ErrInvalidExtendInput): + return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{ + Message: message, + Error: err.Error(), + }) + case errors.Is(err, subscriptionsvc.ErrExtendExpiresInPast): + return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{ + Message: message, + Error: err.Error(), + }) + case errors.Is(err, subscriptionsvc.ErrPlanNotFound): + return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{ + Message: message, + Error: "Subscription plan not found", + }) + case errors.Is(err, subscriptionsvc.ErrNotALearner): + return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{ + Message: message, + Error: err.Error(), + }) + default: + return c.Status(fiber.StatusInternalServerError).JSON(domain.ErrorResponse{ + Message: message, + Error: err.Error(), + }) + } +} diff --git a/internal/web_server/routes.go b/internal/web_server/routes.go index ff7e26d3..110ffd73 100644 --- a/internal/web_server/routes.go +++ b/internal/web_server/routes.go @@ -363,10 +363,13 @@ func (a *App) initAppRoutes() { groupV1.Get("/users/export", a.authMiddleware, a.RequirePermission("users.export"), h.ExportUsersCSV) 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.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)