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 <cursoragent@cursor.com>
272 lines
9.4 KiB
Go
272 lines
9.4 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 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(),
|
|
})
|
|
}
|
|
}
|