package visamasterpay import ( "errors" "net/http" "online-back/internal/appresult" "online-back/internal/handlers" "online-back/internal/identity/rbac" "online-back/internal/identity/rbac/perm" "online-back/internal/shared" "online-back/pkg/logging" "github.com/gin-gonic/gin" "github.com/jackc/pgx/v4" ) const baseURL = "/visa-master-payment-orders" type handler struct { logger *logging.Logger repository Repository } func NewHandler(logger *logging.Logger, repository Repository) handlers.Handler { return &handler{logger: logger, repository: repository} } func (h *handler) Register(router *gin.RouterGroup) { group := rbac.Group(router, baseURL, rbac.Require(perm.Cards)) group.GET("/:id/quote", h.quote) group.POST("/:id/pay", h.pay) group.GET("/:id/status", h.status) // callback is hit by the customer's/operator's browser after GBÜS // redirects back - it carries no Bearer token. rbac.Group(router, baseURL+"/callback", rbac.Public()).GET("", h.callback) } // quote godoc // @Summary Quote a visa/master/sber payment // @Description Returns the current rate, configured fees, and max payable amount for an order's payout // @Tags visa-master-payment // @Produce json // @Security BearerAuth // @Param id path int true "Visa/master payment order ID" // @Param lang query string false "Language of localized fields; all returns the full {en, ru, tm} objects" Enums(tm, ru, en, all) default(tm) // @Success 200 {object} PaymentQuoteDTO // @Failure 400 {object} appresult.AppError // @Failure 404 {object} appresult.AppError // @Failure 500 {object} appresult.AppError // @Router /visa-master-payment-orders/{id}/quote [get] func (h *handler) quote(c *gin.Context) { id, ok := shared.ParseID(c.Param("id")) if !ok { c.JSON(http.StatusBadRequest, appresult.ErrMissingParam) return } if !h.guardOrder(c, id) { return } result, err := h.repository.Quote(c.Request.Context(), id) if h.handleError(c, err, "quote") { return } c.JSON(http.StatusOK, appresult.SuccessWithData(result)) } // pay godoc // @Summary Start a visa/master/sber payout // @Description Registers the payment with GBÜS and returns the hosted-payment-page URL to complete it on. The final outcome is only known once GBÜS redirects back to the callback, which verifies and finalizes it. // @Tags visa-master-payment // @Accept json // @Produce json // @Security BearerAuth // @Param id path int true "Visa/master payment order ID" // @Param body body PayOrderDTO true "Payment payload" // @Param lang query string false "Language of localized fields; all returns the full {en, ru, tm} objects" Enums(tm, ru, en, all) default(tm) // @Success 200 {object} PaymentInitResultDTO // @Failure 400 {object} appresult.AppError // @Failure 404 {object} appresult.AppError // @Failure 500 {object} appresult.AppError // @Router /visa-master-payment-orders/{id}/pay [post] func (h *handler) pay(c *gin.Context) { id, ok := shared.ParseID(c.Param("id")) if !ok { c.JSON(http.StatusBadRequest, appresult.ErrMissingParam) return } if !h.guardOrder(c, id) { return } var dto PayOrderDTO if err := c.ShouldBindJSON(&dto); err != nil { c.JSON(http.StatusBadRequest, appresult.ErrMissingParam) return } if userID, ok := rbac.CurrentUserID(c); ok { dto.CreatedBy = &userID } result, err := h.repository.Pay(c.Request.Context(), id, dto) if h.handleError(c, err, "pay") { return } c.JSON(http.StatusOK, appresult.SuccessWithData(result)) } // status godoc // @Summary Re-check a visa/master/sber order's latest payment attempt // @Description For when the frontend can't rely on GBÜS's redirect having reached the callback (e.g. the user closed the hosted payment page first) - re-verifies the latest attempt with GBÜS server-to-server, the same way the callback does, and finalizes it if needed. gatewayResponse is GBÜS's last stored response for the attempt (null if GBÜS never answered). Safe to call repeatedly. // @Tags visa-master-payment // @Produce json // @Security BearerAuth // @Param id path int true "Visa/master payment order ID" // @Param lang query string false "Language of localized fields; all returns the full {en, ru, tm} objects" Enums(tm, ru, en, all) default(tm) // @Success 200 {object} PaymentResultDTO // @Failure 400 {object} appresult.AppError // @Failure 404 {object} appresult.AppError // @Failure 500 {object} appresult.AppError // @Router /visa-master-payment-orders/{id}/status [get] func (h *handler) status(c *gin.Context) { id, ok := shared.ParseID(c.Param("id")) if !ok { c.JSON(http.StatusBadRequest, appresult.ErrMissingParam) return } if !h.guardOrder(c, id) { return } var requestedBy *int64 if userID, ok := rbac.CurrentUserID(c); ok { requestedBy = &userID } result, err := h.repository.Status(c.Request.Context(), id, requestedBy) if h.handleError(c, err, "status") { return } c.JSON(http.StatusOK, appresult.SuccessWithData(result)) } // callback godoc // @Summary GBÜS payment callback // @Description GBÜS redirects the browser here after payment; the real outcome is verified server-to-server before anything is finalized // @Tags visa-master-payment // @Produce json // @Param paymentId query int true "Payment attempt ID" // @Param lang query string false "Language of localized fields; all returns the full {en, ru, tm} objects" Enums(tm, ru, en, all) default(tm) // @Success 200 {object} CallbackResultDTO // @Router /visa-master-payment-orders/callback [get] func (h *handler) callback(c *gin.Context) { paymentID, ok := shared.ParseID(c.Query("paymentId")) if !ok { c.JSON(http.StatusBadRequest, CallbackResultDTO{Paid: false, Data: "Töleg maglumaty tapylmady."}) return } result, err := h.repository.HandleCallback(c.Request.Context(), paymentID) if err != nil { h.logger.Errorf("visa master payment callback failed (paymentId=%d): %v", paymentID, err) c.JSON(http.StatusOK, CallbackResultDTO{Paid: false, Data: "Tölegiň netijesini barlap bolmady. Operator bilen habarlaşyň."}) return } if result.Paid { c.JSON(http.StatusOK, CallbackResultDTO{Paid: true, Data: "Töleg amala aşyryldy."}) return } c.JSON(http.StatusOK, CallbackResultDTO{Paid: false, Data: "Töleg amala aşyrylmady."}) } func (h *handler) guardOrder(c *gin.Context, id int64) bool { if rbac.SkipRecordGuard(c) { return true } userID, branchID, err := h.repository.OwnerInfo(c.Request.Context(), id) if errors.Is(err, pgx.ErrNoRows) { c.JSON(http.StatusNotFound, appresult.ErrNotFound) return false } if err != nil { c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer) return false } return rbac.GuardOrder(c, userID, branchID) } // handleError writes the appropriate response for a Quote/Pay error and // reports whether the caller should stop (true) or continue with a // successful result (false). func (h *handler) handleError(c *gin.Context, err error, action string) bool { if err == nil { return false } switch { case errors.Is(err, pgx.ErrNoRows), errors.Is(err, ErrPaymentNotFound): c.JSON(http.StatusNotFound, appresult.ErrNotFound) case errors.Is(err, ErrAlreadyPaid), errors.Is(err, ErrAmountExceedsMax), errors.Is(err, ErrPaymentWindowClosed): c.JSON(http.StatusBadRequest, appresult.ErrNotAcceptable) default: h.logger.Errorf("%s visa master payment order failed: %v", action, err) c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer) } return true }