63 lines
2.4 KiB
Go
63 lines
2.4 KiB
Go
package handlers
|
|
|
|
import (
|
|
"Rezina-Backend/internal/domain"
|
|
"Rezina-Backend/internal/services/chapa"
|
|
"errors"
|
|
"github.com/gofiber/fiber/v2"
|
|
"strconv"
|
|
)
|
|
|
|
// CheckoutCourse godoc
|
|
// @Summary Purchase a course
|
|
// @Description Creates a one-time Chapa checkout at the course's server-configured price. Verified payment grants permanent access to this course only. Optional referral_code applies first-touch affiliate attribution before checkout; same-code retries preserve the original expiry. Invalid or conflicting codes return 400.
|
|
// @Tags learning
|
|
// @Accept json
|
|
// @Produce json
|
|
// @Param courseId path int true "Course ID"
|
|
// @Param body body domain.CourseCheckoutRequest false "Optional checkout phone"
|
|
// @Success 200 {object} domain.Response{data=domain.CourseCheckoutResponse}
|
|
// @Failure 400 {object} domain.ErrorResponse
|
|
// @Failure 401 {object} domain.ErrorResponse
|
|
// @Failure 409 {object} domain.ErrorResponse
|
|
// @Failure 500 {object} domain.ErrorResponse
|
|
// @Security Bearer
|
|
// @Router /api/v1/courses/{courseId}/checkout [post]
|
|
func (h *Handler) CheckoutCourse(c *fiber.Ctx) error {
|
|
id, err := strconv.ParseInt(c.Params("courseId"), 10, 64)
|
|
if err != nil || id <= 0 {
|
|
return fiber.NewError(400, "Invalid course ID")
|
|
}
|
|
userID, ok := c.Locals("user_id").(int64)
|
|
if !ok || userID <= 0 {
|
|
return fiber.NewError(401, "Unauthorized")
|
|
}
|
|
var req domain.CourseCheckoutRequest
|
|
if len(c.Body()) > 0 {
|
|
if err := c.BodyParser(&req); err != nil {
|
|
return fiber.NewError(400, "Invalid request body")
|
|
}
|
|
}
|
|
if req.ReferralCode != "" {
|
|
// Attribution is first-touch and persisted before the payment snapshot is created.
|
|
if err := h.referralSvc.Apply(c.Context(), userID, req.ReferralCode); err != nil {
|
|
return referralResponse(c, nil, err)
|
|
}
|
|
}
|
|
out, err := h.chapaSvc.InitiateCoursePayment(c.Context(), userID, id, req)
|
|
if errors.Is(err, chapa.ErrCourseAlreadyOwned) {
|
|
return fiber.NewError(409, err.Error())
|
|
}
|
|
if errors.Is(err, chapa.ErrCourseNotPurchasable) {
|
|
return fiber.NewError(400, err.Error())
|
|
}
|
|
if err != nil {
|
|
return fiber.NewError(500, "Failed to initialize course checkout")
|
|
}
|
|
return c.JSON(domain.Response{Success: true, Message: "Course checkout created", Data: out})
|
|
}
|
|
|
|
func (h *Handler) RetiredSubscriptionCheckout(c *fiber.Ctx) error {
|
|
return c.Status(fiber.StatusGone).JSON(domain.ErrorResponse{Message: "Subscription plans have been replaced by course purchases. Use POST /courses/:courseId/checkout."})
|
|
}
|