2 Commits

Author SHA1 Message Date
41ae56240a visamasteractions: register /:id/actions as its own rbac prefix
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
The server panicked at startup: the actions group declared
require-staff:cards for /visa-master-payment-orders, which
cards/visamaster already registers with require:cards, and rbac allows
one policy per prefix. The group is now /visa-master-payment-orders/:id/actions,
the same way /callback has its own prefix; the routes are unchanged.

manager.New's handler registration moves into registerRoutes, and
TestRegisterRoutes runs it without a database, so a conflicting policy
fails the tests instead of the server.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-25 22:46:43 +05:00
11e1fa4972 visamaster: record order actions for the "Ammallar" table
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
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
20 changed files with 1571 additions and 17 deletions

2
app.go
View File

@@ -49,6 +49,8 @@ import (
// @tag.description User activity audit trail
// @tag.name visa-master-orders
// @tag.description Visa/Master and Sber student-transfer orders: list, view, create, edit, delete
// @tag.name visa-master-order-actions
// @tag.description Visa/Master we Sber sargytlarynyň amallary (Ammallar): kim, haçan, näme goşdy, üýtgetdi ýa-da pozdy. Ulanylyş tertibi: 1) GET /visa-master-payment-orders/{id}/actions - sargydyň amallary; 2) GET /visa-master-payment-orders/{id}/actions/{actionId} - bir amalyň öňki we täze bahalary
// @tag.name visa-master-payment
// @tag.description Paying a Visa/Master or Sber order through GBÜS (HALKBANK): quote, pay, status re-check, bank callback
// @tag.name payment-history

View File

@@ -0,0 +1 @@
DROP TABLE IF EXISTS visa_master_order_actions;

View File

@@ -0,0 +1,25 @@
-- Every create/update/delete of a visa/master or sber order, for the
-- order page's "Ammallar" table: who did it, whether it went through, and
-- for an update only the columns that changed - original holds their
-- values before, changes after. A create has no original and a delete no
-- changes. Failed actions are kept too, with exception set and changes
-- holding what was attempted. created_by is null when no user started it
-- (the GBÜS callback finalizing a payment).
CREATE TABLE IF NOT EXISTS visa_master_order_actions (
id bigserial PRIMARY KEY,
order_id bigint NOT NULL,
name character varying(20) NOT NULL,
status character varying(20) NOT NULL,
original jsonb,
changes jsonb,
exception text,
created_by bigint,
created_at TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL,
CONSTRAINT visa_master_order_actions_order_id_fkey
FOREIGN KEY (order_id) REFERENCES visa_master_payment_orders(id),
CONSTRAINT visa_master_order_actions_created_by_fkey
FOREIGN KEY (created_by) REFERENCES users(id)
);
CREATE INDEX IF NOT EXISTS visa_master_order_actions_order_id_idx
ON visa_master_order_actions (order_id, id DESC);

View File

@@ -9780,6 +9780,169 @@ const docTemplate = `{
}
}
},
"/visa-master-payment-orders/{id}/actions": {
"get": {
"security": [
{
"BearerAuth": []
}
],
"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.",
"produces": [
"application/json"
],
"tags": [
"visa-master-order-actions"
],
"summary": "Sargydyň amallary (Ammallar)",
"parameters": [
{
"type": "integer",
"description": "Sargyt ID-si",
"name": "id",
"in": "path",
"required": true
},
{
"type": "integer",
"default": 1,
"description": "Sahypa belgisi",
"name": "page",
"in": "query"
},
{
"type": "integer",
"default": 10,
"description": "Bir sahypadaky ýazgy sany",
"name": "limit",
"in": "query"
},
{
"enum": [
"tm",
"ru",
"en",
"all"
],
"type": "string",
"default": "tm",
"description": "Lokallaşdyrylan meýdanlaryň dili; all - doly {en, ru, tm} obýektleri",
"name": "lang",
"in": "query"
}
],
"responses": {
"200": {
"description": "OK",
"schema": {
"$ref": "#/definitions/visamasteractions.ListOrderActionDTO"
}
},
"400": {
"description": "Bad Request",
"schema": {
"$ref": "#/definitions/appresult.AppError"
}
},
"403": {
"description": "Forbidden",
"schema": {
"$ref": "#/definitions/appresult.AppError"
}
},
"404": {
"description": "Not Found",
"schema": {
"$ref": "#/definitions/appresult.AppError"
}
},
"500": {
"description": "Internal Server Error",
"schema": {
"$ref": "#/definitions/appresult.AppError"
}
}
}
}
},
"/visa-master-payment-orders/{id}/actions/{actionId}": {
"get": {
"security": [
{
"BearerAuth": []
}
],
"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.",
"produces": [
"application/json"
],
"tags": [
"visa-master-order-actions"
],
"summary": "Sargydyň bir amaly",
"parameters": [
{
"type": "integer",
"description": "Sargyt ID-si",
"name": "id",
"in": "path",
"required": true
},
{
"type": "integer",
"description": "Amalyň ID-si",
"name": "actionId",
"in": "path",
"required": true
},
{
"enum": [
"tm",
"ru",
"en",
"all"
],
"type": "string",
"default": "tm",
"description": "Lokallaşdyrylan meýdanlaryň dili; all - doly {en, ru, tm} obýektleri",
"name": "lang",
"in": "query"
}
],
"responses": {
"200": {
"description": "OK",
"schema": {
"$ref": "#/definitions/visamasteractions.OrderActionDetailDTO"
}
},
"400": {
"description": "Bad Request",
"schema": {
"$ref": "#/definitions/appresult.AppError"
}
},
"403": {
"description": "Forbidden",
"schema": {
"$ref": "#/definitions/appresult.AppError"
}
},
"404": {
"description": "Not Found",
"schema": {
"$ref": "#/definitions/appresult.AppError"
}
},
"500": {
"description": "Internal Server Error",
"schema": {
"$ref": "#/definitions/appresult.AppError"
}
}
}
}
},
"/visa-master-payment-orders/{id}/pay": {
"post": {
"security": [
@@ -12934,6 +13097,110 @@ const docTemplate = `{
}
}
},
"visamasteractions.ListOrderActionDTO": {
"type": "object",
"properties": {
"actions": {
"type": "array",
"items": {
"$ref": "#/definitions/visamasteractions.OrderActionDTO"
}
},
"count": {
"type": "integer"
}
}
},
"visamasteractions.OrderActionDTO": {
"type": "object",
"properties": {
"createdAt": {
"type": "string"
},
"createdById": {
"type": "integer"
},
"createdByName": {
"type": "string"
},
"id": {
"type": "integer"
},
"name": {
"type": "string"
},
"nameLabel": {
"$ref": "#/definitions/shared.LocalizedText"
},
"orderId": {
"type": "integer"
},
"status": {
"type": "string"
},
"target": {
"$ref": "#/definitions/visamasteractions.OrderActionTargetDTO"
}
}
},
"visamasteractions.OrderActionDetailDTO": {
"type": "object",
"properties": {
"changes": {
"type": "object"
},
"createdAt": {
"type": "string"
},
"createdById": {
"type": "integer"
},
"createdByName": {
"type": "string"
},
"exception": {
"type": "string"
},
"id": {
"type": "integer"
},
"name": {
"type": "string"
},
"nameLabel": {
"$ref": "#/definitions/shared.LocalizedText"
},
"orderId": {
"type": "integer"
},
"original": {
"type": "object"
},
"status": {
"type": "string"
},
"target": {
"$ref": "#/definitions/visamasteractions.OrderActionTargetDTO"
}
}
},
"visamasteractions.OrderActionTargetDTO": {
"type": "object",
"properties": {
"id": {
"type": "integer"
},
"label": {
"$ref": "#/definitions/shared.LocalizedText"
},
"type": {
"type": "string"
},
"uniqueId": {
"type": "string"
}
}
},
"visamasterpay.CallbackResultDTO": {
"type": "object",
"properties": {
@@ -13131,6 +13398,10 @@ const docTemplate = `{
"description": "Visa/Master and Sber student-transfer orders: list, view, create, edit, delete",
"name": "visa-master-orders"
},
{
"description": "Visa/Master we Sber sargytlarynyň amallary (Ammallar): kim, haçan, näme goşdy, üýtgetdi ýa-da pozdy. Ulanylyş tertibi: 1) GET /visa-master-payment-orders/{id}/actions - sargydyň amallary; 2) GET /visa-master-payment-orders/{id}/actions/{actionId} - bir amalyň öňki we täze bahalary",
"name": "visa-master-order-actions"
},
{
"description": "Paying a Visa/Master or Sber order through GBÜS (HALKBANK): quote, pay, status re-check, bank callback",
"name": "visa-master-payment"

View File

@@ -9777,6 +9777,169 @@
}
}
},
"/visa-master-payment-orders/{id}/actions": {
"get": {
"security": [
{
"BearerAuth": []
}
],
"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.",
"produces": [
"application/json"
],
"tags": [
"visa-master-order-actions"
],
"summary": "Sargydyň amallary (Ammallar)",
"parameters": [
{
"type": "integer",
"description": "Sargyt ID-si",
"name": "id",
"in": "path",
"required": true
},
{
"type": "integer",
"default": 1,
"description": "Sahypa belgisi",
"name": "page",
"in": "query"
},
{
"type": "integer",
"default": 10,
"description": "Bir sahypadaky ýazgy sany",
"name": "limit",
"in": "query"
},
{
"enum": [
"tm",
"ru",
"en",
"all"
],
"type": "string",
"default": "tm",
"description": "Lokallaşdyrylan meýdanlaryň dili; all - doly {en, ru, tm} obýektleri",
"name": "lang",
"in": "query"
}
],
"responses": {
"200": {
"description": "OK",
"schema": {
"$ref": "#/definitions/visamasteractions.ListOrderActionDTO"
}
},
"400": {
"description": "Bad Request",
"schema": {
"$ref": "#/definitions/appresult.AppError"
}
},
"403": {
"description": "Forbidden",
"schema": {
"$ref": "#/definitions/appresult.AppError"
}
},
"404": {
"description": "Not Found",
"schema": {
"$ref": "#/definitions/appresult.AppError"
}
},
"500": {
"description": "Internal Server Error",
"schema": {
"$ref": "#/definitions/appresult.AppError"
}
}
}
}
},
"/visa-master-payment-orders/{id}/actions/{actionId}": {
"get": {
"security": [
{
"BearerAuth": []
}
],
"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.",
"produces": [
"application/json"
],
"tags": [
"visa-master-order-actions"
],
"summary": "Sargydyň bir amaly",
"parameters": [
{
"type": "integer",
"description": "Sargyt ID-si",
"name": "id",
"in": "path",
"required": true
},
{
"type": "integer",
"description": "Amalyň ID-si",
"name": "actionId",
"in": "path",
"required": true
},
{
"enum": [
"tm",
"ru",
"en",
"all"
],
"type": "string",
"default": "tm",
"description": "Lokallaşdyrylan meýdanlaryň dili; all - doly {en, ru, tm} obýektleri",
"name": "lang",
"in": "query"
}
],
"responses": {
"200": {
"description": "OK",
"schema": {
"$ref": "#/definitions/visamasteractions.OrderActionDetailDTO"
}
},
"400": {
"description": "Bad Request",
"schema": {
"$ref": "#/definitions/appresult.AppError"
}
},
"403": {
"description": "Forbidden",
"schema": {
"$ref": "#/definitions/appresult.AppError"
}
},
"404": {
"description": "Not Found",
"schema": {
"$ref": "#/definitions/appresult.AppError"
}
},
"500": {
"description": "Internal Server Error",
"schema": {
"$ref": "#/definitions/appresult.AppError"
}
}
}
}
},
"/visa-master-payment-orders/{id}/pay": {
"post": {
"security": [
@@ -12931,6 +13094,110 @@
}
}
},
"visamasteractions.ListOrderActionDTO": {
"type": "object",
"properties": {
"actions": {
"type": "array",
"items": {
"$ref": "#/definitions/visamasteractions.OrderActionDTO"
}
},
"count": {
"type": "integer"
}
}
},
"visamasteractions.OrderActionDTO": {
"type": "object",
"properties": {
"createdAt": {
"type": "string"
},
"createdById": {
"type": "integer"
},
"createdByName": {
"type": "string"
},
"id": {
"type": "integer"
},
"name": {
"type": "string"
},
"nameLabel": {
"$ref": "#/definitions/shared.LocalizedText"
},
"orderId": {
"type": "integer"
},
"status": {
"type": "string"
},
"target": {
"$ref": "#/definitions/visamasteractions.OrderActionTargetDTO"
}
}
},
"visamasteractions.OrderActionDetailDTO": {
"type": "object",
"properties": {
"changes": {
"type": "object"
},
"createdAt": {
"type": "string"
},
"createdById": {
"type": "integer"
},
"createdByName": {
"type": "string"
},
"exception": {
"type": "string"
},
"id": {
"type": "integer"
},
"name": {
"type": "string"
},
"nameLabel": {
"$ref": "#/definitions/shared.LocalizedText"
},
"orderId": {
"type": "integer"
},
"original": {
"type": "object"
},
"status": {
"type": "string"
},
"target": {
"$ref": "#/definitions/visamasteractions.OrderActionTargetDTO"
}
}
},
"visamasteractions.OrderActionTargetDTO": {
"type": "object",
"properties": {
"id": {
"type": "integer"
},
"label": {
"$ref": "#/definitions/shared.LocalizedText"
},
"type": {
"type": "string"
},
"uniqueId": {
"type": "string"
}
}
},
"visamasterpay.CallbackResultDTO": {
"type": "object",
"properties": {
@@ -13128,6 +13395,10 @@
"description": "Visa/Master and Sber student-transfer orders: list, view, create, edit, delete",
"name": "visa-master-orders"
},
{
"description": "Visa/Master we Sber sargytlarynyň amallary (Ammallar): kim, haçan, näme goşdy, üýtgetdi ýa-da pozdy. Ulanylyş tertibi: 1) GET /visa-master-payment-orders/{id}/actions - sargydyň amallary; 2) GET /visa-master-payment-orders/{id}/actions/{actionId} - bir amalyň öňki we täze bahalary",
"name": "visa-master-order-actions"
},
{
"description": "Paying a Visa/Master or Sber order through GBÜS (HALKBANK): quote, pay, status re-check, bank callback",
"name": "visa-master-payment"

View File

@@ -2066,6 +2066,74 @@ definitions:
- senderPassportNumber
- senderPassportSerie
type: object
visamasteractions.ListOrderActionDTO:
properties:
actions:
items:
$ref: '#/definitions/visamasteractions.OrderActionDTO'
type: array
count:
type: integer
type: object
visamasteractions.OrderActionDTO:
properties:
createdAt:
type: string
createdById:
type: integer
createdByName:
type: string
id:
type: integer
name:
type: string
nameLabel:
$ref: '#/definitions/shared.LocalizedText'
orderId:
type: integer
status:
type: string
target:
$ref: '#/definitions/visamasteractions.OrderActionTargetDTO'
type: object
visamasteractions.OrderActionDetailDTO:
properties:
changes:
type: object
createdAt:
type: string
createdById:
type: integer
createdByName:
type: string
exception:
type: string
id:
type: integer
name:
type: string
nameLabel:
$ref: '#/definitions/shared.LocalizedText'
orderId:
type: integer
original:
type: object
status:
type: string
target:
$ref: '#/definitions/visamasteractions.OrderActionTargetDTO'
type: object
visamasteractions.OrderActionTargetDTO:
properties:
id:
type: integer
label:
$ref: '#/definitions/shared.LocalizedText'
type:
type: string
uniqueId:
type: string
type: object
visamasterpay.CallbackResultDTO:
properties:
data:
@@ -8770,6 +8838,125 @@ paths:
summary: Update visa/master payment order
tags:
- visa-master-orders
/visa-master-payment-orders/{id}/actions:
get:
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.'
parameters:
- description: Sargyt ID-si
in: path
name: id
required: true
type: integer
- default: 1
description: Sahypa belgisi
in: query
name: page
type: integer
- default: 10
description: Bir sahypadaky ýazgy sany
in: query
name: limit
type: integer
- default: tm
description: Lokallaşdyrylan meýdanlaryň dili; all - doly {en, ru, tm} obýektleri
enum:
- tm
- ru
- en
- all
in: query
name: lang
type: string
produces:
- application/json
responses:
"200":
description: OK
schema:
$ref: '#/definitions/visamasteractions.ListOrderActionDTO'
"400":
description: Bad Request
schema:
$ref: '#/definitions/appresult.AppError'
"403":
description: Forbidden
schema:
$ref: '#/definitions/appresult.AppError'
"404":
description: Not Found
schema:
$ref: '#/definitions/appresult.AppError'
"500":
description: Internal Server Error
schema:
$ref: '#/definitions/appresult.AppError'
security:
- BearerAuth: []
summary: Sargydyň amallary (Ammallar)
tags:
- visa-master-order-actions
/visa-master-payment-orders/{id}/actions/{actionId}:
get:
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.'
parameters:
- description: Sargyt ID-si
in: path
name: id
required: true
type: integer
- description: Amalyň ID-si
in: path
name: actionId
required: true
type: integer
- default: tm
description: Lokallaşdyrylan meýdanlaryň dili; all - doly {en, ru, tm} obýektleri
enum:
- tm
- ru
- en
- all
in: query
name: lang
type: string
produces:
- application/json
responses:
"200":
description: OK
schema:
$ref: '#/definitions/visamasteractions.OrderActionDetailDTO'
"400":
description: Bad Request
schema:
$ref: '#/definitions/appresult.AppError'
"403":
description: Forbidden
schema:
$ref: '#/definitions/appresult.AppError'
"404":
description: Not Found
schema:
$ref: '#/definitions/appresult.AppError'
"500":
description: Internal Server Error
schema:
$ref: '#/definitions/appresult.AppError'
security:
- BearerAuth: []
summary: Sargydyň bir amaly
tags:
- visa-master-order-actions
/visa-master-payment-orders/{id}/pay:
post:
consumes:
@@ -9047,6 +9234,11 @@ tags:
- description: 'Visa/Master and Sber student-transfer orders: list, view, create,
edit, delete'
name: visa-master-orders
- description: 'Visa/Master we Sber sargytlarynyň amallary (Ammallar): kim, haçan,
näme goşdy, üýtgetdi ýa-da pozdy. Ulanylyş tertibi: 1) GET /visa-master-payment-orders/{id}/actions
- sargydyň amallary; 2) GET /visa-master-payment-orders/{id}/actions/{actionId}
- bir amalyň öňki we täze bahalary'
name: visa-master-order-actions
- description: 'Paying a Visa/Master or Sber order through GBÜS (HALKBANK): quote,
pay, status re-check, bank callback'
name: visa-master-payment

View File

@@ -21,6 +21,8 @@ import (
reasonscarddb "online-back/internal/cards/reasonscard/db"
"online-back/internal/cards/visamaster"
visamasterdb "online-back/internal/cards/visamaster/db"
"online-back/internal/cards/visamasteractions"
visamasteractionsdb "online-back/internal/cards/visamasteractions/db"
"online-back/internal/handlers"
"online-back/pkg/client/postgresql"
"online-back/pkg/logging"
@@ -45,5 +47,6 @@ func Handlers(client postgresql.Client, logger *logging.Logger) []handlers.Handl
paymentcard.NewHandler(logger, paymentcarddb.NewRepository(client, logger)),
reasonscard.NewHandler(logger, reasonscarddb.NewRepository(client, logger)),
visamaster.NewHandler(logger, visamasterdb.NewRepository(client, logger)),
visamasteractions.NewHandler(logger, visamasteractionsdb.NewRepository(client, logger)),
}
}

View File

@@ -7,6 +7,8 @@ import (
"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"
@@ -214,7 +216,34 @@ func (r *repository) Create(ctx context.Context, dto visamaster.CreateVisaMaster
orderColumnsSQL, orderSelectColumns,
)
return scanOrder(r.client.QueryRow(ctx, query, args...))
// 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) {
@@ -240,15 +269,124 @@ func (r *repository) Update(ctx context.Context, id int64, dto visamaster.Update
strings.Join(assignments, ", "), len(args), orderColumnsSQL, orderSelectColumns,
)
item, err := scanOrder(r.client.QueryRow(ctx, query, args...))
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) error {
return r.generic.Delete(ctx, id)
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) {

View File

@@ -76,6 +76,8 @@ type CreateVisaMasterPaymentOrderDTO struct {
RecieverDepositAccount *string `json:"recieverDepositAccount"`
AmountUsd float64 `json:"amountUsd"`
Paid *bool `json:"paid"`
// CreatedBy is the caller, recorded on the order's create action.
CreatedBy *int64 `json:"-"`
}
type UpdateVisaMasterPaymentOrderDTO struct {
@@ -104,6 +106,8 @@ type UpdateVisaMasterPaymentOrderDTO struct {
RecieverDepositAccount *string `json:"recieverDepositAccount"`
AmountUsd float64 `json:"amountUsd"`
Paid bool `json:"paid"`
// UpdatedBy is the caller, recorded on the order's update action.
UpdatedBy *int64 `json:"-"`
}
type ListFilter struct {

View File

@@ -164,6 +164,9 @@ func (h *handler) create(c *gin.Context) {
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
return
}
if userID, ok := rbac.CurrentUserID(c); ok {
dto.CreatedBy = &userID
}
item, err := h.repository.Create(c.Request.Context(), dto)
if err != nil {
@@ -206,6 +209,9 @@ func (h *handler) update(c *gin.Context) {
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
return
}
if userID, ok := rbac.CurrentUserID(c); ok {
dto.UpdatedBy = &userID
}
item, err := h.repository.Update(c.Request.Context(), id, dto)
if errors.Is(err, pgx.ErrNoRows) {
@@ -245,7 +251,12 @@ func (h *handler) delete(c *gin.Context) {
return
}
if err := h.repository.Delete(c.Request.Context(), id); errors.Is(err, pgx.ErrNoRows) {
var deletedBy *int64
if userID, ok := rbac.CurrentUserID(c); ok {
deletedBy = &userID
}
if err := h.repository.Delete(c.Request.Context(), id, deletedBy); errors.Is(err, pgx.ErrNoRows) {
c.JSON(http.StatusNotFound, appresult.ErrNotFound)
return
} else if err != nil {

View File

@@ -7,5 +7,7 @@ type Repository interface {
GetByID(ctx context.Context, id int64) (VisaMasterPaymentOrderDTO, error)
Create(ctx context.Context, dto CreateVisaMasterPaymentOrderDTO) (VisaMasterPaymentOrderDTO, error)
Update(ctx context.Context, id int64, dto UpdateVisaMasterPaymentOrderDTO) (VisaMasterPaymentOrderDTO, error)
Delete(ctx context.Context, id int64) error
// Delete soft-deletes the order; deletedBy is the caller, recorded on
// its delete action.
Delete(ctx context.Context, id int64, deletedBy *int64) error
}

View File

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

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
}

View File

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

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
}

View File

@@ -0,0 +1,141 @@
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. The group is
// its own /:id/actions prefix because rbac allows one policy per prefix
// and cards/visamaster already declares require:cards for baseURL.
func (h *handler) Register(router *gin.RouterGroup) {
group := rbac.Group(router, baseURL+"/:id/actions", rbac.RequireStaff(perm.Cards))
group.GET("", h.list)
group.GET("/: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)
}

View File

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

View File

@@ -74,6 +74,19 @@ func New(cfg *config.Config, client *pgxpool.Pool, logger *logging.Logger) *gin.
}
adminGroup.Use(rbac.Guard(rbac.NewService(client)))
registerRoutes(router, adminGroup, cfg, client, logger)
// Deny by default: every admin route must declare its policy via rbac.Group.
if err := rbac.VerifyRoutes(router.Routes(), adminAPIPrefix); err != nil {
logger.Fatal(err)
}
return router
}
// registerRoutes has every bounded context register its handlers. rbac
// panics here if two groups declare different policies for one prefix.
func registerRoutes(router *gin.Engine, adminGroup *gin.RouterGroup, cfg *config.Config, client *pgxpool.Pool, logger *logging.Logger) {
// Each bounded context registers its own modules' handlers.
// Add new modules inside the relevant context's router.go rather than here.
identity.Register(adminGroup, router, client, logger)
@@ -94,13 +107,6 @@ func New(cfg *config.Config, client *pgxpool.Pool, logger *logging.Logger) *gin.
logger,
)
backup.NewHandler(logger, backupSvc).Register(adminGroup)
// Deny by default: every admin route must declare its policy via rbac.Group.
if err := rbac.VerifyRoutes(router.Routes(), adminAPIPrefix); err != nil {
logger.Fatal(err)
}
return router
}
// paymentGatewayClient picks the real GBÜS client outside debug mode, and

View File

@@ -0,0 +1,29 @@
package handlermanager
import (
"testing"
"online-back/internal/config"
"online-back/internal/identity/rbac"
"online-back/pkg/logging"
"github.com/gin-gonic/gin"
)
// TestRegisterRoutes registers every handler the way New does (no database:
// handlers only touch it per request), so a startup panic such as two
// groups declaring different policies for one prefix fails here instead
// of on the server.
func TestRegisterRoutes(t *testing.T) {
gin.SetMode(gin.TestMode)
debug := true
cfg := &config.Config{IsDebug: &debug}
router := gin.New()
adminGroup := router.Group(adminAPIPrefix)
registerRoutes(router, adminGroup, cfg, nil, logging.GetLogger())
if err := rbac.VerifyRoutes(router.Routes(), adminAPIPrefix); err != nil {
t.Fatal(err)
}
}

View File

@@ -10,6 +10,8 @@ import (
"strings"
"time"
"online-back/internal/cards/visamasteractions"
actionsdb "online-back/internal/cards/visamasteractions/db"
"online-back/internal/currency"
"online-back/internal/payment/paymentsettings"
"online-back/internal/payment/visamasterpay"
@@ -409,32 +411,57 @@ func (r *repository) verifyPayment(ctx context.Context, paymentID int64, trigger
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 {
var lockedStatus *string
if err := tx.QueryRow(ctx, `SELECT paid, status FROM visa_master_payment_orders WHERE id = $1 FOR UPDATE`, orderID).Scan(&lockedPaid, &lockedStatus); err != nil {
fail("finalize_lock_order", err)
return visamasterpay.PaymentResultDTO{}, err
}
// orderAction is the order's update action once it is marked paid,
// recorded only after the commit (or as failed if it never lands):
// recording it must never hold up finalizing a payment GBÜS has
// already taken.
var orderAction *visamasteractions.CreateOrderActionDTO
failFinalize := func(stage string, err error) {
fail(stage, err)
if orderAction != nil {
exception := err.Error()
orderAction.Status, orderAction.Exception = visamasteractions.StatusFailed, &exception
r.recordOrderAction(ctx, *orderAction)
}
}
if lockedPaid {
step("order_already_marked_paid", nil)
} else {
original, changes := visamasteractions.Diff(
map[string]interface{}{"paid": false, "status": derefOrNil(lockedStatus)},
map[string]interface{}{"paid": true, "status": "completed"},
)
orderAction = &visamasteractions.CreateOrderActionDTO{
OrderId: orderID, Name: visamasteractions.NameUpdate, Status: visamasteractions.StatusFinished,
Original: original, Changes: changes, CreatedBy: requestedBy,
}
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)
failFinalize("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)
failFinalize("finalize_save_payment_status", err)
return visamasterpay.PaymentResultDTO{}, err
}
if err := tx.Commit(ctx); err != nil {
fail("finalize_commit", err)
failFinalize("finalize_commit", err)
return visamasterpay.PaymentResultDTO{}, err
}
if orderAction != nil {
r.recordOrderAction(ctx, *orderAction)
}
} else if status.InProgress() {
// Not paid yet but not over either (e.g. checked before the card was
// entered): keep it pending so a later callback/Status re-checks it,
@@ -483,6 +510,15 @@ func (r *repository) Status(ctx context.Context, orderID int64, requestedBy *int
return r.verifyPayment(ctx, paymentID, "status", requestedBy)
}
// recordOrderAction records an order action ("Ammallar") of finalizing a
// payment through the plain client. Best-effort, like logStep: a write
// failure is logged, not propagated.
func (r *repository) recordOrderAction(ctx context.Context, dto visamasteractions.CreateOrderActionDTO) {
if err := actionsdb.Insert(context.WithoutCancel(ctx), r.client, dto); err != nil && r.logger != nil {
r.logger.Errorf("visa master order action write failed (order %d, %s %s): %v", dto.OrderId, dto.Name, dto.Status, err)
}
}
// branchCredentials picks the sber or visa/master MPI merchant credentials
// for a branch, matching the type of order being paid.
func (r *repository) branchCredentials(ctx context.Context, branchID int64, sber bool) (username, password string, err error) {
@@ -527,6 +563,15 @@ func isSber(orderType *string) bool {
return orderType != nil && strings.EqualFold(strings.TrimSpace(*orderType), orderTypeSber)
}
// derefOrNil keeps a null column null in an action's original values
// rather than turning it into a typed nil pointer.
func derefOrNil(s *string) interface{} {
if s == nil {
return nil
}
return *s
}
func derefOrEmpty(s *string) string {
if s == nil {
return ""