925 lines
33 KiB
Go
925 lines
33 KiB
Go
package handlers
|
|
|
|
import (
|
|
"Rezina-Backend/internal/domain"
|
|
subscriptionsvc "Rezina-Backend/internal/services/subscriptions"
|
|
"context"
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"strconv"
|
|
"strings"
|
|
|
|
"github.com/gofiber/fiber/v2"
|
|
)
|
|
|
|
// =====================
|
|
// Subscription Plan Types
|
|
// =====================
|
|
|
|
const duplicateSubscriptionPlanPeriodMessage = "Only one subscription plan is allowed per category and billing period. A free plan and a paid plan cannot coexist for the same period—edit the existing plan or change category or duration."
|
|
|
|
type createPlanReq struct {
|
|
Name string `json:"name" validate:"required"`
|
|
Description *string `json:"description"`
|
|
Category string `json:"category" validate:"required,oneof=EDUCATION"`
|
|
DurationValue int32 `json:"duration_value"`
|
|
DurationUnit string `json:"duration_unit"`
|
|
Price float64 `json:"price" validate:"gte=0"`
|
|
Currency string `json:"currency" validate:"required"`
|
|
IsLifetime bool `json:"is_lifetime"`
|
|
IsFree bool `json:"is_free"`
|
|
IsActive *bool `json:"is_active"`
|
|
}
|
|
|
|
type updatePlanReq struct {
|
|
Name *string `json:"name"`
|
|
Description *string `json:"description"`
|
|
Category *string `json:"category" validate:"omitempty,oneof=EDUCATION"`
|
|
DurationValue *int32 `json:"duration_value"`
|
|
DurationUnit *string `json:"duration_unit"`
|
|
Price *float64 `json:"price"`
|
|
Currency *string `json:"currency"`
|
|
IsLifetime *bool `json:"is_lifetime"`
|
|
IsFree *bool `json:"is_free"`
|
|
IsActive *bool `json:"is_active"`
|
|
}
|
|
|
|
type planRes struct {
|
|
ID int64 `json:"id"`
|
|
Name string `json:"name"`
|
|
Description *string `json:"description,omitempty"`
|
|
Category string `json:"category"`
|
|
DurationValue int32 `json:"duration_value"`
|
|
DurationUnit string `json:"duration_unit"`
|
|
Price float64 `json:"price"`
|
|
Currency string `json:"currency"`
|
|
IsLifetime bool `json:"is_lifetime"`
|
|
IsFree bool `json:"is_free"`
|
|
IsActive bool `json:"is_active"`
|
|
CreatedAt string `json:"created_at"`
|
|
}
|
|
|
|
type subscriptionCheckoutRes struct {
|
|
domain.InitiateSubscriptionPaymentResponse
|
|
Subscription *subscriptionRes `json:"subscription,omitempty"`
|
|
}
|
|
|
|
// =====================
|
|
// User Subscription Types
|
|
// =====================
|
|
|
|
type subscribeReq struct {
|
|
PlanID int64 `json:"plan_id" validate:"required"`
|
|
PaymentReference *string `json:"payment_reference"`
|
|
PaymentMethod *string `json:"payment_method"`
|
|
}
|
|
|
|
type subscribeWithPaymentReq struct {
|
|
PlanID int64 `json:"plan_id" validate:"required"`
|
|
Phone string `json:"phone" validate:"required"`
|
|
Email string `json:"email" validate:"required,email"`
|
|
Provider string `json:"provider" validate:"required"`
|
|
}
|
|
|
|
type subscriptionRes struct {
|
|
ID int64 `json:"id"`
|
|
UserID int64 `json:"user_id"`
|
|
PlanID int64 `json:"plan_id"`
|
|
PlanName *string `json:"plan_name,omitempty"`
|
|
Category *string `json:"category,omitempty"`
|
|
IsLifetime *bool `json:"is_lifetime,omitempty"`
|
|
StartsAt string `json:"starts_at"`
|
|
ExpiresAt string `json:"expires_at"`
|
|
Status string `json:"status"`
|
|
PaymentReference *string `json:"payment_reference,omitempty"`
|
|
PaymentMethod *string `json:"payment_method,omitempty"`
|
|
AutoRenew bool `json:"auto_renew"`
|
|
DurationValue *int32 `json:"duration_value,omitempty"`
|
|
DurationUnit *string `json:"duration_unit,omitempty"`
|
|
Price *float64 `json:"price,omitempty"`
|
|
Currency *string `json:"currency,omitempty"`
|
|
CreatedAt string `json:"created_at"`
|
|
}
|
|
|
|
type autoRenewReq struct {
|
|
AutoRenew bool `json:"auto_renew"`
|
|
}
|
|
|
|
// =====================
|
|
// Subscription Plan Handlers
|
|
// =====================
|
|
|
|
// CreateSubscriptionPlan godoc
|
|
// @Summary Create a subscription plan
|
|
// @Description Creates a new subscription plan (admin only)
|
|
// @Tags subscriptions
|
|
// @Accept json
|
|
// @Produce json
|
|
// @Param body body createPlanReq true "Create plan payload"
|
|
// @Success 201 {object} domain.Response{data=planRes}
|
|
// @Failure 400 {object} domain.ErrorResponse
|
|
// @Failure 500 {object} domain.ErrorResponse
|
|
// @Router /api/v1/admin/subscription-plans [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"
|
|
// @Failure 409 {object} domain.ErrorResponse "Resource conflict"
|
|
func (h *Handler) CreateSubscriptionPlan(c *fiber.Ctx) error {
|
|
var req createPlanReq
|
|
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),
|
|
})
|
|
}
|
|
if !req.IsLifetime {
|
|
if req.DurationValue < 1 {
|
|
return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{
|
|
Message: "Validation failed",
|
|
Error: "duration_value must be at least 1 for expiring plans",
|
|
})
|
|
}
|
|
switch strings.ToUpper(strings.TrimSpace(req.DurationUnit)) {
|
|
case "DAY", "WEEK", "MONTH", "YEAR":
|
|
default:
|
|
return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{
|
|
Message: "Validation failed",
|
|
Error: "duration_unit must be one of: DAY, WEEK, MONTH, YEAR",
|
|
})
|
|
}
|
|
}
|
|
|
|
plan, err := h.subscriptionsSvc.CreatePlan(c.Context(), domain.CreateSubscriptionPlanInput{
|
|
Name: req.Name,
|
|
Description: req.Description,
|
|
Category: req.Category,
|
|
DurationValue: req.DurationValue,
|
|
DurationUnit: req.DurationUnit,
|
|
Price: req.Price,
|
|
Currency: req.Currency,
|
|
IsLifetime: req.IsLifetime,
|
|
IsFree: req.IsFree,
|
|
IsActive: req.IsActive,
|
|
})
|
|
if err != nil {
|
|
if errors.Is(err, domain.ErrFreePlanMustHaveZeroPrice) || errors.Is(err, domain.ErrPaidPlanMustHavePositivePrice) {
|
|
return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{
|
|
Message: "Validation failed",
|
|
Error: err.Error(),
|
|
})
|
|
}
|
|
if errors.Is(err, domain.ErrDuplicateSubscriptionPlanPeriod) {
|
|
return c.Status(fiber.StatusConflict).JSON(domain.ErrorResponse{
|
|
Message: "Duplicate subscription plan",
|
|
Error: duplicateSubscriptionPlanPeriodMessage,
|
|
})
|
|
}
|
|
return c.Status(fiber.StatusInternalServerError).JSON(domain.ErrorResponse{
|
|
Message: "Failed to create subscription plan",
|
|
Error: err.Error(),
|
|
})
|
|
}
|
|
|
|
actorID := c.Locals("user_id").(int64)
|
|
actorRole := string(c.Locals("role").(domain.Role))
|
|
ip := c.IP()
|
|
ua := c.Get("User-Agent")
|
|
meta, _ := json.Marshal(map[string]interface{}{"name": plan.Name, "price": plan.Price})
|
|
go h.activityLogSvc.RecordAction(context.Background(), &actorID, &actorRole, domain.ActionSubscriptionPlanCreated, domain.ResourceSubscriptionPlan, &plan.ID, "Created subscription plan: "+plan.Name, meta, &ip, &ua)
|
|
|
|
return c.Status(fiber.StatusCreated).JSON(domain.Response{
|
|
Message: "Subscription plan created successfully",
|
|
Data: planToRes(plan),
|
|
})
|
|
}
|
|
|
|
// ListSubscriptionPlans godoc
|
|
// @Summary List subscription plans
|
|
// @Description Learner endpoint retired: returns 410 Gone. Purchase a course using POST /api/v1/courses/{courseId}/checkout. Administrative subscription history remains available.
|
|
// @Failure 410 {object} domain.ErrorResponse
|
|
// @Tags subscriptions
|
|
// @Produce json
|
|
// @Param active_only query bool false "Customer requests always return active plans; false is honored only by the admin endpoint" default(true)
|
|
// @Param category query string false "Filter by plan category (EDUCATION)"
|
|
// @Success 200 {object} domain.Response{data=[]planRes}
|
|
// @Failure 400 {object} domain.ErrorResponse
|
|
// @Failure 500 {object} domain.ErrorResponse
|
|
// @Router /api/v1/subscription-plans [get]
|
|
func (h *Handler) ListSubscriptionPlans(c *fiber.Ctx) error {
|
|
activeOnly := c.Query("active_only", "true") == "true"
|
|
if c.Locals("api_audience") == "client" {
|
|
activeOnly = true
|
|
}
|
|
|
|
var categoryFilter *string
|
|
if raw := strings.TrimSpace(c.Query("category")); raw != "" {
|
|
normalized := strings.ToUpper(raw)
|
|
if !domain.IsValidSubscriptionCategory(normalized) {
|
|
return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{
|
|
Message: "Invalid category",
|
|
Error: "category must be EDUCATION",
|
|
})
|
|
}
|
|
categoryFilter = &normalized
|
|
}
|
|
|
|
plans, err := h.subscriptionsSvc.ListPlans(c.Context(), activeOnly, categoryFilter)
|
|
if err != nil {
|
|
return c.Status(fiber.StatusInternalServerError).JSON(domain.ErrorResponse{
|
|
Message: "Failed to list subscription plans",
|
|
Error: err.Error(),
|
|
})
|
|
}
|
|
|
|
result := make([]planRes, len(plans))
|
|
for i, p := range plans {
|
|
result[i] = *planToRes(&p)
|
|
}
|
|
|
|
return c.JSON(domain.Response{
|
|
Message: "Subscription plans retrieved successfully",
|
|
Data: result,
|
|
})
|
|
}
|
|
|
|
// GetSubscriptionPlan godoc
|
|
// @Summary Get a subscription plan
|
|
// @Description Learner endpoint retired: returns 410 Gone. Purchase a course using POST /api/v1/courses/{courseId}/checkout. Administrative subscription history remains available.
|
|
// @Failure 410 {object} domain.ErrorResponse
|
|
// @Tags subscriptions
|
|
// @Produce json
|
|
// @Param id path int true "Plan ID"
|
|
// @Success 200 {object} domain.Response{data=planRes}
|
|
// @Failure 404 {object} domain.ErrorResponse
|
|
// @Router /api/v1/subscription-plans/{id} [get]
|
|
// @Failure 400 {object} domain.ErrorResponse "Invalid request"
|
|
func (h *Handler) GetSubscriptionPlan(c *fiber.Ctx) error {
|
|
id, err := strconv.ParseInt(c.Params("id"), 10, 64)
|
|
if err != nil {
|
|
return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{
|
|
Message: "Invalid plan ID",
|
|
})
|
|
}
|
|
|
|
plan, err := h.subscriptionsSvc.GetPlanByID(c.Context(), id)
|
|
if err != nil {
|
|
return c.Status(fiber.StatusNotFound).JSON(domain.ErrorResponse{
|
|
Message: "Subscription plan not found",
|
|
})
|
|
}
|
|
|
|
if c.Locals("api_audience") == "client" && !plan.IsActive {
|
|
return fiber.NewError(fiber.StatusNotFound, "Subscription plan not found")
|
|
}
|
|
|
|
return c.JSON(domain.Response{
|
|
Message: "Subscription plan retrieved successfully",
|
|
Data: planToRes(plan),
|
|
})
|
|
}
|
|
|
|
// UpdateSubscriptionPlan godoc
|
|
// @Summary Update a subscription plan
|
|
// @Description Updates a subscription plan (admin only)
|
|
// @Tags subscriptions
|
|
// @Accept json
|
|
// @Produce json
|
|
// @Param id path int true "Plan ID"
|
|
// @Param body body updatePlanReq true "Update plan payload"
|
|
// @Success 200 {object} MessageResponse
|
|
// @Failure 400 {object} domain.ErrorResponse
|
|
// @Failure 500 {object} domain.ErrorResponse
|
|
// @Router /api/v1/admin/subscription-plans/{id} [put]
|
|
// @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"
|
|
// @Failure 404 {object} domain.ErrorResponse "Resource not found"
|
|
// @Failure 409 {object} domain.ErrorResponse "Resource conflict"
|
|
func (h *Handler) UpdateSubscriptionPlan(c *fiber.Ctx) error {
|
|
id, err := strconv.ParseInt(c.Params("id"), 10, 64)
|
|
if err != nil {
|
|
return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{
|
|
Message: "Invalid plan ID",
|
|
})
|
|
}
|
|
|
|
var req updatePlanReq
|
|
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),
|
|
})
|
|
}
|
|
if req.IsLifetime != nil && !*req.IsLifetime {
|
|
if req.DurationValue == nil || *req.DurationValue < 1 {
|
|
return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{
|
|
Message: "Validation failed",
|
|
Error: "duration_value must be at least 1 for expiring plans",
|
|
})
|
|
}
|
|
if req.DurationUnit == nil {
|
|
return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{
|
|
Message: "Validation failed",
|
|
Error: "duration_unit is required for expiring plans",
|
|
})
|
|
}
|
|
switch strings.ToUpper(strings.TrimSpace(*req.DurationUnit)) {
|
|
case "DAY", "WEEK", "MONTH", "YEAR":
|
|
default:
|
|
return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{
|
|
Message: "Validation failed",
|
|
Error: "duration_unit must be one of: DAY, WEEK, MONTH, YEAR",
|
|
})
|
|
}
|
|
}
|
|
|
|
err = h.subscriptionsSvc.UpdatePlan(c.Context(), id, domain.UpdateSubscriptionPlanInput{
|
|
Name: req.Name,
|
|
Description: req.Description,
|
|
Category: req.Category,
|
|
DurationValue: req.DurationValue,
|
|
DurationUnit: req.DurationUnit,
|
|
Price: req.Price,
|
|
Currency: req.Currency,
|
|
IsLifetime: req.IsLifetime,
|
|
IsFree: req.IsFree,
|
|
IsActive: req.IsActive,
|
|
})
|
|
if err != nil {
|
|
if errors.Is(err, domain.ErrFreePlanMustHaveZeroPrice) || errors.Is(err, domain.ErrPaidPlanMustHavePositivePrice) {
|
|
return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{
|
|
Message: "Validation failed",
|
|
Error: err.Error(),
|
|
})
|
|
}
|
|
if errors.Is(err, subscriptionsvc.ErrPlanNotFound) {
|
|
return c.Status(fiber.StatusNotFound).JSON(domain.ErrorResponse{
|
|
Message: "Subscription plan not found",
|
|
})
|
|
}
|
|
if errors.Is(err, domain.ErrDuplicateSubscriptionPlanPeriod) {
|
|
return c.Status(fiber.StatusConflict).JSON(domain.ErrorResponse{
|
|
Message: "Duplicate subscription plan",
|
|
Error: duplicateSubscriptionPlanPeriodMessage,
|
|
})
|
|
}
|
|
return c.Status(fiber.StatusInternalServerError).JSON(domain.ErrorResponse{
|
|
Message: "Failed to update subscription plan",
|
|
Error: err.Error(),
|
|
})
|
|
}
|
|
|
|
actorID := c.Locals("user_id").(int64)
|
|
actorRole := string(c.Locals("role").(domain.Role))
|
|
ip := c.IP()
|
|
ua := c.Get("User-Agent")
|
|
meta, _ := json.Marshal(map[string]interface{}{"plan_id": id})
|
|
go h.activityLogSvc.RecordAction(context.Background(), &actorID, &actorRole, domain.ActionSubscriptionPlanUpdated, domain.ResourceSubscriptionPlan, &id, fmt.Sprintf("Updated subscription plan ID: %d", id), meta, &ip, &ua)
|
|
|
|
return c.JSON(domain.Response{
|
|
Message: "Subscription plan updated successfully",
|
|
})
|
|
}
|
|
|
|
// DeleteSubscriptionPlan godoc
|
|
// @Summary Delete a subscription plan
|
|
// @Description Deletes a subscription plan (admin only)
|
|
// @Tags subscriptions
|
|
// @Produce json
|
|
// @Param id path int true "Plan ID"
|
|
// @Success 200 {object} MessageResponse
|
|
// @Failure 500 {object} domain.ErrorResponse
|
|
// @Router /api/v1/admin/subscription-plans/{id} [delete]
|
|
// @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"
|
|
// @Failure 400 {object} domain.ErrorResponse "Invalid request"
|
|
// @Failure 404 {object} domain.ErrorResponse "Resource not found"
|
|
// @Failure 409 {object} domain.ErrorResponse "Resource conflict"
|
|
func (h *Handler) DeleteSubscriptionPlan(c *fiber.Ctx) error {
|
|
id, err := strconv.ParseInt(c.Params("id"), 10, 64)
|
|
if err != nil {
|
|
return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{
|
|
Message: "Invalid plan ID",
|
|
})
|
|
}
|
|
|
|
err = h.subscriptionsSvc.DeletePlan(c.Context(), id)
|
|
if err != nil {
|
|
if errors.Is(err, subscriptionsvc.ErrPlanNotFound) {
|
|
return c.Status(fiber.StatusNotFound).JSON(domain.ErrorResponse{
|
|
Message: "Subscription plan not found",
|
|
Error: err.Error(),
|
|
})
|
|
}
|
|
if errors.Is(err, subscriptionsvc.ErrPlanInUse) {
|
|
return c.Status(fiber.StatusConflict).JSON(domain.ErrorResponse{
|
|
Message: "This plan cannot be deleted because learners already have subscriptions on it. Deactivate the plan instead so it is hidden from new purchases.",
|
|
Error: err.Error(),
|
|
})
|
|
}
|
|
return c.Status(fiber.StatusInternalServerError).JSON(domain.ErrorResponse{
|
|
Message: "Failed to delete subscription plan",
|
|
Error: err.Error(),
|
|
})
|
|
}
|
|
|
|
actorID := c.Locals("user_id").(int64)
|
|
actorRole := string(c.Locals("role").(domain.Role))
|
|
ip := c.IP()
|
|
ua := c.Get("User-Agent")
|
|
meta, _ := json.Marshal(map[string]interface{}{"plan_id": id})
|
|
go h.activityLogSvc.RecordAction(context.Background(), &actorID, &actorRole, domain.ActionSubscriptionPlanDeleted, domain.ResourceSubscriptionPlan, &id, fmt.Sprintf("Deleted subscription plan ID: %d", id), meta, &ip, &ua)
|
|
|
|
return c.JSON(domain.Response{
|
|
Message: "Subscription plan deleted successfully",
|
|
})
|
|
}
|
|
|
|
// =====================
|
|
// User Subscription Handlers
|
|
// =====================
|
|
|
|
// Subscribe godoc
|
|
// @Summary Subscribe to a plan (Admin only - bypasses payment)
|
|
// @Description Learner endpoint retired: returns 410 Gone. Purchase a course using POST /api/v1/courses/{courseId}/checkout. Administrative subscription history remains available.
|
|
// @Failure 410 {object} domain.ErrorResponse
|
|
// @Tags subscriptions
|
|
// @Accept json
|
|
// @Produce json
|
|
// @Param body body subscribeReq true "Subscribe payload"
|
|
// @Success 201 {object} domain.Response{data=subscriptionRes}
|
|
// @Failure 400 {object} domain.ErrorResponse
|
|
// @Failure 500 {object} domain.ErrorResponse
|
|
// @deprecated Use POST /api/v1/payments/subscribe for user subscriptions with payment
|
|
// @Router /api/v1/subscriptions [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) Subscribe(c *fiber.Ctx) error {
|
|
userID, ok := c.Locals("user_id").(int64)
|
|
if !ok {
|
|
return c.Status(fiber.StatusUnauthorized).JSON(domain.ErrorResponse{
|
|
Message: "Unauthorized",
|
|
})
|
|
}
|
|
|
|
// Check role - only admins can create subscriptions without payment
|
|
role, ok := c.Locals("role").(domain.Role)
|
|
if !ok || (role != domain.RoleAdmin && role != domain.RoleSuperAdmin) {
|
|
return c.Status(fiber.StatusForbidden).JSON(domain.ErrorResponse{
|
|
Message: "Use /api/v1/payments/subscribe to subscribe with payment",
|
|
Error: "Direct subscription creation requires admin privileges",
|
|
})
|
|
}
|
|
|
|
var req subscribeReq
|
|
if err := c.BodyParser(&req); err != nil {
|
|
return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{
|
|
Message: "Invalid request body",
|
|
Error: err.Error(),
|
|
})
|
|
}
|
|
|
|
plan, err := h.subscriptionsSvc.GetPlanByID(c.Context(), req.PlanID)
|
|
if err != nil {
|
|
return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{
|
|
Message: "Invalid subscription plan",
|
|
Error: err.Error(),
|
|
})
|
|
}
|
|
|
|
sub, err := h.subscriptionsSvc.Subscribe(c.Context(), userID, req.PlanID, req.PaymentReference, req.PaymentMethod)
|
|
if err != nil {
|
|
status := fiber.StatusInternalServerError
|
|
if err.Error() == "user already has an active subscription" {
|
|
status = fiber.StatusConflict
|
|
}
|
|
return c.Status(status).JSON(domain.ErrorResponse{
|
|
Message: "Failed to create subscription",
|
|
Error: err.Error(),
|
|
})
|
|
}
|
|
if h.learnerNotifSvc != nil {
|
|
h.learnerNotifSvc.MaybeNotifyLearnPackageSubscribed(userID, plan.Category, plan.Name, sub.ExpiresAt)
|
|
}
|
|
|
|
h.recordActivity(c, domain.ActionSubscriptionCreated, domain.ResourceSubscription, &sub.ID, fmt.Sprintf("Created subscription ID: %d", sub.ID), nil)
|
|
|
|
return c.Status(fiber.StatusCreated).JSON(domain.Response{
|
|
Message: "Subscription created successfully",
|
|
Data: subscriptionToRes(sub),
|
|
})
|
|
}
|
|
|
|
// SubscribeWithPayment godoc
|
|
// @Summary Subscribe to a plan with payment
|
|
// @Description Learner endpoint retired: returns 410 Gone. Purchase a course using POST /api/v1/courses/{courseId}/checkout. Administrative subscription history remains available.
|
|
// @Failure 410 {object} domain.ErrorResponse
|
|
// @Tags subscriptions
|
|
// @Accept json
|
|
// @Produce json
|
|
// @Param body body subscribeWithPaymentReq true "Subscribe with payment payload"
|
|
// @Success 200 {object} domain.Response{data=subscriptionCheckoutRes}
|
|
// @Failure 400 {object} domain.ErrorResponse
|
|
// @Failure 409 {object} domain.ErrorResponse "User already has active subscription"
|
|
// @Failure 500 {object} domain.ErrorResponse
|
|
// @Router /api/v1/subscriptions/checkout [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"
|
|
// @Failure 404 {object} domain.ErrorResponse "Resource not found"
|
|
func (h *Handler) SubscribeWithPayment(c *fiber.Ctx) error {
|
|
userID, ok := c.Locals("user_id").(int64)
|
|
if !ok {
|
|
return c.Status(fiber.StatusUnauthorized).JSON(domain.ErrorResponse{
|
|
Message: "Unauthorized",
|
|
})
|
|
}
|
|
|
|
var req subscribeWithPaymentReq
|
|
if err := c.BodyParser(&req); err != nil {
|
|
return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{
|
|
Message: "Invalid request body",
|
|
Error: err.Error(),
|
|
})
|
|
}
|
|
|
|
plan, err := h.subscriptionsSvc.GetPlanByID(c.Context(), req.PlanID)
|
|
if err != nil {
|
|
if errors.Is(err, subscriptionsvc.ErrPlanNotFound) {
|
|
return c.Status(fiber.StatusNotFound).JSON(domain.ErrorResponse{
|
|
Message: "Subscription plan not found",
|
|
})
|
|
}
|
|
return c.Status(fiber.StatusInternalServerError).JSON(domain.ErrorResponse{
|
|
Message: "Failed to load subscription plan",
|
|
Error: err.Error(),
|
|
})
|
|
}
|
|
|
|
if plan.IsFree {
|
|
sub, enrollErr := h.subscriptionsSvc.EnrollFreePlan(c.Context(), userID, req.PlanID)
|
|
if enrollErr != nil {
|
|
status := fiber.StatusInternalServerError
|
|
message := "Failed to activate free subscription"
|
|
switch {
|
|
case errors.Is(enrollErr, subscriptionsvc.ErrAlreadySubscribed):
|
|
status = fiber.StatusConflict
|
|
message = "User already has an active subscription for this category"
|
|
case errors.Is(enrollErr, subscriptionsvc.ErrInvalidPlan):
|
|
status = fiber.StatusBadRequest
|
|
message = "Subscription plan is not available"
|
|
case errors.Is(enrollErr, subscriptionsvc.ErrPlanNotFound):
|
|
status = fiber.StatusNotFound
|
|
message = "Subscription plan not found"
|
|
}
|
|
return c.Status(status).JSON(domain.ErrorResponse{
|
|
Message: message,
|
|
Error: enrollErr.Error(),
|
|
})
|
|
}
|
|
|
|
if h.learnerNotifSvc != nil {
|
|
h.learnerNotifSvc.MaybeNotifyLearnPackageSubscribed(userID, plan.Category, plan.Name, sub.ExpiresAt)
|
|
}
|
|
|
|
subID := sub.ID
|
|
h.recordActivity(c, domain.ActionSubscriptionCreated, domain.ResourceSubscription, &subID, fmt.Sprintf("Activated free subscription plan ID: %d", req.PlanID), nil)
|
|
|
|
return c.JSON(domain.Response{
|
|
Message: "Subscription activated successfully.",
|
|
Data: subscriptionCheckoutRes{
|
|
InitiateSubscriptionPaymentResponse: domain.InitiateSubscriptionPaymentResponse{
|
|
FreeEnrollment: true,
|
|
SubscriptionID: sub.ID,
|
|
},
|
|
Subscription: subscriptionToRes(sub),
|
|
},
|
|
})
|
|
}
|
|
|
|
provider, err := domain.ParsePaymentProvider(req.Provider)
|
|
if err != nil {
|
|
return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{
|
|
Message: "Invalid payment provider",
|
|
Error: err.Error(),
|
|
})
|
|
}
|
|
|
|
result, err := h.initiateSubscriptionPayment(c.Context(), userID, domain.InitiateSubscriptionPaymentRequest{
|
|
PlanID: req.PlanID,
|
|
Phone: req.Phone,
|
|
Email: req.Email,
|
|
Provider: provider,
|
|
})
|
|
if err != nil {
|
|
status := paymentInitiationStatus(err)
|
|
return c.Status(status).JSON(domain.ErrorResponse{
|
|
Message: "Failed to initiate subscription payment",
|
|
Error: err.Error(),
|
|
})
|
|
}
|
|
|
|
paymentID := result.PaymentID
|
|
h.recordActivity(c, domain.ActionPaymentInitiated, domain.ResourcePayment, &paymentID, fmt.Sprintf("Initiated subscription payment ID: %d", paymentID), nil)
|
|
|
|
return c.JSON(domain.Response{
|
|
Message: "Payment initiated. Complete payment to activate subscription.",
|
|
Data: result,
|
|
})
|
|
}
|
|
|
|
// GetMySubscription godoc
|
|
// @Summary Get active subscriptions
|
|
// @Description Returns all active subscriptions for the authenticated user (one per plan category)
|
|
// @Tags subscriptions
|
|
// @Produce json
|
|
// @Success 200 {object} domain.Response{data=[]subscriptionRes}
|
|
// @Router /api/v1/subscriptions/me [get]
|
|
// @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"
|
|
// @Failure 500 {object} domain.ErrorResponse "Internal server error"
|
|
func (h *Handler) GetMySubscription(c *fiber.Ctx) error {
|
|
userID, ok := c.Locals("user_id").(int64)
|
|
if !ok {
|
|
return c.Status(fiber.StatusUnauthorized).JSON(domain.ErrorResponse{
|
|
Message: "Unauthorized",
|
|
})
|
|
}
|
|
|
|
subs, err := h.subscriptionsSvc.GetActiveSubscriptions(c.Context(), userID)
|
|
if err != nil {
|
|
return c.Status(fiber.StatusInternalServerError).JSON(domain.ErrorResponse{
|
|
Message: "Failed to get subscriptions",
|
|
Error: err.Error(),
|
|
})
|
|
}
|
|
|
|
result := make([]subscriptionRes, len(subs))
|
|
for i, s := range subs {
|
|
result[i] = *subscriptionToRes(&s)
|
|
}
|
|
|
|
return c.JSON(domain.Response{
|
|
Message: "Subscriptions retrieved successfully",
|
|
Data: result,
|
|
})
|
|
}
|
|
|
|
// GetMySubscriptionHistory godoc
|
|
// @Summary Get subscription history
|
|
// @Description Returns the authenticated user's subscription history
|
|
// @Tags subscriptions
|
|
// @Produce json
|
|
// @Param limit query int false "Limit" default(20)
|
|
// @Param offset query int false "Offset" default(0)
|
|
// @Success 200 {object} domain.Response{data=[]subscriptionRes}
|
|
// @Router /api/v1/subscriptions/history [get]
|
|
// @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"
|
|
// @Failure 500 {object} domain.ErrorResponse "Internal server error"
|
|
func (h *Handler) GetMySubscriptionHistory(c *fiber.Ctx) error {
|
|
userID, ok := c.Locals("user_id").(int64)
|
|
if !ok {
|
|
return c.Status(fiber.StatusUnauthorized).JSON(domain.ErrorResponse{
|
|
Message: "Unauthorized",
|
|
})
|
|
}
|
|
|
|
limit, _ := strconv.Atoi(c.Query("limit", "20"))
|
|
offset, _ := strconv.Atoi(c.Query("offset", "0"))
|
|
|
|
subs, err := h.subscriptionsSvc.GetSubscriptionHistory(c.Context(), userID, int32(limit), int32(offset))
|
|
if err != nil {
|
|
return c.Status(fiber.StatusInternalServerError).JSON(domain.ErrorResponse{
|
|
Message: "Failed to get subscription history",
|
|
Error: err.Error(),
|
|
})
|
|
}
|
|
|
|
result := make([]subscriptionRes, len(subs))
|
|
for i, s := range subs {
|
|
result[i] = *subscriptionToRes(&s)
|
|
}
|
|
|
|
return c.JSON(domain.Response{
|
|
Message: "Subscription history retrieved successfully",
|
|
Data: result,
|
|
})
|
|
}
|
|
|
|
// CheckSubscriptionStatus godoc
|
|
// @Summary Check subscription status
|
|
// @Description Returns whether the authenticated user has an active subscription
|
|
// @Tags subscriptions
|
|
// @Produce json
|
|
// @Success 200 {object} domain.Response{data=CheckSubscriptionStatusData}
|
|
// @Router /api/v1/subscriptions/status [get]
|
|
// @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"
|
|
// @Failure 500 {object} domain.ErrorResponse "Internal server error"
|
|
func (h *Handler) CheckSubscriptionStatus(c *fiber.Ctx) error {
|
|
userID, ok := c.Locals("user_id").(int64)
|
|
if !ok {
|
|
return c.Status(fiber.StatusUnauthorized).JSON(domain.ErrorResponse{
|
|
Message: "Unauthorized",
|
|
})
|
|
}
|
|
|
|
hasActive, err := h.subscriptionsSvc.HasActiveSubscription(c.Context(), userID)
|
|
if err != nil {
|
|
return c.Status(fiber.StatusInternalServerError).JSON(domain.ErrorResponse{
|
|
Message: "Failed to check subscription status",
|
|
Error: err.Error(),
|
|
})
|
|
}
|
|
|
|
return c.JSON(domain.Response{
|
|
Message: "Subscription status retrieved",
|
|
Data: fiber.Map{
|
|
"has_active_subscription": hasActive,
|
|
},
|
|
})
|
|
}
|
|
|
|
// CancelSubscription godoc
|
|
// @Summary Cancel subscription
|
|
// @Description Cancels the user's subscription
|
|
// @Tags subscriptions
|
|
// @Produce json
|
|
// @Param id path int true "Subscription ID"
|
|
// @Success 200 {object} MessageResponse
|
|
// @Failure 500 {object} domain.ErrorResponse
|
|
// @Router /api/v1/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"
|
|
// @Failure 400 {object} domain.ErrorResponse "Invalid request"
|
|
// @Failure 404 {object} domain.ErrorResponse "Resource not found"
|
|
func (h *Handler) CancelSubscription(c *fiber.Ctx) error {
|
|
userID, ok := c.Locals("user_id").(int64)
|
|
if !ok {
|
|
return c.Status(fiber.StatusUnauthorized).JSON(domain.ErrorResponse{
|
|
Message: "Unauthorized",
|
|
})
|
|
}
|
|
id, err := strconv.ParseInt(c.Params("id"), 10, 64)
|
|
if err != nil {
|
|
return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{
|
|
Message: "Invalid subscription ID",
|
|
})
|
|
}
|
|
|
|
err = h.subscriptionsSvc.CancelSubscriptionForUser(c.Context(), id, userID)
|
|
if err != nil {
|
|
switch {
|
|
case errors.Is(err, subscriptionsvc.ErrSubscriptionNotFound):
|
|
return c.Status(fiber.StatusNotFound).JSON(domain.ErrorResponse{
|
|
Message: "Subscription not found",
|
|
Error: err.Error(),
|
|
})
|
|
case errors.Is(err, subscriptionsvc.ErrSubscriptionNotOwned):
|
|
return c.Status(fiber.StatusForbidden).JSON(domain.ErrorResponse{
|
|
Message: "You do not have access to this subscription",
|
|
Error: err.Error(),
|
|
})
|
|
default:
|
|
return c.Status(fiber.StatusInternalServerError).JSON(domain.ErrorResponse{
|
|
Message: "Failed to cancel subscription",
|
|
Error: err.Error(),
|
|
})
|
|
}
|
|
}
|
|
|
|
h.recordActivity(c, domain.ActionSubscriptionCancelled, domain.ResourceSubscription, &id, fmt.Sprintf("Cancelled subscription ID: %d", id), nil)
|
|
|
|
return c.JSON(domain.Response{
|
|
Message: "Subscription cancelled successfully",
|
|
})
|
|
}
|
|
|
|
// SetAutoRenew godoc
|
|
// @Summary Set auto-renew
|
|
// @Description Enables or disables auto-renewal for a subscription
|
|
// @Tags subscriptions
|
|
// @Accept json
|
|
// @Produce json
|
|
// @Param id path int true "Subscription ID"
|
|
// @Param body body autoRenewReq true "Auto-renew payload"
|
|
// @Success 200 {object} MessageResponse
|
|
// @Failure 500 {object} domain.ErrorResponse
|
|
// @Router /api/v1/subscriptions/{id}/auto-renew [put]
|
|
// @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"
|
|
// @Failure 400 {object} domain.ErrorResponse "Invalid request"
|
|
// @Failure 404 {object} domain.ErrorResponse "Resource not found"
|
|
func (h *Handler) SetAutoRenew(c *fiber.Ctx) error {
|
|
userID, ok := c.Locals("user_id").(int64)
|
|
if !ok {
|
|
return c.Status(fiber.StatusUnauthorized).JSON(domain.ErrorResponse{
|
|
Message: "Unauthorized",
|
|
})
|
|
}
|
|
id, err := strconv.ParseInt(c.Params("id"), 10, 64)
|
|
if err != nil {
|
|
return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{
|
|
Message: "Invalid subscription ID",
|
|
})
|
|
}
|
|
|
|
var req autoRenewReq
|
|
if err := c.BodyParser(&req); err != nil {
|
|
return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{
|
|
Message: "Invalid request body",
|
|
Error: err.Error(),
|
|
})
|
|
}
|
|
|
|
err = h.subscriptionsSvc.SetAutoRenewForUser(c.Context(), id, userID, req.AutoRenew)
|
|
if err != nil {
|
|
switch {
|
|
case errors.Is(err, subscriptionsvc.ErrSubscriptionNotFound):
|
|
return c.Status(fiber.StatusNotFound).JSON(domain.ErrorResponse{
|
|
Message: "Subscription not found",
|
|
Error: err.Error(),
|
|
})
|
|
case errors.Is(err, subscriptionsvc.ErrSubscriptionNotOwned):
|
|
return c.Status(fiber.StatusForbidden).JSON(domain.ErrorResponse{
|
|
Message: "You do not have access to this subscription",
|
|
Error: err.Error(),
|
|
})
|
|
default:
|
|
return c.Status(fiber.StatusInternalServerError).JSON(domain.ErrorResponse{
|
|
Message: "Failed to update auto-renew setting",
|
|
Error: err.Error(),
|
|
})
|
|
}
|
|
}
|
|
|
|
autoRenewMeta, _ := json.Marshal(map[string]bool{"auto_renew": req.AutoRenew})
|
|
h.recordActivity(c, domain.ActionSubscriptionAutoRenewUpdated, domain.ResourceSubscription, &id, fmt.Sprintf("Updated auto-renew for subscription ID: %d", id), autoRenewMeta)
|
|
|
|
return c.JSON(domain.Response{
|
|
Message: "Auto-renew setting updated successfully",
|
|
})
|
|
}
|
|
|
|
// Helper functions
|
|
|
|
func planToRes(p *domain.SubscriptionPlan) *planRes {
|
|
return &planRes{
|
|
ID: p.ID,
|
|
Name: p.Name,
|
|
Description: p.Description,
|
|
Category: p.Category,
|
|
DurationValue: p.DurationValue,
|
|
DurationUnit: p.DurationUnit,
|
|
Price: p.Price,
|
|
Currency: p.Currency,
|
|
IsLifetime: p.IsLifetime,
|
|
IsFree: p.IsFree,
|
|
IsActive: p.IsActive,
|
|
CreatedAt: p.CreatedAt.Format("2006-01-02T15:04:05Z07:00"),
|
|
}
|
|
}
|
|
|
|
func subscriptionToRes(s *domain.UserSubscription) *subscriptionRes {
|
|
return &subscriptionRes{
|
|
ID: s.ID,
|
|
UserID: s.UserID,
|
|
PlanID: s.PlanID,
|
|
PlanName: s.PlanName,
|
|
Category: s.PlanCategory,
|
|
IsLifetime: s.PlanIsLifetime,
|
|
StartsAt: s.StartsAt.Format("2006-01-02T15:04:05Z07:00"),
|
|
ExpiresAt: s.ExpiresAt.Format("2006-01-02T15:04:05Z07:00"),
|
|
Status: s.Status,
|
|
PaymentReference: s.PaymentReference,
|
|
PaymentMethod: s.PaymentMethod,
|
|
AutoRenew: s.AutoRenew,
|
|
DurationValue: s.DurationValue,
|
|
DurationUnit: s.DurationUnit,
|
|
Price: s.Price,
|
|
Currency: s.Currency,
|
|
CreatedAt: s.CreatedAt.Format("2006-01-02T15:04:05Z07:00"),
|
|
}
|
|
}
|