payment-history: payment detail with GBÜS response, sorting, newest-first logs
- GET /payment-history/payments/{id}: single payment attempt with the raw
gateway_response (last HALKBANK JSON) for the "storage" icon modal
- GET /payment-history: sort (id/created_at/status/amount) and order
(asc/desc, default desc) query params
- GET /payment-history/{id}: order logs now newest first
- index on visa_master_order_payments (gateway_status, id DESC)
- regenerate swagger docs
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
25
internal/payment/paymenthistory/db/order_test.go
Normal file
25
internal/payment/paymenthistory/db/order_test.go
Normal file
@@ -0,0 +1,25 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"online-back/internal/payment/paymenthistory"
|
||||
)
|
||||
|
||||
func TestOrderByClause(t *testing.T) {
|
||||
cases := []struct {
|
||||
filter paymenthistory.ListFilter
|
||||
want string
|
||||
}{
|
||||
{paymenthistory.ListFilter{Desc: true}, "p.id DESC"},
|
||||
{paymenthistory.ListFilter{Sort: "id"}, "p.id ASC"},
|
||||
{paymenthistory.ListFilter{Sort: "status", Desc: true}, "p.gateway_status DESC, p.id DESC"},
|
||||
{paymenthistory.ListFilter{Sort: "amount"}, "p.amount_tmt ASC, p.id DESC"},
|
||||
{paymenthistory.ListFilter{Sort: "p.id; DROP TABLE users", Desc: true}, "p.id DESC"},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
if got := orderByClause(tc.filter); got != tc.want {
|
||||
t.Errorf("orderByClause(%+v) = %q, want %q", tc.filter, got, tc.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -2,7 +2,6 @@ package db
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
@@ -25,23 +24,41 @@ func NewRepository(client postgresql.Client, logger *logging.Logger, publicBaseU
|
||||
return &repository{client: client, logger: logger, publicBaseURL: strings.TrimRight(publicBaseURL, "/")}
|
||||
}
|
||||
|
||||
const historyFromClause = ` FROM visa_master_order_payments p
|
||||
JOIN visa_master_payment_orders o ON o.id = p.order_id
|
||||
// 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'`
|
||||
|
||||
// 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.
|
||||
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, p.gateway_response, p.created_by, ` + shared.UserDisplaySQL + `,
|
||||
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 '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'), ''),
|
||||
NULLIF(p.gateway_response->>'formUrl', ''),
|
||||
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
|
||||
countQuery := `SELECT COUNT(*)` + historyCountFromClause + whereClause
|
||||
if err := r.client.QueryRow(ctx, countQuery, args...).Scan(&count); err != nil {
|
||||
return paymenthistory.ListPaymentHistoryDTO{}, err
|
||||
}
|
||||
@@ -50,8 +67,8 @@ func (r *repository) List(ctx context.Context, filter paymenthistory.ListFilter)
|
||||
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,
|
||||
`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)...)
|
||||
@@ -60,7 +77,7 @@ func (r *repository) List(ctx context.Context, filter paymenthistory.ListFilter)
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var items []paymenthistory.PaymentHistoryItemDTO
|
||||
items := make([]paymenthistory.PaymentHistoryItemDTO, 0, filter.Limit)
|
||||
for rows.Next() {
|
||||
item, err := r.scanHistoryItem(rows)
|
||||
if err != nil {
|
||||
@@ -75,6 +92,19 @@ func (r *repository) List(ctx context.Context, filter paymenthistory.ListFilter)
|
||||
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
|
||||
}
|
||||
|
||||
// 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) {
|
||||
@@ -92,7 +122,7 @@ func (r *repository) Logs(ctx context.Context, orderID int64) ([]paymenthistory.
|
||||
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 ASC`,
|
||||
ORDER BY l.id DESC`,
|
||||
orderID,
|
||||
)
|
||||
if err != nil {
|
||||
@@ -117,6 +147,20 @@ func (r *repository) Logs(ctx context.Context, orderID int64) ([]paymenthistory.
|
||||
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"}
|
||||
|
||||
@@ -153,49 +197,42 @@ func buildListQuery(filter paymenthistory.ListFilter) (whereClause string, args
|
||||
return " WHERE " + strings.Join(conditions, " AND "), args
|
||||
}
|
||||
|
||||
func (r *repository) scanHistoryItem(row pgx.Row) (paymenthistory.PaymentHistoryItemDTO, error) {
|
||||
// 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 gatewayStatus string
|
||||
var branchNameJSON []byte
|
||||
var gatewayResponse []byte
|
||||
if err := row.Scan(
|
||||
var formURL *string
|
||||
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,
|
||||
&gatewayStatus, &item.GatewayReference, &gatewayResponse, &item.CreatedById, &item.CreatedByName,
|
||||
&item.GatewayStatus, &item.GatewayReference,
|
||||
&item.ApiClient, &item.Description,
|
||||
&item.CardholderName, &item.MaskedPan, &formURL,
|
||||
&item.CreatedById, &item.CreatedByName,
|
||||
&item.CreatedAt, &item.UpdatedAt,
|
||||
); err != nil {
|
||||
}
|
||||
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.GatewayStatus = gatewayStatus
|
||||
item.Paid = gatewayStatus == "success"
|
||||
item.Paid = item.GatewayStatus == "success"
|
||||
|
||||
// formUrl only survives in gateway_response while the attempt is still
|
||||
// pending - once finalized, gateway_response is overwritten with the
|
||||
// status-check response, which has no formUrl, so there's nothing to
|
||||
// resume for a paid/failed row.
|
||||
if formURL := extractFormURL(gatewayResponse); formURL != "" {
|
||||
item.FormUrl = &formURL
|
||||
successURL := fmt.Sprintf("%s/api/admin/visa-master-payment-orders/callback?paymentId=%d", r.publicBaseURL, item.Id)
|
||||
// resume for a paid/failed row. SuccessUrl must match the ReturnURL
|
||||
// visamasterpay registered with GBÜS (see its Pay).
|
||||
if formURL != nil {
|
||||
item.FormUrl = formURL
|
||||
successURL := r.publicBaseURL + "/online/visa-master"
|
||||
item.SuccessUrl = &successURL
|
||||
}
|
||||
|
||||
return item, nil
|
||||
}
|
||||
|
||||
func extractFormURL(gatewayResponse []byte) string {
|
||||
if len(gatewayResponse) == 0 {
|
||||
return ""
|
||||
}
|
||||
var parsed struct {
|
||||
FormUrl string `json:"formUrl"`
|
||||
}
|
||||
if err := json.Unmarshal(gatewayResponse, &parsed); err != nil {
|
||||
return ""
|
||||
}
|
||||
return parsed.FormUrl
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user