added payment history
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

This commit is contained in:
2026-09-21 18:12:08 +05:00
parent 23d208769c
commit 99788a853f
9 changed files with 768 additions and 0 deletions

View File

@@ -556,6 +556,7 @@ func operatorPathModule(_, path string) string {
"/card-pin-orders",
"/card-rekwizit-orders",
"/visa-master-payment-orders",
"/payment-history",
"/payment-cards",
"/reasons-cards",
}):
@@ -671,6 +672,7 @@ var operatorGetPrefixes = []string{
"/payment-cards",
"/reasons-cards",
"/visa-master-payment-orders",
"/payment-history",
"/loan-orders",
"/loan-types",
"/loans-documents",

View File

@@ -0,0 +1,128 @@
package db
import (
"context"
"fmt"
"strings"
"online-back/internal/identity/rbac"
"online-back/internal/payment/paymenthistory"
"online-back/internal/shared"
"online-back/pkg/client/postgresql"
"online-back/pkg/logging"
"github.com/jackc/pgx/v4"
)
type repository struct {
client postgresql.Client
logger *logging.Logger
}
func NewRepository(client postgresql.Client, logger *logging.Logger) paymenthistory.Repository {
return &repository{client: client, logger: logger}
}
const historyFromClause = ` FROM visa_master_order_payments p
JOIN visa_master_payment_orders o ON o.id = p.order_id
LEFT JOIN branches b ON b.id = o.branch_id
LEFT JOIN users u ON u.id = p.created_by`
const historySelectColumns = `p.id, p.order_id, COALESCE(o.unique_id, ''), COALESCE(o.type, ''),
o.branch_id, COALESCE(b.name, ''), COALESCE(o.passport_name, ''), COALESCE(o.passport_surname, ''), p.user_id,
p.amount_tmt, p.bank_fee_tmt, p.gbus_fee_tmt, p.tveb_fee_usd, p.tveb_fee_tmt, p.total_amount_tmt,
p.exchange_rate_usd, p.exchange_rate_rub, p.payment_period,
p.gateway_status, p.gateway_reference, p.created_by, ` + shared.UserDisplaySQL + `,
p.created_at, p.updated_at`
func (r *repository) List(ctx context.Context, filter paymenthistory.ListFilter) (paymenthistory.ListPaymentHistoryDTO, error) {
whereClause, args := buildListQuery(filter)
var count int64
countQuery := `SELECT COUNT(*)` + historyFromClause + whereClause
if err := r.client.QueryRow(ctx, countQuery, args...).Scan(&count); err != nil {
return paymenthistory.ListPaymentHistoryDTO{}, err
}
offset := (filter.Page - 1) * filter.Limit
limitPlaceholder := len(args) + 1
offsetPlaceholder := len(args) + 2
query := fmt.Sprintf(
`SELECT %s%s%s ORDER BY p.id DESC LIMIT $%d OFFSET $%d`,
historySelectColumns, historyFromClause, whereClause, limitPlaceholder, offsetPlaceholder,
)
rows, err := r.client.Query(ctx, query, append(args, filter.Limit, offset)...)
if err != nil {
return paymenthistory.ListPaymentHistoryDTO{}, err
}
defer rows.Close()
var items []paymenthistory.PaymentHistoryItemDTO
for rows.Next() {
item, err := scanHistoryItem(rows)
if err != nil {
return paymenthistory.ListPaymentHistoryDTO{}, err
}
items = append(items, item)
}
if err := rows.Err(); err != nil {
return paymenthistory.ListPaymentHistoryDTO{}, err
}
return paymenthistory.ListPaymentHistoryDTO{Count: count, Items: items}, nil
}
func buildListQuery(filter paymenthistory.ListFilter) (whereClause string, args []interface{}) {
conditions := []string{"p.deleted_at IS NULL", "o.deleted_at IS NULL"}
if filter.OrderId != nil {
args = append(args, *filter.OrderId)
conditions = append(conditions, fmt.Sprintf("p.order_id = $%d", len(args)))
}
if len(filter.BranchIds) > 0 {
conditions, args = rbac.AppendBranchIDs(conditions, args, "o.branch_id", filter.BranchIds)
} else if filter.BranchId != nil {
args = append(args, *filter.BranchId)
conditions = append(conditions, fmt.Sprintf("o.branch_id = $%d", len(args)))
}
if filter.UserId != nil {
args = append(args, *filter.UserId)
conditions = append(conditions, fmt.Sprintf("p.user_id = $%d", len(args)))
}
if filter.Status != nil {
args = append(args, *filter.Status)
conditions = append(conditions, fmt.Sprintf("p.gateway_status = $%d", len(args)))
}
if filter.Search != "" {
args = append(args, shared.LikePattern(filter.Search))
n := len(args)
conditions = append(conditions, fmt.Sprintf(`(
o.passport_name ILIKE $%[1]d OR o.passport_surname ILIKE $%[1]d OR o.unique_id ILIKE $%[1]d
)`, n))
}
return " WHERE " + strings.Join(conditions, " AND "), args
}
func scanHistoryItem(row pgx.Row) (paymenthistory.PaymentHistoryItemDTO, error) {
var item paymenthistory.PaymentHistoryItemDTO
var gatewayStatus string
if err := row.Scan(
&item.Id, &item.OrderId, &item.OrderUniqueId, &item.Type,
&item.BranchId, &item.BranchName, &item.PassportName, &item.PassportSurname, &item.UserId,
&item.AmountTmt, &item.BankFeeTmt, &item.GbusFeeTmt, &item.TvebFeeUsd, &item.TvebFeeTmt, &item.TotalAmountTmt,
&item.ExchangeRateUsd, &item.ExchangeRateRub, &item.PaymentPeriod,
&gatewayStatus, &item.GatewayReference, &item.CreatedById, &item.CreatedByName,
&item.CreatedAt, &item.UpdatedAt,
); err != nil {
return paymenthistory.PaymentHistoryItemDTO{}, err
}
item.GatewayStatus = gatewayStatus
item.Paid = gatewayStatus == "success"
return item, nil
}

View File

@@ -0,0 +1,59 @@
// Package paymenthistory exposes a read-only, branch-scoped audit view over
// every visa/master/sber payout attempt (visa_master_order_payments) - the
// full trail visamasterpay.PaymentResultDTO deliberately keeps per-order
// (see its doc comment), denormalized here with order/branch/operator info
// so an admin/operator can browse and filter payment history across orders
// without N+1 calls.
package paymenthistory
import "time"
// PaymentHistoryItemDTO is one payout attempt (paid, failed, or still
// pending) enriched with the order/branch/client/operator context needed to
// display it in a history list, without requiring a separate lookup per row.
type PaymentHistoryItemDTO struct {
Id int64 `json:"id"`
OrderId int64 `json:"orderId"`
OrderUniqueId string `json:"orderUniqueId"`
Type string `json:"type"`
BranchId int64 `json:"branchId"`
BranchName string `json:"branchName"`
PassportName string `json:"passportName"`
PassportSurname string `json:"passportSurname"`
UserId int64 `json:"userId"`
Paid bool `json:"paid"`
AmountTmt float64 `json:"amountTmt"`
BankFeeTmt float64 `json:"bankFeeTmt"`
GbusFeeTmt *float64 `json:"gbusFeeTmt,omitempty"`
TvebFeeUsd *float64 `json:"tvebFeeUsd,omitempty"`
TvebFeeTmt *float64 `json:"tvebFeeTmt,omitempty"`
TotalAmountTmt float64 `json:"totalAmountTmt"`
ExchangeRateUsd float64 `json:"exchangeRateUsd"`
ExchangeRateRub *float64 `json:"exchangeRateRub,omitempty"`
PaymentPeriod time.Time `json:"paymentPeriod"`
GatewayStatus string `json:"gatewayStatus"`
GatewayReference *string `json:"gatewayReference,omitempty"`
CreatedById *int64 `json:"createdById,omitempty"`
CreatedByName string `json:"createdByName,omitempty"`
CreatedAt time.Time `json:"createdAt"`
UpdatedAt time.Time `json:"updatedAt"`
}
// ListFilter narrows the history list. BranchIds is populated by
// rbac.BindBranchIDs and takes priority over BranchId when set (see
// rbac.AppendBranchIDs), the same way visamaster.ListFilter works.
type ListFilter struct {
OrderId *int64
BranchId *int64
BranchIds []int64
UserId *int64
Status *string // gateway_status: pending/success/failed
Search string // matches order passport name/surname or unique id
Page int
Limit int
}
type ListPaymentHistoryDTO struct {
Count int64 `json:"count"`
Items []PaymentHistoryItemDTO `json:"items"`
}

View File

@@ -0,0 +1,98 @@
package paymenthistory
import (
"net/http"
"online-back/internal/appresult"
"online-back/internal/handlers"
"online-back/internal/identity/rbac"
"online-back/internal/shared"
"online-back/pkg/logging"
"github.com/gin-gonic/gin"
)
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 := router.Group(baseURL, appresult.JwtTokenCheck())
group.GET("", h.list)
}
// list godoc
// @Summary List payment history
// @Description Returns a paginated, branch-scoped audit trail of visa/master/sber payout attempts (paid, failed, or pending), across orders
// @Tags payment-history
// @Produce json
// @Security BearerAuth
// @Param order_id query int false "Filter by order ID"
// @Param branch_id query int false "Filter by branch ID"
// @Param user_id query int false "Filter by order owner (client) user ID"
// @Param status query string false "Filter by gateway status (pending, success, failed)"
// @Param search query string false "Filter by passport name/surname or order unique ID"
// @Param page query int false "Page number" default(1)
// @Param limit query int false "Items per page" default(10)
// @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))
}
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")
rbac.BindBranchIDs(c, &filter.BranchIds)
return filter, true
}

View File

@@ -0,0 +1,7 @@
package paymenthistory
import "context"
type Repository interface {
List(ctx context.Context, filter ListFilter) (ListPaymentHistoryDTO, error)
}

View File

@@ -7,6 +7,8 @@ package payment
import (
"online-back/internal/currency"
"online-back/internal/handlers"
"online-back/internal/payment/paymenthistory"
paymenthistorydb "online-back/internal/payment/paymenthistory/db"
"online-back/internal/payment/paymentsettings"
paymentsettingsdb "online-back/internal/payment/paymentsettings/db"
"online-back/internal/payment/visamasterpay"
@@ -30,5 +32,6 @@ func Handlers(client postgresql.Client, logger *logging.Logger, currencyRepo cur
return []handlers.Handler{
paymentsettings.NewHandler(logger, settingsRepo),
visamasterpay.NewHandler(logger, visamasterpaydb.NewRepository(client, logger, currencyRepo, settingsRepo, gateway, publicBaseURL)),
paymenthistory.NewHandler(logger, paymenthistorydb.NewRepository(client, logger)),
}
}