added log
This commit is contained in:
1 parent
c01429d2a4
commit
e47e8c24d0
7 files changed
+400
-21
No files matched your search
@@ -0,0 +1,61 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestRound2(t *testing.T) {
|
||||
// Values that round cleanly.
|
||||
cases := map[float64]float64{
|
||||
2.344: 2.34,
|
||||
100.0: 100.0,
|
||||
0.1 + 0.2: 0.30,
|
||||
}
|
||||
for in, want := range cases {
|
||||
if got := round2(in); got != want {
|
||||
t.Errorf("round2(%v)=%v want %v", in, got, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// round2 is built on float64 (math.Round(v*100)/100). Classic .xx5 amounts
|
||||
// like 1.005 and 2.345 are NOT representable exactly, so they round DOWN
|
||||
// instead of to the nearer cent. This test pins that real behaviour: money
|
||||
// math on float64 loses tenths of a cent, which is why totals should be
|
||||
// computed in integer minor units (tetri) or a decimal type. If round2 is
|
||||
// ever fixed to true half-up cents, update these expectations deliberately.
|
||||
func TestRound2_FloatImprecision(t *testing.T) {
|
||||
// 1.005 cannot be represented exactly; v*100 lands just under 100.5, so
|
||||
// math.Round drops it to 100 -> 1.00 instead of the expected 1.01.
|
||||
if got := round2(1.005); got != 1.00 {
|
||||
t.Errorf("round2(1.005)=%v; documented float behaviour is 1.00 (loses a cent)", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestIsSber(t *testing.T) {
|
||||
sber := "sber"
|
||||
upper := " SBER "
|
||||
visa := "visa"
|
||||
if !isSber(&sber) || !isSber(&upper) {
|
||||
t.Error("sber/SBER should be detected (case- and space-insensitive)")
|
||||
}
|
||||
if isSber(&visa) || isSber(nil) {
|
||||
t.Error("non-sber and nil should be false")
|
||||
}
|
||||
}
|
||||
|
||||
// isPayableDay currently has skipPayableDayCheck hard-wired to true, so it
|
||||
// returns true for EVERY day - including weekends. This test documents that
|
||||
// live behaviour so it can't change silently: if the weekend guard is ever
|
||||
// re-enabled, this test will flip and force a deliberate update.
|
||||
func TestIsPayableDay_GuardIsDisabled(t *testing.T) {
|
||||
saturday := time.Date(2026, 9, 26, 12, 0, 0, 0, ashgabatZone) // a Saturday
|
||||
sunday := time.Date(2026, 9, 27, 12, 0, 0, 0, ashgabatZone) // a Sunday
|
||||
if !skipPayableDayCheck {
|
||||
t.Skip("weekend guard re-enabled; update this test intentionally")
|
||||
}
|
||||
if !isPayableDay(saturday) || !isPayableDay(sunday) {
|
||||
t.Error("with skipPayableDayCheck=true, weekends must still report payable")
|
||||
}
|
||||
}
|
||||
@@ -136,9 +136,18 @@ func (r *repository) Pay(ctx context.Context, orderID int64, dto visamasterpay.P
|
||||
orderID,
|
||||
).Scan(&orderType, &paid, &branchID, &userID)
|
||||
if err != nil {
|
||||
// No log row for a missing order: visa_master_payment_logs.order_id
|
||||
// references it, so the insert would fail anyway.
|
||||
if !errors.Is(err, pgx.ErrNoRows) {
|
||||
r.logFailure(ctx, orderID, dto.CreatedBy, "load_order", err, nil)
|
||||
}
|
||||
return visamasterpay.PaymentInitResultDTO{}, err
|
||||
}
|
||||
|
||||
r.logStep(ctx, orderID, dto.CreatedBy, "pay_requested", map[string]interface{}{
|
||||
"orderType": derefOrEmpty(orderType), "requestedAmountTmt": dto.AmountTmt, "paymentPeriod": dto.PaymentPeriod,
|
||||
})
|
||||
|
||||
if !isPayableDay(time.Now()) {
|
||||
r.logStep(ctx, orderID, dto.CreatedBy, "rejected", map[string]string{"reason": "payment_window_closed"})
|
||||
return visamasterpay.PaymentInitResultDTO{}, visamasterpay.ErrPaymentWindowClosed
|
||||
@@ -150,11 +159,13 @@ func (r *repository) Pay(ctx context.Context, orderID int64, dto visamasterpay.P
|
||||
|
||||
usdRate, err := r.fetchRate(ctx, "USD")
|
||||
if err != nil {
|
||||
r.logFailure(ctx, orderID, dto.CreatedBy, "fetch_rate_usd", err, nil)
|
||||
return visamasterpay.PaymentInitResultDTO{}, err
|
||||
}
|
||||
|
||||
settings, err := r.settingsRepo.Get(ctx)
|
||||
if err != nil {
|
||||
r.logFailure(ctx, orderID, dto.CreatedBy, "load_payment_settings", err, nil)
|
||||
return visamasterpay.PaymentInitResultDTO{}, err
|
||||
}
|
||||
|
||||
@@ -183,6 +194,7 @@ func (r *repository) Pay(ctx context.Context, orderID int64, dto visamasterpay.P
|
||||
if sber {
|
||||
rate, err := r.fetchRate(ctx, "RUB")
|
||||
if err != nil {
|
||||
r.logFailure(ctx, orderID, dto.CreatedBy, "fetch_rate_rub", err, nil)
|
||||
return visamasterpay.PaymentInitResultDTO{}, err
|
||||
}
|
||||
tveb := round2(settings.TvebFeeUsd * usdRate)
|
||||
@@ -210,6 +222,7 @@ func (r *repository) Pay(ctx context.Context, orderID int64, dto visamasterpay.P
|
||||
|
||||
username, password, err := r.branchCredentials(ctx, branchID, sber)
|
||||
if err != nil {
|
||||
r.logFailure(ctx, orderID, dto.CreatedBy, "load_branch_credentials", err, map[string]interface{}{"branchId": branchID, "sber": sber})
|
||||
return visamasterpay.PaymentInitResultDTO{}, err
|
||||
}
|
||||
|
||||
@@ -220,9 +233,14 @@ func (r *repository) Pay(ctx context.Context, orderID int64, dto visamasterpay.P
|
||||
total: total, createdBy: dto.CreatedBy,
|
||||
})
|
||||
if err != nil {
|
||||
r.logFailure(ctx, orderID, dto.CreatedBy, "create_payment_record", err, nil)
|
||||
return visamasterpay.PaymentInitResultDTO{}, err
|
||||
}
|
||||
|
||||
r.logStep(ctx, orderID, dto.CreatedBy, "payment_record_created", map[string]interface{}{
|
||||
"paymentId": paymentID, "paymentPeriod": period.Format("2006-01-02"), "amountTmt": amountTmt, "totalAmountTmt": total,
|
||||
})
|
||||
|
||||
returnURL := fmt.Sprintf("%s/online/visa-master", r.publicBaseURL)
|
||||
orderNumber := fmt.Sprintf("vmo-%d-%d", orderID, paymentID)
|
||||
description := "Visa/Master tölegi"
|
||||
@@ -251,7 +269,9 @@ func (r *repository) Pay(ctx context.Context, orderID int64, dto visamasterpay.P
|
||||
"success": false, "errorCode": result.ErrorCode, "errorMessage": result.ErrorMessage,
|
||||
"error": errString(regErr), "rawResponse": rawJSON(result.RawResponse),
|
||||
})
|
||||
_ = updatePaymentGatewayResult(ctx, r.client, paymentID, "failed", nil, result.RawResponse)
|
||||
if err := updatePaymentGatewayResult(ctx, r.client, paymentID, "failed", nil, result.RawResponse); err != nil {
|
||||
r.logFailure(ctx, orderID, dto.CreatedBy, "save_register_result", err, map[string]interface{}{"paymentId": paymentID, "gatewayStatus": "failed"})
|
||||
}
|
||||
return visamasterpay.PaymentInitResultDTO{}, fmt.Errorf("payment gateway registration failed: %s", firstNonEmpty(result.ErrorMessage, errString(regErr)))
|
||||
}
|
||||
|
||||
@@ -261,14 +281,28 @@ func (r *repository) Pay(ctx context.Context, orderID int64, dto visamasterpay.P
|
||||
|
||||
ref := result.OrderId
|
||||
if err := updatePaymentGatewayResult(ctx, r.client, paymentID, "pending", &ref, result.RawResponse); err != nil {
|
||||
r.logFailure(ctx, orderID, dto.CreatedBy, "save_register_result", err, map[string]interface{}{
|
||||
"paymentId": paymentID, "gatewayStatus": "pending", "gbusOrderId": ref,
|
||||
})
|
||||
return visamasterpay.PaymentInitResultDTO{}, err
|
||||
}
|
||||
|
||||
r.logStep(ctx, orderID, dto.CreatedBy, "redirected_to_payment_page", map[string]interface{}{
|
||||
"paymentId": paymentID, "gbusOrderId": ref, "formUrl": result.FormUrl,
|
||||
})
|
||||
|
||||
return visamasterpay.PaymentInitResultDTO{PaymentId: paymentID, OrderId: orderID, FormUrl: result.FormUrl, SuccessUrl: returnURL}, nil
|
||||
}
|
||||
|
||||
func (r *repository) HandleCallback(ctx context.Context, paymentID int64) (visamasterpay.PaymentResultDTO, error) {
|
||||
return r.verifyPayment(ctx, paymentID, "callback", nil)
|
||||
}
|
||||
|
||||
// verifyPayment is the shared body of HandleCallback and Status: trigger
|
||||
// ("callback" or "status") and requestedBy (the caller of Status; nil for
|
||||
// the tokenless callback) are recorded on every log step so each check is
|
||||
// traceable to what started it.
|
||||
func (r *repository) verifyPayment(ctx context.Context, paymentID int64, trigger string, requestedBy *int64) (visamasterpay.PaymentResultDTO, error) {
|
||||
var orderID int64
|
||||
var gatewayStatus string
|
||||
var gatewayReference *string
|
||||
@@ -278,18 +312,38 @@ func (r *repository) HandleCallback(ctx context.Context, paymentID int64) (visam
|
||||
paymentID,
|
||||
).Scan(&orderID, &gatewayStatus, &gatewayReference, &createdBy)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
// Unknown payment id: there's no order to attach a log row to.
|
||||
return visamasterpay.PaymentResultDTO{}, visamasterpay.ErrPaymentNotFound
|
||||
}
|
||||
if err != nil {
|
||||
return visamasterpay.PaymentResultDTO{}, err
|
||||
}
|
||||
|
||||
// step logs a step of this check with its trigger/caller attached.
|
||||
step := func(name string, detail map[string]interface{}) {
|
||||
if detail == nil {
|
||||
detail = map[string]interface{}{}
|
||||
}
|
||||
detail["paymentId"] = paymentID
|
||||
detail["trigger"] = trigger
|
||||
if requestedBy != nil {
|
||||
detail["requestedBy"] = *requestedBy
|
||||
}
|
||||
r.logStep(ctx, orderID, createdBy, name, detail)
|
||||
}
|
||||
fail := func(stage string, err error) {
|
||||
step("failed", map[string]interface{}{"stage": stage, "error": errString(err)})
|
||||
}
|
||||
|
||||
step(trigger+"_received", map[string]interface{}{"gatewayStatus": gatewayStatus})
|
||||
|
||||
var orderType *string
|
||||
var amountUsd *float64
|
||||
var branchID int64
|
||||
if err := r.client.QueryRow(ctx,
|
||||
`SELECT type, amount_usd, branch_id FROM visa_master_payment_orders WHERE id = $1 AND deleted_at IS NULL`, orderID,
|
||||
).Scan(&orderType, &amountUsd, &branchID); err != nil {
|
||||
fail("load_order", err)
|
||||
return visamasterpay.PaymentResultDTO{}, err
|
||||
}
|
||||
|
||||
@@ -304,95 +358,111 @@ func (r *repository) HandleCallback(ctx context.Context, paymentID int64) (visam
|
||||
if gatewayStatus != "pending" {
|
||||
item, err := fetchPaymentByID(ctx, r.client, paymentID)
|
||||
if err != nil {
|
||||
fail("load_payment", err)
|
||||
return visamasterpay.PaymentResultDTO{}, err
|
||||
}
|
||||
item.Paid = item.GatewayStatus == "success"
|
||||
step("already_finalized", map[string]interface{}{"gatewayStatus": item.GatewayStatus, "paid": item.Paid})
|
||||
return finish(item), nil
|
||||
}
|
||||
|
||||
if gatewayReference == nil || *gatewayReference == "" {
|
||||
return visamasterpay.PaymentResultDTO{}, fmt.Errorf("payment %d has no gateway reference yet", paymentID)
|
||||
err := fmt.Errorf("payment %d has no gateway reference yet", paymentID)
|
||||
fail("missing_gateway_reference", err)
|
||||
return visamasterpay.PaymentResultDTO{}, err
|
||||
}
|
||||
|
||||
username, password, err := r.branchCredentials(ctx, branchID, isSber(orderType))
|
||||
if err != nil {
|
||||
fail("load_branch_credentials", err)
|
||||
return visamasterpay.PaymentResultDTO{}, err
|
||||
}
|
||||
|
||||
r.logStep(ctx, orderID, createdBy, "callback_received", map[string]interface{}{"paymentId": paymentID})
|
||||
r.logStep(ctx, orderID, createdBy, "status_check_request", map[string]interface{}{"gbusOrderId": *gatewayReference})
|
||||
step("status_check_request", map[string]interface{}{"gbusOrderId": *gatewayReference})
|
||||
|
||||
status, err := r.gateway.CheckStatus(ctx, paymentgateway.StatusRequest{OrderId: *gatewayReference, Username: username, Password: password})
|
||||
if err != nil {
|
||||
r.logStep(ctx, orderID, createdBy, "status_check_response", map[string]interface{}{"error": errString(err)})
|
||||
step("status_check_response", map[string]interface{}{"success": false, "error": errString(err)})
|
||||
return visamasterpay.PaymentResultDTO{}, err
|
||||
}
|
||||
|
||||
r.logStep(ctx, orderID, createdBy, "status_check_response", map[string]interface{}{
|
||||
"paid": status.Paid, "orderStatus": status.OrderStatus, "actionCode": status.ActionCode,
|
||||
step("status_check_response", map[string]interface{}{
|
||||
"success": true, "paid": status.Paid, "orderStatus": status.OrderStatus, "actionCode": status.ActionCode,
|
||||
"actionCodeDescription": status.ActionCodeDescription, "rawResponse": rawJSON(status.RawResponse),
|
||||
})
|
||||
|
||||
var item visamasterpay.PaymentResultDTO
|
||||
if status.Paid {
|
||||
// GBÜS has taken the money from here on, so every failure below is
|
||||
// logged: it leaves a paid payment the order doesn't reflect yet.
|
||||
tx, err := r.client.Begin(ctx)
|
||||
if err != nil {
|
||||
fail("finalize_begin_tx", err)
|
||||
return visamasterpay.PaymentResultDTO{}, err
|
||||
}
|
||||
defer tx.Rollback(ctx)
|
||||
|
||||
var lockedPaid bool
|
||||
if err := tx.QueryRow(ctx, `SELECT paid FROM visa_master_payment_orders WHERE id = $1 FOR UPDATE`, orderID).Scan(&lockedPaid); err != nil {
|
||||
fail("finalize_lock_order", err)
|
||||
return visamasterpay.PaymentResultDTO{}, err
|
||||
}
|
||||
if !lockedPaid {
|
||||
if lockedPaid {
|
||||
step("order_already_marked_paid", nil)
|
||||
} else {
|
||||
if _, err := tx.Exec(ctx,
|
||||
`UPDATE visa_master_payment_orders SET paid = true, status = 'completed', updated_at = (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') WHERE id = $1`,
|
||||
orderID,
|
||||
); err != nil {
|
||||
fail("finalize_mark_order_paid", err)
|
||||
return visamasterpay.PaymentResultDTO{}, err
|
||||
}
|
||||
}
|
||||
|
||||
item, err = updatePaymentStatus(ctx, tx, paymentID, "success", status.RawResponse)
|
||||
if err != nil {
|
||||
fail("finalize_save_payment_status", err)
|
||||
return visamasterpay.PaymentResultDTO{}, err
|
||||
}
|
||||
|
||||
if err := tx.Commit(ctx); err != nil {
|
||||
fail("finalize_commit", err)
|
||||
return visamasterpay.PaymentResultDTO{}, err
|
||||
}
|
||||
} else {
|
||||
item, err = updatePaymentStatus(ctx, r.client, paymentID, "failed", status.RawResponse)
|
||||
if err != nil {
|
||||
fail("finalize_save_payment_status", err)
|
||||
return visamasterpay.PaymentResultDTO{}, err
|
||||
}
|
||||
}
|
||||
|
||||
r.logStep(ctx, orderID, createdBy, "payment_finalized", map[string]interface{}{"paymentId": paymentID, "paid": status.Paid})
|
||||
step("payment_finalized", map[string]interface{}{"paid": status.Paid, "gatewayStatus": item.GatewayStatus})
|
||||
|
||||
item.Paid = status.Paid
|
||||
return finish(item), nil
|
||||
}
|
||||
|
||||
// Status re-checks orderID's latest payment attempt via HandleCallback -
|
||||
// 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). Safe to
|
||||
// call repeatedly: HandleCallback only hits GBÜS while the attempt is still
|
||||
// "pending" and otherwise just returns the already-finalized row.
|
||||
func (r *repository) Status(ctx context.Context, orderID int64) (visamasterpay.PaymentResultDTO, error) {
|
||||
// Status re-checks orderID's latest payment attempt the same way
|
||||
// HandleCallback does - 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). Safe to call repeatedly: it only hits GBÜS while the attempt is
|
||||
// still "pending" and otherwise just returns the already-finalized row.
|
||||
func (r *repository) Status(ctx context.Context, orderID int64, requestedBy *int64) (visamasterpay.PaymentResultDTO, error) {
|
||||
var paymentID int64
|
||||
err := r.client.QueryRow(ctx,
|
||||
`SELECT id FROM visa_master_order_payments WHERE order_id = $1 AND deleted_at IS NULL ORDER BY created_at DESC LIMIT 1`,
|
||||
orderID,
|
||||
).Scan(&paymentID)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
r.logStep(ctx, orderID, requestedBy, "status_received", map[string]interface{}{"trigger": "status", "paymentId": nil})
|
||||
return visamasterpay.PaymentResultDTO{}, visamasterpay.ErrPaymentNotFound
|
||||
}
|
||||
if err != nil {
|
||||
r.logFailure(ctx, orderID, requestedBy, "find_latest_payment", err, map[string]interface{}{"trigger": "status"})
|
||||
return visamasterpay.PaymentResultDTO{}, err
|
||||
}
|
||||
return r.HandleCallback(ctx, paymentID)
|
||||
return r.verifyPayment(ctx, paymentID, "status", requestedBy)
|
||||
}
|
||||
|
||||
// branchCredentials picks the sber or visa/master MPI merchant credentials
|
||||
@@ -458,6 +528,9 @@ func (r *repository) logStep(ctx context.Context, orderID int64, createdBy *int6
|
||||
if err != nil {
|
||||
payload = []byte(`{}`)
|
||||
}
|
||||
// Detached from cancellation: a client dropping the request mid-payment
|
||||
// must not cost us the record of the steps that still run.
|
||||
ctx = context.WithoutCancel(ctx)
|
||||
if _, err := r.client.Exec(ctx,
|
||||
`INSERT INTO visa_master_payment_logs (order_id, step, detail, created_by) VALUES ($1, $2, $3, $4)`,
|
||||
orderID, step, payload, createdBy,
|
||||
@@ -466,6 +539,16 @@ func (r *repository) logStep(ctx context.Context, orderID int64, createdBy *int6
|
||||
}
|
||||
}
|
||||
|
||||
// logFailure records a "failed" step naming the stage that broke and the
|
||||
// error, plus any extra detail, so every error path of a payout leaves a row.
|
||||
func (r *repository) logFailure(ctx context.Context, orderID int64, createdBy *int64, stage string, err error, extra map[string]interface{}) {
|
||||
detail := map[string]interface{}{"stage": stage, "error": errString(err)}
|
||||
for k, v := range extra {
|
||||
detail[k] = v
|
||||
}
|
||||
r.logStep(ctx, orderID, createdBy, "failed", detail)
|
||||
}
|
||||
|
||||
// querier is satisfied by both postgresql.Client and pgx.Tx, so helpers
|
||||
// below can run either against the plain client or an open transaction.
|
||||
type querier interface {
|
||||
|
||||
@@ -133,7 +133,12 @@ func (h *handler) status(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
result, err := h.repository.Status(c.Request.Context(), id)
|
||||
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
|
||||
}
|
||||
|
||||
@@ -37,6 +37,7 @@ type Repository interface {
|
||||
// HandleCallback does - for the frontend to call (authenticated,
|
||||
// order-scoped) when it can't rely on GBÜS having redirected the
|
||||
// browser back to the callback, e.g. the user closed the hosted
|
||||
// payment page before the redirect fired.
|
||||
Status(ctx context.Context, orderID int64) (PaymentResultDTO, error)
|
||||
// payment page before the redirect fired. requestedBy is the caller,
|
||||
// recorded on the payment log.
|
||||
Status(ctx context.Context, orderID int64, requestedBy *int64) (PaymentResultDTO, error)
|
||||
}
|
||||
Reference in new issue
Block a user