RezinaLMS-BackEnd/internal/web_server/handlers/admin_subscription_handler.go

245 lines
8.5 KiB
Go

package handlers
import (
"Rezina-Backend/internal/domain"
subscriptionsvc "Rezina-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"`
// 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). Optionally records a SUCCESS payment at the plan price (record_payment, default true).
// @Tags subscriptions
// @Accept json
// @Produce json
// @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]
// @Security Bearer
// @Failure 401 {string} string "Missing, invalid, or expired Bearer token"
// @Failure 403 {string} string "Account audience, status, permission, or subscription does not allow this operation"
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",
})
}
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,
"record_payment": recordPayment,
"payment_recorded": result.PaymentRecorded,
})
if result.Created {
if h.learnerNotifSvc != nil {
h.learnerNotifSvc.MaybeNotifyLearnPackageSubscribed(targetID, plan.Category, plan.Name, sub.ExpiresAt)
}
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: msg,
Data: subscriptionToRes(sub),
Success: true,
StatusCode: fiber.StatusCreated,
})
}
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: msg,
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
// @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]
// @Security Bearer
// @Failure 401 {string} string "Missing, invalid, or expired Bearer token"
// @Failure 403 {string} string "Account audience, status, permission, or subscription does not allow this operation"
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(),
})
}
}