visamaster: record order actions for the "Ammallar" table
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

Every create, update and delete of a visa/master or sber order is now
recorded in visa_master_order_actions: who did it, finished or failed
(with the exception), and for an update only the columns that changed -
original before, changes after. Marking an order paid when a payment is
finalized is recorded the same way, with no user when the GBÜS callback
did it.

Actions are written in the transaction that changes the order, so one is
on record exactly when its change is; failed ones are written after the
rollback with the values they attempted. The payment finalize records
after its commit instead, so recording never holds up a payment GBÜS has
already taken. Updates that change nothing and creates that fail (no
order to attach to) are not recorded.

GET /visa-master-payment-orders/{id}/actions lists them, newest first;
GET /visa-master-payment-orders/{id}/actions/{actionId} adds original,
changes and exception. Both are staff-only and order-scoped.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
guwandykandClaude Opus 5.5 committed 2026-10-25 22:39:42 +05:00
1 parent 742e078090
commit 11e1fa4972
18 files changed
+1527 -10

No files matched your search

@@ -0,0 +1,166 @@
package db
import (
"context"
"encoding/json"
"online-back/internal/cards/visamasteractions"
"online-back/internal/shared"
"online-back/pkg/client/postgresql"
"online-back/pkg/logging"
"github.com/jackc/pgconn"
"github.com/jackc/pgx/v4"
)
type repository struct {
client postgresql.Client
logger *logging.Logger
}
func NewRepository(client postgresql.Client, logger *logging.Logger) visamasteractions.Repository {
return &repository{client: client, logger: logger}
}
// Querier is satisfied by both postgresql.Client and pgx.Tx, so the order
// repositories can snapshot and record inside the transaction that changes
// the order - an action is on record exactly when its change is.
type Querier interface {
QueryRow(ctx context.Context, sql string, args ...interface{}) pgx.Row
Exec(ctx context.Context, sql string, args ...interface{}) (pgconn.CommandTag, error)
}
// Snapshot locks orderID's row (FOR UPDATE) and returns its columns as
// recorded on an action - everything but id and the timestamps, which
// change on every write. pgx.ErrNoRows if the order doesn't exist or is
// deleted.
func Snapshot(ctx context.Context, q Querier, orderID int64) (map[string]interface{}, error) {
var raw []byte
err := q.QueryRow(ctx,
`SELECT to_jsonb(o) - 'id' - 'created_at' - 'updated_at' - 'deleted_at'
FROM visa_master_payment_orders o WHERE o.id = $1 AND o.deleted_at IS NULL FOR UPDATE`,
orderID,
).Scan(&raw)
if err != nil {
return nil, err
}
var row map[string]interface{}
if err := json.Unmarshal(raw, &row); err != nil {
return nil, err
}
return row, nil
}
// Insert records one action. A failed action must be recorded through the
// plain client after its transaction rolled back, or it is rolled back too.
func Insert(ctx context.Context, q Querier, dto visamasteractions.CreateOrderActionDTO) error {
original, err := jsonOrNull(dto.Original)
if err != nil {
return err
}
changes, err := jsonOrNull(dto.Changes)
if err != nil {
return err
}
_, err = q.Exec(ctx,
`INSERT INTO visa_master_order_actions (order_id, name, status, original, changes, exception, created_by)
VALUES ($1, $2, $3, $4, $5, $6, $7)`,
dto.OrderId, dto.Name, dto.Status, original, changes, dto.Exception, dto.CreatedBy,
)
return err
}
func jsonOrNull(values map[string]interface{}) ([]byte, error) {
if values == nil {
return nil, nil
}
return json.Marshal(values)
}
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`, orderID,
).Scan(&userID, &branchID)
return userID, branchID, err
}
const actionSelectColumns = `a.id, a.order_id, a.name, a.status, o.unique_id, o.type,
a.created_by, ` + shared.UserDisplaySQL + `, a.created_at`
const actionFromClause = ` FROM visa_master_order_actions a
JOIN visa_master_payment_orders o ON o.id = a.order_id
LEFT JOIN users u ON u.id = a.created_by`
func (r *repository) List(ctx context.Context, filter visamasteractions.ListFilter) (visamasteractions.ListOrderActionDTO, error) {
result := visamasteractions.ListOrderActionDTO{Actions: []visamasteractions.OrderActionDTO{}}
if err := r.client.QueryRow(ctx,
`SELECT COUNT(*) FROM visa_master_order_actions WHERE order_id = $1`, filter.OrderId,
).Scan(&result.Count); err != nil {
return visamasteractions.ListOrderActionDTO{}, err
}
rows, err := r.client.Query(ctx,
`SELECT `+actionSelectColumns+actionFromClause+` WHERE a.order_id = $1 ORDER BY a.id DESC LIMIT $2 OFFSET $3`,
filter.OrderId, filter.Limit, (filter.Page-1)*filter.Limit,
)
if err != nil {
return visamasteractions.ListOrderActionDTO{}, err
}
defer rows.Close()
for rows.Next() {
item, err := scanAction(rows)
if err != nil {
return visamasteractions.ListOrderActionDTO{}, err
}
result.Actions = append(result.Actions, item)
}
if err := rows.Err(); err != nil {
return visamasteractions.ListOrderActionDTO{}, err
}
return result, nil
}
func (r *repository) GetByID(ctx context.Context, orderID, actionID int64) (visamasteractions.OrderActionDetailDTO, error) {
var detail visamasteractions.OrderActionDetailDTO
var original, changes []byte
row := r.client.QueryRow(ctx,
`SELECT `+actionSelectColumns+`, a.original, a.changes, a.exception`+actionFromClause+` WHERE a.id = $1 AND a.order_id = $2`,
actionID, orderID,
)
item, err := scanAction(row, &original, &changes, &detail.Exception)
if err != nil {
return visamasteractions.OrderActionDetailDTO{}, err
}
detail.OrderActionDTO = item
detail.Original = rawOrNull(original)
detail.Changes = rawOrNull(changes)
return detail, nil
}
// scanAction reads actionSelectColumns, followed by any extra columns into
// extra.
func scanAction(row pgx.Row, extra ...interface{}) (visamasteractions.OrderActionDTO, error) {
var item visamasteractions.OrderActionDTO
dest := append([]interface{}{
&item.Id, &item.OrderId, &item.Name, &item.Status, &item.Target.UniqueId, &item.Target.Type,
&item.CreatedById, &item.CreatedByName, &item.CreatedAt,
}, extra...)
if err := row.Scan(dest...); err != nil {
return visamasteractions.OrderActionDTO{}, err
}
item.NameLabel = visamasteractions.NameLabel(item.Name)
item.Target.Id = item.OrderId
item.Target.Label = visamasteractions.TargetLabel(item.Target.Type)
return item, nil
}
func rawOrNull(raw []byte) json.RawMessage {
if len(raw) == 0 {
return json.RawMessage("null")
}
return json.RawMessage(raw)
}
+52
View File
@@ -0,0 +1,52 @@
package visamasteractions
import (
"encoding/json"
"reflect"
)
// Normalize round-trips values through JSON, so Go values (pointers, raw
// JSON bytes, float64s) compare equal to the same values read back from a
// jsonb snapshot of the row.
func Normalize(values map[string]interface{}) (map[string]interface{}, error) {
if values == nil {
return nil, nil
}
data, err := json.Marshal(values)
if err != nil {
return nil, err
}
var normalized map[string]interface{}
if err := json.Unmarshal(data, &normalized); err != nil {
return nil, err
}
return normalized, nil
}
// Diff keeps only the columns whose value differs between before and
// after: original gets their before values and changes their after
// values. A column missing on one side counts as null there. Both are nil
// when nothing changed.
func Diff(before, after map[string]interface{}) (original, changes map[string]interface{}) {
for key, value := range after {
if old, ok := before[key]; ok && reflect.DeepEqual(old, value) {
continue
}
if original == nil {
original, changes = map[string]interface{}{}, map[string]interface{}{}
}
original[key] = before[key]
changes[key] = value
}
for key, old := range before {
if _, ok := after[key]; ok || old == nil {
continue
}
if original == nil {
original, changes = map[string]interface{}{}, map[string]interface{}{}
}
original[key] = old
changes[key] = nil
}
return original, changes
}
@@ -0,0 +1,64 @@
package visamasteractions
import (
"encoding/json"
"reflect"
"testing"
)
func TestDiffKeepsOnlyChangedColumns(t *testing.T) {
before := map[string]interface{}{"status": "pending", "paid": false, "amount_usd": 250.0, "notes": nil}
after := map[string]interface{}{"status": "completed", "paid": false, "amount_usd": 250.0, "notes": nil}
original, changes := Diff(before, after)
if !reflect.DeepEqual(original, map[string]interface{}{"status": "pending"}) {
t.Errorf("original = %v, want only status: pending", original)
}
if !reflect.DeepEqual(changes, map[string]interface{}{"status": "completed"}) {
t.Errorf("changes = %v, want only status: completed", changes)
}
}
func TestDiffNothingChanged(t *testing.T) {
row := map[string]interface{}{"status": "pending", "sender_datas": map[string]interface{}{"a": 1.0}}
if original, changes := Diff(row, row); original != nil || changes != nil {
t.Errorf("Diff of equal rows = %v, %v, want nil, nil", original, changes)
}
}
func TestDiffMissingColumnCountsAsNull(t *testing.T) {
before := map[string]interface{}{"status": "pending", "notes": "old"}
after := map[string]interface{}{"status": "pending", "email": "a@b.tm"}
original, changes := Diff(before, after)
if !reflect.DeepEqual(original, map[string]interface{}{"notes": "old", "email": nil}) {
t.Errorf("original = %v", original)
}
if !reflect.DeepEqual(changes, map[string]interface{}{"notes": nil, "email": "a@b.tm"}) {
t.Errorf("changes = %v", changes)
}
}
func TestNormalizeMatchesJSONBSnapshot(t *testing.T) {
status := "pending"
attempted, err := Normalize(map[string]interface{}{
"status": &status,
"amount_usd": 250.0,
"sender_datas": json.RawMessage(`{"a": 1}`),
"notes": (*string)(nil),
})
if err != nil {
t.Fatal(err)
}
var snapshot map[string]interface{}
if err := json.Unmarshal([]byte(`{"status": "pending", "amount_usd": 250, "sender_datas": {"a": 1}, "notes": null}`), &snapshot); err != nil {
t.Fatal(err)
}
if original, changes := Diff(snapshot, attempted); original != nil || changes != nil {
t.Errorf("normalized values differ from the snapshot: %v -> %v", original, changes)
}
}
+117
View File
@@ -0,0 +1,117 @@
package visamasteractions
import (
"encoding/json"
"strings"
"time"
"online-back/internal/shared"
)
// Action names, as the "Ammallar" table's Amalyň ady column shows them.
const (
NameCreate = "create"
NameUpdate = "update"
NameDelete = "delete"
)
// Action statuses: finished once the change is committed, failed (with
// Exception) when it was attempted but rolled back.
const (
StatusFinished = "finished"
StatusFailed = "failed"
)
// orderTypeSber is the type value of Sber orders, matched case-insensitively
// like visamaster and visamasterpay do.
const orderTypeSber = "sber"
var nameLabels = map[string]shared.LocalizedText{
NameCreate: {Tm: "Goşmak", Ru: "Создание", En: "Create"},
NameUpdate: {Tm: "Üýtgetmek", Ru: "Изменение", En: "Update"},
NameDelete: {Tm: "Pozmak", Ru: "Удаление", En: "Delete"},
}
var (
sberTargetLabel = shared.LocalizedText{Tm: "Sber töleg (talyplar üçin)", Ru: "Оплата Sber (для студентов)", En: "Sber payment (for students)"}
visaMasterTargetLabel = shared.LocalizedText{Tm: "Visa/Master töleg (talyplar üçin)", Ru: "Оплата Visa/Master (для студентов)", En: "Visa/Master payment (for students)"}
)
// NameLabel is the display name of an action name; unknown names fall
// back to the name itself.
func NameLabel(name string) shared.LocalizedText {
if label, ok := nameLabels[name]; ok {
return label
}
return shared.LocalizedText{Tm: name, Ru: name, En: name}
}
// TargetLabel is the display name of the order an action was done to,
// by the order's (current) type.
func TargetLabel(orderType *string) shared.LocalizedText {
if orderType != nil && strings.EqualFold(strings.TrimSpace(*orderType), orderTypeSber) {
return sberTargetLabel
}
return visaMasterTargetLabel
}
// OrderActionTargetDTO is the order an action was done to - Amalyň
// nyşany (targedi), e.g. "TB6312-14083 (Sber töleg (talyplar üçin))".
type OrderActionTargetDTO struct {
Id int64 `json:"id"`
UniqueId *string `json:"uniqueId"`
Type *string `json:"type"`
Label shared.LocalizedText `json:"label"`
}
// OrderActionDTO is one row of an order's "Ammallar" table. CreatedById is
// null (and CreatedByName empty) when no user started the action - the
// GBÜS callback finalizing a payment.
type OrderActionDTO struct {
Id int64 `json:"id"`
OrderId int64 `json:"orderId"`
Name string `json:"name"`
NameLabel shared.LocalizedText `json:"nameLabel"`
Status string `json:"status"`
Target OrderActionTargetDTO `json:"target"`
CreatedById *int64 `json:"createdById"`
CreatedByName string `json:"createdByName"`
CreatedAt time.Time `json:"createdAt"`
}
// OrderActionDetailDTO is a single action with what it changed - the list
// leaves these out so pages stay small. Original holds the changed
// columns' values before the action and Changes their values after (or,
// for a failed action, the values it attempted); either is null when
// there's nothing on that side (Original for a create, Changes for a
// delete).
type OrderActionDetailDTO struct {
OrderActionDTO
Original json.RawMessage `json:"original" swaggertype:"object"`
Changes json.RawMessage `json:"changes" swaggertype:"object"`
Exception *string `json:"exception"`
}
type ListOrderActionDTO struct {
Count int64 `json:"count"`
Actions []OrderActionDTO `json:"actions"`
}
// CreateOrderActionDTO is one action to record, written by the
// repositories that change orders (cards/visamaster, payment/visamasterpay)
// - never through the API.
type CreateOrderActionDTO struct {
OrderId int64
Name string
Status string
Original map[string]interface{}
Changes map[string]interface{}
Exception *string
CreatedBy *int64
}
type ListFilter struct {
OrderId int64
Page int
Limit int
}
+139
View File
@@ -0,0 +1,139 @@
package visamasteractions
import (
"errors"
"net/http"
"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 = "/visa-master-payment-orders"
type handler struct {
logger *logging.Logger
repository Repository
}
func NewHandler(logger *logging.Logger, repository Repository) handlers.Handler {
return &handler{logger: logger, repository: repository}
}
// Register only wires read endpoints: actions are recorded by the
// repositories that change orders, never through the API.
func (h *handler) Register(router *gin.RouterGroup) {
group := rbac.Group(router, baseURL, rbac.RequireStaff(perm.Cards))
group.GET("/:id/actions", h.list)
group.GET("/:id/actions/:actionId", h.get)
}
// list godoc
// @Summary Sargydyň amallary (Ammallar)
// @Description Bir Visa/Master ýa-da Sber sargydynyň ähli amallaryny gaýtarýar: goşmak, üýtgetmek, pozmak (name/nameLabel), kim tarapyndan (createdByName), haýsy sargyt (target: uniqueId we label, mysal üçin "Sber töleg (talyplar üçin)"), statusy (finished ýa-da failed) we senesi. Tertip: iň täzesi birinji. Bellik: näme üýtgändigi (original/changes) we ýalňyşlyk (exception) /visa-master-payment-orders/{id}/actions/{actionId} salgysynda; töleg tamamlananda sargydyň status/paid üýtgemegi hem şu ýere ýazylýar, GBÜS callback-dan gelse createdById null.
// @Tags visa-master-order-actions
// @Produce json
// @Security BearerAuth
// @Param id path int true "Sargyt ID-si"
// @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} ListOrderActionDTO
// @Failure 400 {object} appresult.AppError
// @Failure 403 {object} appresult.AppError
// @Failure 404 {object} appresult.AppError
// @Failure 500 {object} appresult.AppError
// @Router /visa-master-payment-orders/{id}/actions [get]
func (h *handler) list(c *gin.Context) {
orderID, ok := shared.ParseID(c.Param("id"))
if !ok {
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
return
}
page, limit, ok := shared.ParsePageLimit(c)
if !ok {
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
return
}
if !h.guardOrder(c, orderID) {
return
}
result, err := h.repository.List(c.Request.Context(), ListFilter{OrderId: orderID, Page: page, Limit: limit})
if err != nil {
h.logger.Errorf("list visa master order actions failed (order %d): %v", orderID, err)
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return
}
c.JSON(http.StatusOK, appresult.SuccessWithData(result))
}
// get godoc
// @Summary Sargydyň bir amaly
// @Description Sargydyň bir amalyny näme üýtgändigi bilen gaýtarýar: original - üýtgän meýdanlaryň öňki bahalary (Asyl), changes - täze bahalary (Üýtgeşmeler), exception - şowsuz amalyň ýalňyşlygy. Tertip: ýeke ýazgy. Bellik: goşmakda original null we changes ähli meýdanlar, pozmakda original ähli meýdanlar we changes null; şowsuz amalda changes synanyşylan bahalar.
// @Tags visa-master-order-actions
// @Produce json
// @Security BearerAuth
// @Param id path int true "Sargyt ID-si"
// @Param actionId path int true "Amalyň 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} OrderActionDetailDTO
// @Failure 400 {object} appresult.AppError
// @Failure 403 {object} appresult.AppError
// @Failure 404 {object} appresult.AppError
// @Failure 500 {object} appresult.AppError
// @Router /visa-master-payment-orders/{id}/actions/{actionId} [get]
func (h *handler) get(c *gin.Context) {
orderID, ok := shared.ParseID(c.Param("id"))
if !ok {
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
return
}
actionID, ok := shared.ParseID(c.Param("actionId"))
if !ok {
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
return
}
if !h.guardOrder(c, orderID) {
return
}
item, err := h.repository.GetByID(c.Request.Context(), orderID, actionID)
if errors.Is(err, pgx.ErrNoRows) {
c.JSON(http.StatusNotFound, appresult.ErrNotFound)
return
}
if err != nil {
h.logger.Errorf("get visa master order action failed (order %d, action %d): %v", orderID, actionID, err)
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return
}
c.JSON(http.StatusOK, appresult.SuccessWithData(item))
}
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("visa master order actions owner lookup failed (order %d): %v", orderID, err)
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return false
}
return rbac.GuardOrder(c, userID, branchID)
}
@@ -0,0 +1,14 @@
package visamasteractions
import "context"
type Repository interface {
// OwnerInfo returns the order's owner/branch so the handler can run
// rbac.GuardOrder without importing cards/visamaster. Deleted orders
// are included: their actions stay readable.
OwnerInfo(ctx context.Context, orderID int64) (userID *int64, branchID int64, err error)
List(ctx context.Context, filter ListFilter) (ListOrderActionDTO, error)
// GetByID returns orderID's action actionID - pgx.ErrNoRows if it
// belongs to another order.
GetByID(ctx context.Context, orderID, actionID int64) (OrderActionDetailDTO, error)
}