Files
online-backend/internal/payment/paymenthistory/db/postgresql.go
GuwandykA ef3a1baee2
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
payment-history: apiClientName, formUrl/successUrl after finalizing, callbackStatus
To match the old online payment history page:
- apiClientName: billing_visa_master_username / billing_sber_username
- formUrl falls back to the logged register.do response, so finalized
  attempts keep it; successUrl is the returnUrl logged with register.do
- callbackStatus ("received") and callbackAt from the attempt's first
  callback_received log
- index visa_master_payment_logs (order_id, step) for those lookups

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

279 lines
10 KiB
Go

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
publicBaseURL string
}
func NewRepository(client postgresql.Client, logger *logging.Logger, publicBaseURL string) paymenthistory.Repository {
return &repository{client: client, logger: logger, publicBaseURL: strings.TrimRight(publicBaseURL, "/")}
}
// historyCountFromClause is historyFromClause without the display-only
// joins, so COUNT(*) never touches branches/users.
const historyCountFromClause = ` FROM visa_master_order_payments p
JOIN visa_master_payment_orders o ON o.id = p.order_id`
const historyFromClause = historyCountFromClause + `
LEFT JOIN branches b ON b.id = o.branch_id
LEFT JOIN users u ON u.id = p.created_by`
// isSberSQL mirrors visamasterpay's isSber for the order joined as o.
const isSberSQL = `LOWER(TRIM(COALESCE(o.type, ''))) = 'sber'`
// paymentLogSQL selects from the order's visa_master_payment_logs rows of
// one step (served by visa_master_payment_logs_order_step_idx).
const paymentLogSQL = `FROM visa_master_payment_logs l WHERE l.order_id = p.order_id AND l.step = `
// historySelectColumns pulls only the handful of gateway_response fields a
// row needs (formUrl, cardAuthInfo) out in SQL rather than shipping every
// row's whole jsonb blob to Go and decoding it there. formUrl falls back to
// the register.do response logged for the attempt (gateway_response drops
// it once finalized), successUrl is the returnUrl logged with register.do,
// and the callback columns come from its first callback_received log.
const historySelectColumns = `p.id, p.order_id, COALESCE(p.order_number, ''), COALESCE(o.unique_id, ''), COALESCE(o.type, ''),
o.branch_id, 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,
ROUND(p.amount_tmt * 100)::bigint,
COALESCE(ROUND(p.amount_tmt / NULLIF(p.exchange_rate_usd, 0), 2), 0),
p.exchange_rate_usd, p.exchange_rate_rub, p.payment_period,
p.gateway_status, p.gateway_reference,
CASE WHEN ` + isSberSQL + ` THEN COALESCE(b.billing_sber_username, '') ELSE COALESCE(b.billing_visa_master_username, '') END,
CASE WHEN ` + isSberSQL + ` THEN 'billing_sber_username' ELSE 'billing_visa_master_username' END,
CASE WHEN ` + isSberSQL + ` THEN 'Sber tölegi' ELSE 'Visa/Master tölegi' END,
NULLIF(p.gateway_response->'cardAuthInfo'->>'cardholderName', ''),
NULLIF(COALESCE(p.gateway_response->'cardAuthInfo'->>'maskedPan', p.gateway_response->'cardAuthInfo'->>'pan'), ''),
COALESCE(NULLIF(p.gateway_response->>'formUrl', ''), (SELECT NULLIF(l.detail->>'formUrl', '') ` + paymentLogSQL + `'register_response'
AND l.detail->>'gbusOrderId' = p.gateway_reference ORDER BY l.id DESC LIMIT 1)),
(SELECT NULLIF(l.detail->>'returnUrl', '') ` + paymentLogSQL + `'register_request'
AND l.detail->>'paymentId' = p.id::text ORDER BY l.id DESC LIMIT 1),
(SELECT MIN(l.created_at) ` + paymentLogSQL + `'callback_received' AND l.detail->>'paymentId' = p.id::text),
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(*)` + historyCountFromClause + 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 %s LIMIT $%d OFFSET $%d`,
historySelectColumns, historyFromClause, whereClause, orderByClause(filter), limitPlaceholder, offsetPlaceholder,
)
rows, err := r.client.Query(ctx, query, append(args, filter.Limit, offset)...)
if err != nil {
return paymenthistory.ListPaymentHistoryDTO{}, err
}
defer rows.Close()
items := make([]paymenthistory.PaymentHistoryItemDTO, 0, filter.Limit)
for rows.Next() {
item, err := r.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 (r *repository) Get(ctx context.Context, paymentID int64) (paymenthistory.PaymentHistoryDetailDTO, error) {
query := `SELECT ` + historySelectColumns + `, p.gateway_response` +
historyFromClause + ` WHERE p.id = $1 AND p.deleted_at IS NULL AND o.deleted_at IS NULL`
var detail paymenthistory.PaymentHistoryDetailDTO
item, err := r.scanHistoryItem(r.client.QueryRow(ctx, query, paymentID), &detail.GatewayResponse)
if err != nil {
return paymenthistory.PaymentHistoryDetailDTO{}, err
}
detail.PaymentHistoryItemDTO = item
return detail, nil
}
func (r *repository) OrderPayments(ctx context.Context, orderID int64) ([]paymenthistory.PaymentHistoryItemDTO, error) {
whereClause, args := buildListQuery(paymenthistory.ListFilter{OrderId: &orderID})
query := `SELECT ` + historySelectColumns + historyFromClause + whereClause + ` ORDER BY p.id DESC`
rows, err := r.client.Query(ctx, query, args...)
if err != nil {
return nil, err
}
defer rows.Close()
items := []paymenthistory.PaymentHistoryItemDTO{}
for rows.Next() {
item, err := r.scanHistoryItem(rows)
if err != nil {
return nil, err
}
items = append(items, item)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
// OwnerInfo returns orderID's owning user/branch, so the handler can run
// rbac.GuardOrder before returning its logs to a branch/own-scoped caller.
func (r *repository) OwnerInfo(ctx context.Context, orderID int64) (*int64, int64, error) {
var userID *int64
var branchID int64
err := r.client.QueryRow(ctx,
`SELECT user_id, branch_id FROM visa_master_payment_orders WHERE id = $1 AND deleted_at IS NULL`, orderID,
).Scan(&userID, &branchID)
return userID, branchID, err
}
func (r *repository) Logs(ctx context.Context, orderID int64) ([]paymenthistory.PaymentLogDTO, error) {
rows, err := r.client.Query(ctx,
`SELECT l.id, l.order_id, l.step, l.detail, l.created_by, `+shared.UserDisplaySQL+`, l.created_at
FROM visa_master_payment_logs l
LEFT JOIN users u ON u.id = l.created_by
WHERE l.order_id = $1
ORDER BY l.id DESC`,
orderID,
)
if err != nil {
return nil, err
}
defer rows.Close()
items := []paymenthistory.PaymentLogDTO{}
for rows.Next() {
var item paymenthistory.PaymentLogDTO
if err := rows.Scan(
&item.Id, &item.OrderId, &item.Step, &item.Detail, &item.CreatedById, &item.CreatedByName, &item.CreatedAt,
); err != nil {
return nil, err
}
items = append(items, item)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
// orderByClause sorts by the whitelisted filter.Sort column, falling back
// to newest-first; p.id breaks ties so paging stays stable.
func orderByClause(filter paymenthistory.ListFilter) string {
direction := "ASC"
if filter.Desc {
direction = "DESC"
}
column, ok := paymenthistory.SortColumns[filter.Sort]
if !ok || column == "p.id" {
return "p.id " + direction
}
return column + " " + direction + ", p.id DESC"
}
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 OR p.order_number ILIKE $%[1]d
)`, n))
}
return " WHERE " + strings.Join(conditions, " AND "), args
}
// scanHistoryItem scans historySelectColumns, followed by any extra
// columns the caller appended (scanned into extra, in order).
func (r *repository) scanHistoryItem(row pgx.Row, extra ...interface{}) (paymenthistory.PaymentHistoryItemDTO, error) {
var item paymenthistory.PaymentHistoryItemDTO
var branchNameJSON []byte
dest := []interface{}{
&item.Id, &item.OrderId, &item.OrderNumber, &item.OrderUniqueId, &item.Type,
&item.BranchId, &branchNameJSON, &item.PassportName, &item.PassportSurname, &item.UserId,
&item.AmountTmt, &item.BankFeeTmt, &item.GbusFeeTmt, &item.TvebFeeUsd, &item.TvebFeeTmt, &item.TotalAmountTmt,
&item.AmountMinor, &item.AmountUsd,
&item.ExchangeRateUsd, &item.ExchangeRateRub, &item.PaymentPeriod,
&item.GatewayStatus, &item.GatewayReference,
&item.ApiClient, &item.ApiClientName, &item.Description,
&item.CardholderName, &item.MaskedPan, &item.FormUrl, &item.SuccessUrl, &item.CallbackAt,
&item.CreatedById, &item.CreatedByName,
&item.CreatedAt, &item.UpdatedAt,
}
if err := row.Scan(append(dest, extra...)...); err != nil {
return paymenthistory.PaymentHistoryItemDTO{}, err
}
if err := shared.UnmarshalLocalized(branchNameJSON, &item.BranchName); err != nil {
return paymenthistory.PaymentHistoryItemDTO{}, err
}
item.Paid = item.GatewayStatus == "success"
if item.CallbackAt != nil {
received := paymenthistory.CallbackReceived
item.CallbackStatus = &received
}
// A returnUrl only matters for an attempt GBÜS registered (has a
// formUrl). Ones registered before register_request logged its
// returnUrl fall back to the ReturnURL visamasterpay's Pay uses.
if item.FormUrl == nil {
item.SuccessUrl = nil
} else if item.SuccessUrl == nil {
successURL := r.publicBaseURL + "/online/visa-master"
item.SuccessUrl = &successURL
}
return item, nil
}