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 <cursoragent@cursor.com>
This commit is contained in:
parent
615c5f733f
commit
0e0203ab37
|
|
@ -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
|
||||
)
|
||||
|
|
|
|||
|
|
@ -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
|
||||
|
|
|
|||
File diff suppressed because it is too large
Load Diff
|
|
@ -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
|
||||
)
|
||||
|
|
|
|||
|
|
@ -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
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -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
|
||||
|
|
|
|||
|
|
@ -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)
|
||||
|
||||
|
|
|
|||
|
|
@ -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)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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,
|
||||
})
|
||||
|
|
|
|||
|
|
@ -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",
|
||||
|
||||
|
|
|
|||
|
|
@ -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()),
|
||||
|
|
|
|||
|
|
@ -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):
|
||||
|
|
|
|||
|
|
@ -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)
|
||||
|
|
|
|||
Loading…
Reference in New Issue
Block a user