Files
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

484 lines
17 KiB
Go

package db
import (
"context"
"encoding/json"
"fmt"
"strings"
"online-back/internal/cards/visamaster"
"online-back/internal/cards/visamasteractions"
actionsdb "online-back/internal/cards/visamasteractions/db"
"online-back/internal/identity/rbac"
"online-back/internal/shared"
"online-back/pkg/client/postgresql"
"online-back/pkg/logging"
"online-back/pkg/repository/genericrepo"
)
type repository struct {
client postgresql.Client
generic *genericrepo.Repository[visamaster.VisaMasterPaymentOrderDTO]
logger *logging.Logger
}
func NewRepository(client postgresql.Client, logger *logging.Logger) visamaster.Repository {
return &repository{
client: client,
generic: genericrepo.New(client, "visa_master_payment_orders", orderColumnsSQL, scanOrder),
logger: logger,
}
}
const orderFromClause = ` FROM visa_master_payment_orders o
LEFT JOIN branches b ON b.id = o.branch_id
LEFT JOIN users u ON u.id = o.user_id
LEFT JOIN provinces p ON p.id = b.province_id`
var orderWritableColumns = []string{
"unique_id", "type", "passport_name", "passport_surname", "phone", "email",
"region", "branch_id", "user_id", "address",
"sender_datas", "payment_reciever", "documents",
"status", "notes",
"sender_full_name", "sender_passport_serie", "sender_passport_number", "sender_deposit_account",
"reciever_full_name", "reciever_passport_serie", "reciever_passport_number", "reciever_deposit_account",
"amount_usd", "paid",
}
var orderColumns = append(append([]string{"id"}, orderWritableColumns...), "created_at", "updated_at")
var orderColumnsSQL = strings.Join(orderColumns, ", ")
var orderWritableColumnsSQL = strings.Join(orderWritableColumns, ", ")
var orderSelectColumns = shared.PrefixedColumns("o", orderColumns) + `, p.region, b.name, COALESCE(b.unique_code, ''), COALESCE(b.region, ''), b.province_id, p.name, ` + shared.UserDisplaySQL + `, COALESCE(u.username, ''), COALESCE(u.phone, ''), COALESCE(u.email, '')`
func resolveStatus(status *string) *string {
if status == nil || strings.TrimSpace(*status) == "" {
pending := "pending"
return &pending
}
return status
}
func resolvePaid(paid *bool) bool {
if paid == nil {
return false
}
return *paid
}
func jsonArg(raw json.RawMessage, fallback string) []byte {
if len(raw) == 0 {
return []byte(fallback)
}
return raw
}
func createArgs(dto visamaster.CreateVisaMasterPaymentOrderDTO) []interface{} {
return []interface{}{
dto.UniqueId, dto.Type, dto.PassportName, dto.PassportSurname, dto.Phone, dto.Email,
dto.Region, dto.BranchId, dto.UserId, dto.Address,
jsonArg(dto.SenderDatas, `{}`), jsonArg(dto.PaymentReciever, `[]`), jsonArg(dto.Documents, `{}`),
resolveStatus(dto.Status), dto.Notes,
dto.SenderFullName, dto.SenderPassportSerie, dto.SenderPassportNumber, dto.SenderDepositAccount,
dto.RecieverFullName, dto.RecieverPassportSerie, dto.RecieverPassportNumber, dto.RecieverDepositAccount,
dto.AmountUsd, resolvePaid(dto.Paid),
}
}
func updateArgs(dto visamaster.UpdateVisaMasterPaymentOrderDTO) []interface{} {
return []interface{}{
dto.UniqueId, dto.Type, dto.PassportName, dto.PassportSurname, dto.Phone, dto.Email,
dto.Region, dto.BranchId, dto.UserId, dto.Address,
jsonArg(dto.SenderDatas, `{}`), jsonArg(dto.PaymentReciever, `[]`), jsonArg(dto.Documents, `{}`),
resolveStatus(dto.Status), dto.Notes,
dto.SenderFullName, dto.SenderPassportSerie, dto.SenderPassportNumber, dto.SenderDepositAccount,
dto.RecieverFullName, dto.RecieverPassportSerie, dto.RecieverPassportNumber, dto.RecieverDepositAccount,
dto.AmountUsd, dto.Paid,
}
}
func (r *repository) List(ctx context.Context, filter visamaster.ListFilter) (visamaster.ListVisaMasterPaymentOrderDTO, error) {
whereClause, args := buildListQuery(filter)
var count int64
if err := r.client.QueryRow(ctx, `SELECT COUNT(*) FROM visa_master_payment_orders o`+whereClause, args...).Scan(&count); err != nil {
return visamaster.ListVisaMasterPaymentOrderDTO{}, err
}
offset := (filter.Page - 1) * filter.Limit
limitPlaceholder := len(args) + 1
offsetPlaceholder := len(args) + 2
query := fmt.Sprintf(
`SELECT o.id, o.unique_id, o.type, o.created_at, o.region, p.region, o.branch_id, b.name, p.name,
o.passport_name, o.passport_surname, o.phone, o.status, o.paid, `+paidThisMonthSQL+`
FROM visa_master_payment_orders o
LEFT JOIN branches b ON b.id = o.branch_id
LEFT JOIN provinces p ON p.id = b.province_id%s ORDER BY o.id DESC LIMIT $%d OFFSET $%d`,
whereClause, limitPlaceholder, offsetPlaceholder,
)
rows, err := r.client.Query(ctx, query, append(args, filter.Limit, offset)...)
if err != nil {
return visamaster.ListVisaMasterPaymentOrderDTO{}, err
}
defer rows.Close()
items := []visamaster.VisaMasterPaymentOrderListItemDTO{}
for rows.Next() {
item, err := scanOrderListItem(rows)
if err != nil {
return visamaster.ListVisaMasterPaymentOrderDTO{}, err
}
items = append(items, item)
}
if err := rows.Err(); err != nil {
return visamaster.ListVisaMasterPaymentOrderDTO{}, err
}
return visamaster.ListVisaMasterPaymentOrderDTO{Count: count, VisaMasterPaymentOrders: items}, nil
}
func buildListQuery(filter visamaster.ListFilter) (whereClause string, args []interface{}) {
conditions := []string{"o.deleted_at IS NULL"}
if filter.Name != "" {
args = append(args, shared.LikePattern(filter.Name))
n := len(args)
conditions = append(conditions, fmt.Sprintf(`(
o.passport_name ILIKE $%[1]d OR o.passport_surname ILIKE $%[1]d
OR o.sender_full_name ILIKE $%[1]d OR COALESCE(o.reciever_full_name, '') ILIKE $%[1]d
)`, n))
}
// Case-insensitive and trimmed, the same match visamasterpay uses to
// pick Sber fees and credentials.
if filter.Type != "" {
args = append(args, strings.TrimSpace(filter.Type))
conditions = append(conditions, fmt.Sprintf("LOWER(TRIM(o.type)) = LOWER($%d)", len(args)))
}
if filter.ExcludeType != "" {
args = append(args, strings.TrimSpace(filter.ExcludeType))
conditions = append(conditions, fmt.Sprintf("LOWER(TRIM(COALESCE(o.type, ''))) <> LOWER($%d)", len(args)))
}
if filter.Status != nil {
args = append(args, *filter.Status)
conditions = append(conditions, fmt.Sprintf("o.status = $%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("o.user_id = $%d", len(args)))
}
if filter.Region != "" {
args = append(args, filter.Region)
conditions = append(conditions, fmt.Sprintf("o.region = $%d", len(args)))
}
return " WHERE " + strings.Join(conditions, " AND "), args
}
func (r *repository) GetByID(ctx context.Context, id int64) (visamaster.VisaMasterPaymentOrderDTO, error) {
query := `SELECT ` + orderSelectColumns + orderFromClause + ` WHERE o.id = $1 AND o.deleted_at IS NULL`
return scanOrder(r.client.QueryRow(ctx, query, id))
}
func (r *repository) Create(ctx context.Context, dto visamaster.CreateVisaMasterPaymentOrderDTO) (visamaster.VisaMasterPaymentOrderDTO, error) {
args := createArgs(dto)
placeholders := make([]string, len(args))
for i := range args {
placeholders[i] = fmt.Sprintf("$%d", i+1)
}
query := fmt.Sprintf(`
WITH inserted AS (
INSERT INTO visa_master_payment_orders (%s) VALUES (%s)
RETURNING %s
)
SELECT %s
FROM inserted o
LEFT JOIN branches b ON b.id = o.branch_id
LEFT JOIN users u ON u.id = o.user_id
LEFT JOIN provinces p ON p.id = b.province_id`,
orderWritableColumnsSQL, strings.Join(placeholders, ", "),
orderColumnsSQL, orderSelectColumns,
)
// A failed create has no order to attach an action to, so only the
// successful one is recorded - in the same transaction as the insert.
tx, err := r.client.Begin(ctx)
if err != nil {
return visamaster.VisaMasterPaymentOrderDTO{}, err
}
defer tx.Rollback(ctx)
item, err := scanOrder(tx.QueryRow(ctx, query, args...))
if err != nil {
return visamaster.VisaMasterPaymentOrderDTO{}, err
}
created, err := actionsdb.Snapshot(ctx, tx, item.Id)
if err != nil {
return visamaster.VisaMasterPaymentOrderDTO{}, err
}
if err := actionsdb.Insert(ctx, tx, visamasteractions.CreateOrderActionDTO{
OrderId: item.Id, Name: visamasteractions.NameCreate, Status: visamasteractions.StatusFinished,
Changes: created, CreatedBy: dto.CreatedBy,
}); err != nil {
return visamaster.VisaMasterPaymentOrderDTO{}, err
}
if err := tx.Commit(ctx); err != nil {
return visamaster.VisaMasterPaymentOrderDTO{}, err
}
return item, nil
}
func (r *repository) Update(ctx context.Context, id int64, dto visamaster.UpdateVisaMasterPaymentOrderDTO) (visamaster.VisaMasterPaymentOrderDTO, error) {
args := updateArgs(dto)
assignments := make([]string, len(orderWritableColumns))
for i, column := range orderWritableColumns {
assignments[i] = fmt.Sprintf("%s = $%d", column, i+1)
}
args = append(args, id)
query := fmt.Sprintf(`
WITH updated AS (
UPDATE visa_master_payment_orders SET %s, updated_at = (CURRENT_TIMESTAMP AT TIME ZONE 'UTC')
WHERE id = $%d AND deleted_at IS NULL
RETURNING %s
)
SELECT %s
FROM updated o
LEFT JOIN branches b ON b.id = o.branch_id
LEFT JOIN users u ON u.id = o.user_id
LEFT JOIN provinces p ON p.id = b.province_id`,
strings.Join(assignments, ", "), len(args), orderColumnsSQL, orderSelectColumns,
)
tx, err := r.client.Begin(ctx)
if err != nil {
return visamaster.VisaMasterPaymentOrderDTO{}, err
}
defer tx.Rollback(ctx)
before, err := actionsdb.Snapshot(ctx, tx, id)
if err != nil {
return visamaster.VisaMasterPaymentOrderDTO{}, err
}
// fail rolls the update back and records it as failed, with the
// values it attempted.
fail := func(err error) (visamaster.VisaMasterPaymentOrderDTO, error) {
tx.Rollback(ctx)
original, changes := r.attemptedChanges(before, args)
r.recordFailure(ctx, id, visamasteractions.NameUpdate, dto.UpdatedBy, original, changes, err)
return visamaster.VisaMasterPaymentOrderDTO{}, err
}
item, err := scanOrder(tx.QueryRow(ctx, query, args...))
if err != nil {
return fail(err)
}
after, err := actionsdb.Snapshot(ctx, tx, id)
if err != nil {
return fail(err)
}
// An update that changed nothing (the form saved as-is) is not an action.
if original, changes := visamasteractions.Diff(before, after); changes != nil {
if err := actionsdb.Insert(ctx, tx, visamasteractions.CreateOrderActionDTO{
OrderId: id, Name: visamasteractions.NameUpdate, Status: visamasteractions.StatusFinished,
Original: original, Changes: changes, CreatedBy: dto.UpdatedBy,
}); err != nil {
return fail(err)
}
}
if err := tx.Commit(ctx); err != nil {
return fail(err)
}
return item, nil
}
func (r *repository) Delete(ctx context.Context, id int64, deletedBy *int64) error {
tx, err := r.client.Begin(ctx)
if err != nil {
return err
}
defer tx.Rollback(ctx)
before, err := actionsdb.Snapshot(ctx, tx, id)
if err != nil {
return err
}
fail := func(err error) error {
tx.Rollback(ctx)
r.recordFailure(ctx, id, visamasteractions.NameDelete, deletedBy, before, nil, err)
return err
}
// Same soft delete as genericrepo.Delete, inside the transaction.
if _, err := tx.Exec(ctx, `UPDATE visa_master_payment_orders SET deleted_at = now() WHERE id = $1 AND deleted_at IS NULL`, id); err != nil {
return fail(err)
}
if err := actionsdb.Insert(ctx, tx, visamasteractions.CreateOrderActionDTO{
OrderId: id, Name: visamasteractions.NameDelete, Status: visamasteractions.StatusFinished,
Original: before, CreatedBy: deletedBy,
}); err != nil {
return fail(err)
}
if err := tx.Commit(ctx); err != nil {
return fail(err)
}
return nil
}
// attemptedChanges is what a failed update tried to change: the writable
// columns whose attempted value (args, in orderWritableColumns order)
// differs from before.
func (r *repository) attemptedChanges(before map[string]interface{}, args []interface{}) (original, changes map[string]interface{}) {
values := make(map[string]interface{}, len(orderWritableColumns))
current := make(map[string]interface{}, len(orderWritableColumns))
for i, column := range orderWritableColumns {
value := args[i]
// jsonArg's bytes are JSON, not a byte string to base64-encode.
if raw, ok := value.([]byte); ok {
value = json.RawMessage(raw)
}
values[column] = value
current[column] = before[column]
}
attempted, err := visamasteractions.Normalize(values)
if err != nil {
// Unencodable (e.g. invalid JSON in senderDatas): record the failure
// without the attempted values rather than not at all.
r.logger.Errorf("visa master order action: encode attempted values failed: %v", err)
return nil, nil
}
return visamasteractions.Diff(current, attempted)
}
// recordFailure records a failed action through the plain client, after
// its transaction rolled back. Best-effort: a write failure here is
// logged, not propagated over the action's own error.
func (r *repository) recordFailure(ctx context.Context, orderID int64, name string, createdBy *int64, original, changes map[string]interface{}, cause error) {
exception := cause.Error()
// Detached from cancellation: a client dropping the request must not
// cost us the record of what it tried.
if err := actionsdb.Insert(context.WithoutCancel(ctx), r.client, visamasteractions.CreateOrderActionDTO{
OrderId: orderID, Name: name, Status: visamasteractions.StatusFailed,
Original: original, Changes: changes, Exception: &exception, CreatedBy: createdBy,
}); err != nil {
r.logger.Errorf("record failed visa master order action (order %d, %s) failed: %v", orderID, name, err)
}
}
func scanOrder(row genericrepo.Scanner) (visamaster.VisaMasterPaymentOrderDTO, error) {
var item visamaster.VisaMasterPaymentOrderDTO
var senderDatas, paymentReciever, documents []byte
var regionNameJSON, branchNameJSON, provinceNameJSON []byte
var branchRegion, userName, userUsername, userPhone, userEmail string
err := row.Scan(
&item.Id, &item.UniqueId, &item.Type, &item.PassportName, &item.PassportSurname, &item.Phone, &item.Email,
&item.Region, &item.BranchId, &item.UserId, &item.Address,
&senderDatas, &paymentReciever, &documents,
&item.Status, &item.Notes,
&item.SenderFullName, &item.SenderPassportSerie, &item.SenderPassportNumber, &item.SenderDepositAccount,
&item.RecieverFullName, &item.RecieverPassportSerie, &item.RecieverPassportNumber, &item.RecieverDepositAccount,
&item.AmountUsd, &item.Paid, &item.CreatedAt, &item.UpdatedAt,
&regionNameJSON, &branchNameJSON, &item.Branch.UniqueCode, &branchRegion, &item.Branch.ProvinceId, &provinceNameJSON,
&userName, &userUsername, &userPhone, &userEmail,
)
if err != nil {
return visamaster.VisaMasterPaymentOrderDTO{}, err
}
item.SenderDatas = jsonOrDefault(senderDatas, `{}`)
item.PaymentReciever = jsonOrDefault(paymentReciever, `[]`)
item.Documents = jsonOrDefault(documents, `{}`)
item.Branch.Id = item.BranchId
item.Branch.Region = branchRegion
if err := shared.UnmarshalLocalized(regionNameJSON, &item.RegionName); err != nil {
return visamaster.VisaMasterPaymentOrderDTO{}, err
}
if err := shared.UnmarshalLocalized(branchNameJSON, &item.Branch.Name); err != nil {
return visamaster.VisaMasterPaymentOrderDTO{}, err
}
if err := shared.UnmarshalLocalized(provinceNameJSON, &item.Branch.ProvinceName); err != nil {
return visamaster.VisaMasterPaymentOrderDTO{}, err
}
if item.UserId != nil {
item.User = &shared.UserInfo{
Id: *item.UserId,
Name: userName,
Username: userUsername,
Phone: userPhone,
Email: userEmail,
}
}
return item, nil
}
func jsonOrDefault(raw []byte, fallback string) json.RawMessage {
if len(raw) == 0 {
return json.RawMessage(fallback)
}
return json.RawMessage(raw)
}
// paidThisMonthSQL: the order has a successful payment whose payment_period
// falls in the current month in Ashgabat time (UTC+5, as visamasterpay).
const paidThisMonthSQL = `EXISTS (
SELECT 1 FROM visa_master_order_payments vp
WHERE vp.order_id = o.id AND vp.gateway_status = 'success' AND vp.deleted_at IS NULL
AND date_trunc('month', vp.payment_period) = date_trunc('month', (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') + INTERVAL '5 hours')
)`
func scanOrderListItem(row genericrepo.Scanner) (visamaster.VisaMasterPaymentOrderListItemDTO, error) {
var item visamaster.VisaMasterPaymentOrderListItemDTO
var branchId int64
var regionNameJSON, branchNameJSON, provinceNameJSON []byte
if err := row.Scan(
&item.Id, &item.UniqueId, &item.Type, &item.CreatedAt, &item.Region, &regionNameJSON, &branchId, &branchNameJSON, &provinceNameJSON,
&item.PassportName, &item.PassportSurname, &item.Phone, &item.Status, &item.Paid, &item.PaidThisMonth,
); err != nil {
return visamaster.VisaMasterPaymentOrderListItemDTO{}, err
}
if err := shared.UnmarshalLocalized(regionNameJSON, &item.RegionName); err != nil {
return visamaster.VisaMasterPaymentOrderListItemDTO{}, err
}
var branchName shared.LocalizedText
if err := shared.UnmarshalLocalized(branchNameJSON, &branchName); err != nil {
return visamaster.VisaMasterPaymentOrderListItemDTO{}, err
}
if err := shared.UnmarshalLocalized(provinceNameJSON, &item.ProvinceName); err != nil {
return visamaster.VisaMasterPaymentOrderListItemDTO{}, err
}
if branchId != 0 {
item.Branch = &shared.NamedInfo{Id: branchId, Name: branchName}
}
return item, nil
}