package handlers import ( "Rezina-Backend/internal/domain" "Rezina-Backend/internal/services/referrals" "encoding/json" "errors" "github.com/gofiber/fiber/v2" "github.com/jackc/pgx/v5" "strconv" ) func referralLearner(c *fiber.Ctx) (int64, error) { id, ok := c.Locals("user_id").(int64) if !ok || id <= 0 { return 0, fiber.NewError(401, "Unauthorized") } role, _ := c.Locals("role").(domain.Role) if !role.IsCustomerLearnerRole() { return 0, fiber.NewError(403, "Learner account required") } return id, nil } func referralAdmin(c *fiber.Ctx) (int64, error) { id, ok := c.Locals("user_id").(int64) if !ok || id <= 0 { return 0, fiber.NewError(401, "Unauthorized") } role, _ := c.Locals("role").(domain.Role) if role != domain.RoleAdmin && role != domain.RoleSuperAdmin { return 0, fiber.NewError(403, "Administrator required") } return id, nil } func referralResponse(c *fiber.Ctx, data any, err error) error { if err != nil { if errors.Is(err, domain.ErrInvalidReferralCode) || errors.Is(err, referrals.ErrInvalidCommissionPercent) { return fiber.NewError(400, err.Error()) } if errors.Is(err, pgx.ErrNoRows) { return fiber.NewError(403, "Active learner account required") } return fiber.NewError(500, "Unable to process referral request") } return c.JSON(domain.Response{Success: true, StatusCode: 200, Message: "Referral request successful", Data: data}) } func referralPagination(c *fiber.Ctx) (int32, int32, error) { limit, err := strconv.Atoi(c.Query("limit", "20")) if err != nil || limit < 1 || limit > 100 { return 0, 0, fiber.NewError(400, "limit must be between 1 and 100") } offset, err := strconv.ParseInt(c.Query("offset", "0"), 10, 32) if err != nil || offset < 0 { return 0, 0, fiber.NewError(400, "offset must be a non-negative integer") } return int32(limit), int32(offset), nil } // CreateReferralCode creates or returns the authenticated learner's stable share code. // @Router /api/v1/referrals/code [post] // @Summary Create Referral Code // @Tags referrals // @Security Bearer // @Description Creates or returns the authenticated learner's stable share code. Requires an active STUDENT or OPEN_LEARNER account; a subscription is not required. // @Success 200 {object} domain.Response{data=ReferralCodeData} // @Produce json // @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 {string} string "Unable to process referral request" func (h *Handler) CreateReferralCode(c *fiber.Ctx) error { id, err := referralLearner(c) if err != nil { return err } code, err := h.referralSvc.Code(c.Context(), id) return referralResponse(c, fiber.Map{"code": code}, err) } // GetReferralCode godoc // @Summary Get Referral Code // @Tags referrals // @Router /api/v1/referrals/code [get] // @Security Bearer // @Description Returns the authenticated learner's stable share code, creating it when necessary. Codes are case-insensitive. // @Success 200 {object} domain.Response{data=ReferralCodeData} // @Produce json // @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 {string} string "Unable to process referral request" func (h *Handler) GetReferralCode(c *fiber.Ctx) error { return h.CreateReferralCode(c) } // GetMyReferrals godoc // @Summary Get My Referrals // @Tags referrals // @Router /api/v1/referrals/me [get] // @Security Bearer // @Description Returns the learner's code, current commission percentage, referral/conversion counts, and commission-wallet balances by currency. // @Success 200 {object} domain.Response{data=ReferralOverviewData} // @Produce json // @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 {string} string "Unable to process referral request" func (h *Handler) GetMyReferrals(c *fiber.Ctx) error { id, err := referralLearner(c) if err != nil { return err } data, err := h.referralSvc.Overview(c.Context(), id) return referralResponse(c, data, err) } // ApplyReferralCode godoc // @Summary Apply Referral Code // @Tags referrals // @Router /api/v1/referrals/apply [post] // @Security Bearer // @Description Attributes the authenticated learner to one referrer. Apply within seven days of account creation and before any successful positive payment. Codes are case-insensitive and surrounding whitespace is ignored. Self referral, reassignment, inactive referrers, and invalid codes are rejected. // @Accept json // @Param body body applyReferralReq true "Referral share code" // @Success 200 {object} domain.Response // @Produce json // @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 {string} string "Invalid request or ineligible referral" // @Failure 500 {string} string "Unable to process referral request" func (h *Handler) ApplyReferralCode(c *fiber.Ctx) error { id, err := referralLearner(c) if err != nil { return err } var input applyReferralReq if c.BodyParser(&input) != nil { return fiber.NewError(400, "Invalid request body") } return referralResponse(c, nil, h.referralSvc.Apply(c.Context(), id, input.Code)) } // ListMyReferrals godoc // @Summary List My Referrals // @Tags referrals // @Router /api/v1/referrals [get] // @Security Bearer // @Description Returns only the authenticated learner's referral history and conversion flags. Referred learners' names, emails, and phone numbers are not exposed. // @Success 200 {object} domain.Response{data=ReferralHistoryData} // @Produce json // @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 {string} string "Invalid pagination" // @Failure 500 {string} string "Unable to process referral request" // @Param limit query int false "Page size" default(20) minimum(1) maximum(100) // @Param offset query int false "Number of entries to skip" default(0) minimum(0) func (h *Handler) ListMyReferrals(c *fiber.Ctx) error { id, err := referralLearner(c) if err != nil { return err } limit, offset, err := referralPagination(c) if err != nil { return err } data, err := h.referralSvc.List(c.Context(), id, limit, offset) return referralResponse(c, fiber.Map{"items": data, "limit": limit, "offset": offset}, err) } // GetReferralWallet godoc // @Summary Get Referral Wallet // @Tags referrals // @Router /api/v1/referrals/wallet [get] // @Security Bearer // @Description Returns wallet balances separately by currency and a paginated commission ledger. Decimal amounts and percentages are strings. Only the first successful positive subscription payment earns a commission; duplicate callbacks and renewals do not. Reversed credits are excluded from balances. This endpoint does not initiate cash payouts. // @Success 200 {object} domain.Response{data=ReferralWalletData} // @Produce json // @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 {string} string "Invalid pagination" // @Failure 500 {string} string "Unable to process referral request" // @Param limit query int false "Page size" default(20) minimum(1) maximum(100) // @Param offset query int false "Number of entries to skip" default(0) minimum(0) func (h *Handler) GetReferralWallet(c *fiber.Ctx) error { id, err := referralLearner(c) if err != nil { return err } limit, offset, err := referralPagination(c) if err != nil { return err } overview, err := h.referralSvc.Overview(c.Context(), id) if err != nil { return referralResponse(c, nil, err) } entries, err := h.referralSvc.Commissions(c.Context(), id, limit, offset) return referralResponse(c, fiber.Map{"balances": overview.Wallet, "transactions": entries, "limit": limit, "offset": offset}, err) } // GetReferralSettings godoc // @Summary Get Referral Settings // @Tags referrals // @Router /api/v1/admin/referrals/settings [get] // @Security Bearer // @Description Returns the saved referral commission percentage. Restricted to ADMIN and SUPER_ADMIN. The initial percentage is 0, which disables new credits. // @Success 200 {object} domain.Response{data=ReferralSettingsData} // @Produce json // @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 {string} string "Unable to process referral request" func (h *Handler) GetReferralSettings(c *fiber.Ctx) error { if _, err := referralAdmin(c); err != nil { return err } data, err := h.referralSvc.Settings(c.Context()) return referralResponse(c, data, err) } // UpdateReferralSettings godoc // @Summary Update Referral Settings // @Tags referrals // @Router /api/v1/admin/referrals/settings [put] // @Security Bearer // @Description Sets the percentage credited on a referred learner's first successful positive subscription payment. Accepts 0 through 100 with at most two decimal places. Zero disables new credits. Changes affect future conversions only; existing credits retain their rate. Restricted to ADMIN and SUPER_ADMIN; changes are audited. // @Accept json // @Param body body updateReferralSettingsReq true "Commission percentage configuration" // @Success 200 {object} domain.Response{data=ReferralSettingsData} // @Produce json // @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 {string} string "Missing or invalid commission_percent; use 0 through 100 with at most two decimal places" // @Failure 500 {string} string "Unable to process referral request" func (h *Handler) UpdateReferralSettings(c *fiber.Ctx) error { id, err := referralAdmin(c) if err != nil { return err } var input updateReferralSettingsReq if c.BodyParser(&input) != nil || input.Percent == nil { return fiber.NewError(400, "commission_percent is required") } data, err := h.referralSvc.UpdateSettings(c.Context(), id, *input.Percent) if err == nil { metadata, _ := json.Marshal(map[string]string{"commission_percent": data.CommissionPercent}) h.recordActivity(c, domain.ActionSettingsUpdated, domain.ResourceSettings, nil, "Updated referral commission percentage", metadata) } return referralResponse(c, data, err) }