Files
online-backend/internal/cards/visamasteractions/db/postgresql.go
GuwandykA 11e1fa4972
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
visamaster: record order actions for the "Ammallar" table
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>
2026-10-25 22:39:42 +05:00

167 lines
5.4 KiB
Go

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)
}