RezinaLMS-BackEnd/internal/web_server/handlers/admin_subscription_handler.go
Yared Yemane 0e0203ab37 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>
2026-07-10 04:25:11 -07:00

212 lines
7.2 KiB
Go

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 adminApplySubscriptionReq struct {
PlanID int64 `json:"plan_id" validate:"required,min=1"`
}
// 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 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 500 {object} domain.ErrorResponse
// @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{
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 apply subscription",
Error: "Target user is not a learner account",
})
}
var req adminApplySubscriptionReq
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 apply subscription",
Error: "Subscription plan not found",
})
}
result, err := h.subscriptionsSvc.AdminApplySubscription(c.Context(), targetID, req.PlanID)
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,
})
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.StatusOK,
})
}
// 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,
})
}
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(),
})
}
}