Files
online-backend/internal/payment/paymenthistory/handler.go
GuwandykA d7e5d1f989
Some checks failed
CI/CD / Vet, test, build (push) Has been cancelled
CI/CD / Docker image (push) Has been cancelled
CI/CD / Deploy binary to server (push) Has been cancelled
swagger: split the Visa/Master tag and document payment-history in Turkmen
visa-master-payment-orders mixed order CRUD with the GBÜS payment flow;
they are now visa-master-orders and visa-master-payment. payment-history
summaries, descriptions and params are in Turkmen with one shape
(what it returns, Tertip, Bellik), and its tag description lists the
endpoints in the order they are used.

@securityDefinitions.apikey moves to the end of the general info block:
swag read every line after it as its attributes, so @schemes and all
@tag.* declarations were silently dropped from the spec.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-24 23:21:07 +05:00

293 lines
11 KiB
Go

package paymenthistory
import (
"errors"
"net/http"
"strings"
"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 = "/payment-history"
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.RequireStaff(perm.Cards))
group.GET("", h.list)
group.GET("/payments/:id", h.get)
group.GET("/payments/:id/gateway", h.gateway)
group.GET("/:id/gateway", h.gateway)
group.GET("/:id", h.orderPayments)
group.GET("/:id/logs", h.logs)
}
// list godoc
// @Summary Tölegleriň taryhy
// @Description Ähli sargytlaryň Visa/Master we Sber töleg synanyşyklaryny (tölenen, şowsuz, garaşylýan) sahypalap gaýtarýar. Tertip: sort/order boýunça (adaty ýagdaýda iň täzesi birinji). Bellik: diňe ulanyjynyň öz şahamçasynyň tölegleri görünýär.
// @Tags payment-history
// @Produce json
// @Security BearerAuth
// @Param order_id query int false "Sargyt ID-si boýunça süzmek"
// @Param branch_id query int false "Şahamça ID-si boýunça süzmek"
// @Param user_id query int false "Sargyt eýesiniň (müşderiniň) ulanyjy ID-si boýunça süzmek"
// @Param status query string false "GBÜS statusy boýunça süzmek (pending, success, failed)"
// @Param search query string false "Pasport ady/familiýasy ýa-da sargydyň unique ID-si boýunça gözlemek"
// @Param sort query string false "Tertiplenýän sütün" Enums(id, created_at, status, amount) default(id)
// @Param order query string false "Tertip ugry" Enums(asc, desc) default(desc)
// @Param page query int false "Sahypa belgisi" default(1)
// @Param limit query int false "Bir sahypadaky ýazgy sany" default(10)
// @Param lang query string false "Lokallaşdyrylan meýdanlaryň dili; all - doly {en, ru, tm} obýektleri" Enums(tm, ru, en, all) default(tm)
// @Success 200 {object} ListPaymentHistoryDTO
// @Failure 400 {object} appresult.AppError
// @Failure 500 {object} appresult.AppError
// @Router /payment-history [get]
func (h *handler) list(c *gin.Context) {
filter, ok := parseListFilter(c)
if !ok {
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
return
}
result, err := h.repository.List(c.Request.Context(), filter)
if err != nil {
h.logger.Errorf("list payment history failed: %v", err)
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return
}
c.JSON(http.StatusOK, appresult.SuccessWithData(result))
}
// get godoc
// @Summary Bir tölegiň jikme-jikligi
// @Description Töleg ID-si boýunça bir Visa/Master ýa-da Sber töleg synanyşygyny GBÜS-iň soňky jogaby (gatewayResponse) bilen gaýtarýar. Tertip: ýeke ýazgy. Bellik: taryh sanawyndaky bir setiriň jikme-jik görnüşi.
// @Tags payment-history
// @Produce json
// @Security BearerAuth
// @Param id path int true "Töleg ID-si"
// @Param lang query string false "Lokallaşdyrylan meýdanlaryň dili; all - doly {en, ru, tm} obýektleri" Enums(tm, ru, en, all) default(tm)
// @Success 200 {object} PaymentHistoryDetailDTO
// @Failure 400 {object} appresult.AppError
// @Failure 403 {object} appresult.AppError
// @Failure 404 {object} appresult.AppError
// @Failure 500 {object} appresult.AppError
// @Router /payment-history/payments/{id} [get]
func (h *handler) get(c *gin.Context) {
paymentID, ok := shared.ParseID(c.Param("id"))
if !ok {
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
return
}
result, err := h.repository.Get(c.Request.Context(), paymentID)
if errors.Is(err, pgx.ErrNoRows) {
c.JSON(http.StatusNotFound, appresult.ErrNotFound)
return
}
if err != nil {
h.logger.Errorf("get payment history failed (payment %d): %v", paymentID, err)
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return
}
if !h.guardOrder(c, result.OrderId) {
return
}
c.JSON(http.StatusOK, appresult.SuccessWithData(result))
}
// gateway godoc
// @Summary Sargydyň tölegleri GBÜS jogaplary bilen
// @Description Bir sargydyň ähli tölegini her biriniň GBÜS (HALKBANK) soňky jogaby (gatewayResponse) bilen gaýtarýar: tölendimi, haýsy kartdan tölendi (cardholderName/maskedPan), wagty (createdAt), töleg ýyly/aýy, mukdarlary we belgisi (orderNumber). Tertip: iň täzesi birinji. Bellik: GBÜS kart maglumatyny habar berýänçä cardholderName/maskedPan null, GBÜS asla jogap bermedik bolsa gatewayResponse null; tablisadaky ammar nyşany şu endpoint-den işleýär.
// @Tags payment-history
// @Produce json
// @Security BearerAuth
// @Param id path int true "Sargyt ID-si"
// @Param lang query string false "Lokallaşdyrylan meýdanlaryň dili; all - doly {en, ru, tm} obýektleri" Enums(tm, ru, en, all) default(tm)
// @Success 200 {array} PaymentGatewayDTO
// @Failure 400 {object} appresult.AppError
// @Failure 403 {object} appresult.AppError
// @Failure 404 {object} appresult.AppError
// @Failure 500 {object} appresult.AppError
// @Router /payment-history/payments/{id}/gateway [get]
// @Router /payment-history/{id}/gateway [get]
func (h *handler) gateway(c *gin.Context) {
orderID, ok := shared.ParseID(c.Param("id"))
if !ok {
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
return
}
if !h.guardOrder(c, orderID) {
return
}
details, err := h.repository.OrderPaymentDetails(c.Request.Context(), orderID)
if err != nil {
h.logger.Errorf("list order payment gateway responses failed (order %d): %v", orderID, err)
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return
}
result := make([]PaymentGatewayDTO, 0, len(details))
for _, detail := range details {
result = append(result, NewPaymentGatewayDTO(detail))
}
c.JSON(http.StatusOK, appresult.SuccessWithData(result))
}
// orderPayments godoc
// @Summary Sargydyň tölegleri
// @Description Bir sargydyň ähli Visa/Master we Sber töleg synanyşyklaryny gaýtarýar: her töleg üçin bir setir - tölendimi (paid/gatewayStatus), haýsy kartdan tölendi (cardholderName/maskedPan), wagty (createdAt) we döwri (paymentPeriod). Tertip: iň täzesi birinji. Bellik: bir tölegiň GBÜS jogaby /payment-history/payments/{id}, ähli tölegleriňki /payment-history/{id}/gateway, ädimme-ädim loglar /payment-history/{id}/logs salgysynda.
// @Tags payment-history
// @Produce json
// @Security BearerAuth
// @Param id path int true "Sargyt ID-si"
// @Param lang query string false "Lokallaşdyrylan meýdanlaryň dili; all - doly {en, ru, tm} obýektleri" Enums(tm, ru, en, all) default(tm)
// @Success 200 {array} PaymentHistoryItemDTO
// @Failure 400 {object} appresult.AppError
// @Failure 403 {object} appresult.AppError
// @Failure 404 {object} appresult.AppError
// @Failure 500 {object} appresult.AppError
// @Router /payment-history/{id} [get]
func (h *handler) orderPayments(c *gin.Context) {
orderID, ok := shared.ParseID(c.Param("id"))
if !ok {
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
return
}
if !h.guardOrder(c, orderID) {
return
}
result, err := h.repository.OrderPayments(c.Request.Context(), orderID)
if err != nil {
h.logger.Errorf("list order payments failed (order %d): %v", orderID, err)
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return
}
c.JSON(http.StatusOK, appresult.SuccessWithData(result))
}
// logs godoc
// @Summary Sargydyň töleg loglary
// @Description Sargydyň tölegi işlenende ýazylan ähli ädimleri (visa_master_payment_logs) gaýtarýar. Tertip: iň täzesi birinji. Bellik: /payment-history/{id} setirlerinden garaşsyz, hakykatda näme bolandygynyň subutnamasy.
// @Tags payment-history
// @Produce json
// @Security BearerAuth
// @Param id path int true "Sargyt ID-si"
// @Param lang query string false "Lokallaşdyrylan meýdanlaryň dili; all - doly {en, ru, tm} obýektleri" Enums(tm, ru, en, all) default(tm)
// @Success 200 {array} PaymentLogDTO
// @Failure 400 {object} appresult.AppError
// @Failure 403 {object} appresult.AppError
// @Failure 404 {object} appresult.AppError
// @Failure 500 {object} appresult.AppError
// @Router /payment-history/{id}/logs [get]
func (h *handler) logs(c *gin.Context) {
orderID, ok := shared.ParseID(c.Param("id"))
if !ok {
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
return
}
if !h.guardOrder(c, orderID) {
return
}
result, err := h.repository.Logs(c.Request.Context(), orderID)
if err != nil {
h.logger.Errorf("list payment logs failed (order %d): %v", orderID, err)
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return
}
c.JSON(http.StatusOK, appresult.SuccessWithData(result))
}
// guardOrder 404s if orderID doesn't exist, then enforces the same
// branch/own-scope rules as every other order-scoped endpoint (see
// visamasterpay.handler.guardOrder) before its logs are returned.
func (h *handler) guardOrder(c *gin.Context, orderID int64) bool {
if rbac.SkipRecordGuard(c) {
return true
}
userID, branchID, err := h.repository.OwnerInfo(c.Request.Context(), orderID)
if errors.Is(err, pgx.ErrNoRows) {
c.JSON(http.StatusNotFound, appresult.ErrNotFound)
return false
}
if err != nil {
h.logger.Errorf("payment history owner lookup failed (order %d): %v", orderID, err)
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return false
}
return rbac.GuardOrder(c, userID, branchID)
}
func parseListFilter(c *gin.Context) (ListFilter, bool) {
page, limit, ok := shared.ParsePageLimit(c)
if !ok {
return ListFilter{}, false
}
filter := ListFilter{Page: page, Limit: limit}
if id, ok := shared.OptionalQueryID(c, "order_id", "orderId"); !ok {
return ListFilter{}, false
} else if id != nil {
filter.OrderId = id
}
if id, ok := shared.OptionalQueryID(c, "branch_id", "branchId"); !ok {
return ListFilter{}, false
} else if id != nil {
filter.BranchId = id
}
if id, ok := shared.OptionalQueryID(c, "user_id", "userId"); !ok {
return ListFilter{}, false
} else if id != nil {
filter.UserId = id
}
if raw := shared.QueryValue(c, "status"); raw != "" {
filter.Status = &raw
}
filter.Search = shared.QueryValue(c, "search", "q")
if raw := shared.QueryValue(c, "sort", "sort_by", "sortBy"); raw != "" {
if _, ok := SortColumns[raw]; !ok {
return ListFilter{}, false
}
filter.Sort = raw
}
switch strings.ToLower(shared.QueryValue(c, "order", "direction")) {
case "", "desc":
filter.Desc = true
case "asc":
default:
return ListFilter{}, false
}
rbac.BindBranchIDs(c, &filter.BranchIds)
return filter, true
}