75 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
742e078090 visamasterpay: return gatewayResponse from GET /{id}/status
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 status check now carries GBÜS's last stored response for the
attempt alongside gatewayStatus - the fresh getOrderStatusExtended.do
answer when it was just checked, the stored one when the attempt was
already finalized, null if GBÜS never answered. The callback is
unchanged: it is public and only reports paid plus a message.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-25 01:25:12 +05:00
570d4c6d20 payment-history: drop /payments/{id}/gateway in favour of /{id}/gateway
Some checks failed
CI/CD / Deploy binary to server (push) Has been cancelled
CI/CD / Vet, test, build (push) Has been cancelled
CI/CD / Docker image (push) Has been cancelled
Both routes served the same handler and took an order ID, while
/payments/{id} takes a payment ID - so the /payments/ one read as
per-payment and showed up twice in Swagger. /payment-history/{id}/gateway
is the one to use.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-24 23:30:11 +05:00
d7e5d1f989 swagger: split the Visa/Master tag and document payment-history in Turkmen
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
visa-master-payment-orders mixed order CRUD with the GBÜS payment flow;
they are now visa-master-orders and visa-master-payment. payment-history
summaries, descriptions and params are in Turkmen with one shape
(what it returns, Tertip, Bellik), and its tag description lists the
endpoints in the order they are used.

@securityDefinitions.apikey moves to the end of the general info block:
swag read every line after it as its attributes, so @schemes and all
@tag.* declarations were silently dropped from the spec.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-24 23:21:07 +05:00
78e1976e53 visamasterpay: keep a payment pending while GBÜS still reports it in progress
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
A status check that ran before the card was entered (orderStatus 0,
"no payment attempts") finalized the payment as failed, and later
callbacks returned it as already finalized without asking GBÜS again -
so cardholderName/maskedPan stayed null and a real payment was never
recorded. Unpaid in-progress statuses (0, 1, 5) now keep the row
pending with the latest response stored, and rows already failed that
way are re-checked.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-24 22:58:49 +05:00
f1337706f0 swagger: document the ?lang= query parameter on every admin endpoint
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
appresult.Localize applies to all /api/admin routes, so each handler's
godoc now declares lang (tm, ru, en, all; default tm) and Swagger UI
offers it as a dropdown.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-24 22:08:32 +05:00
72a5ac52b0 shared: use one LocalizedText type everywhere
Some checks failed
CI/CD / Deploy binary to server (push) Has been cancelled
CI/CD / Vet, test, build (push) Has been cancelled
CI/CD / Docker image (push) Has been cancelled
auth, user, userbranch and org/branches each declared their own identical
{en, ru, tm} struct; they now use shared.LocalizedText. No JSON change.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-24 21:48:03 +05:00
c6540a658b api: return localized fields only in the requested ?lang=
appresult.Localize, the first admin middleware, rewrites JSON responses so
every {en, ru, tm} object becomes the plain string for ?lang= (tm, ru, en;
default tm), falling back tm -> ru -> en when that translation is empty.
?lang=all keeps the full objects for edit forms; other values are 400.
Key order and number precision are preserved; non-JSON responses and
/swagger are untouched.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-24 21:48:02 +05:00
f067872cd7 payment-history: /payments/{id}/gateway takes an order ID and lists its payments
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 frontend calls /payments/{id}/gateway with an order ID, so that URL
now returns every payment of the order (newest first, each with its
HALKBANK JSON) instead of one payment by payment ID. /{id}/gateway stays
as an alias of the same handler.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-24 20:18:05 +05:00
6dd6110914 payment-history: bring back GET /payments/{id}/gateway for the frontend
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 frontend still calls the single-payment gateway view, so it's back
as it was (payment ID -> one PaymentGatewayDTO), alongside the new
order-wide /{id}/gateway.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-24 20:10:07 +05:00
a3cbb52f4b payment-history: GET /{id}/gateway - all of an order's payments with their HALKBANK JSON
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 gateway view now takes an order ID and returns every payment of the
order, newest first, each in the same PaymentGatewayDTO shape with its
own last stored GBÜS response. It moves from /payments/{id}/gateway to
/{id}/gateway, next to the other order-scoped routes (/{id}, /{id}/logs).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-24 20:05:18 +05:00
ef3a1baee2 payment-history: apiClientName, formUrl/successUrl after finalizing, callbackStatus
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
To match the old online payment history page:
- apiClientName: billing_visa_master_username / billing_sber_username
- formUrl falls back to the logged register.do response, so finalized
  attempts keep it; successUrl is the returnUrl logged with register.do
- callbackStatus ("received") and callbackAt from the attempt's first
  callback_received log
- index visa_master_payment_logs (order_id, step) for those lookups

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-24 19:49:24 +05:00
ae6bf0b7e3 payment-history: GET /payments/{id}/gateway - one payment with its HALKBANK JSON
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
Returns a payment the way the per-order payment table shows it (paid,
cardholder name, masked card, time, payment year/month, USD/TMT amounts,
reference) plus the last stored GBÜS response, for the storage icon.
Card fields and gatewayResponse are null until GBÜS reports them.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-24 19:10:32 +05:00
c209f338c2 payment-history: /{id} lists the order's payments, logs move to /{id}/logs
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
GET /payment-history/{id} now returns one row per payment of the order
(paid, card, time, period, amounts), newest first - the per-order payment
table the frontend already calls. The step-by-step logs it used to return
are kept at GET /payment-history/{id}/logs.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-24 18:38:02 +05:00
a715cd23ea payment-history: payment detail with GBÜS response, sorting, newest-first logs
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
- GET /payment-history/payments/{id}: single payment attempt with the raw
  gateway_response (last HALKBANK JSON) for the "storage" icon modal
- GET /payment-history: sort (id/created_at/status/amount) and order
  (asc/desc, default desc) query params
- GET /payment-history/{id}: order logs now newest first
- index on visa_master_order_payments (gateway_status, id DESC)
- regenerate swagger docs

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-24 13:32:36 +05:00
e5f01d0e94 add docker
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
2026-10-23 00:39:04 +05:00
965b00dba5 analytics: customers totals, open counts, normalize education/marriage
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
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-02 11:06:18 +05:00
29867561d1 ch panel statistik
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
2026-10-01 18:14:20 +05:00
ebedeba009 add payment text
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
2026-09-30 16:26:38 +05:00
7e403dab13 rm -file
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
2026-09-30 14:41:31 +05:00
60787c8149 ch something
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
2026-09-30 14:41:13 +05:00
3b33e25703 ch data
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
2026-09-30 14:28:52 +05:00
0de3900ed1 rm file
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
2026-09-30 14:24:18 +05:00
94eb2aa4e9 ch pin-orders
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
2026-09-30 14:23:58 +05:00
27ad42528c ch card-rekwezit
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
2026-09-30 14:20:28 +05:00
15774d2bc4 ch card-orders
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
2026-09-30 14:16:36 +05:00
69d1495b1f remove some daata
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
2026-09-30 14:10:10 +05:00
a44c10d445 added province name
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
2026-09-30 14:00:27 +05:00
68ead82827 ch data
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
2026-09-30 13:55:49 +05:00
4f3631c70d ch branches
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
2026-09-30 13:48:35 +05:00
6f54e9c20b ch role list added name
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
2026-09-30 13:44:10 +05:00
5ab17b1539 ch role list
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
2026-09-30 13:42:14 +05:00
19a1f70588 ch en -tk
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
2026-09-30 13:35:32 +05:00
8b73df4435 ch en-tk
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
2026-09-30 13:29:59 +05:00
0058411cdd add order number
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
2026-09-29 19:29:07 +05:00
e47e8c24d0 added log
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
2026-09-28 16:53:34 +05:00
c01429d2a4 ch mg
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
2026-09-26 21:57:41 +05:00
323e131216 changed role permission
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
2026-09-26 16:34:28 +05:00
f0ecf23879 ch return url
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
2026-09-22 18:31:22 +05:00
d6a1053003 swagger
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
2026-09-22 17:03:23 +05:00
205aaafc63 remove something
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
2026-09-22 13:39:02 +05:00
f2b55f9896 add status api
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
2026-09-22 12:42:31 +05:00
ac94e0dd8a add /order-id
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
2026-09-21 19:52:10 +05:00
235ef5ec9e ch some
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
2026-09-21 19:12:07 +05:00
febd190d6e fixed error
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
2026-09-21 18:31:31 +05:00
99788a853f added payment history
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
2026-09-21 18:12:08 +05:00
23d208769c fixed error
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
2026-09-21 17:51:10 +05:00
f42ad01828 added print
Some checks failed
CI/CD / Vet, test, build (push) Has been cancelled
CI/CD / Deploy binary to server (push) Has been cancelled
CI/CD / Docker image (push) Has been cancelled
2026-09-19 12:26:35 +05:00
87e4b33322 rm -rf amount in db
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
2026-09-19 12:16:24 +05:00
45378559ca todo check day
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
2026-09-19 11:51:23 +05:00
599c12ef87 add some
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
2026-09-19 04:47:43 +05:00
6c7c402390 add pay
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
2026-09-19 03:54:40 +05:00
848a07324f rm -rf permission module
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
2026-09-19 02:40:38 +05:00
c6b9cb7462 ch
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
2026-09-19 02:14:27 +05:00
b8455625b5 add payment settting
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
2026-09-19 02:12:59 +05:00
0971158e98 ch users <-> branches
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
2026-09-18 22:59:58 +05:00
d3e188affe ch logika
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
2026-09-18 11:53:37 +05:00
e0d03730de added soft deleted
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
2026-09-05 17:58:23 +05:00
d1a6fcaadc ch some
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
2026-09-04 19:33:26 +05:00
28509eb4ca Add backups, currencies and dashboard APIs, and scope access by guard_name.
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
Web users may only CRUD their own records, operators stay in assigned branches, and admin/manager/superadmin keep full access.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-31 18:14:47 +05:00
0d000f9af6 Harden loan-order create validation and cover gin JSON binding.
Some checks failed
CI/CD / Vet, test, build (push) Has been cancelled
CI/CD / Docker image (push) Has been cancelled
Reject zero loanType/branchId/dates before insert, and assert mobile-style payloads bind through gin required tags.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-26 13:13:38 +05:00
6683826662 Accept flexible loan payloads and nest related info on lending responses.
Some checks failed
CI/CD / Vet, test, build (push) Has been cancelled
CI/CD / Docker image (push) Has been cancelled
Widen loan_orders.region in the init migration and share common relation helpers across loan APIs.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-26 13:06:06 +05:00
0098422798 Enrich cards API responses with joined relations and share common helpers.
Some checks failed
CI/CD / Vet, test, build (push) Has been cancelled
CI/CD / Docker image (push) Has been cancelled
Nest user/branch/cardType/cardState on card, order, pin-order, and visa-master
reads; accept flexible dates/IDs on pin create; widen pin region; ignore undefined
list query params; extract internal/cards/shared to remove duplicated types and helpers.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-26 12:46:50 +05:00
1fd0abbcb2 Bind permissions to roles and scope operator access by branch.
Replace permission_user with permission_role, enforce RBAC on admin routes, and limit operators to their assigned branches.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-24 18:24:43 +05:00
427d5b4e07 Add GET /loan-orders/mobile to list loan orders created from the mobile app.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-22 18:37:31 +05:00
8795ae2195 Put the user's role and branch on GET /profile, upsert role_user and branch_user on POST, and drop their list endpoints.
Also accept flexible card-order form values, move mock seed under db/mock, and regenerate Swagger.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-22 17:56:07 +05:00
7225dc0399 Add visa/master payment orders API and related names on loan paid letters.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-20 15:24:59 +05:00
d7cdd53597 Return role IDs on users and related names on loan APIs.
Loan orders, paid-off letters, and repayments now include user, branch, type, and document names alongside foreign-key IDs.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-19 11:58:15 +05:00
2853bed2ec Regenerate Swagger for public file GET and user branches.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-18 14:29:52 +05:00
9c07439089 Include assigned branches on GET user by ID.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-18 14:12:47 +05:00
6191b7536c Serve public MinIO files at /file/:file_name and add a native Ubuntu MinIO install.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-18 13:47:57 +05:00
71479f4355 Search users by username, first name, last name, and full name across all list endpoints.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-18 12:28:21 +05:00
fb65d35d3c Link seeded users to roles by code and list only clients not assigned to a branch.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-18 12:01:58 +05:00
0788585c0e Assign users to roles via role_user and drop unused social media and light-mode fields.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-18 11:13:53 +05:00
194 changed files with 35193 additions and 5532 deletions

BIN
.DS_Store vendored

Binary file not shown.

26
.dockerignore Normal file
View File

@@ -0,0 +1,26 @@
.git
.github
.cursor
.claude
.DS_Store
logs
tmp
temp
dist
*.md
*.log
*.tar
*.tar.gz
coverage.out
coverage.html
config.yaml
config.local.yaml
docker-compose.yaml
docker-compose.override.yaml
docker-compose.override.yml
deployment/minio.deb
myapp
public/images/*
!public/images/.gitkeep
public/backups/*
!public/backups/.gitkeep

116
.github/workflows/ci-cd.yml vendored Normal file
View File

@@ -0,0 +1,116 @@
name: CI/CD
on:
push:
branches: [main]
tags: ["v*"]
pull_request:
workflow_dispatch:
concurrency:
group: cicd-${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: ${{ github.ref != 'refs/heads/main' && !startsWith(github.ref, 'refs/tags/') }}
permissions:
contents: read
jobs:
ci:
name: Vet, test, build
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v5
- name: Set up Go
uses: actions/setup-go@v5
with:
go-version-file: go.mod
cache-dependency-path: go.sum
- name: Vet
run: go vet ./...
- name: Test
run: go test -race -count=1 -shuffle=on ./...
- name: Build
run: CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -o myapp ./app.go
image:
name: Docker image
needs: ci
if: github.event_name == 'push' && (github.ref == 'refs/heads/main' || startsWith(github.ref, 'refs/tags/v'))
runs-on: ubuntu-latest
permissions:
contents: read
packages: write
steps:
- name: Checkout
uses: actions/checkout@v5
- name: Provide config for image build
run: test -f config.yaml || cp config.example.yaml config.yaml
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v3
- name: Log in to GHCR
uses: docker/login-action@v3
with:
registry: ghcr.io
username: ${{ github.actor }}
password: ${{ secrets.GITHUB_TOKEN }}
- name: Docker metadata
id: meta
uses: docker/metadata-action@v5
with:
images: ghcr.io/${{ github.repository }}
tags: |
type=raw,value=latest,enable={{is_default_branch}}
type=sha
type=semver,pattern={{version}}
type=ref,event=tag
- name: Build and push
uses: docker/build-push-action@v6
with:
context: .
push: true
tags: ${{ steps.meta.outputs.tags }}
labels: ${{ steps.meta.outputs.labels }}
cache-from: type=gha
cache-to: type=gha,mode=max
deploy:
name: Deploy binary to server
needs: ci
if: github.event_name == 'push' && (github.ref == 'refs/heads/main' || startsWith(github.ref, 'refs/tags/v'))
runs-on: ubuntu-latest
permissions:
contents: read
steps:
- name: Checkout
uses: actions/checkout@v5
- name: Set up Go
uses: actions/setup-go@v5
with:
go-version-file: go.mod
cache-dependency-path: go.sum
- name: Set up SSH agent
uses: webfactory/ssh-agent@v0.9.0
with:
ssh-private-key: ${{ secrets.DEPLOY_SSH_KEY }}
- name: Trust deploy host
run: ssh-keyscan -H "${DEPLOY_HOST#*@}" >> ~/.ssh/known_hosts
env:
DEPLOY_HOST: ${{ vars.DEPLOY_HOST || 'ubuntu@216.250.10.141' }}
- name: Deploy
run: make deploy
env:
DEPLOY_HOST: ${{ vars.DEPLOY_HOST || 'ubuntu@216.250.10.141' }}

9
.gitignore vendored
View File

@@ -1,6 +1,7 @@
# Binaries
online-back
myapp
app
*.exe
*.exe~
*.dll
@@ -31,6 +32,8 @@ logs/
# Uploaded files (keep directory structure)
public/images/*
!public/images/.gitkeep
public/backups/*
!public/backups/.gitkeep
# IDE & editors
.idea/
@@ -54,6 +57,9 @@ Desktop.ini
docker-compose.override.yaml
docker-compose.override.yml
# Local MinIO Ubuntu package (do not commit)
deployment/minio.deb
# Temporary files
tmp/
temp/
@@ -71,3 +77,6 @@ bank_db_schema.drawio
# Debug
__debug_bin
debug
# Docker image bundles (make docker-bundle)
dist/

View File

@@ -1,30 +1,39 @@
#!/bin/ash
# Specifies a parent image
# Offline build: nothing in this file touches the network.
# - Go modules come from the committed vendor/ directory.
# - The runtime stage is postgres:14.1-alpine, the same image main-db uses,
# so pg_dump (backups), tzdata and CA certificates are already there and no
# `apk add` is needed. Its layers are shared with main-db on the server.
# The server only needs the base images loaded once (see `make docker-bundle`).
#
# No "# syntax=" directive on purpose: it makes BuildKit pull a frontend image.
FROM golang:1.26.4-alpine AS builder
# Creates an app directory to hold your app’s source code
WORKDIR /build
# Installs Go dependencies
COPY go.mod ./
COPY go.sum ./
RUN go mod download
ENV CGO_ENABLED=0 \
GOOS=linux \
GOARCH=amd64 \
GOFLAGS=-mod=vendor \
GOPROXY=off
COPY . .
# Builds your app with optional configuration
RUN GOARCH=amd64 GOOS=linux go build -o myapp ./app.go
RUN go build -trimpath -ldflags="-s -w" -o myapp ./app.go
FROM scratch
FROM postgres:14.1-alpine
WORKDIR /app/
# Fresher CA bundle than the 2021 one in postgres:14.1-alpine (HTTPS to mpi.gov.tm).
COPY --from=builder /etc/ssl/certs/ca-certificates.crt /etc/ssl/certs/ca-certificates.crt
WORKDIR /app
COPY --from=builder /build/myapp .
COPY --from=builder /build/config.yaml .
# Tells Docker which network port your container listens on
# config.yaml is mounted at runtime (see docker-compose.yaml), not baked in.
RUN mkdir -p /app/public/images /app/public/backups /app/logs
EXPOSE 5050
#ENTRYPOINT ["/app/myapp"]
CMD ["/app/myapp"]
# Replaces the postgres docker-entrypoint.sh inherited from the base image.
ENTRYPOINT ["/app/myapp"]

View File

@@ -19,3 +19,47 @@ seed:
# migrate -database 'postgresql://bank_admin:bank%40%2323%23%40_password@localhost:5454/bank_db?sslmode=disable' -path db/migrations up
# migrate-rollback:
# migrate -database 'postgresql://bank_admin:bank%40%2323%23%40_password@localhost:5454/bank_db?sslmode=disable' -path db/migrations down
# ---------------------------------------------------------------------------
# Deploy: build + upload only (PM2-ni serwerde özüň restart et)
# ---------------------------------------------------------------------------
DEPLOY_HOST ?= ubuntu@216.250.10.141
DEPLOY_DIR ?= /home/ubuntu
BINARY ?= myapp
.PHONY: build-linux deploy swagger
swagger:
swag init -g app.go
build-linux:
CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -ldflags="-s -w" -o $(BINARY) ./app.go
deploy: build-linux
ssh $(DEPLOY_HOST) 'mkdir -p $(DEPLOY_DIR)'
scp ./$(BINARY) $(DEPLOY_HOST):$(DEPLOY_DIR)/$(BINARY).new
ssh $(DEPLOY_HOST) 'cd $(DEPLOY_DIR) && chmod +x $(BINARY).new && mv $(BINARY).new $(BINARY)'
# ---------------------------------------------------------------------------
# Docker (serwerde internet ýok). Papka serwere göni göçürilýär:
# 1) internet bar maşynda: make docker-bundle → dist/ içine ähli image-ler
# 2) serwerde: make docker-load (bir gezek, ýa-da täze bundle-da)
# docker compose up -d --build (internetsiz build)
# ---------------------------------------------------------------------------
DOCKER_PLATFORM ?= linux/amd64
DOCKER_BASE_IMAGES ?= golang:1.26.4-alpine postgres:14.1-alpine
DOCKER_IMAGES ?= main-app:latest main-minio:latest $(DOCKER_BASE_IMAGES)
DOCKER_BUNDLE ?= dist/online-back-images.tar.gz
.PHONY: docker-bundle docker-load
docker-bundle:
for img in $(DOCKER_BASE_IMAGES); do \
docker image inspect $$img >/dev/null 2>&1 || docker pull --platform $(DOCKER_PLATFORM) $$img || exit 1; \
done
DOCKER_DEFAULT_PLATFORM=$(DOCKER_PLATFORM) docker compose build
mkdir -p $(dir $(DOCKER_BUNDLE))
docker save $(DOCKER_IMAGES) | gzip > $(DOCKER_BUNDLE)
docker-load:
gunzip -c $(DOCKER_BUNDLE) | docker load

View File

@@ -56,14 +56,21 @@ Additional Swagger endpoints (categories, settings) are documented but not yet i
├── config.yaml # Runtime configuration
├── docker-compose.yaml # Local development stack
├── db/migrations/ # SQL migrations
├── db/seed.sql # Consolidated, idempotent seed data
├── docs/ # Generated Swagger docs
├── internal/
│ ├── admin/auth/ # Admin auth handlers & repository
│ ├── appresult/ # Response helpers & JWT middleware
│ ├── config/ # Config loader
│ └── handlers/manager/ # Route registration
│ ├── shared/ # Cross-module DTOs, HTTP/SQL/query helpers
│ ├── handlers/manager/ # Route registration (composition root)
│ ├── identity/ # auth, rbac, permission, role, user, userbranch, activitylog
│ ├── cards/ # card orders, balances, PIN orders, rekwizit, etc.
│ ├── lending/ # loan orders, repayments, documents, letters, types
│ ├── org/ # branches, provinces
│ ├── currency/, dashboard/, backup/
└── pkg/
├── client/postgresql/ # PostgreSQL connection pool
├── repository/genericrepo/ # Shared List/GetByID/Delete repository helper
├── logging/ # Structured logging
└── utils/ # JWT & file utilities
```
@@ -165,6 +172,23 @@ make migrate-rollback
Migration files live in `db/migrations/`.
> **Current practice:** the schema currently lives in a single `db/migrations/20260702125108_init.{up,down}.sql` pair, edited in place as the schema evolves rather than appended to. This means an already-migrated database won't pick up later edits to `init` automatically (`golang-migrate` sees it as already applied) — a fresh `make migrate` against an empty database is the reliable path. Switching to append-only migrations going forward is worth deciding on as a team.
Seed data (`db/seed.sql`) loads a consolidated, idempotent set of test accounts/roles/branches:
```bash
make seed
```
## Roles & permissions (RBAC)
- **Permission = module.** One code per module (`cards`, `loans`, `users`, `roles`, `branches`, `provinces`, `currencies`, `payment-settings`, `backups`, `activity-logs`, `dashboard`), defined in `internal/identity/rbac/perm`. Holding it grants read and write in that module. The catalog is synced to the `permissions` table on startup; the API only lets roles pick from it.
- **Role = permissions + scope.** `scope` decides whose records: `own` (clients — only their own), `branch` (the user's `branch_user` branches, possibly several), `all` (every branch). E.g. a head of loans is `scope=all` + `loans`. `is_super` roles hold every permission; `is_system` roles (`superadmin`, `user`) cannot be deleted or re-scoped.
- **One role per user:** `users.role_id`.
- **Every `/api/admin` route declares its policy** with `rbac.Group(router, path, policy)` — `Require(perm.X)`, `RequireStaff`, `Catalog`, `StaffRead`, `Staff`, `Authenticated`, `Public`. Startup fails if a route has none, and an undeclared route is denied at runtime.
- **No escalation:** a caller can only create/assign roles within their own scope and permissions, cannot touch superadmin unless superadmin, cannot change their own role, and cannot remove the last superadmin.
- Principals are cached per user; DB triggers bump `rbac_version` on role/permission/branch changes, which clears the cache within ~2s.
## Development
### Run tests

View File

@@ -235,7 +235,7 @@ Admin users for the back-office panel.
| avatar | varchar(250) | |
| social_media | json | |
| light_mode | integer | Default `1` |
| role | varchar(250) | Default `'user'` |
| role_id | bigint | FK → roles.id, NOT NULL |
| status | boolean | Default `true` |
| created_at | timestamp UTC | |
| updated_at | timestamp UTC | |

27
app.go
View File

@@ -21,12 +21,9 @@ import (
// @title Service APIs
// @version 1.0
// @description Online payment system admin API.
// @description Online payment system admin API. Localized fields ({en, ru, tm} objects) come back as a plain string in the language of the `lang` query parameter: tm, ru or en (default tm), falling back to tm, ru, en when that translation is empty. lang=all returns the full {en, ru, tm} objects (for edit forms); any other value is 400.
// @host localhost:5005
// @BasePath /api/admin
// @securityDefinitions.apikey BearerAuth
// @in header
// @name Authorization
// @schemes http
// @tag.name auth
// @tag.description Authentication
@@ -46,15 +43,35 @@ import (
// @tag.description Loan repayments
// @tag.name card-orders
// @tag.description Card orders
// @tag.name card-rekwizit-orders
// @tag.description Card rekwizit (card details) orders
// @tag.name activity-logs
// @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
// @tag.description Visa/Master we Sber töleg synanyşyklarynyň taryhy. Ulanylyş tertibi: 1) GET /payment-history - ähli tölegler; 2) GET /payment-history/{id} - bir sargydyň tölegleri; 3) GET /payment-history/payments/{id} - bir tölegiň jikme-jikligi; 4) GET /payment-history/{id}/gateway - sargydyň tölegleri GBÜS jogaplary bilen; 5) GET /payment-history/{id}/logs - sargydyň ädimme-ädim töleg loglary
// @tag.name backups
// @tag.description Database SQL backups
// @tag.name currencies
// @tag.description Currency exchange rates
//
// Security definitions go last: swag reads every line after one as its
// attributes, so anything declared below it (tags, schemes) is dropped.
// @securityDefinitions.apikey BearerAuth
// @in header
// @name Authorization
func main() {
cfg := config.GetConfig()
logger := logging.GetLogger()
docs.SwaggerInfo.Title = "Service APIs"
docs.SwaggerInfo.Version = "1.0"
docs.SwaggerInfo.Description = "Online payment system admin API."
docs.SwaggerInfo.Description = "Online payment system admin API. Localized fields ({en, ru, tm} objects) come back as a plain string in the language of the `lang` query parameter: tm, ru or en (default tm), falling back to tm, ru, en when that translation is empty. lang=all returns the full {en, ru, tm} objects (for edit forms); any other value is 400."
docs.SwaggerInfo.Host = "localhost:" + cfg.Listen.Port
docs.SwaggerInfo.BasePath = "/api/admin"
docs.SwaggerInfo.Schemes = []string{"http"}

View File

@@ -12,10 +12,11 @@ storage:
password: <your-db-password>
pg_pool_max_conn: 10
minio:
endpoint: example-minio:9000 # use localhost:9003 when running outside Docker
access_key: <your-minio-access-key>
secret_key: <your-minio-secret-key>
endpoint: 127.0.0.1:9000
access_key: TX3H1H6XTS288QW07S8Z
secret_key: FWWspiI4n4LMknnxYCmzFTCY1ObkGiuaU9SNwOCU
bucket: dev-minio
use_ssl: false
app_version: 0.0.1
public_file_path: ./public
public_file_path: ./public
public_base_url: https://your-api-domain.example # used to build the GBÜS payment callback (returnUrl)

View File

@@ -1,7 +1,56 @@
DROP TABLE IF EXISTS payment_texts;
DROP TABLE IF EXISTS rbac_version;
DROP FUNCTION IF EXISTS rbac_bump_version() CASCADE;
DROP TABLE IF EXISTS visa_master_payment_logs;
DROP TABLE IF EXISTS visa_master_order_payments;
DROP TABLE IF EXISTS payment_settings;
DROP INDEX IF EXISTS idx_currencies_updated_by;
DROP INDEX IF EXISTS idx_currencies_created_by;
DROP INDEX IF EXISTS idx_currencies_to;
DROP INDEX IF EXISTS idx_currencies_from;
DROP INDEX IF EXISTS idx_backups_created_by;
DROP INDEX IF EXISTS idx_backups_created_at;
DROP INDEX IF EXISTS idx_visa_master_payment_orders_branch_id;
DROP INDEX IF EXISTS idx_visa_master_payment_orders_user_id;
DROP INDEX IF EXISTS idx_loan_paid_off_letters_branch_id;
DROP INDEX IF EXISTS idx_loan_paid_off_letters_user_id;
DROP INDEX IF EXISTS idx_loan_orders_branch_id;
DROP INDEX IF EXISTS idx_loan_orders_user_id;
DROP INDEX IF EXISTS idx_card_rekwizit_orders_branch_id;
DROP INDEX IF EXISTS idx_card_rekwizit_orders_user_id;
DROP INDEX IF EXISTS idx_card_balances_branch_id;
DROP INDEX IF EXISTS idx_card_pin_orders_branch_id;
DROP INDEX IF EXISTS idx_card_pin_orders_user_id;
DROP INDEX IF EXISTS idx_card_orders_branch_id;
DROP INDEX IF EXISTS idx_card_orders_user_id;
DROP INDEX IF EXISTS idx_cards_user_id;
DROP INDEX IF EXISTS idx_branches_province_id;
DROP INDEX IF EXISTS idx_branch_user_branch_id;
DROP INDEX IF EXISTS idx_users_role_id;
DROP INDEX IF EXISTS idx_branch_user_user_id;
DROP TABLE IF EXISTS currencies;
DROP TABLE IF EXISTS backups;
DROP TABLE IF EXISTS card_balances;
DROP TABLE IF EXISTS card_rekwizit_orders;
DROP INDEX IF EXISTS idx_activity_logs_created_at;
DROP INDEX IF EXISTS idx_activity_logs_module;
DROP INDEX IF EXISTS idx_activity_logs_user_id;
DROP TABLE IF EXISTS activity_logs;
DROP TABLE IF EXISTS visa_master_payment_orders;
DROP TABLE IF EXISTS loan_paid_off_letters;
DROP TABLE IF EXISTS loans;
DROP TABLE IF EXISTS loan_orders;
@@ -12,14 +61,22 @@ DROP TABLE IF EXISTS loan_order_required_docs;
DROP TABLE IF EXISTS loan_types;
DROP TABLE IF EXISTS card_states;
DROP TABLE IF EXISTS card_types;
DROP INDEX IF EXISTS branch_user_branch_id_user_id_idx;
DROP TABLE IF EXISTS branch_user;
DROP INDEX IF EXISTS branches_unique_code_idx;
DROP TABLE IF EXISTS branches;
DROP TABLE IF EXISTS provinces;
DROP TABLE IF EXISTS permission_user;
DROP TABLE IF EXISTS role_user;
DROP TABLE IF EXISTS permissions;
DROP TABLE IF EXISTS roles;
DROP TABLE IF EXISTS registration_verifications;
DROP INDEX IF EXISTS idx_users_phone;
DROP INDEX IF EXISTS idx_users_username;
DROP TABLE IF EXISTS users;
DROP TABLE IF EXISTS role_permissions;
DROP TABLE IF EXISTS permissions;
DROP INDEX IF EXISTS roles_code_uq;
DROP TABLE IF EXISTS roles;

View File

@@ -1,4 +1,57 @@
-- 1. Identity
-- RBAC: permission = modul (bir permission her modul üçin), rol = permission-lar + scope
-- (own | branch | all). Her ulanyjynyň bir roly bar (users.role_id).
CREATE TABLE IF NOT EXISTS roles (
id bigserial PRIMARY KEY,
code character varying(255) NOT NULL DEFAULT '',
name character varying(255) NOT NULL,
scope character varying(16) NOT NULL,
is_super boolean NOT NULL DEFAULT false,
is_system boolean NOT NULL DEFAULT false,
created_at TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL,
updated_at TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL,
deleted_at TIMESTAMPTZ,
CONSTRAINT roles_scope_check CHECK (scope IN ('own', 'branch', 'all'))
);
CREATE UNIQUE INDEX IF NOT EXISTS roles_code_uq ON roles (code) WHERE deleted_at IS NULL;
-- Katalog kodda (internal/identity/rbac/perm); app başlanda şu sanawy sinhronlaýar.
CREATE TABLE IF NOT EXISTS permissions (
code character varying(64) PRIMARY KEY,
name character varying(255) NOT NULL DEFAULT ''
);
INSERT INTO permissions (code, name) VALUES
('dashboard', 'Dashboard'),
('cards', 'Cards'),
('loans', 'Loans'),
('users', 'Users'),
('roles', 'Roles'),
('branches', 'Branches'),
('provinces', 'Provinces'),
('currencies', 'Currencies'),
('payment-settings', 'Payment settings'),
('backups', 'Backups'),
('activity-logs', 'Activity logs')
ON CONFLICT (code) DO NOTHING;
CREATE TABLE IF NOT EXISTS role_permissions (
role_id bigint NOT NULL REFERENCES roles(id) ON DELETE CASCADE,
permission_code character varying(64) NOT NULL REFERENCES permissions(code) ON DELETE CASCADE,
PRIMARY KEY (role_id, permission_code)
);
INSERT INTO roles (code, name, scope, is_super, is_system) VALUES
('superadmin', 'Superadmin', 'all', true, true),
('user', 'User', 'own', false, true)
ON CONFLICT DO NOTHING;
INSERT INTO role_permissions (role_id, permission_code)
SELECT r.id, x.code
FROM roles r CROSS JOIN (VALUES ('cards'), ('loans')) x(code)
WHERE r.code = 'user'
ON CONFLICT DO NOTHING;
CREATE TABLE IF NOT EXISTS users (
id bigserial PRIMARY KEY,
email character varying(250) NOT NULL DEFAULT '',
@@ -11,19 +64,20 @@ CREATE TABLE IF NOT EXISTS users (
avatar character varying(250) NOT NULL DEFAULT '',
social_media json NOT NULL DEFAULT '{}'::json,
light_mode integer NOT NULL DEFAULT 1,
role character varying(250) NOT NULL DEFAULT 'user',
role_id bigint NOT NULL REFERENCES roles(id),
active boolean NOT NULL DEFAULT true,
created_at TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL,
updated_at TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL
updated_at TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL,
deleted_at TIMESTAMPTZ
);
CREATE UNIQUE INDEX IF NOT EXISTS idx_users_username
ON users (LOWER(username))
WHERE username <> '';
WHERE username <> '' AND deleted_at IS NULL;
CREATE UNIQUE INDEX IF NOT EXISTS idx_users_phone
ON users (phone)
WHERE phone <> '';
WHERE phone <> '' AND deleted_at IS NULL;
CREATE TABLE IF NOT EXISTS registration_verifications (
id bigserial PRIMARY KEY,
@@ -38,53 +92,19 @@ CREATE TABLE IF NOT EXISTS registration_verifications (
updated_at TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL
);
CREATE TABLE IF NOT EXISTS roles (
id bigserial PRIMARY KEY,
code character varying(255) NOT NULL DEFAULT '',
name character varying(255) NOT NULL,
guard_name character varying(255) NOT NULL,
created_at TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL,
updated_at TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL
);
CREATE TABLE IF NOT EXISTS permissions (
id bigserial PRIMARY KEY,
code character varying(255) NOT NULL DEFAULT '',
name character varying(255) NOT NULL,
guard_name character varying(255) NOT NULL,
created_at TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL,
updated_at TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL
);
CREATE TABLE IF NOT EXISTS role_user (
id bigserial PRIMARY KEY,
role_id bigint REFERENCES roles(id),
user_id bigint REFERENCES users(id),
created_at TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL,
updated_at TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL
);
CREATE TABLE IF NOT EXISTS permission_user (
id bigserial PRIMARY KEY,
permission_id bigint REFERENCES permissions(id),
user_id bigint REFERENCES users(id),
created_at TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL,
updated_at TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL
);
-- 2. Geography
CREATE TABLE IF NOT EXISTS provinces (
id bigserial PRIMARY KEY,
name json NOT NULL DEFAULT '{}'::json,
region json NOT NULL DEFAULT '{}'::json,
active boolean NOT NULL DEFAULT true,
created_at TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL,
updated_at TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL
updated_at TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL,
deleted_at TIMESTAMPTZ
);
CREATE TABLE IF NOT EXISTS branches (
id bigserial PRIMARY KEY,
unique_code character varying(255) UNIQUE,
unique_code character varying(255),
name json NOT NULL DEFAULT '{}'::json,
address json NOT NULL DEFAULT '{}'::json,
region character varying(20) NOT NULL DEFAULT '',
@@ -101,19 +121,31 @@ CREATE TABLE IF NOT EXISTS branches (
active boolean NOT NULL DEFAULT true,
created_at TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL,
updated_at TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL,
deleted_at TIMESTAMPTZ,
CONSTRAINT branches_province_id_fkey
FOREIGN KEY (province_id) REFERENCES provinces(id) ON UPDATE CASCADE
);
CREATE UNIQUE INDEX IF NOT EXISTS branches_unique_code_idx
ON branches (unique_code)
WHERE deleted_at IS NULL;
CREATE TABLE IF NOT EXISTS branch_user (
id bigserial PRIMARY KEY,
branch_id bigint REFERENCES branches(id),
user_id bigint REFERENCES users(id),
created_at TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL,
updated_at TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL
updated_at TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL,
deleted_at TIMESTAMPTZ
);
-- 3. Catalogs
-- branch_user is many-to-many (a user may be assigned to several branches at
-- once); this index only stops the same pair being assigned twice while
-- active, so re-assigning it can be a no-op instead of a duplicate row.
CREATE UNIQUE INDEX IF NOT EXISTS branch_user_branch_id_user_id_idx
ON branch_user (branch_id, user_id)
WHERE deleted_at IS NULL;
CREATE TABLE IF NOT EXISTS card_types (
id bigserial PRIMARY KEY,
name json NOT NULL DEFAULT '{}'::json,
@@ -121,7 +153,8 @@ CREATE TABLE IF NOT EXISTS card_types (
notes character varying(255) NOT NULL DEFAULT '',
active boolean NOT NULL DEFAULT true,
created_at TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL,
updated_at TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL
updated_at TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL,
deleted_at TIMESTAMPTZ
);
CREATE TABLE IF NOT EXISTS card_states (
@@ -131,7 +164,8 @@ CREATE TABLE IF NOT EXISTS card_states (
notes character varying(255) NOT NULL DEFAULT '',
active boolean NOT NULL DEFAULT true,
created_at TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL,
updated_at TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL
updated_at TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL,
deleted_at TIMESTAMPTZ
);
CREATE TABLE IF NOT EXISTS loan_types (
@@ -142,7 +176,8 @@ CREATE TABLE IF NOT EXISTS loan_types (
notes json NOT NULL DEFAULT '{}'::json,
active boolean NOT NULL DEFAULT true,
created_at TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL,
updated_at TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL
updated_at TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL,
deleted_at TIMESTAMPTZ
);
CREATE TABLE IF NOT EXISTS loan_order_required_docs (
@@ -151,10 +186,10 @@ CREATE TABLE IF NOT EXISTS loan_order_required_docs (
value text NOT NULL DEFAULT '',
active boolean NOT NULL DEFAULT true,
created_at TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL,
updated_at TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL
updated_at TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL,
deleted_at TIMESTAMPTZ
);
-- 4. Cards
CREATE TABLE IF NOT EXISTS cards (
id bigserial PRIMARY KEY,
user_id bigint,
@@ -165,6 +200,7 @@ CREATE TABLE IF NOT EXISTS cards (
type character varying(250),
created_at TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL,
updated_at TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL,
deleted_at TIMESTAMPTZ,
CONSTRAINT cards_user_id_fkey
FOREIGN KEY (user_id) REFERENCES users(id)
);
@@ -174,7 +210,7 @@ CREATE TABLE IF NOT EXISTS card_orders (
unique_id character varying(255),
card_state_id bigint NOT NULL,
card_type_id bigint NOT NULL,
region character varying(2) NOT NULL,
region character varying(255) NOT NULL,
branch_id bigint NOT NULL,
customer_name character varying(255) NOT NULL,
customer_surname character varying(255) NOT NULL,
@@ -202,6 +238,7 @@ CREATE TABLE IF NOT EXISTS card_orders (
paid boolean NOT NULL DEFAULT false,
created_at TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL,
updated_at TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL,
deleted_at TIMESTAMPTZ,
CONSTRAINT card_orders_card_state_id_fkey
FOREIGN KEY (card_state_id) REFERENCES card_states(id),
CONSTRAINT card_orders_card_type_id_fkey
@@ -218,7 +255,7 @@ CREATE TABLE IF NOT EXISTS card_pin_orders (
user_id bigint,
card_type_id bigint NOT NULL,
card_number character varying(255),
region character varying(2) NOT NULL,
region character varying(255) NOT NULL,
branch_id bigint NOT NULL,
customer_name character varying(255) NOT NULL,
customer_surname character varying(255) NOT NULL,
@@ -235,6 +272,7 @@ CREATE TABLE IF NOT EXISTS card_pin_orders (
notes character varying(250),
created_at TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL,
updated_at TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL,
deleted_at TIMESTAMPTZ,
CONSTRAINT card_pin_orders_card_type_id_fkey
FOREIGN KEY (card_type_id) REFERENCES card_types(id),
CONSTRAINT card_pin_orders_branch_id_fkey
@@ -243,14 +281,13 @@ CREATE TABLE IF NOT EXISTS card_pin_orders (
FOREIGN KEY (user_id) REFERENCES users(id)
);
-- 5. Loans
CREATE TABLE IF NOT EXISTS loan_orders (
id bigserial PRIMARY KEY,
unique_id character varying(255),
source character varying(255) DEFAULT 'web'::character varying,
user_id bigint,
loan_type bigint NOT NULL,
region character varying(2) NOT NULL,
region character varying(255) NOT NULL,
branch_id bigint NOT NULL,
customer_name character varying(255) NOT NULL,
customer_surname character varying(255) NOT NULL,
@@ -314,7 +351,8 @@ CREATE TABLE IF NOT EXISTS loan_orders (
satisfiable character varying(255),
notes text,
created_at TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL,
updated_at TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL
updated_at TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL,
deleted_at TIMESTAMPTZ
);
CREATE TABLE IF NOT EXISTS loans (
@@ -325,6 +363,7 @@ CREATE TABLE IF NOT EXISTS loans (
account_number character varying(255) NOT NULL,
created_at TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL,
updated_at TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL,
deleted_at TIMESTAMPTZ,
CONSTRAINT loans_user_id_fkey
FOREIGN KEY (user_id) REFERENCES users(id)
);
@@ -332,7 +371,7 @@ CREATE TABLE IF NOT EXISTS loans (
CREATE TABLE IF NOT EXISTS loan_paid_off_letters (
id bigserial PRIMARY KEY,
unique_id character varying(255),
region character varying(2) NOT NULL,
region character varying(255) NOT NULL,
branch_id bigint NOT NULL,
user_id bigint,
customer_name character varying(255) NOT NULL,
@@ -351,13 +390,49 @@ CREATE TABLE IF NOT EXISTS loan_paid_off_letters (
loan_file text,
created_at TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL,
updated_at TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL,
deleted_at TIMESTAMPTZ,
CONSTRAINT loan_paid_off_letters_branch_id_fkey
FOREIGN KEY (branch_id) REFERENCES branches(id),
CONSTRAINT loan_paid_off_letters_user_id_fkey
FOREIGN KEY (user_id) REFERENCES users(id)
);
-- 6. Logs
CREATE TABLE IF NOT EXISTS visa_master_payment_orders (
id bigserial PRIMARY KEY,
unique_id character varying(255),
type character varying(255),
passport_name character varying(255) NOT NULL,
passport_surname character varying(255) NOT NULL,
phone character varying(255) NOT NULL,
email character varying(255),
region character varying(255) NOT NULL,
branch_id bigint NOT NULL,
user_id bigint,
address character varying(255) NOT NULL,
sender_datas json DEFAULT '{}'::json,
payment_reciever json DEFAULT '[]'::json,
documents json DEFAULT '{}'::json,
status character varying(255) DEFAULT 'pending',
notes character varying(255),
sender_full_name character varying(255) NOT NULL,
sender_passport_serie character varying(255) NOT NULL,
sender_passport_number character varying(255) NOT NULL,
sender_deposit_account character varying(255) NOT NULL,
reciever_full_name character varying(255),
reciever_passport_serie character varying(255),
reciever_passport_number character varying(255),
reciever_deposit_account character varying(255),
paid boolean NOT NULL DEFAULT false,
amount_usd numeric(18, 2),
created_at TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL,
updated_at TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL,
deleted_at TIMESTAMPTZ,
CONSTRAINT visa_master_payment_orders_branch_id_fkey
FOREIGN KEY (branch_id) REFERENCES branches(id),
CONSTRAINT visa_master_payment_orders_user_id_fkey
FOREIGN KEY (user_id) REFERENCES users(id)
);
CREATE TABLE IF NOT EXISTS activity_logs (
id bigserial PRIMARY KEY,
user_id bigint,
@@ -376,3 +451,292 @@ CREATE TABLE IF NOT EXISTS activity_logs (
CREATE INDEX IF NOT EXISTS idx_activity_logs_user_id ON activity_logs(user_id);
CREATE INDEX IF NOT EXISTS idx_activity_logs_module ON activity_logs(module);
CREATE INDEX IF NOT EXISTS idx_activity_logs_created_at ON activity_logs(created_at);
CREATE TABLE IF NOT EXISTS card_rekwizit_orders (
id bigserial PRIMARY KEY,
unique_id character varying(255),
user_id bigint,
card_type_id bigint NOT NULL,
card_number character varying(255) NOT NULL,
card_month character varying(255) NOT NULL,
card_year character varying(255) NOT NULL,
region character varying(255) NOT NULL,
branch_id bigint NOT NULL,
customer_name character varying(255) NOT NULL,
customer_surname character varying(255) NOT NULL,
customer_patronic_name character varying(255),
born_at date NOT NULL,
phone character varying(255) NOT NULL,
passport_serie character varying(255) NOT NULL,
passport_id character varying(255) NOT NULL,
passport_one text NOT NULL,
passport_two text NOT NULL,
passport_three text NOT NULL,
passport_four text NOT NULL,
status character varying(255) DEFAULT 'pending'::character varying,
notes text,
created_at TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL,
updated_at TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL,
deleted_at TIMESTAMPTZ,
CONSTRAINT card_rekwizit_orders_card_type_id_fkey
FOREIGN KEY (card_type_id) REFERENCES card_types(id),
CONSTRAINT card_rekwizit_orders_branch_id_fkey
FOREIGN KEY (branch_id) REFERENCES branches(id),
CONSTRAINT card_rekwizit_orders_user_id_fkey
FOREIGN KEY (user_id) REFERENCES users(id)
);
CREATE TABLE IF NOT EXISTS card_balances (
id bigserial PRIMARY KEY,
passport_number TEXT NOT NULL,
card_number TEXT NOT NULL,
card_last4 CHAR(4) GENERATED ALWAYS AS (right(card_number, 4)) STORED,
expiry_month SMALLINT NOT NULL,
expiry_year SMALLINT NOT NULL,
expiry_at DATE GENERATED ALWAYS AS
(make_date(expiry_year, expiry_month, 1)) STORED,
balance_amount NUMERIC(18,2),
balance_currency CHAR(3) DEFAULT 'TMT',
status TEXT NOT NULL DEFAULT 'pending',
checked_at TIMESTAMPTZ,
branch_id BIGINT,
created_by BIGINT,
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
deleted_at TIMESTAMPTZ,
CONSTRAINT chk_month CHECK (expiry_month BETWEEN 1 AND 12),
-- CONSTRAINT chk_card CHECK (card_number ~ '^[0-9]{16,19}$'),
CONSTRAINT chk_status CHECK (status IN ('pending','success','failed','expired')),
CONSTRAINT card_balances_branch_id_fkey
FOREIGN KEY (branch_id) REFERENCES branches(id)
);
CREATE TABLE IF NOT EXISTS backups (
id bigserial PRIMARY KEY,
file_name character varying(255) NOT NULL,
size_bytes bigint NOT NULL DEFAULT 0,
status character varying(50) NOT NULL DEFAULT 'pending',
error_message text,
created_by bigint,
created_at TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL,
updated_at TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL,
deleted_at TIMESTAMPTZ,
CONSTRAINT backups_created_by_fkey
FOREIGN KEY (created_by) REFERENCES users(id),
CONSTRAINT backups_status_chk CHECK (status IN ('pending', 'completed', 'failed'))
);
CREATE UNIQUE INDEX IF NOT EXISTS backups_file_name_idx
ON backups (file_name)
WHERE deleted_at IS NULL;
CREATE TABLE IF NOT EXISTS currencies (
id bigserial PRIMARY KEY,
currency_from character varying(10) NOT NULL,
currency_to character varying(10) NOT NULL,
value numeric(18, 8) NOT NULL,
created_by bigint,
updated_by bigint,
created_at TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL,
updated_at TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL,
deleted_at TIMESTAMPTZ,
CONSTRAINT currencies_created_by_fkey FOREIGN KEY (created_by) REFERENCES users(id),
CONSTRAINT currencies_updated_by_fkey FOREIGN KEY (updated_by) REFERENCES users(id)
);
CREATE UNIQUE INDEX IF NOT EXISTS currencies_from_to_idx
ON currencies (currency_from, currency_to)
WHERE deleted_at IS NULL;
-- Single-row, admin-configurable commission fees used on every Töleg
-- (Visa/Master/Sber money-transfer) payout. Visa/Master orders use
-- bank_fee_tmt + gbus_fee_tmt; Sber orders use their own sber_bank_fee_tmt
-- plus a USD-denominated tveb_fee_usd (converted to TMT at payout time via
-- the USD rate) - Sber has no GBÜS fee. max_amount_usd is the single
-- admin-configurable payout cap (converted to TMT at the current rate in
-- /quote and /pay) instead of a per-order value the client supplied when
-- creating the order.
CREATE TABLE IF NOT EXISTS payment_settings (
id smallint PRIMARY KEY DEFAULT 1,
bank_fee_tmt numeric(12, 2) NOT NULL DEFAULT 100,
gbus_fee_tmt numeric(12, 2) NOT NULL DEFAULT 15,
sber_bank_fee_tmt numeric(12, 2) NOT NULL DEFAULT 100,
tveb_fee_usd numeric(12, 2) NOT NULL DEFAULT 18,
max_amount_usd numeric(12, 2) NOT NULL DEFAULT 250,
updated_by bigint,
updated_at TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL,
CONSTRAINT payment_settings_single_row CHECK (id = 1),
CONSTRAINT payment_settings_updated_by_fkey
FOREIGN KEY (updated_by) REFERENCES users(id)
);
INSERT INTO payment_settings (id, bank_fee_tmt, gbus_fee_tmt, sber_bank_fee_tmt, tveb_fee_usd)
VALUES (1, 100, 15, 100, 18)
ON CONFLICT (id) DO NOTHING;
-- Every payout attempt for a visa/master/sber order, as its own row - a full
-- audit trail (including failed gateway attempts) rather than columns on the
-- order itself, so a retry after a failure doesn't erase what the previous
-- attempt did. The Sber-specific columns (exchange_rate_rub, tveb_fee_usd,
-- tveb_fee_tmt) stay null for non-Sber attempts, same as gbus_fee_tmt stays
-- null for Sber ones. gateway_status/gateway_reference/gateway_response
-- track the GBÜS register→callback round trip (pending until the callback
-- verifies the outcome server-to-server).
CREATE TABLE IF NOT EXISTS visa_master_order_payments (
id bigserial PRIMARY KEY,
order_id bigint NOT NULL,
user_id bigint NOT NULL,
payment_period date NOT NULL,
exchange_rate_usd numeric(18, 8) NOT NULL,
exchange_rate_rub numeric(18, 8),
amount_tmt numeric(18, 2) NOT NULL,
bank_fee_tmt numeric(12, 2) NOT NULL,
gbus_fee_tmt numeric(12, 2),
tveb_fee_usd numeric(12, 2),
tveb_fee_tmt numeric(12, 2),
total_amount_tmt numeric(18, 2) NOT NULL,
gateway_status character varying(32) NOT NULL DEFAULT 'pending',
gateway_reference character varying(255),
gateway_response jsonb,
-- orderNumber sent to GBÜS register.do and shown on its hosted payment
-- page ("Номер заказа"): ddMMyyHHmmss in Ashgabat time, e.g.
-- 290926133808 for 29.09.2026 13:38:08. GBÜS rejects a repeated
-- orderNumber per merchant, hence the unique index below.
order_number character varying(32),
created_by bigint,
created_at TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL,
updated_at TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL,
deleted_at TIMESTAMPTZ,
CONSTRAINT visa_master_order_payments_order_id_fkey
FOREIGN KEY (order_id) REFERENCES visa_master_payment_orders(id),
CONSTRAINT visa_master_order_payments_user_id_fkey
FOREIGN KEY (user_id) REFERENCES users(id),
CONSTRAINT visa_master_order_payments_created_by_fkey
FOREIGN KEY (created_by) REFERENCES users(id)
);
CREATE INDEX IF NOT EXISTS visa_master_order_payments_order_id_idx ON visa_master_order_payments (order_id);
CREATE INDEX IF NOT EXISTS visa_master_order_payments_user_id_idx ON visa_master_order_payments (user_id);
CREATE UNIQUE INDEX IF NOT EXISTS visa_master_order_payments_order_number_idx
ON visa_master_order_payments (order_number);
-- Every individual step taken while processing a payout (validated, rate
-- fetched, gateway request sent, gateway response received, order marked
-- paid/attempt recorded) as its own row, so there's a step-by-step,
-- timestamped record of what actually happened for a given order -
-- evidence if a payout is later disputed, independent of (and more
-- granular than) the one summary row in visa_master_order_payments.
CREATE TABLE IF NOT EXISTS visa_master_payment_logs (
id bigserial PRIMARY KEY,
order_id bigint NOT NULL,
step character varying(100) NOT NULL,
detail jsonb,
created_by bigint,
created_at TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL,
CONSTRAINT visa_master_payment_logs_order_id_fkey
FOREIGN KEY (order_id) REFERENCES visa_master_payment_orders(id),
CONSTRAINT visa_master_payment_logs_created_by_fkey
FOREIGN KEY (created_by) REFERENCES users(id)
);
CREATE INDEX IF NOT EXISTS visa_master_payment_logs_order_id_idx ON visa_master_payment_logs (order_id);
-- Admin-editable texts shown to clients around a visa/master/sber payout
-- (e.g. the warning before paying). Clients look a text up by its fixed
-- code, so codes are seeded here and never created/deleted from the admin
-- UI - only name/text/is_active are editable. text is {"tm","ru","en"}.
CREATE TABLE IF NOT EXISTS payment_texts (
id bigserial PRIMARY KEY,
code character varying(64) NOT NULL,
name character varying(255) NOT NULL,
text jsonb NOT NULL DEFAULT '{"tm":"","ru":"","en":""}'::jsonb,
is_active boolean NOT NULL DEFAULT true,
updated_by bigint,
updated_at TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL,
CONSTRAINT payment_texts_code_key UNIQUE (code),
CONSTRAINT payment_texts_updated_by_fkey
FOREIGN KEY (updated_by) REFERENCES users(id) ON DELETE SET NULL
);
INSERT INTO payment_texts (code, name, text) VALUES
('payment_warning_text', 'Visa/Master töleg duýduryş',
'{"tm":"Dogry töleg aýyny saýlamagyňyzy haýyş edýäris","ru":"","en":""}'::jsonb),
('sber_payment_warning', 'Sber töleg duýduryş',
'{"tm":"Sber töleg duýduryş","ru":"","en":""}'::jsonb)
ON CONFLICT (code) DO NOTHING;
-- Indexes for hot filter/join columns: users.role_id and branch_user are
-- queried on every authenticated request (RBAC role and branch resolution),
-- and every order table below is list-filtered by user_id/branch_id.
-- Postgres does not index foreign key columns automatically, so without
-- these every one of those lookups was a full table scan.
CREATE INDEX IF NOT EXISTS idx_users_role_id ON users(role_id);
CREATE INDEX IF NOT EXISTS idx_branch_user_user_id ON branch_user(user_id);
CREATE INDEX IF NOT EXISTS idx_branch_user_branch_id ON branch_user(branch_id);
CREATE INDEX IF NOT EXISTS idx_branches_province_id ON branches(province_id);
CREATE INDEX IF NOT EXISTS idx_cards_user_id ON cards(user_id);
CREATE INDEX IF NOT EXISTS idx_card_orders_user_id ON card_orders(user_id);
CREATE INDEX IF NOT EXISTS idx_card_orders_branch_id ON card_orders(branch_id);
CREATE INDEX IF NOT EXISTS idx_card_pin_orders_user_id ON card_pin_orders(user_id);
CREATE INDEX IF NOT EXISTS idx_card_pin_orders_branch_id ON card_pin_orders(branch_id);
CREATE INDEX IF NOT EXISTS idx_card_rekwizit_orders_user_id ON card_rekwizit_orders(user_id);
CREATE INDEX IF NOT EXISTS idx_card_rekwizit_orders_branch_id ON card_rekwizit_orders(branch_id);
CREATE INDEX IF NOT EXISTS idx_card_balances_branch_id ON card_balances(branch_id);
CREATE INDEX IF NOT EXISTS idx_loan_orders_user_id ON loan_orders(user_id);
CREATE INDEX IF NOT EXISTS idx_loan_orders_branch_id ON loan_orders(branch_id);
CREATE INDEX IF NOT EXISTS idx_loan_paid_off_letters_user_id ON loan_paid_off_letters(user_id);
CREATE INDEX IF NOT EXISTS idx_loan_paid_off_letters_branch_id ON loan_paid_off_letters(branch_id);
CREATE INDEX IF NOT EXISTS idx_visa_master_payment_orders_user_id ON visa_master_payment_orders(user_id);
CREATE INDEX IF NOT EXISTS idx_visa_master_payment_orders_branch_id ON visa_master_payment_orders(branch_id);
CREATE INDEX IF NOT EXISTS idx_backups_created_at ON backups(created_at);
CREATE INDEX IF NOT EXISTS idx_backups_created_by ON backups(created_by);
CREATE INDEX IF NOT EXISTS idx_currencies_from ON currencies(currency_from);
CREATE INDEX IF NOT EXISTS idx_currencies_to ON currencies(currency_to);
CREATE INDEX IF NOT EXISTS idx_currencies_created_by ON currencies(created_by);
CREATE INDEX IF NOT EXISTS idx_currencies_updated_by ON currencies(updated_by);
-- ---------------------------------------------------------------------------
-- RBAC cache wersiýasy: trigger-ler bilen artdyrylýar; app cache-i şony görüp arassalaýar
-- ---------------------------------------------------------------------------
CREATE TABLE IF NOT EXISTS rbac_version (
id int PRIMARY KEY DEFAULT 1 CHECK (id = 1),
version bigint NOT NULL DEFAULT 0
);
INSERT INTO rbac_version (id, version) VALUES (1, 0) ON CONFLICT (id) DO NOTHING;
CREATE OR REPLACE FUNCTION rbac_bump_version() RETURNS trigger AS $$
BEGIN
UPDATE rbac_version SET version = version + 1 WHERE id = 1;
RETURN NULL;
END;
$$ LANGUAGE plpgsql;
CREATE OR REPLACE TRIGGER rbac_bump_roles
AFTER INSERT OR UPDATE OR DELETE ON roles
FOR EACH STATEMENT EXECUTE FUNCTION rbac_bump_version();
CREATE OR REPLACE TRIGGER rbac_bump_role_permissions
AFTER INSERT OR UPDATE OR DELETE ON role_permissions
FOR EACH STATEMENT EXECUTE FUNCTION rbac_bump_version();
CREATE OR REPLACE TRIGGER rbac_bump_users
AFTER UPDATE OF role_id, deleted_at OR DELETE ON users
FOR EACH STATEMENT EXECUTE FUNCTION rbac_bump_version();
CREATE OR REPLACE TRIGGER rbac_bump_branch_user
AFTER INSERT OR UPDATE OR DELETE ON branch_user
FOR EACH STATEMENT EXECUTE FUNCTION rbac_bump_version();
CREATE OR REPLACE TRIGGER rbac_bump_branches
AFTER UPDATE OF deleted_at OR DELETE ON branches
FOR EACH STATEMENT EXECUTE FUNCTION rbac_bump_version();

View File

@@ -0,0 +1 @@
DROP INDEX IF EXISTS idx_visa_master_order_payments_status_id;

View File

@@ -0,0 +1,6 @@
-- payment-history lists newest-first (ORDER BY p.id DESC) and is commonly
-- filtered to one gateway_status; without this, a rare status (e.g.
-- pending) means walking the whole primary key backwards to fill a page.
CREATE INDEX IF NOT EXISTS idx_visa_master_order_payments_status_id
ON visa_master_order_payments (gateway_status, id DESC)
WHERE deleted_at IS NULL;

View File

@@ -0,0 +1 @@
DROP INDEX IF EXISTS visa_master_payment_logs_order_step_idx;

View File

@@ -0,0 +1,5 @@
-- payment-history reads each attempt's register/callback log rows
-- (formUrl, returnUrl, first callback) by order and step; without this
-- every row of a page scans all of its order's logs.
CREATE INDEX IF NOT EXISTS visa_master_payment_logs_order_step_idx
ON visa_master_payment_logs (order_id, step);

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

File diff suppressed because it is too large Load Diff

View File

@@ -1,4 +1,33 @@
FROM quay.io/minio/minio
# MinIO no longer publishes images (quay.io/minio/minio and minio/minio are not
# pullable), so the server binary comes from minio.deb next to this file.
# Both stages use golang:1.26.4-alpine, which is already in the offline bundle,
# so this builds without network.
FROM golang:1.26.4-alpine AS extract
WORKDIR /tmp/deb
COPY minio.deb .
# A .deb is an ar archive and busybox here has no `ar`, so read it by hand:
# 8-byte magic, then per member a 60-byte header (name at 1-16, size at 49-58),
# the data, and one pad byte when the size is odd.
RUN set -e; \
f=minio.deb; off=8; total=$(stat -c %s "$f"); \
while [ "$off" -lt "$total" ]; do \
name=$(tail -c +$((off + 1)) "$f" | head -c 16 | tr -d ' /'); \
size=$(tail -c +$((off + 49)) "$f" | head -c 10 | tr -d ' '); \
if [ "$name" = "data.tar.gz" ]; then \
tail -c +$((off + 61)) "$f" | head -c "$size" | tar -xzf - ./usr/local/bin/minio; \
break; \
fi; \
off=$((off + 60 + size + size % 2)); \
done; \
./usr/local/bin/minio --version
FROM golang:1.26.4-alpine
COPY --from=extract /tmp/deb/usr/local/bin/minio /usr/bin/minio
RUN mkdir /storage
@@ -8,4 +37,4 @@ ENV MINIO_VOLUMES="/storage"
EXPOSE 9000
EXPOSE 9093
CMD ["minio", "server", "/storage", "--console-address", ":9093"]
CMD ["minio", "server", "/storage", "--console-address", ":9093"]

View File

@@ -0,0 +1,74 @@
#!/usr/bin/env bash
set -euo pipefail
# Native MinIO for Ubuntu (no Docker). Binds only to 127.0.0.1.
#
# Fresh install (keeps existing data if present):
# sudo bash install-minio-ubuntu.sh /path/to/minio.deb
#
# Wipe data + config, then install:
# sudo bash install-minio-ubuntu.sh --wipe /path/to/minio.deb
WIPE=0
DEB_PATH=""
for arg in "$@"; do
case "$arg" in
--wipe) WIPE=1 ;;
*) DEB_PATH="$arg" ;;
esac
done
DEB_PATH="${DEB_PATH:-./minio.deb}"
ENV_SRC="$(cd "$(dirname "$0")" && pwd)/minio.env"
if [[ "$(id -u)" -ne 0 ]]; then
echo "run as root: sudo bash $0 [--wipe] $DEB_PATH" >&2
exit 1
fi
if [[ ! -f "$DEB_PATH" ]]; then
echo "deb not found: $DEB_PATH" >&2
exit 1
fi
if [[ ! -f "$ENV_SRC" ]]; then
echo "env file not found: $ENV_SRC" >&2
exit 1
fi
systemctl stop minio 2>/dev/null || true
systemctl reset-failed minio 2>/dev/null || true
pkill -x minio 2>/dev/null || true
sleep 1
if [[ "$WIPE" -eq 1 ]]; then
echo "wiping /data/minio and /etc/default/minio"
rm -rf /data/minio
rm -f /etc/default/minio
fi
port_busy() {
local port="$1"
ss -H -tln | awk '{print $4}' | grep -E ":${port}$" >/dev/null
}
for port in 9000 9001; do
if port_busy "$port"; then
echo "port $port is already in use:" >&2
ss -tlnp | grep -E ":${port}\\b" >&2 || true
exit 1
fi
done
id minio-user >/dev/null 2>&1 || useradd --system --home-dir /data/minio --shell /sbin/nologin minio-user
mkdir -p /data/minio
chown -R minio-user:minio-user /data/minio
cp "$ENV_SRC" /etc/default/minio
chmod 600 /etc/default/minio
dpkg -i "$DEB_PATH"
systemctl daemon-reload
systemctl enable minio
systemctl start minio
systemctl --no-pager --full status minio

6
deployment/minio.env Normal file
View File

@@ -0,0 +1,6 @@
MINIO_ROOT_USER=TX3H1H6XTS288QW07S8Z
MINIO_ROOT_PASSWORD=FWWspiI4n4LMknnxYCmzFTCY1ObkGiuaU9SNwOCU
MINIO_VOLUMES=/data/minio
MINIO_ADDRESS=127.0.0.1:9000
MINIO_CONSOLE_ADDRESS=127.0.0.1:9001
MINIO_OPTS=

View File

@@ -1,5 +1,6 @@
services:
main-db:
# Keep in sync with the runtime stage in Dockerfile: pg_dump must match this major version.
image: postgres:14.1-alpine
container_name: "main-db"
restart: always
@@ -11,38 +12,51 @@ services:
- '5424:5432'
volumes:
- main-db-storage:/var/lib/postgresql/data
healthcheck:
test: ["CMD-SHELL", "pg_isready -U bank_admin -d bank_db"]
interval: 5s
timeout: 5s
retries: 20
networks:
- myNetwork
main-server:
image: main-app
image: main-app:latest
restart: unless-stopped
container_name: "main-app"
build:
context: .
dockerfile: Dockerfile
environment:
- TZ=Asia/Ashgabat
ports:
- "5050:5050"
volumes:
# Inside this network the config must point at main-db:5432 and main-minio:9000.
- ./config.yaml:/app/config.yaml:ro
- ./public:/app/public
- ./logs:/app/logs
depends_on:
- main-db
- main-minio
main-db:
condition: service_healthy
main-minio:
condition: service_started
networks:
- myNetwork
main-minio:
image: main-minio:latest
container_name: "main-minio"
build:
context: .
dockerfile: deployment/Dockerfile.minio
context: ./deployment
dockerfile: Dockerfile.minio
restart: unless-stopped
environment:
- MINIO_ROOT_USER=TX3H1H6XTS288QW07S8Z
- MINIO_ROOT_PASSWORD=FWWspiI4n4LMknnxYCmzFTCY1ObkGiuaU9SNwOCU
ports:
- '9003:9000'
- '9093:9093'
- '127.0.0.1:9003:9000'
- '127.0.0.1:9093:9093'
volumes:
- main-minio-storage:/storage
networks:
@@ -54,4 +68,4 @@ volumes:
networks:
myNetwork:
driver: bridge
driver: bridge

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -13,20 +13,24 @@ var swaggerTagOrder = []struct {
{Name: "branch-users", Description: "Branch users"},
{Name: "user", Description: "Users"},
{Name: "role", Description: "Roles"},
{Name: "role-users", Description: "Role users"},
{Name: "permission", Description: "Permissions"},
{Name: "permission-users", Description: "Permission users"},
{Name: "payment-card", Description: "Payment cards"},
{Name: "reason-card", Description: "Reason cards"},
{Name: "cards", Description: "Cards"},
{Name: "card-balances", Description: "Card balances"},
{Name: "card-orders", Description: "Card orders"},
{Name: "card-pin-orders", Description: "Card pin orders"},
{Name: "card-rekwizit-orders", Description: "Card rekwizit (card details) orders"},
{Name: "loan-type", Description: "Loan types"},
{Name: "loan-document", Description: "Loan required documents"},
{Name: "loan-orders", Description: "Loan orders"},
{Name: "loans-repayment", Description: "Loan repayments"},
{Name: "loan-paid-off-letters", Description: "Loan paid-off letters"},
{Name: "file-upload", Description: "File upload"},
{Name: "backups", Description: "Database SQL backups"},
{Name: "currencies", Description: "Currency exchange rates"},
{Name: "payment-texts", Description: "Payment warning texts (Visa/Master, Sber)"},
{Name: "dashboard", Description: "Admin dashboard overview"},
}
func init() {

BIN
internal/.DS_Store vendored

Binary file not shown.

View File

@@ -0,0 +1,928 @@
package db
import (
"context"
"encoding/json"
"fmt"
"math"
"sort"
"strings"
"time"
"online-back/internal/analytics"
"online-back/pkg/client/postgresql"
"online-back/pkg/logging"
)
type repository struct {
client postgresql.Client
logger *logging.Logger
}
func NewRepository(client postgresql.Client, logger *logging.Logger) analytics.Repository {
return &repository{client: client, logger: logger}
}
// orderTables maps each order type to its table. Every table has branch_id,
// region, status, created_at, updated_at and deleted_at, so they can be
// unioned into one "orders" set.
var orderTables = []struct{ typ, table string }{
{analytics.OrderLoan, "loan_orders"},
{analytics.OrderLoanLetter, "loan_paid_off_letters"},
{analytics.OrderCard, "card_orders"},
{analytics.OrderCardPin, "card_pin_orders"},
{analytics.OrderCardRekwizit, "card_rekwizit_orders"},
{analytics.OrderVisaMaster, "visa_master_payment_orders"},
}
// statusBucketSQL folds a free-text status column into open / approved /
// rejected / other. NULL and empty mean a fresh order nobody has handled.
func statusBucketSQL(col string) string {
return fmt.Sprintf(`
CASE
WHEN lower(coalesce(%[1]s, '')) IN ('', 'pending', 'new', 'registered', 'review', 'processing', 'in_process', 'in-process') THEN 'open'
WHEN lower(%[1]s) IN ('approved', 'satisfied', 'completed', 'paid', 'success', 'done', 'accepted') THEN 'approved'
WHEN lower(%[1]s) IN ('rejected', 'cancelled', 'canceled', 'declined', 'failed') THEN 'rejected'
ELSE 'other'
END`, col)
}
// sqlArgs collects positional arguments and hands out their $n placeholders.
type sqlArgs []interface{}
func (a *sqlArgs) add(v interface{}) string {
*a = append(*a, v)
return fmt.Sprintf("$%d", len(*a))
}
// rangeCond returns " AND <col> >= $x AND <col> < $y".
func rangeCond(args *sqlArgs, col string, f analytics.Filter) string {
return fmt.Sprintf(" AND %s >= %s AND %s < %s", col, args.add(f.From), col, args.add(f.To))
}
// branchCond returns " AND <col> = ANY($x)" for branch-scope callers.
func branchCond(args *sqlArgs, col string, f analytics.Filter) string {
if len(f.BranchIds) == 0 {
return ""
}
return fmt.Sprintf(" AND %s = ANY(%s)", col, args.add(f.BranchIds))
}
// ordersUnionSQL unions the caller's visible order tables into rows of
// (type, branch_id, region, bucket, created_at, updated_at). withRange
// limits rows to the filter's date range.
func ordersUnionSQL(args *sqlArgs, f analytics.Filter, withRange bool) string {
var tables []string
for _, t := range orderTables {
if containsString(f.Types, t.typ) {
tables = append(tables, t.typ, t.table)
}
}
if len(tables) == 0 {
// Keep the column shape so callers' queries still run and return
// nothing; add no args, since no placeholder would use them.
return `SELECT ''::text AS type, 0::bigint AS branch_id, ''::text AS region, ''::text AS bucket, now()::timestamp AS created_at, now()::timestamp AS updated_at WHERE false`
}
cond := branchCond(args, "branch_id", f)
if withRange {
cond += rangeCond(args, "created_at", f)
}
parts := make([]string, 0, len(tables)/2)
for i := 0; i < len(tables); i += 2 {
parts = append(parts, fmt.Sprintf(
`SELECT '%s' AS type, branch_id, coalesce(region, '') AS region, %s AS bucket, created_at, updated_at FROM %s WHERE deleted_at IS NULL%s`,
tables[i], statusBucketSQL("status"), tables[i+1], cond))
}
return strings.Join(parts, "\nUNION ALL\n")
}
func round2(v float64) float64 {
return math.Round(v*100) / 100
}
func pct(part, total int64) float64 {
if total == 0 {
return 0
}
return round2(float64(part) / float64(total) * 100)
}
func ratePtr(part, total int64) *float64 {
if total == 0 {
return nil
}
v := pct(part, total)
return &v
}
func roundPtr(v *float64) *float64 {
if v == nil {
return nil
}
r := round2(*v)
return &r
}
// withPercent fills Percent on counts relative to their sum.
func withPercent(items []analytics.CountDTO) []analytics.CountDTO {
var total int64
for _, it := range items {
total += it.Count
}
for i := range items {
items[i].Percent = pct(items[i].Count, total)
}
return items
}
func (r *repository) countsByKey(ctx context.Context, query string, args ...interface{}) ([]analytics.CountDTO, error) {
rows, err := r.client.Query(ctx, query, args...)
if err != nil {
return nil, err
}
defer rows.Close()
items := []analytics.CountDTO{}
for rows.Next() {
var it analytics.CountDTO
if err := rows.Scan(&it.Key, &it.Count); err != nil {
return nil, err
}
items = append(items, it)
}
if err := rows.Err(); err != nil {
return nil, err
}
return withPercent(items), nil
}
// ---------------------------------------------------------------- finance
// paymentsFromSQL is the FROM/WHERE shared by payment queries: payments in
// range, joined to their order for branch scoping.
func paymentsFromSQL(args *sqlArgs, f analytics.Filter) string {
return `
FROM visa_master_order_payments p
JOIN visa_master_payment_orders o ON o.id = p.order_id AND o.deleted_at IS NULL
WHERE p.deleted_at IS NULL` + rangeCond(args, "p.created_at", f) + branchCond(args, "o.branch_id", f)
}
func (r *repository) Finance(ctx context.Context, f analytics.Filter) (analytics.FinanceDTO, error) {
out := analytics.FinanceDTO{Gateway: []analytics.CountDTO{}, Monthly: []analytics.FinanceMonthDTO{}}
var args sqlArgs
query := `
SELECT
COUNT(*),
COALESCE(SUM(p.amount_tmt), 0)::float8,
COALESCE(SUM(p.bank_fee_tmt), 0)::float8,
COALESCE(SUM(p.gbus_fee_tmt), 0)::float8,
COALESCE(SUM(p.tveb_fee_tmt), 0)::float8,
COALESCE(SUM(p.total_amount_tmt), 0)::float8` + paymentsFromSQL(&args, f) + ` AND p.gateway_status = 'success'`
pt := &out.Payments
if err := r.client.QueryRow(ctx, query, args...).Scan(
&pt.Count, &pt.AmountTmt, &pt.BankFeeTmt, &pt.GbusFeeTmt, &pt.TvebFeeTmt, &pt.TotalTmt,
); err != nil {
return out, err
}
pt.AmountTmt, pt.BankFeeTmt = round2(pt.AmountTmt), round2(pt.BankFeeTmt)
pt.GbusFeeTmt, pt.TvebFeeTmt, pt.TotalTmt = round2(pt.GbusFeeTmt), round2(pt.TvebFeeTmt), round2(pt.TotalTmt)
if pt.Count > 0 {
pt.AvgTotalTmt = round2(pt.TotalTmt / float64(pt.Count))
}
args = nil
gateway, err := r.countsByKey(ctx, `SELECT p.gateway_status, COUNT(*)`+paymentsFromSQL(&args, f)+` GROUP BY 1 ORDER BY 2 DESC`, args...)
if err != nil {
return out, err
}
out.Gateway = gateway
var success, failed int64
for _, g := range gateway {
switch g.Key {
case "success":
success = g.Count
case "failed":
failed = g.Count
}
}
out.GatewaySuccessRate = ratePtr(success, success+failed)
monthly, err := r.financeMonthly(ctx, f)
if err != nil {
return out, err
}
out.Monthly = monthly
loanRequested, err := r.loanRequested(ctx, f)
if err != nil {
return out, err
}
out.LoanRequested = loanRequested
return out, nil
}
func (r *repository) financeMonthly(ctx context.Context, f analytics.Filter) ([]analytics.FinanceMonthDTO, error) {
var args sqlArgs
query := `
SELECT to_char(date_trunc('month', p.created_at), 'YYYY-MM'), COUNT(*),
COALESCE(SUM(p.total_amount_tmt), 0)::float8, COALESCE(SUM(p.bank_fee_tmt), 0)::float8` +
paymentsFromSQL(&args, f) + ` AND p.gateway_status = 'success' GROUP BY 1`
rows, err := r.client.Query(ctx, query, args...)
if err != nil {
return nil, err
}
defer rows.Close()
byMonth := map[string]analytics.FinanceMonthDTO{}
for rows.Next() {
var m analytics.FinanceMonthDTO
if err := rows.Scan(&m.Month, &m.Count, &m.TotalTmt, &m.BankFeeTmt); err != nil {
return nil, err
}
m.TotalTmt, m.BankFeeTmt = round2(m.TotalTmt), round2(m.BankFeeTmt)
byMonth[m.Month] = m
}
if err := rows.Err(); err != nil {
return nil, err
}
// One point per month in range, zero-filled, so the chart has no gaps.
out := []analytics.FinanceMonthDTO{}
last := f.To.Add(-time.Nanosecond)
for m := time.Date(f.From.Year(), f.From.Month(), 1, 0, 0, 0, 0, time.UTC); !m.After(last); m = m.AddDate(0, 1, 0) {
key := m.Format("2006-01")
point, ok := byMonth[key]
if !ok {
point = analytics.FinanceMonthDTO{Month: key}
}
out = append(out, point)
}
return out, nil
}
// loanAmountSQL parses the free-text loan_amount ("30 000", "30,000.50")
// into numeric, NULL when it is not a plain number after stripping.
const loanAmountSQL = `
CASE WHEN regexp_replace(coalesce(loan_amount, ''), '[^0-9.]', '', 'g') ~ '^[0-9]+(\.[0-9]+)?$'
THEN regexp_replace(loan_amount, '[^0-9.]', '', 'g')::numeric
END`
func (r *repository) loanRequested(ctx context.Context, f analytics.Filter) (analytics.LoanRequestedDTO, error) {
var out analytics.LoanRequestedDTO
var args sqlArgs
query := fmt.Sprintf(`
SELECT
COUNT(amt),
COALESCE(SUM(amt), 0)::float8,
COUNT(*) FILTER (WHERE amt IS NULL AND trim(coalesce(loan_amount, '')) <> '')
FROM (
SELECT loan_amount, %s AS amt
FROM loan_orders
WHERE deleted_at IS NULL%s%s
) x`, loanAmountSQL, rangeCond(&args, "created_at", f), branchCond(&args, "branch_id", f))
if err := r.client.QueryRow(ctx, query, args...).Scan(&out.Count, &out.TotalTmt, &out.Unparsed); err != nil {
return out, err
}
out.TotalTmt = round2(out.TotalTmt)
if out.Count > 0 {
out.AvgTmt = round2(out.TotalTmt / float64(out.Count))
}
return out, nil
}
// ---------------------------------------------------------------- backlog
func (r *repository) Backlog(ctx context.Context, f analytics.Filter) (analytics.BacklogResponseDTO, error) {
out := analytics.BacklogResponseDTO{Items: []analytics.BacklogDTO{}}
// The open queue is current state, so it ignores the date range; only
// the "finished" figures are limited to orders created in range.
var args sqlArgs
union := ordersUnionSQL(&args, f, false)
from, to := args.add(f.From), args.add(f.To)
query := fmt.Sprintf(`
WITH o AS (%s), now_utc AS (SELECT (now() AT TIME ZONE 'UTC') AS ts)
SELECT
o.type,
COUNT(*) FILTER (WHERE bucket = 'open'),
COUNT(*) FILTER (WHERE bucket = 'open' AND created_at > n.ts - interval '1 day'),
COUNT(*) FILTER (WHERE bucket = 'open' AND created_at <= n.ts - interval '1 day' AND created_at > n.ts - interval '3 days'),
COUNT(*) FILTER (WHERE bucket = 'open' AND created_at <= n.ts - interval '3 days'),
MIN(created_at) FILTER (WHERE bucket = 'open'),
(EXTRACT(EPOCH FROM n.ts - MIN(created_at) FILTER (WHERE bucket = 'open')) / 86400)::float8,
COUNT(*) FILTER (WHERE bucket <> 'open' AND created_at >= %[2]s AND created_at < %[3]s),
(AVG(EXTRACT(EPOCH FROM updated_at - created_at) / 3600)
FILTER (WHERE bucket <> 'open' AND created_at >= %[2]s AND created_at < %[3]s))::float8
FROM o CROSS JOIN now_utc n
GROUP BY o.type, n.ts`, union, from, to)
rows, err := r.client.Query(ctx, query, args...)
if err != nil {
return out, err
}
byType := map[string]analytics.BacklogDTO{}
for rows.Next() {
var it analytics.BacklogDTO
var oldest *time.Time
if err := rows.Scan(&it.Type, &it.Open, &it.Under1Day, &it.From1To3Days, &it.Over3Days,
&oldest, &it.OldestOpenDays, &it.Finished, &it.AvgProcessHours); err != nil {
rows.Close()
return out, err
}
if oldest != nil {
s := oldest.UTC().Format(time.RFC3339)
it.OldestOpenAt = &s
}
it.OldestOpenDays = roundPtr(it.OldestOpenDays)
it.AvgProcessHours = roundPtr(it.AvgProcessHours)
byType[it.Type] = it
}
rows.Close()
if err := rows.Err(); err != nil {
return out, err
}
// Stable order, zero rows included, so the UI table never reshuffles.
for _, t := range orderTables {
if !containsString(f.Types, t.typ) {
continue
}
it, ok := byType[t.typ]
if !ok {
it = analytics.BacklogDTO{Type: t.typ}
}
out.Items = append(out.Items, it)
}
if containsString(f.Types, analytics.OrderVisaMaster) {
timing, err := r.visaMasterTiming(ctx, f)
if err != nil {
return out, err
}
out.VisaMasterTiming = timing
}
return out, nil
}
func (r *repository) visaMasterTiming(ctx context.Context, f analytics.Filter) (analytics.VisaMasterTimingDTO, error) {
var out analytics.VisaMasterTimingDTO
var args sqlArgs
query := `
WITH t AS (
SELECT l.order_id,
MIN(l.created_at) AS started,
MAX(l.created_at) FILTER (WHERE l.step = 'payment_finalized') AS finished
FROM visa_master_payment_logs l
JOIN visa_master_payment_orders o ON o.id = l.order_id AND o.deleted_at IS NULL
WHERE true` + rangeCond(&args, "l.created_at", f) + branchCond(&args, "o.branch_id", f) + `
GROUP BY l.order_id
), m AS (
SELECT EXTRACT(EPOCH FROM finished - started) / 60 AS minutes FROM t WHERE finished IS NOT NULL
)
SELECT COUNT(*), AVG(minutes)::float8,
(percentile_cont(0.9) WITHIN GROUP (ORDER BY minutes))::float8, MAX(minutes)::float8
FROM m`
if err := r.client.QueryRow(ctx, query, args...).Scan(&out.Orders, &out.AvgMinutes, &out.P90Minutes, &out.MaxMinutes); err != nil {
return out, err
}
out.AvgMinutes, out.P90Minutes, out.MaxMinutes = roundPtr(out.AvgMinutes), roundPtr(out.P90Minutes), roundPtr(out.MaxMinutes)
return out, nil
}
func containsString(list []string, v string) bool {
for _, s := range list {
if s == v {
return true
}
}
return false
}
// ---------------------------------------------------------------- branches
func (r *repository) Branches(ctx context.Context, f analytics.Filter) (analytics.BranchesDTO, error) {
out := analytics.BranchesDTO{Branches: []analytics.BranchStatDTO{}, Regions: []analytics.CountDTO{}}
var bargs sqlArgs
branchQuery := `SELECT id, name, region FROM branches WHERE deleted_at IS NULL` + branchCond(&bargs, "id", f) + ` ORDER BY id`
rows, err := r.client.Query(ctx, branchQuery, bargs...)
if err != nil {
return out, err
}
byID := map[int64]*analytics.BranchStatDTO{}
var order []int64
for rows.Next() {
var b analytics.BranchStatDTO
var name []byte
if err := rows.Scan(&b.BranchId, &name, &b.Region); err != nil {
rows.Close()
return out, err
}
b.Name = json.RawMessage(name)
b.Orders = map[string]int64{}
byID[b.BranchId] = &b
order = append(order, b.BranchId)
}
rows.Close()
if err := rows.Err(); err != nil {
return out, err
}
var args sqlArgs
query := fmt.Sprintf(`
WITH o AS (%s)
SELECT branch_id, type, COUNT(*),
COUNT(*) FILTER (WHERE bucket = 'open'),
COUNT(*) FILTER (WHERE bucket = 'approved'),
COUNT(*) FILTER (WHERE bucket = 'rejected'),
COUNT(*) FILTER (WHERE bucket <> 'open'),
COALESCE(SUM(EXTRACT(EPOCH FROM updated_at - created_at) / 3600) FILTER (WHERE bucket <> 'open'), 0)::float8
FROM o
GROUP BY branch_id, type`, ordersUnionSQL(&args, f, true))
rows, err = r.client.Query(ctx, query, args...)
if err != nil {
return out, err
}
finished := map[int64]int64{}
hours := map[int64]float64{}
for rows.Next() {
var branchID, total, open, approved, rejected, fin int64
var typ string
var h float64
if err := rows.Scan(&branchID, &typ, &total, &open, &approved, &rejected, &fin, &h); err != nil {
rows.Close()
return out, err
}
b, ok := byID[branchID]
if !ok {
continue // order on a deleted branch
}
b.Orders[typ] = total
b.Total += total
b.Open += open
b.Approved += approved
b.Rejected += rejected
finished[branchID] += fin
hours[branchID] += h
}
rows.Close()
if err := rows.Err(); err != nil {
return out, err
}
for _, id := range order {
b := byID[id]
b.ApprovalRate = ratePtr(b.Approved, b.Approved+b.Rejected)
if finished[id] > 0 {
avg := round2(hours[id] / float64(finished[id]))
b.AvgProcessHours = &avg
}
out.Branches = append(out.Branches, *b)
}
sort.SliceStable(out.Branches, func(i, j int) bool { return out.Branches[i].Total > out.Branches[j].Total })
args = nil
regions, err := r.countsByKey(ctx, fmt.Sprintf(`
WITH o AS (%s)
SELECT CASE WHEN region = '' THEN 'unknown' ELSE region END, COUNT(*) FROM o GROUP BY 1 ORDER BY 2 DESC`,
ordersUnionSQL(&args, f, true)), args...)
if err != nil {
return out, err
}
out.Regions = regions
return out, nil
}
// ---------------------------------------------------------------- products
func (r *repository) Products(ctx context.Context, f analytics.Filter) (analytics.ProductsDTO, error) {
out := analytics.ProductsDTO{
LoanSources: []analytics.CountDTO{},
LoanTypes: []analytics.NamedCountDTO{},
CardTypes: []analytics.NamedCountDTO{},
CardOrderPay: []analytics.CountDTO{},
}
if containsString(f.Types, analytics.OrderLoan) {
var args sqlArgs
sources, err := r.countsByKey(ctx, `
SELECT coalesce(nullif(trim(source), ''), 'web'), COUNT(*)
FROM loan_orders WHERE deleted_at IS NULL`+rangeCond(&args, "created_at", f)+branchCond(&args, "branch_id", f)+`
GROUP BY 1 ORDER BY 2 DESC`, args...)
if err != nil {
return out, err
}
out.LoanSources = sources
args = nil
loanTypes, err := r.namedCounts(ctx, `
SELECT t.id, t.name, COUNT(o.id)
FROM loan_types t
LEFT JOIN loan_orders o ON o.loan_type = t.id AND o.deleted_at IS NULL`+
rangeCond(&args, "o.created_at", f)+branchCond(&args, "o.branch_id", f)+`
WHERE t.deleted_at IS NULL
GROUP BY t.id ORDER BY 3 DESC, t.id`, args...)
if err != nil {
return out, err
}
out.LoanTypes = loanTypes
}
if containsString(f.Types, analytics.OrderCard) {
var args sqlArgs
cardTypes, err := r.namedCounts(ctx, `
SELECT t.id, t.name, COUNT(o.id)
FROM card_types t
LEFT JOIN card_orders o ON o.card_type_id = t.id AND o.deleted_at IS NULL`+
rangeCond(&args, "o.created_at", f)+branchCond(&args, "o.branch_id", f)+`
WHERE t.deleted_at IS NULL
GROUP BY t.id ORDER BY 3 DESC, t.id`, args...)
if err != nil {
return out, err
}
out.CardTypes = cardTypes
args = nil
pay, err := r.countsByKey(ctx, `
SELECT CASE WHEN paid THEN 'paid' ELSE 'unpaid' END, COUNT(*)
FROM card_orders WHERE deleted_at IS NULL`+rangeCond(&args, "created_at", f)+branchCond(&args, "branch_id", f)+`
GROUP BY 1 ORDER BY 1`, args...)
if err != nil {
return out, err
}
out.CardOrderPay = pay
}
return out, nil
}
func (r *repository) namedCounts(ctx context.Context, query string, args ...interface{}) ([]analytics.NamedCountDTO, error) {
rows, err := r.client.Query(ctx, query, args...)
if err != nil {
return nil, err
}
defer rows.Close()
items := []analytics.NamedCountDTO{}
var total int64
for rows.Next() {
var it analytics.NamedCountDTO
var name []byte
if err := rows.Scan(&it.Id, &name, &it.Count); err != nil {
return nil, err
}
it.Name = json.RawMessage(name)
total += it.Count
items = append(items, it)
}
if err := rows.Err(); err != nil {
return nil, err
}
for i := range items {
items[i].Percent = pct(items[i].Count, total)
}
return items, nil
}
// ---------------------------------------------------------------- customers
var ageGroupOrder = []string{"under25", "25-34", "35-44", "45-54", "55+", "unknown"}
const ageGroupSQL = `
CASE
WHEN born_at IS NULL THEN 'unknown'
WHEN date_part('year', age(born_at)) < 25 THEN 'under25'
WHEN date_part('year', age(born_at)) < 35 THEN '25-34'
WHEN date_part('year', age(born_at)) < 45 THEN '35-44'
WHEN date_part('year', age(born_at)) < 55 THEN '45-54'
ELSE '55+'
END`
const guarantorsSQL = `
CASE
WHEN trim(coalesce(guarantor_2_name, '')) <> '' THEN 'two'
WHEN trim(coalesce(guarantor_name, '')) <> '' THEN 'one'
ELSE 'none'
END`
// Older rows spell some education values differently from the form's options
// (higher/secondary vs high/school); fold them so each level is one group.
const educationSQL = `
CASE lower(trim(coalesce(education, '')))
WHEN '' THEN 'unknown'
WHEN 'higher' THEN 'high'
WHEN 'secondary' THEN 'school'
ELSE lower(trim(education))
END`
// Form options are upper case (MARRIED, SINGLE, ...); older rows are lower case.
const marriageSQL = `coalesce(nullif(upper(trim(marriage_status)), ''), 'unknown')`
func (r *repository) Customers(ctx context.Context, f analytics.Filter) (analytics.CustomersDTO, error) {
out := analytics.CustomersDTO{
AgeGroups: []analytics.ApprovalCountDTO{},
Education: []analytics.ApprovalCountDTO{},
MarriageStatus: []analytics.ApprovalCountDTO{},
Guarantors: []analytics.ApprovalCountDTO{},
}
if !containsString(f.Types, analytics.OrderLoan) {
return out, nil
}
var err error
if out.AgeGroups, err = r.loanApprovalBy(ctx, f, ageGroupSQL); err != nil {
return out, err
}
sortByOrder(out.AgeGroups, ageGroupOrder)
if out.Education, err = r.loanApprovalBy(ctx, f, educationSQL); err != nil {
return out, err
}
if out.MarriageStatus, err = r.loanApprovalBy(ctx, f, marriageSQL); err != nil {
return out, err
}
if out.Guarantors, err = r.loanApprovalBy(ctx, f, guarantorsSQL); err != nil {
return out, err
}
sortByOrder(out.Guarantors, []string{"none", "one", "two"})
// Every order falls in exactly one age group, so its totals are the overall ones.
for _, g := range out.AgeGroups {
out.Total += g.Count
out.Approved += g.Approved
out.Rejected += g.Rejected
out.Open += g.Open
}
out.ApprovalRate = ratePtr(out.Approved, out.Approved+out.Rejected)
return out, nil
}
// loanApprovalBy groups loan orders in range by keyExpr with approved,
// rejected and open counts per group.
func (r *repository) loanApprovalBy(ctx context.Context, f analytics.Filter, keyExpr string) ([]analytics.ApprovalCountDTO, error) {
var args sqlArgs
query := fmt.Sprintf(`
SELECT k, COUNT(*), COUNT(*) FILTER (WHERE bucket = 'approved'), COUNT(*) FILTER (WHERE bucket = 'rejected'),
COUNT(*) FILTER (WHERE bucket = 'open')
FROM (
SELECT %s AS k, %s AS bucket
FROM loan_orders
WHERE deleted_at IS NULL%s%s
) x
GROUP BY k ORDER BY 2 DESC, k`,
keyExpr, statusBucketSQL("status"), rangeCond(&args, "created_at", f), branchCond(&args, "branch_id", f))
rows, err := r.client.Query(ctx, query, args...)
if err != nil {
return nil, err
}
defer rows.Close()
items := []analytics.ApprovalCountDTO{}
var total int64
for rows.Next() {
var it analytics.ApprovalCountDTO
if err := rows.Scan(&it.Key, &it.Count, &it.Approved, &it.Rejected, &it.Open); err != nil {
return nil, err
}
it.ApprovalRate = ratePtr(it.Approved, it.Approved+it.Rejected)
total += it.Count
items = append(items, it)
}
if err := rows.Err(); err != nil {
return nil, err
}
for i := range items {
items[i].Percent = pct(items[i].Count, total)
}
return items, nil
}
func sortByOrder(items []analytics.ApprovalCountDTO, order []string) {
rank := make(map[string]int, len(order))
for i, k := range order {
rank[k] = i
}
sort.SliceStable(items, func(i, j int) bool { return rank[items[i].Key] < rank[items[j].Key] })
}
// ---------------------------------------------------------------- system
func (r *repository) System(ctx context.Context, f analytics.Filter, opts analytics.SystemOptions) (analytics.SystemDTO, error) {
out := analytics.SystemDTO{
Operators: []analytics.OperatorActivityDTO{},
ModuleErrors: []analytics.ModuleErrorDTO{},
PeakHours: []analytics.HeatmapCellDTO{},
}
if opts.Registration {
reg, err := r.registrationFunnel(ctx, f)
if err != nil {
return out, err
}
out.Registration = &reg
}
if opts.Operators {
operators, err := r.operators(ctx, f, opts.OperatorLimit)
if err != nil {
return out, err
}
out.Operators = operators
moduleErrors, err := r.moduleErrors(ctx, f)
if err != nil {
return out, err
}
out.ModuleErrors = moduleErrors
}
peak, err := r.peakHours(ctx, f)
if err != nil {
return out, err
}
out.PeakHours = peak
if opts.CardBalances {
cb, err := r.cardBalances(ctx, f)
if err != nil {
return out, err
}
out.CardBalances = &cb
}
return out, nil
}
func (r *repository) registrationFunnel(ctx context.Context, f analytics.Filter) (analytics.RegistrationFunnelDTO, error) {
var out analytics.RegistrationFunnelDTO
var args sqlArgs
query := `
SELECT
(SELECT COUNT(*) FROM users u
WHERE u.deleted_at IS NULL
AND u.role_id = (SELECT id FROM roles WHERE code = 'user' AND deleted_at IS NULL)` +
rangeCond(&args, "u.created_at", f) + `),
COUNT(*) FILTER (WHERE v.expires_at < (now() AT TIME ZONE 'UTC')),
COUNT(*) FILTER (WHERE v.expires_at >= (now() AT TIME ZONE 'UTC')),
COALESCE(SUM(v.attempts), 0)
FROM registration_verifications v
WHERE true` + rangeCond(&args, "v.created_at", f)
if err := r.client.QueryRow(ctx, query, args...).Scan(&out.Completed, &out.Abandoned, &out.WaitingCode, &out.WrongCodeTries); err != nil {
return out, err
}
out.Started = out.Completed + out.Abandoned + out.WaitingCode
out.ConversionPct = ratePtr(out.Completed, out.Started)
return out, nil
}
// activityUserCond limits activity_logs to users of the caller's branches.
func activityUserCond(args *sqlArgs, f analytics.Filter) string {
if len(f.BranchIds) == 0 {
return ""
}
return fmt.Sprintf(` AND EXISTS (SELECT 1 FROM branch_user bu WHERE bu.user_id = a.user_id AND bu.branch_id = ANY(%s) AND bu.deleted_at IS NULL)`,
args.add(f.BranchIds))
}
func (r *repository) operators(ctx context.Context, f analytics.Filter, limit int) ([]analytics.OperatorActivityDTO, error) {
var args sqlArgs
where := rangeCond(&args, "a.created_at", f) + activityUserCond(&args, f)
query := fmt.Sprintf(`
SELECT a.user_id,
MAX(coalesce(nullif(trim(u.first_name || ' ' || u.last_name), ''), nullif(u.name, ''), u.username)),
COUNT(*),
COUNT(*) FILTER (WHERE a.status_code >= 400),
MAX(a.created_at)
FROM activity_logs a
JOIN users u ON u.id = a.user_id
WHERE a.user_id IS NOT NULL%s
GROUP BY a.user_id
ORDER BY 3 DESC
LIMIT %s`, where, args.add(limit))
rows, err := r.client.Query(ctx, query, args...)
if err != nil {
return nil, err
}
defer rows.Close()
items := []analytics.OperatorActivityDTO{}
for rows.Next() {
var it analytics.OperatorActivityDTO
var last time.Time
if err := rows.Scan(&it.UserId, &it.Name, &it.Actions, &it.Errors, &last); err != nil {
return nil, err
}
s := last.UTC().Format(time.RFC3339)
it.LastSeen = &s
items = append(items, it)
}
return items, rows.Err()
}
func (r *repository) moduleErrors(ctx context.Context, f analytics.Filter) ([]analytics.ModuleErrorDTO, error) {
var args sqlArgs
query := `
SELECT coalesce(nullif(a.module, ''), 'unknown'), COUNT(*), COUNT(*) FILTER (WHERE a.status_code >= 400)
FROM activity_logs a
WHERE true` + rangeCond(&args, "a.created_at", f) + activityUserCond(&args, f) + `
GROUP BY 1
ORDER BY 3 DESC, 2 DESC`
rows, err := r.client.Query(ctx, query, args...)
if err != nil {
return nil, err
}
defer rows.Close()
items := []analytics.ModuleErrorDTO{}
for rows.Next() {
var it analytics.ModuleErrorDTO
if err := rows.Scan(&it.Module, &it.Requests, &it.Errors); err != nil {
return nil, err
}
it.ErrorRate = pct(it.Errors, it.Requests)
items = append(items, it)
}
return items, rows.Err()
}
// peakHours counts orders in range by weekday and hour in Ashgabat time
// (created_at is stored as UTC wall-clock time).
func (r *repository) peakHours(ctx context.Context, f analytics.Filter) ([]analytics.HeatmapCellDTO, error) {
var args sqlArgs
query := fmt.Sprintf(`
WITH o AS (%s), l AS (
SELECT (created_at AT TIME ZONE 'UTC') AT TIME ZONE 'Asia/Ashgabat' AS ts FROM o
)
SELECT EXTRACT(ISODOW FROM ts)::int, EXTRACT(HOUR FROM ts)::int, COUNT(*)
FROM l GROUP BY 1, 2`, ordersUnionSQL(&args, f, true))
rows, err := r.client.Query(ctx, query, args...)
if err != nil {
return nil, err
}
defer rows.Close()
var grid [7][24]int64
for rows.Next() {
var weekday, hour int
var count int64
if err := rows.Scan(&weekday, &hour, &count); err != nil {
return nil, err
}
if weekday >= 1 && weekday <= 7 && hour >= 0 && hour < 24 {
grid[weekday-1][hour] = count
}
}
if err := rows.Err(); err != nil {
return nil, err
}
// Full 7x24 grid so the heatmap needs no gap filling client-side.
cells := make([]analytics.HeatmapCellDTO, 0, 7*24)
for d := 0; d < 7; d++ {
for h := 0; h < 24; h++ {
cells = append(cells, analytics.HeatmapCellDTO{Weekday: d + 1, Hour: h, Count: grid[d][h]})
}
}
return cells, nil
}
func (r *repository) cardBalances(ctx context.Context, f analytics.Filter) (analytics.CardBalanceStatsDTO, error) {
out := analytics.CardBalanceStatsDTO{Statuses: []analytics.CountDTO{}}
var args sqlArgs
statuses, err := r.countsByKey(ctx, `
SELECT status, COUNT(*) FROM card_balances
WHERE deleted_at IS NULL`+rangeCond(&args, "created_at", f)+branchCond(&args, "branch_id", f)+`
GROUP BY 1 ORDER BY 2 DESC`, args...)
if err != nil {
return out, err
}
out.Statuses = statuses
var success, failed int64
for _, s := range statuses {
switch s.Key {
case "success":
success = s.Count
case "failed":
failed = s.Count
}
}
out.FailureRate = ratePtr(failed, success+failed)
// A card is valid through the last day of its expiry month; this counts
// distinct checked cards whose last valid day falls in the next 30 days.
args = nil
query := `
SELECT COUNT(DISTINCT card_number) FROM card_balances
WHERE deleted_at IS NULL
AND (expiry_at + interval '1 month' - interval '1 day')::date BETWEEN current_date AND current_date + 30` +
branchCond(&args, "branch_id", f)
if err := r.client.QueryRow(ctx, query, args...).Scan(&out.ExpiringIn30d); err != nil {
return out, err
}
return out, nil
}

217
internal/analytics/dto.go Normal file
View File

@@ -0,0 +1,217 @@
package analytics
import (
"encoding/json"
"time"
)
// Filter narrows every analytics query to [From, To) and, for branch-scope
// callers, to their branches.
type Filter struct {
BranchIds []int64
// Types are the order types the caller may see; queries over "all
// orders" union only these tables.
Types []string
From time.Time
To time.Time // exclusive
}
// Order types: one per customer-facing order table.
const (
OrderLoan = "loan"
OrderLoanLetter = "loan_paid_off_letter"
OrderCard = "card"
OrderCardPin = "card_pin"
OrderCardRekwizit = "card_rekwizit"
OrderVisaMaster = "visa_master"
)
type CountDTO struct {
Key string `json:"key"`
Count int64 `json:"count"`
Percent float64 `json:"percent"`
}
// ---- /finance ----
// PaymentTotalsDTO sums successful payouts only (gateway_status = success).
// BankFeeTmt is the bank's own fee; GBÜS and TVEB fees are reported apart
// since they go to those parties.
type PaymentTotalsDTO struct {
Count int64 `json:"count"`
AmountTmt float64 `json:"amountTmt"`
BankFeeTmt float64 `json:"bankFeeTmt"`
GbusFeeTmt float64 `json:"gbusFeeTmt"`
TvebFeeTmt float64 `json:"tvebFeeTmt"`
TotalTmt float64 `json:"totalTmt"`
AvgTotalTmt float64 `json:"avgTotalTmt"`
}
type FinanceMonthDTO struct {
Month string `json:"month"` // YYYY-MM
Count int64 `json:"count"`
TotalTmt float64 `json:"totalTmt"`
BankFeeTmt float64 `json:"bankFeeTmt"`
}
// LoanRequestedDTO sums loan_orders.loan_amount, a free-text column; rows
// whose amount does not parse as a number are counted in Unparsed.
type LoanRequestedDTO struct {
Count int64 `json:"count"`
TotalTmt float64 `json:"totalTmt"`
AvgTmt float64 `json:"avgTmt"`
Unparsed int64 `json:"unparsed"`
}
type FinanceDTO struct {
Payments PaymentTotalsDTO `json:"payments"`
Gateway []CountDTO `json:"gateway"`
GatewaySuccessRate *float64 `json:"gatewaySuccessRate"`
Monthly []FinanceMonthDTO `json:"monthly"`
LoanRequested LoanRequestedDTO `json:"loanRequested"`
}
// ---- /backlog ----
// BacklogDTO is one order type's open queue, aged by created_at, plus the
// average time finished orders took (updated_at - created_at, so any later
// edit makes it an upper bound rather than an exact figure).
type BacklogDTO struct {
Type string `json:"type"`
Open int64 `json:"open"`
Under1Day int64 `json:"under1Day"`
From1To3Days int64 `json:"from1To3Days"`
Over3Days int64 `json:"over3Days"`
OldestOpenAt *string `json:"oldestOpenAt"`
OldestOpenDays *float64 `json:"oldestOpenDays"`
Finished int64 `json:"finished"`
AvgProcessHours *float64 `json:"avgProcessHours"`
}
// VisaMasterTimingDTO is exact payout timing from visa_master_payment_logs:
// first logged step to payment_finalized, per order.
type VisaMasterTimingDTO struct {
Orders int64 `json:"orders"`
AvgMinutes *float64 `json:"avgMinutes"`
P90Minutes *float64 `json:"p90Minutes"`
MaxMinutes *float64 `json:"maxMinutes"`
}
type BacklogResponseDTO struct {
Items []BacklogDTO `json:"items"`
VisaMasterTiming VisaMasterTimingDTO `json:"visaMasterTiming"`
}
// ---- /branches ----
type BranchStatDTO struct {
BranchId int64 `json:"branchId"`
Name json.RawMessage `json:"name"`
Region string `json:"region"`
Orders map[string]int64 `json:"orders"`
Total int64 `json:"total"`
Open int64 `json:"open"`
Approved int64 `json:"approved"`
Rejected int64 `json:"rejected"`
ApprovalRate *float64 `json:"approvalRate"`
AvgProcessHours *float64 `json:"avgProcessHours"`
}
type BranchesDTO struct {
Branches []BranchStatDTO `json:"branches"`
Regions []CountDTO `json:"regions"`
}
// ---- /products ----
type NamedCountDTO struct {
Id int64 `json:"id"`
Name json.RawMessage `json:"name"`
Count int64 `json:"count"`
Percent float64 `json:"percent"`
}
type ProductsDTO struct {
LoanSources []CountDTO `json:"loanSources"`
LoanTypes []NamedCountDTO `json:"loanTypes"`
CardTypes []NamedCountDTO `json:"cardTypes"`
CardOrderPay []CountDTO `json:"cardOrderPay"` // paid / unpaid
}
// ---- /customers ----
// ApprovalCountDTO is a CountDTO plus how many of those loan orders were
// approved / rejected / still open, so the UI can show approval rate per group.
type ApprovalCountDTO struct {
Key string `json:"key"`
Count int64 `json:"count"`
Percent float64 `json:"percent"`
Approved int64 `json:"approved"`
Rejected int64 `json:"rejected"`
Open int64 `json:"open"`
ApprovalRate *float64 `json:"approvalRate"`
}
type CustomersDTO struct {
Total int64 `json:"total"`
Approved int64 `json:"approved"`
Rejected int64 `json:"rejected"`
Open int64 `json:"open"`
ApprovalRate *float64 `json:"approvalRate"`
AgeGroups []ApprovalCountDTO `json:"ageGroups"`
Education []ApprovalCountDTO `json:"education"`
MarriageStatus []ApprovalCountDTO `json:"marriageStatus"`
Guarantors []ApprovalCountDTO `json:"guarantors"` // none / one / two
}
// ---- /system ----
// RegistrationFunnelDTO: a verification row is deleted once registration
// completes, so Completed counts new customer accounts and the rows still
// present are unfinished. Password resets reuse the same table, so
// Abandoned/WaitingCode slightly overcount registrations.
type RegistrationFunnelDTO struct {
Started int64 `json:"started"`
Completed int64 `json:"completed"`
Abandoned int64 `json:"abandoned"` // code expired, never finished
WaitingCode int64 `json:"waitingCode"` // code still valid
WrongCodeTries int64 `json:"wrongCodeTries"`
ConversionPct *float64 `json:"conversionPct"`
}
type OperatorActivityDTO struct {
UserId int64 `json:"userId"`
Name string `json:"name"`
Actions int64 `json:"actions"`
Errors int64 `json:"errors"`
LastSeen *string `json:"lastSeen"`
}
type ModuleErrorDTO struct {
Module string `json:"module"`
Requests int64 `json:"requests"`
Errors int64 `json:"errors"`
ErrorRate float64 `json:"errorRate"`
}
// HeatmapCellDTO: Weekday is Monday=1 .. Sunday=7, Hour is 0..23, both in
// Asia/Ashgabat time.
type HeatmapCellDTO struct {
Weekday int `json:"weekday"`
Hour int `json:"hour"`
Count int64 `json:"count"`
}
type CardBalanceStatsDTO struct {
Statuses []CountDTO `json:"statuses"`
FailureRate *float64 `json:"failureRate"`
ExpiringIn30d int64 `json:"expiringIn30d"`
}
type SystemDTO struct {
Registration *RegistrationFunnelDTO `json:"registration"`
Operators []OperatorActivityDTO `json:"operators"`
ModuleErrors []ModuleErrorDTO `json:"moduleErrors"`
PeakHours []HeatmapCellDTO `json:"peakHours"`
CardBalances *CardBalanceStatsDTO `json:"cardBalances"`
}

View File

@@ -0,0 +1,272 @@
package analytics
import (
"net/http"
"strconv"
"time"
"online-back/internal/appresult"
"online-back/internal/handlers"
"online-back/internal/identity/rbac"
"online-back/internal/identity/rbac/perm"
"online-back/pkg/logging"
"github.com/gin-gonic/gin"
)
// Lives under the dashboard URL but is its own module; rbac picks the
// longest registered prefix, so this group's policy applies here.
const baseURL = "/dashboard/analytics"
const (
dateLayout = "2006-01-02"
maxRangeDays = 366 * 3
defaultOperatorLimit = 10
maxOperatorLimit = 50
)
type handler struct {
logger *logging.Logger
repository Repository
}
func NewHandler(logger *logging.Logger, repository Repository) handlers.Handler {
return &handler{logger: logger, repository: repository}
}
func (h *handler) Register(router *gin.RouterGroup) {
group := rbac.Group(router, baseURL, rbac.RequireStaff(perm.Dashboard))
group.GET("/finance", h.finance)
group.GET("/backlog", h.backlog)
group.GET("/branches", h.branches)
group.GET("/products", h.products)
group.GET("/customers", h.customers)
group.GET("/system", h.system)
}
// finance godoc
// @Summary Dashboard analytics: finance
// @Description Successful visa/master payouts (amount, bank/GBÜS/TVEB fees), gateway status breakdown and success rate, monthly payout totals, and the total loan amount requested. Payouts need the cards permission, the loan total the loans permission.
// @Tags dashboard-analytics
// @Produce json
// @Security BearerAuth
// @Param from query string false "Start date YYYY-MM-DD (inclusive)" default(Jan 1 of current year)
// @Param to query string false "End date YYYY-MM-DD (inclusive)" default(today)
// @Param lang query string false "Language of localized fields; all returns the full {en, ru, tm} objects" Enums(tm, ru, en, all) default(tm)
// @Success 200 {object} appresult.AppSuccess
// @Failure 400 {object} appresult.AppError
// @Failure 500 {object} appresult.AppError
// @Router /dashboard/analytics/finance [get]
func (h *handler) finance(c *gin.Context) {
filter, ok := h.parseFilter(c)
if !ok {
return
}
result, err := h.repository.Finance(c.Request.Context(), filter)
if err != nil {
h.fail(c, "finance", err)
return
}
if !rbac.Can(c, perm.Cards) {
result.Payments = PaymentTotalsDTO{}
result.Gateway = []CountDTO{}
result.GatewaySuccessRate = nil
result.Monthly = []FinanceMonthDTO{}
}
if !rbac.Can(c, perm.Loans) {
result.LoanRequested = LoanRequestedDTO{}
}
c.JSON(http.StatusOK, appresult.SuccessWithData(result))
}
// backlog godoc
// @Summary Dashboard analytics: backlog
// @Description Open (unhandled) orders per order type aged under 1 day / 1-3 days / over 3 days, the oldest open order, and the average processing time of orders finished in range; plus exact visa/master payout timing from the payment log. Order types are limited to the modules the caller can open.
// @Tags dashboard-analytics
// @Produce json
// @Security BearerAuth
// @Param from query string false "Start date YYYY-MM-DD (inclusive)" default(Jan 1 of current year)
// @Param to query string false "End date YYYY-MM-DD (inclusive)" default(today)
// @Param lang query string false "Language of localized fields; all returns the full {en, ru, tm} objects" Enums(tm, ru, en, all) default(tm)
// @Success 200 {object} appresult.AppSuccess
// @Failure 400 {object} appresult.AppError
// @Failure 500 {object} appresult.AppError
// @Router /dashboard/analytics/backlog [get]
func (h *handler) backlog(c *gin.Context) {
filter, ok := h.parseFilter(c)
if !ok {
return
}
result, err := h.repository.Backlog(c.Request.Context(), filter)
if err != nil {
h.fail(c, "backlog", err)
return
}
c.JSON(http.StatusOK, appresult.SuccessWithData(result))
}
// branches godoc
// @Summary Dashboard analytics: branches
// @Description Per-branch leaderboard (orders per type, open/approved/rejected, approval rate, average processing hours) and order counts per region, for orders created in range.
// @Tags dashboard-analytics
// @Produce json
// @Security BearerAuth
// @Param from query string false "Start date YYYY-MM-DD (inclusive)" default(Jan 1 of current year)
// @Param to query string false "End date YYYY-MM-DD (inclusive)" default(today)
// @Param lang query string false "Language of localized fields; all returns the full {en, ru, tm} objects" Enums(tm, ru, en, all) default(tm)
// @Success 200 {object} appresult.AppSuccess
// @Failure 400 {object} appresult.AppError
// @Failure 500 {object} appresult.AppError
// @Router /dashboard/analytics/branches [get]
func (h *handler) branches(c *gin.Context) {
filter, ok := h.parseFilter(c)
if !ok {
return
}
result, err := h.repository.Branches(c.Request.Context(), filter)
if err != nil {
h.fail(c, "branches", err)
return
}
c.JSON(http.StatusOK, appresult.SuccessWithData(result))
}
// products godoc
// @Summary Dashboard analytics: products
// @Description Loan orders by source (web/mobile) and loan type, card orders by card type, and paid vs unpaid card orders, for orders created in range.
// @Tags dashboard-analytics
// @Produce json
// @Security BearerAuth
// @Param from query string false "Start date YYYY-MM-DD (inclusive)" default(Jan 1 of current year)
// @Param to query string false "End date YYYY-MM-DD (inclusive)" default(today)
// @Param lang query string false "Language of localized fields; all returns the full {en, ru, tm} objects" Enums(tm, ru, en, all) default(tm)
// @Success 200 {object} appresult.AppSuccess
// @Failure 400 {object} appresult.AppError
// @Failure 500 {object} appresult.AppError
// @Router /dashboard/analytics/products [get]
func (h *handler) products(c *gin.Context) {
filter, ok := h.parseFilter(c)
if !ok {
return
}
result, err := h.repository.Products(c.Request.Context(), filter)
if err != nil {
h.fail(c, "products", err)
return
}
c.JSON(http.StatusOK, appresult.SuccessWithData(result))
}
// customers godoc
// @Summary Dashboard analytics: customers
// @Description Loan applicants in range by age group, education, marriage status and number of guarantors, each with its approval rate. Needs the loans permission.
// @Tags dashboard-analytics
// @Produce json
// @Security BearerAuth
// @Param from query string false "Start date YYYY-MM-DD (inclusive)" default(Jan 1 of current year)
// @Param to query string false "End date YYYY-MM-DD (inclusive)" default(today)
// @Param lang query string false "Language of localized fields; all returns the full {en, ru, tm} objects" Enums(tm, ru, en, all) default(tm)
// @Success 200 {object} appresult.AppSuccess
// @Failure 400 {object} appresult.AppError
// @Failure 500 {object} appresult.AppError
// @Router /dashboard/analytics/customers [get]
func (h *handler) customers(c *gin.Context) {
filter, ok := h.parseFilter(c)
if !ok {
return
}
result, err := h.repository.Customers(c.Request.Context(), filter)
if err != nil {
h.fail(c, "customers", err)
return
}
c.JSON(http.StatusOK, appresult.SuccessWithData(result))
}
// system godoc
// @Summary Dashboard analytics: system
// @Description Registration funnel (all-scope callers with the users permission), operator activity and error rate per module (activity-logs permission), order peak hours heatmap in Ashgabat time, and card balance check stats (cards permission). Widgets the caller cannot see are null or empty.
// @Tags dashboard-analytics
// @Produce json
// @Security BearerAuth
// @Param from query string false "Start date YYYY-MM-DD (inclusive)" default(Jan 1 of current year)
// @Param to query string false "End date YYYY-MM-DD (inclusive)" default(today)
// @Param operator_limit query int false "Number of operators to return" default(10)
// @Param lang query string false "Language of localized fields; all returns the full {en, ru, tm} objects" Enums(tm, ru, en, all) default(tm)
// @Success 200 {object} appresult.AppSuccess
// @Failure 400 {object} appresult.AppError
// @Failure 500 {object} appresult.AppError
// @Router /dashboard/analytics/system [get]
func (h *handler) system(c *gin.Context) {
filter, ok := h.parseFilter(c)
if !ok {
return
}
opts := SystemOptions{
// Registrations are not tied to a branch, so branch-scope callers
// would otherwise see bank-wide numbers.
Registration: rbac.Can(c, perm.Users) && len(filter.BranchIds) == 0,
Operators: rbac.Can(c, perm.ActivityLogs),
CardBalances: rbac.Can(c, perm.Cards),
OperatorLimit: defaultOperatorLimit,
}
if raw := c.Query("operator_limit"); raw != "" {
limit, err := strconv.Atoi(raw)
if err != nil || limit < 1 {
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
return
}
opts.OperatorLimit = min(limit, maxOperatorLimit)
}
result, err := h.repository.System(c.Request.Context(), filter, opts)
if err != nil {
h.fail(c, "system", err)
return
}
c.JSON(http.StatusOK, appresult.SuccessWithData(result))
}
func (h *handler) fail(c *gin.Context, widget string, err error) {
h.logger.Errorf("dashboard analytics %s failed: %v", widget, err)
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
}
// parseFilter reads from/to (inclusive dates, default: this year so far),
// the caller's branch scope, and the order types their permissions allow.
// It writes the 400 itself and returns false on bad input.
func (h *handler) parseFilter(c *gin.Context) (Filter, bool) {
now := time.Now().UTC()
today := time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, time.UTC)
from := time.Date(now.Year(), 1, 1, 0, 0, 0, 0, time.UTC)
to := today
var err error
if raw := c.Query("from"); raw != "" {
if from, err = time.Parse(dateLayout, raw); err != nil {
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
return Filter{}, false
}
}
if raw := c.Query("to"); raw != "" {
if to, err = time.Parse(dateLayout, raw); err != nil {
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
return Filter{}, false
}
}
if to.Before(from) || to.Sub(from) > maxRangeDays*24*time.Hour {
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
return Filter{}, false
}
filter := Filter{From: from, To: to.AddDate(0, 0, 1)}
if rbac.Can(c, perm.Loans) {
filter.Types = append(filter.Types, OrderLoan, OrderLoanLetter)
}
if rbac.Can(c, perm.Cards) {
filter.Types = append(filter.Types, OrderCard, OrderCardPin, OrderCardRekwizit, OrderVisaMaster)
}
rbac.BindBranchIDs(c, &filter.BranchIds)
return filter, true
}

View File

@@ -0,0 +1,21 @@
package analytics
import "context"
type Repository interface {
Finance(ctx context.Context, filter Filter) (FinanceDTO, error)
Backlog(ctx context.Context, filter Filter) (BacklogResponseDTO, error)
Branches(ctx context.Context, filter Filter) (BranchesDTO, error)
Products(ctx context.Context, filter Filter) (ProductsDTO, error)
Customers(ctx context.Context, filter Filter) (CustomersDTO, error)
System(ctx context.Context, filter Filter, opts SystemOptions) (SystemDTO, error)
}
// SystemOptions says which /system widgets the caller may see, so the
// repository skips queries whose result would be redacted anyway.
type SystemOptions struct {
Registration bool
Operators bool
CardBalances bool
OperatorLimit int
}

View File

@@ -7,10 +7,16 @@ var (
ErrUnauthorized = NewAppError(nil, "Invalid credentials or unauthorized access.", "SE-00002")
ErrNotFound = NewAppError(nil, "The requested resource was not found.", "SE-00003")
ErrInternalServer = NewAppError(nil, "An internal server error occurred. Please try again later.", "SE-00004")
ErrForbidden = NewAppError(nil, "Sana rugsat yok.", "SE-00011")
ErrNotAcceptable = NewAppError(nil, "The request could not be processed.", "SE-00007")
ErrConflict = NewAppError(nil, "A user with this phone or username already exists.", "SE-00008")
ErrInvalidCode = NewAppError(nil, "Invalid or expired verification code.", "SE-00009")
ErrPasswordMismatch = NewAppError(nil, "Password confirmation does not match.", "SE-00010")
ErrDuplicate = NewAppError(nil, "A record with these values already exists.", "SE-00012")
ErrRoleInUse = NewAppError(nil, "The role is still assigned to users.", "SE-00013")
ErrLastSuperadmin = NewAppError(nil, "The last superadmin cannot be removed or demoted.", "SE-00014")
ErrUnknownRole = NewAppError(nil, "Role not found.", "SE-00015")
ErrSystemRole = NewAppError(nil, "System roles cannot be deleted or have their scope changed.", "SE-00016")
)
type AppError struct {

230
internal/appresult/lang.go Normal file
View File

@@ -0,0 +1,230 @@
package appresult
import (
"bytes"
"encoding/json"
"net/http"
"strings"
"github.com/gin-gonic/gin"
)
// DefaultLang is the language localized fields collapse to when the caller
// passes no ?lang=.
const DefaultLang = "tm"
// LangAll keeps every localized field as its full {en, ru, tm} object - what
// admin edit forms need to fill all three inputs.
const LangAll = "all"
// langFallback is the order empty translations are filled from.
var langFallback = []string{"tm", "ru", "en"}
// Localize collapses every {"en", "ru", "tm"} object (shared.LocalizedText)
// in a JSON response into the plain string for ?lang= (tm, ru or en;
// default tm), so clients only download the language they show. ?lang=all
// leaves responses untouched. It rewrites the encoded body rather than the
// DTOs, so every module gets it without knowing about it; non-JSON
// responses (files, images) are streamed through as-is.
func Localize() gin.HandlerFunc {
return func(c *gin.Context) {
lang := strings.ToLower(strings.TrimSpace(c.Query("lang")))
switch lang {
case "":
lang = DefaultLang
case "tm", "ru", "en":
case LangAll:
c.Next()
return
default:
c.AbortWithStatusJSON(http.StatusBadRequest, ErrMissingParam)
return
}
w := &localizeWriter{ResponseWriter: c.Writer}
c.Writer = w
c.Next()
c.Writer = w.ResponseWriter
w.flush(lang)
}
}
// localizeWriter buffers JSON bodies until the handler is done, so they can
// be rewritten as a whole; anything else goes straight to the client.
type localizeWriter struct {
gin.ResponseWriter
decided bool
buffer bool
body bytes.Buffer
}
func (w *localizeWriter) Write(data []byte) (int, error) {
if !w.decided {
w.decided = true
w.buffer = strings.HasPrefix(w.Header().Get("Content-Type"), "application/json")
}
if !w.buffer {
return w.ResponseWriter.Write(data)
}
return w.body.Write(data)
}
func (w *localizeWriter) WriteString(s string) (int, error) {
return w.Write([]byte(s))
}
func (w *localizeWriter) flush(lang string) {
if w.body.Len() == 0 {
return
}
out, err := localizeJSON(w.body.Bytes(), lang)
if err != nil {
out = w.body.Bytes()
}
w.ResponseWriter.Write(out)
}
// localizeJSON re-encodes data token by token - keeping key order and
// number precision - with localized objects replaced by their lang string.
func localizeJSON(data []byte, lang string) ([]byte, error) {
dec := json.NewDecoder(bytes.NewReader(data))
dec.UseNumber()
var out bytes.Buffer
if err := localizeValue(dec, &out, lang); err != nil {
return nil, err
}
return out.Bytes(), nil
}
func localizeValue(dec *json.Decoder, out *bytes.Buffer, lang string) error {
tok, err := dec.Token()
if err != nil {
return err
}
switch t := tok.(type) {
case json.Delim:
if t == '[' {
return localizeArray(dec, out, lang)
}
return localizeObject(dec, out, lang)
case string:
return writeString(out, t)
case json.Number:
out.WriteString(t.String())
case bool:
if t {
out.WriteString("true")
} else {
out.WriteString("false")
}
case nil:
out.WriteString("null")
}
return nil
}
func localizeArray(dec *json.Decoder, out *bytes.Buffer, lang string) error {
out.WriteByte('[')
for i := 0; dec.More(); i++ {
if i > 0 {
out.WriteByte(',')
}
if err := localizeValue(dec, out, lang); err != nil {
return err
}
}
if _, err := dec.Token(); err != nil { // ']'
return err
}
out.WriteByte(']')
return nil
}
type jsonField struct {
key string
value []byte
}
func localizeObject(dec *json.Decoder, out *bytes.Buffer, lang string) error {
var fields []jsonField
for dec.More() {
keyTok, err := dec.Token()
if err != nil {
return err
}
var value bytes.Buffer
if err := localizeValue(dec, &value, lang); err != nil {
return err
}
fields = append(fields, jsonField{key: keyTok.(string), value: value.Bytes()})
}
if _, err := dec.Token(); err != nil { // '}'
return err
}
if text, ok := pickLocalized(fields, lang); ok {
return writeString(out, text)
}
out.WriteByte('{')
for i, f := range fields {
if i > 0 {
out.WriteByte(',')
}
if err := writeString(out, f.key); err != nil {
return err
}
out.WriteByte(':')
out.Write(f.value)
}
out.WriteByte('}')
return nil
}
// pickLocalized reports whether fields is exactly a {en, ru, tm} object of
// strings/nulls and, if so, returns lang's text - falling back through
// langFallback when it's empty.
func pickLocalized(fields []jsonField, lang string) (string, bool) {
if len(fields) != 3 {
return "", false
}
texts := make(map[string]string, 3)
for _, f := range fields {
if f.key != "en" && f.key != "ru" && f.key != "tm" {
return "", false
}
if _, dup := texts[f.key]; dup {
return "", false
}
var text *string
if err := json.Unmarshal(f.value, &text); err != nil {
return "", false
}
texts[f.key] = ""
if text != nil {
texts[f.key] = *text
}
}
if text := texts[lang]; text != "" {
return text, true
}
for _, l := range langFallback {
if text := texts[l]; text != "" {
return text, true
}
}
return "", true
}
// writeString encodes s the way gin's c.JSON does (json.Marshal, HTML
// escaped), so rewritten bodies match untouched ones byte for byte.
func writeString(out *bytes.Buffer, s string) error {
encoded, err := json.Marshal(s)
if err != nil {
return err
}
out.Write(encoded)
return nil
}

View File

@@ -0,0 +1,106 @@
package appresult
import (
"net/http"
"net/http/httptest"
"testing"
"github.com/gin-gonic/gin"
)
func serve(t *testing.T, query string, handler gin.HandlerFunc) *httptest.ResponseRecorder {
t.Helper()
gin.SetMode(gin.TestMode)
router := gin.New()
router.Use(Localize())
router.GET("/x", handler)
rec := httptest.NewRecorder()
router.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/x"+query, nil))
return rec
}
func jsonHandler(body string) gin.HandlerFunc {
return func(c *gin.Context) {
c.Data(http.StatusOK, "application/json; charset=utf-8", []byte(body))
}
}
const branchBody = `{"id":1,"name":{"en":"Branch","ru":"Филиал","tm":"Şahamça"}}`
func TestLocalizeLanguages(t *testing.T) {
tests := []struct {
query string
want string
}{
{"", `{"id":1,"name":"Şahamça"}`},
{"?lang=tm", `{"id":1,"name":"Şahamça"}`},
{"?lang=ru", `{"id":1,"name":"Филиал"}`},
{"?lang=EN", `{"id":1,"name":"Branch"}`},
{"?lang=all", branchBody},
}
for _, tt := range tests {
rec := serve(t, tt.query, jsonHandler(branchBody))
if rec.Code != http.StatusOK || rec.Body.String() != tt.want {
t.Errorf("%q: got %d %s, want %s", tt.query, rec.Code, rec.Body.String(), tt.want)
}
}
}
func TestLocalizeRejectsUnknownLang(t *testing.T) {
called := false
rec := serve(t, "?lang=xx", func(c *gin.Context) { called = true })
if rec.Code != http.StatusBadRequest || called {
t.Fatalf("got %d (handler called: %v), want 400 without calling the handler", rec.Code, called)
}
}
func TestLocalizeFallback(t *testing.T) {
tests := []struct {
body string
want string
}{
{`{"tm":"","ru":"Филиал","en":"Branch"}`, `"Филиал"`},
{`{"tm":null,"ru":"","en":"Branch"}`, `"Branch"`},
{`{"tm":"","ru":"","en":""}`, `""`},
}
for _, tt := range tests {
if got := serve(t, "", jsonHandler(tt.body)).Body.String(); got != tt.want {
t.Errorf("%s: got %s, want %s", tt.body, got, tt.want)
}
}
}
func TestLocalizeKeepsStructure(t *testing.T) {
body := `{"z":9007199254740993,"a":[{"b":{"en":"E","ru":"R","tm":"T"},"f":1.10}],` +
`"extra":{"en":"E","ru":"R","tm":"T","id":2},"partial":{"en":"E","ru":"R"},` +
`"nested":{"en":{"x":1},"ru":"R","tm":"T"},"ok":true,"none":null,"html":"<a&b>"}`
want := `{"z":9007199254740993,"a":[{"b":"T","f":1.10}],` +
`"extra":{"en":"E","ru":"R","tm":"T","id":2},"partial":{"en":"E","ru":"R"},` +
`"nested":{"en":{"x":1},"ru":"R","tm":"T"},"ok":true,"none":null,"html":` + "\"\\u003ca\\u0026b\\u003e\"}"
if got := serve(t, "", jsonHandler(body)).Body.String(); got != want {
t.Fatalf("got %s\nwant %s", got, want)
}
}
func TestLocalizeMatchesGinJSON(t *testing.T) {
rec := serve(t, "?lang=ru", func(c *gin.Context) {
c.JSON(http.StatusCreated, SuccessWithData(map[string]interface{}{
"name": map[string]string{"en": "Branch", "ru": "Филиал", "tm": "Şahamça"},
}))
})
want := `{"status":true,"message":"Request completed successfully.","code":"SS-10000","data":{"name":"Филиал"}}`
if rec.Code != http.StatusCreated || rec.Body.String() != want {
t.Fatalf("got %d %s, want 201 %s", rec.Code, rec.Body.String(), want)
}
}
func TestLocalizeSkipsNonJSON(t *testing.T) {
body := `{"en":"E","ru":"R","tm":"T"}`
rec := serve(t, "", func(c *gin.Context) {
c.Data(http.StatusOK, "text/plain", []byte(body))
})
if rec.Body.String() != body {
t.Fatalf("got %s, want body untouched", rec.Body.String())
}
}

View File

@@ -0,0 +1,217 @@
package db
import (
"context"
"fmt"
"strings"
"online-back/internal/backup"
"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[backup.BackupDTO]
logger *logging.Logger
}
func NewRepository(client postgresql.Client, logger *logging.Logger) backup.Repository {
return &repository{
client: client,
generic: genericrepo.New(client, "backups", backupColumnsSQL, scanBackup),
logger: logger,
}
}
var backupColumns = []string{
"id", "file_name", "size_bytes", "status", "error_message",
"created_by", "created_at", "updated_at",
}
var backupColumnsSQL = strings.Join(backupColumns, ", ")
const backupFromClause = ` FROM backups b
LEFT JOIN users u ON u.id = b.created_by`
var backupSelectColumns = shared.PrefixedColumns("b", backupColumns) + `,
` + shared.UserDisplaySQL + `, COALESCE(u.username, ''), COALESCE(u.phone, ''), COALESCE(u.email, '')`
func (r *repository) List(ctx context.Context, filter backup.ListFilter) (backup.ListBackupDTO, error) {
whereClause, args := buildListQuery(filter)
var count int64
if err := r.client.QueryRow(ctx, `SELECT COUNT(*) FROM backups b`+whereClause, args...).Scan(&count); err != nil {
return backup.ListBackupDTO{}, err
}
offset := (filter.Page - 1) * filter.Limit
limitPlaceholder := len(args) + 1
offsetPlaceholder := len(args) + 2
query := fmt.Sprintf(
`SELECT %s%s%s ORDER BY b.created_at DESC, b.id DESC LIMIT $%d OFFSET $%d`,
backupSelectColumns, backupFromClause, whereClause, limitPlaceholder, offsetPlaceholder,
)
rows, err := r.client.Query(ctx, query, append(args, filter.Limit, offset)...)
if err != nil {
return backup.ListBackupDTO{}, err
}
defer rows.Close()
var items []backup.BackupDTO
for rows.Next() {
item, err := scanBackupWithUser(rows)
if err != nil {
return backup.ListBackupDTO{}, err
}
items = append(items, item)
}
if err := rows.Err(); err != nil {
return backup.ListBackupDTO{}, err
}
return backup.ListBackupDTO{Count: count, Backups: items}, nil
}
func buildListQuery(filter backup.ListFilter) (whereClause string, args []interface{}) {
conditions := []string{"b.deleted_at IS NULL"}
if filter.Search != "" {
args = append(args, shared.LikePattern(filter.Search))
conditions = append(conditions, fmt.Sprintf(`b.file_name ILIKE $%d ESCAPE '\'`, len(args)))
}
if filter.Status != nil {
args = append(args, *filter.Status)
conditions = append(conditions, fmt.Sprintf("b.status = $%d", len(args)))
}
return " WHERE " + strings.Join(conditions, " AND "), args
}
func escapeLike(term string) string {
term = strings.ReplaceAll(term, `\`, `\\`)
term = strings.ReplaceAll(term, `%`, `\%`)
term = strings.ReplaceAll(term, `_`, `\_`)
return term
}
func (r *repository) GetByID(ctx context.Context, id int64) (backup.BackupDTO, error) {
query := `SELECT ` + backupSelectColumns + backupFromClause + ` WHERE b.id = $1 AND b.deleted_at IS NULL`
return scanBackupWithUser(r.client.QueryRow(ctx, query, id))
}
func (r *repository) Create(ctx context.Context, dto backup.CreateBackupDTO) (backup.BackupDTO, error) {
query := `
WITH inserted AS (
INSERT INTO backups (file_name, created_by)
VALUES ($1, $2)
RETURNING ` + backupColumnsSQL + `
)
SELECT ` + backupSelectColumns + `
FROM inserted b
LEFT JOIN users u ON u.id = b.created_by`
return scanBackupWithUser(r.client.QueryRow(ctx, query, dto.FileName, dto.CreatedBy))
}
func (r *repository) Finish(ctx context.Context, id int64, sizeBytes int64, status string, errMsg *string) (backup.BackupDTO, error) {
query := `
WITH updated AS (
UPDATE backups SET
size_bytes = $1,
status = $2,
error_message = $3,
updated_at = (CURRENT_TIMESTAMP AT TIME ZONE 'UTC')
WHERE id = $4
RETURNING ` + backupColumnsSQL + `
)
SELECT ` + backupSelectColumns + `
FROM updated b
LEFT JOIN users u ON u.id = b.created_by`
item, err := scanBackupWithUser(r.client.QueryRow(ctx, query, sizeBytes, status, errMsg, id))
if err != nil {
return backup.BackupDTO{}, err
}
return item, nil
}
func (r *repository) Delete(ctx context.Context, id int64) error {
return r.generic.Delete(ctx, id)
}
func (r *repository) CountByFilePrefix(ctx context.Context, prefix string) (int64, error) {
var count int64
err := r.client.QueryRow(ctx,
`SELECT COUNT(*) FROM backups WHERE file_name LIKE $1 ESCAPE '\'`,
escapeLike(prefix)+"%",
).Scan(&count)
return count, err
}
func scanBackup(row genericrepo.Scanner) (backup.BackupDTO, error) {
return scanBackupRow(row, false)
}
func scanBackupWithUser(row genericrepo.Scanner) (backup.BackupDTO, error) {
return scanBackupRow(row, true)
}
func scanBackupRow(row genericrepo.Scanner, withUser bool) (backup.BackupDTO, error) {
var item backup.BackupDTO
dest := []interface{}{
&item.Id, &item.FileName, &item.SizeBytes, &item.Status, &item.ErrorMessage,
&item.CreatedById, &item.CreatedAt, &item.UpdatedAt,
}
var userName, userUsername, userPhone, userEmail string
if withUser {
dest = append(dest, &userName, &userUsername, &userPhone, &userEmail)
}
if err := row.Scan(dest...); err != nil {
return backup.BackupDTO{}, err
}
item.Size = formatSize(item.SizeBytes)
if withUser {
if item.CreatedById != nil {
item.CreatedBy = &backup.UserInfo{
Id: *item.CreatedById,
Name: userName,
Username: userUsername,
Phone: userPhone,
Email: userEmail,
}
} else {
item.CreatedBy = &backup.UserInfo{Name: "System", Username: "system"}
}
}
return item, nil
}
func formatSize(bytes int64) string {
const (
kb = 1024
mb = 1024 * 1024
gb = 1024 * 1024 * 1024
)
switch {
case bytes >= gb:
return fmt.Sprintf("%.1f GB", float64(bytes)/float64(gb))
case bytes >= mb:
if bytes%mb == 0 {
return fmt.Sprintf("%d MB", bytes/mb)
}
return fmt.Sprintf("%.1f MB", float64(bytes)/float64(mb))
case bytes >= kb:
return fmt.Sprintf("%d KB", bytes/kb)
default:
return fmt.Sprintf("%d B", bytes)
}
}

41
internal/backup/dto.go Normal file
View File

@@ -0,0 +1,41 @@
package backup
import "time"
type UserInfo struct {
Id int64 `json:"id"`
Name string `json:"name"`
Username string `json:"username"`
Phone string `json:"phone"`
Email string `json:"email"`
}
type BackupDTO struct {
Id int64 `json:"id"`
FileName string `json:"fileName"`
SizeBytes int64 `json:"sizeBytes"`
Size string `json:"size"`
Status string `json:"status"`
ErrorMessage *string `json:"errorMessage,omitempty"`
CreatedById *int64 `json:"-"`
CreatedBy *UserInfo `json:"createdBy,omitempty"`
CreatedAt time.Time `json:"createdAt"`
UpdatedAt time.Time `json:"updatedAt"`
}
type CreateBackupDTO struct {
FileName string
CreatedBy *int64
}
type ListFilter struct {
Search string
Status *string
Page int
Limit int
}
type ListBackupDTO struct {
Count int64 `json:"count"`
Backups []BackupDTO `json:"backups"`
}

55
internal/backup/dump.go Normal file
View File

@@ -0,0 +1,55 @@
package backup
import (
"context"
"fmt"
"os"
"os/exec"
"strings"
"time"
"online-back/internal/config"
)
const dumpTimeout = 10 * time.Minute
type Dumper interface {
Dump(ctx context.Context, destPath string) error
}
type PgDumper struct {
storage config.StorageConfig
}
func NewPgDumper(storage config.StorageConfig) *PgDumper {
return &PgDumper{storage: storage}
}
func (d *PgDumper) Dump(ctx context.Context, destPath string) error {
ctx, cancel := context.WithTimeout(ctx, dumpTimeout)
defer cancel()
cmd := exec.CommandContext(ctx, "pg_dump",
"-h", d.storage.Host,
"-p", d.storage.Port,
"-U", d.storage.Username,
"-d", d.storage.Database,
"--no-owner",
"--no-acl",
"-f", destPath,
)
cmd.Env = append(os.Environ(), "PGPASSWORD="+d.storage.Password)
out, err := cmd.CombinedOutput()
if err != nil {
msg := strings.TrimSpace(string(out))
if msg == "" {
msg = err.Error()
}
if len(msg) > 512 {
msg = msg[:512]
}
return fmt.Errorf("pg_dump: %s", msg)
}
return nil
}

211
internal/backup/handler.go Normal file
View File

@@ -0,0 +1,211 @@
package backup
import (
"errors"
"net/http"
"os"
"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 = "/backups"
type handler struct {
logger *logging.Logger
service *Service
}
func NewHandler(logger *logging.Logger, service *Service) handlers.Handler {
return &handler{logger: logger, service: service}
}
func (h *handler) Register(router *gin.RouterGroup) {
group := rbac.Group(router, baseURL, rbac.RequireStaff(perm.Backups))
group.GET("", h.list)
group.POST("", h.create)
group.GET("/:id/download", h.download)
group.GET("/:id", h.getByID)
group.DELETE("/:id", h.delete)
}
// list godoc
// @Summary List backups
// @Description Returns paginated SQL backup files
// @Tags backups
// @Produce json
// @Security BearerAuth
// @Param search query string false "Filter by file name"
// @Param status query string false "Filter by status (pending, completed, failed)"
// @Param page query int false "Page number" default(1)
// @Param limit query int false "Items per page" default(10)
// @Param lang query string false "Language of localized fields; all returns the full {en, ru, tm} objects" Enums(tm, ru, en, all) default(tm)
// @Success 200 {object} appresult.AppSuccess
// @Failure 400 {object} appresult.AppError
// @Failure 500 {object} appresult.AppError
// @Router /backups [get]
func (h *handler) list(c *gin.Context) {
filter, ok := parseListFilter(c)
if !ok {
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
return
}
result, err := h.service.List(c.Request.Context(), filter)
if err != nil {
h.logger.Errorf("list backups failed: %v", err)
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return
}
c.JSON(http.StatusOK, appresult.SuccessWithData(result))
}
// getByID godoc
// @Summary Get backup by ID
// @Description Returns a single backup record
// @Tags backups
// @Produce json
// @Security BearerAuth
// @Param id path int true "Backup ID"
// @Param lang query string false "Language of localized fields; all returns the full {en, ru, tm} objects" Enums(tm, ru, en, all) default(tm)
// @Success 200 {object} appresult.AppSuccess
// @Failure 400 {object} appresult.AppError
// @Failure 404 {object} appresult.AppError
// @Failure 500 {object} appresult.AppError
// @Router /backups/{id} [get]
func (h *handler) getByID(c *gin.Context) {
id, ok := shared.ParseID(c.Param("id"))
if !ok {
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
return
}
item, err := h.service.GetByID(c.Request.Context(), id)
if errors.Is(err, pgx.ErrNoRows) {
c.JSON(http.StatusNotFound, appresult.ErrNotFound)
return
}
if err != nil {
h.logger.Errorf("get backup failed: %v", err)
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return
}
c.JSON(http.StatusOK, appresult.SuccessWithData(item))
}
// create godoc
// @Summary Create SQL backup
// @Description Runs pg_dump and stores the resulting .sql file
// @Tags backups
// @Produce json
// @Security BearerAuth
// @Param lang query string false "Language of localized fields; all returns the full {en, ru, tm} objects" Enums(tm, ru, en, all) default(tm)
// @Success 201 {object} appresult.AppSuccess
// @Failure 500 {object} appresult.AppError
// @Router /backups [post]
func (h *handler) create(c *gin.Context) {
item, err := h.service.Create(c.Request.Context(), currentUserID(c))
if err != nil {
h.logger.Errorf("create backup failed: %v", err)
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return
}
c.JSON(http.StatusCreated, appresult.SuccessWithData(item))
}
// download godoc
// @Summary Download backup SQL file
// @Description Downloads the .sql dump for a completed backup
// @Tags backups
// @Produce application/sql
// @Security BearerAuth
// @Param id path int true "Backup ID"
// @Param lang query string false "Language of localized fields; all returns the full {en, ru, tm} objects" Enums(tm, ru, en, all) default(tm)
// @Success 200 {file} file
// @Failure 400 {object} appresult.AppError
// @Failure 404 {object} appresult.AppError
// @Failure 500 {object} appresult.AppError
// @Router /backups/{id}/download [get]
func (h *handler) download(c *gin.Context) {
id, ok := shared.ParseID(c.Param("id"))
if !ok {
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
return
}
item, path, err := h.service.FilePath(c.Request.Context(), id)
if errors.Is(err, pgx.ErrNoRows) {
c.JSON(http.StatusNotFound, appresult.ErrNotFound)
return
}
if err != nil {
h.logger.Errorf("download backup failed: %v", err)
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return
}
if item.Status != "completed" {
c.JSON(http.StatusNotFound, appresult.ErrNotFound)
return
}
if _, err := os.Stat(path); err != nil {
c.JSON(http.StatusNotFound, appresult.ErrNotFound)
return
}
c.FileAttachment(path, item.FileName)
}
// delete godoc
// @Summary Delete backup
// @Description Deletes a backup record and its SQL file
// @Tags backups
// @Produce json
// @Security BearerAuth
// @Param id path int true "Backup ID"
// @Param lang query string false "Language of localized fields; all returns the full {en, ru, tm} objects" Enums(tm, ru, en, all) default(tm)
// @Success 200 {object} appresult.AppSuccess
// @Failure 400 {object} appresult.AppError
// @Failure 404 {object} appresult.AppError
// @Failure 500 {object} appresult.AppError
// @Router /backups/{id} [delete]
func (h *handler) delete(c *gin.Context) {
id, ok := shared.ParseID(c.Param("id"))
if !ok {
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
return
}
if err := h.service.Delete(c.Request.Context(), id); errors.Is(err, pgx.ErrNoRows) {
c.JSON(http.StatusNotFound, appresult.ErrNotFound)
return
} else if err != nil {
h.logger.Errorf("delete backup failed: %v", err)
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return
}
c.JSON(http.StatusOK, appresult.SuccessWithData("backup removed"))
}
func parseListFilter(c *gin.Context) (ListFilter, bool) {
page, limit, ok := parsePageLimit(c)
if !ok {
return ListFilter{}, false
}
filter := ListFilter{Page: page, Limit: limit, Search: queryValue(c, "search", "q")}
if raw := queryValue(c, "status"); raw != "" {
filter.Status = &raw
}
return filter, true
}

69
internal/backup/http.go Normal file
View File

@@ -0,0 +1,69 @@
package backup
import (
"strconv"
"strings"
"github.com/gin-gonic/gin"
"online-back/internal/shared"
)
func queryValue(c *gin.Context, keys ...string) string {
for _, key := range keys {
if raw := strings.TrimSpace(c.Query(key)); raw != "" && raw != "undefined" && raw != "null" {
return raw
}
}
return ""
}
func parsePageLimit(c *gin.Context) (page, limit int, ok bool) {
page = shared.DefaultPage
limit = shared.DefaultLimit
if raw := queryValue(c, "page"); raw != "" {
p, err := strconv.Atoi(raw)
if err != nil || p < 1 {
return 0, 0, false
}
page = p
}
if raw := queryValue(c, "limit"); raw != "" {
l, err := strconv.Atoi(raw)
if err != nil || l < 1 {
return 0, 0, false
}
if l > shared.MaxLimit {
l = shared.MaxLimit
}
limit = l
}
return page, limit, true
}
func currentUserID(c *gin.Context) *int64 {
rawID, exists := c.Get("id")
if !exists {
return nil
}
switch id := rawID.(type) {
case int64:
if id > 0 {
return &id
}
case int:
if id > 0 {
v := int64(id)
return &v
}
case string:
parsed, err := strconv.ParseInt(id, 10, 64)
if err == nil && parsed > 0 {
return &parsed
}
}
return nil
}

154
internal/backup/service.go Normal file
View File

@@ -0,0 +1,154 @@
package backup
import (
"context"
"fmt"
"os"
"path/filepath"
"strings"
"time"
"unicode"
"online-back/pkg/logging"
)
type Service struct {
repo Repository
dumper Dumper
dir string
logger *logging.Logger
}
func NewService(repo Repository, dumper Dumper, dir string, logger *logging.Logger) *Service {
return &Service{repo: repo, dumper: dumper, dir: dir, logger: logger}
}
func (s *Service) List(ctx context.Context, filter ListFilter) (ListBackupDTO, error) {
return s.repo.List(ctx, filter)
}
func (s *Service) GetByID(ctx context.Context, id int64) (BackupDTO, error) {
return s.repo.GetByID(ctx, id)
}
func (s *Service) Create(ctx context.Context, userID *int64) (BackupDTO, error) {
if err := os.MkdirAll(s.dir, 0o750); err != nil {
return BackupDTO{}, fmt.Errorf("create backup dir: %w", err)
}
fileName, err := s.nextFileName(ctx)
if err != nil {
return BackupDTO{}, err
}
item, err := s.repo.Create(ctx, CreateBackupDTO{FileName: fileName, CreatedBy: userID})
if err != nil {
return BackupDTO{}, err
}
dest, err := s.absPath(fileName)
if err != nil {
_, _ = s.repo.Finish(ctx, item.Id, 0, "failed", errString(err))
return BackupDTO{}, err
}
if dumpErr := s.dumper.Dump(ctx, dest); dumpErr != nil {
_ = os.Remove(dest)
msg := dumpErr.Error()
s.logger.Errorf("sql backup dump failed: %v", dumpErr)
return s.repo.Finish(ctx, item.Id, 0, "failed", &msg)
}
info, statErr := os.Stat(dest)
if statErr != nil {
_ = os.Remove(dest)
msg := statErr.Error()
return s.repo.Finish(ctx, item.Id, 0, "failed", &msg)
}
return s.repo.Finish(ctx, item.Id, info.Size(), "completed", nil)
}
func (s *Service) Delete(ctx context.Context, id int64) error {
item, err := s.repo.GetByID(ctx, id)
if err != nil {
return err
}
if err := s.repo.Delete(ctx, id); err != nil {
return err
}
if path, pathErr := s.absPath(item.FileName); pathErr == nil {
if rmErr := os.Remove(path); rmErr != nil && !os.IsNotExist(rmErr) {
s.logger.Errorf("remove backup file %s: %v", item.FileName, rmErr)
}
}
return nil
}
func (s *Service) FilePath(ctx context.Context, id int64) (BackupDTO, string, error) {
item, err := s.repo.GetByID(ctx, id)
if err != nil {
return BackupDTO{}, "", err
}
path, err := s.absPath(item.FileName)
if err != nil {
return BackupDTO{}, "", err
}
return item, path, nil
}
func (s *Service) nextFileName(ctx context.Context) (string, error) {
day := time.Now().UTC().Format("2006_01_02")
prefix := "backup_" + day + "_"
n, err := s.repo.CountByFilePrefix(ctx, prefix)
if err != nil {
return "", err
}
return fmt.Sprintf("backup_%s_%02d.sql", day, n+1), nil
}
func (s *Service) absPath(fileName string) (string, error) {
if !validBackupFileName(fileName) {
return "", fmt.Errorf("invalid backup file name")
}
dir, err := filepath.Abs(s.dir)
if err != nil {
return "", err
}
full, err := filepath.Abs(filepath.Join(dir, fileName))
if err != nil {
return "", err
}
sep := string(os.PathSeparator)
if full != dir && !strings.HasPrefix(full, dir+sep) {
return "", fmt.Errorf("invalid backup path")
}
return full, nil
}
func validBackupFileName(name string) bool {
if name == "" || name != filepath.Base(name) || strings.Contains(name, "..") {
return false
}
if !strings.HasPrefix(name, "backup_") || !strings.HasSuffix(name, ".sql") {
return false
}
for _, r := range name {
if unicode.IsLetter(r) || unicode.IsDigit(r) || r == '_' || r == '.' {
continue
}
return false
}
return true
}
func errString(err error) *string {
if err == nil {
return nil
}
msg := err.Error()
return &msg
}

View File

@@ -0,0 +1,24 @@
package backup
import "testing"
func TestValidBackupFileName(t *testing.T) {
tests := []struct {
name string
ok bool
}{
{"backup_2026_05_22_01.sql", true},
{"backup_2026_08_29_12.sql", true},
{"", false},
{"../etc/passwd", false},
{"backup_2026_05_22_01.sql/../../x", false},
{"foo.sql", false},
{"backup_2026_05_22_01.sql.exe", false},
{"backup_2026_05_22_01.sql ", false},
}
for _, tt := range tests {
if got := validBackupFileName(tt.name); got != tt.ok {
t.Errorf("validBackupFileName(%q) = %v, want %v", tt.name, got, tt.ok)
}
}
}

View File

@@ -0,0 +1,12 @@
package backup
import "context"
type Repository interface {
List(ctx context.Context, filter ListFilter) (ListBackupDTO, error)
GetByID(ctx context.Context, id int64) (BackupDTO, error)
Create(ctx context.Context, dto CreateBackupDTO) (BackupDTO, error)
Finish(ctx context.Context, id int64, sizeBytes int64, status string, errMsg *string) (BackupDTO, error)
Delete(ctx context.Context, id int64) error
CountByFilePrefix(ctx context.Context, prefix string) (int64, error)
}

View File

@@ -0,0 +1,251 @@
package db
import (
"context"
"database/sql"
"fmt"
"strings"
"online-back/internal/cards/cardbalance"
"online-back/internal/identity/rbac"
"online-back/internal/shared"
"online-back/pkg/client/postgresql"
"online-back/pkg/logging"
"online-back/pkg/repository/genericrepo"
"github.com/jackc/pgx/v4"
)
type repository struct {
client postgresql.Client
logger *logging.Logger
}
func NewRepository(client postgresql.Client, logger *logging.Logger) cardbalance.Repository {
return &repository{client: client, logger: logger}
}
// cardBalanceColumns lists the columns returned to callers. card_last4 and
// expiry_at are DB-generated (see migration), so they are never written but
// are always readable; the raw card_number is intentionally excluded here so
// full PANs never leave the API - only the masked last4 is exposed.
var cardBalanceColumns = []string{
"id", "passport_number", "card_last4", "expiry_month", "expiry_year", "expiry_at",
"balance_amount", "balance_currency", "status", "checked_at",
"branch_id", "created_by", "created_at", "updated_at",
}
var cardBalanceColumnsSQL = strings.Join(cardBalanceColumns, ", ")
var cardBalanceWritableColumns = []string{
"passport_number", "card_number", "expiry_month", "expiry_year",
"balance_amount", "balance_currency", "status", "checked_at", "branch_id", "created_by",
}
var cardBalanceWritableColumnsSQL = strings.Join(cardBalanceWritableColumns, ", ")
const cardBalanceFromClause = ` FROM card_balances cb
LEFT JOIN users u ON u.id = cb.created_by
LEFT JOIN branches b ON b.id = cb.branch_id`
var cardBalanceSelectColumns = shared.PrefixedColumns("cb", cardBalanceColumns) + `,
COALESCE(u.username, ''), COALESCE(u.phone, ''), COALESCE(u.email, ''), ` + shared.UserDisplaySQL + `, b.name`
func resolveStatus(status *string) string {
if status == nil || strings.TrimSpace(*status) == "" {
return "pending"
}
return *status
}
func resolveCurrency(currency *string) string {
if currency == nil || strings.TrimSpace(*currency) == "" {
return "TMT"
}
return *currency
}
func createArgs(dto cardbalance.CreateCardBalanceDTO) []interface{} {
return []interface{}{
dto.PassportNumber, dto.CardNumber, dto.ExpiryMonth, dto.ExpiryYear,
dto.BalanceAmount, resolveCurrency(dto.BalanceCurrency), resolveStatus(dto.Status),
shared.OptionalTime(dto.CheckedAt), shared.OptionalInt64(dto.BranchId), shared.OptionalInt64(dto.CreatedBy),
}
}
func updateArgs(dto cardbalance.UpdateCardBalanceDTO) []interface{} {
return []interface{}{
dto.PassportNumber, dto.CardNumber, dto.ExpiryMonth, dto.ExpiryYear,
dto.BalanceAmount, resolveCurrency(dto.BalanceCurrency), resolveStatus(dto.Status),
shared.OptionalTime(dto.CheckedAt), shared.OptionalInt64(dto.BranchId), shared.OptionalInt64(dto.CreatedBy),
}
}
func (r *repository) List(ctx context.Context, filter cardbalance.ListFilter) (cardbalance.ListCardBalanceDTO, error) {
whereClause, args := buildListQuery(filter)
var count int64
if err := r.client.QueryRow(ctx, `SELECT COUNT(*) FROM card_balances cb`+whereClause, args...).Scan(&count); err != nil {
return cardbalance.ListCardBalanceDTO{}, err
}
offset := (filter.Page - 1) * filter.Limit
limitPlaceholder := len(args) + 1
offsetPlaceholder := len(args) + 2
query := fmt.Sprintf(
`SELECT %s%s%s ORDER BY cb.id DESC LIMIT $%d OFFSET $%d`,
cardBalanceSelectColumns, cardBalanceFromClause, whereClause, limitPlaceholder, offsetPlaceholder,
)
rows, err := r.client.Query(ctx, query, append(args, filter.Limit, offset)...)
if err != nil {
return cardbalance.ListCardBalanceDTO{}, err
}
defer rows.Close()
var items []cardbalance.CardBalanceDTO
for rows.Next() {
item, err := scanCardBalanceWithJoins(rows)
if err != nil {
return cardbalance.ListCardBalanceDTO{}, err
}
items = append(items, item)
}
if err := rows.Err(); err != nil {
return cardbalance.ListCardBalanceDTO{}, err
}
return cardbalance.ListCardBalanceDTO{Count: count, CardBalances: items}, nil
}
func buildListQuery(filter cardbalance.ListFilter) (whereClause string, args []interface{}) {
conditions := []string{"cb.deleted_at IS NULL"}
if filter.Status != nil {
args = append(args, *filter.Status)
conditions = append(conditions, fmt.Sprintf("cb.status = $%d", len(args)))
}
if filter.PassportNumber != "" {
args = append(args, filter.PassportNumber)
conditions = append(conditions, fmt.Sprintf("cb.passport_number = $%d", len(args)))
}
if filter.CreatedBy != nil {
args = append(args, *filter.CreatedBy)
conditions = append(conditions, fmt.Sprintf("cb.created_by = $%d", len(args)))
}
if len(filter.BranchIds) > 0 {
conditions, args = rbac.AppendBranchIDs(conditions, args, "cb.branch_id", filter.BranchIds)
} else if filter.BranchId != nil {
args = append(args, *filter.BranchId)
conditions = append(conditions, fmt.Sprintf("cb.branch_id = $%d", len(args)))
}
return " WHERE " + strings.Join(conditions, " AND "), args
}
func (r *repository) GetByID(ctx context.Context, id int64) (cardbalance.CardBalanceDTO, error) {
query := `SELECT ` + cardBalanceSelectColumns + cardBalanceFromClause + ` WHERE cb.id = $1 AND cb.deleted_at IS NULL`
return scanCardBalanceWithJoins(r.client.QueryRow(ctx, query, id))
}
func (r *repository) Create(ctx context.Context, dto cardbalance.CreateCardBalanceDTO) (cardbalance.CardBalanceDTO, 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 card_balances (%s) VALUES (%s)
RETURNING %s
)
SELECT %s
FROM inserted cb
LEFT JOIN users u ON u.id = cb.created_by
LEFT JOIN branches b ON b.id = cb.branch_id`,
cardBalanceWritableColumnsSQL, strings.Join(placeholders, ", "),
cardBalanceColumnsSQL, cardBalanceSelectColumns,
)
return scanCardBalanceWithJoins(r.client.QueryRow(ctx, query, args...))
}
func (r *repository) Update(ctx context.Context, id int64, dto cardbalance.UpdateCardBalanceDTO) (cardbalance.CardBalanceDTO, error) {
args := updateArgs(dto)
assignments := make([]string, len(cardBalanceWritableColumns))
for i, column := range cardBalanceWritableColumns {
assignments[i] = fmt.Sprintf("%s = $%d", column, i+1)
}
args = append(args, id)
query := fmt.Sprintf(`
WITH updated AS (
UPDATE card_balances SET %s, updated_at = now()
WHERE id = $%d AND deleted_at IS NULL
RETURNING %s
)
SELECT %s
FROM updated cb
LEFT JOIN users u ON u.id = cb.created_by
LEFT JOIN branches b ON b.id = cb.branch_id`,
strings.Join(assignments, ", "), len(args), cardBalanceColumnsSQL, cardBalanceSelectColumns,
)
return scanCardBalanceWithJoins(r.client.QueryRow(ctx, query, args...))
}
func (r *repository) Delete(ctx context.Context, id int64) error {
tag, err := r.client.Exec(ctx, `UPDATE card_balances SET deleted_at = now() WHERE id = $1 AND deleted_at IS NULL`, id)
if err != nil {
return err
}
if tag.RowsAffected() == 0 {
return pgx.ErrNoRows
}
return nil
}
func scanCardBalanceWithJoins(row genericrepo.Scanner) (cardbalance.CardBalanceDTO, error) {
var item cardbalance.CardBalanceDTO
var branchID sql.NullInt64
var branchNameJSON []byte
var userUsername, userPhone, userEmail, userName string
dest := []interface{}{
&item.Id, &item.PassportNumber, &item.CardLast4, &item.ExpiryMonth, &item.ExpiryYear, &item.ExpiryAt,
&item.BalanceAmount, &item.BalanceCurrency, &item.Status, &item.CheckedAt,
&branchID, &item.CreatedById, &item.CreatedAt, &item.UpdatedAt,
&userUsername, &userPhone, &userEmail, &userName, &branchNameJSON,
}
if err := row.Scan(dest...); err != nil {
return cardbalance.CardBalanceDTO{}, err
}
if branchID.Valid {
item.BranchId = branchID.Int64
var branchName shared.LocalizedText
if err := shared.UnmarshalLocalized(branchNameJSON, &branchName); err != nil {
return cardbalance.CardBalanceDTO{}, err
}
item.Branch = &shared.NamedInfo{Id: item.BranchId, Name: branchName}
}
if item.CreatedById != nil {
item.CreatedBy = &shared.UserInfo{
Id: *item.CreatedById,
Name: userName,
Username: userUsername,
Phone: userPhone,
Email: userEmail,
}
}
return item, nil
}

View File

@@ -0,0 +1,67 @@
package cardbalance
import (
"time"
"online-back/internal/shared"
)
type CardBalanceDTO struct {
Id int64 `json:"id"`
PassportNumber string `json:"passportNumber"`
CardLast4 string `json:"cardLast4"`
ExpiryMonth int16 `json:"expiryMonth"`
ExpiryYear int16 `json:"expiryYear"`
ExpiryAt time.Time `json:"expiryAt"`
BalanceAmount *float64 `json:"balanceAmount"`
BalanceCurrency string `json:"balanceCurrency"`
Status string `json:"status"`
CheckedAt *time.Time `json:"checkedAt"`
BranchId int64 `json:"-"`
Branch *shared.NamedInfo `json:"branch,omitempty"`
CreatedById *int64 `json:"-"`
CreatedBy *shared.UserInfo `json:"createdBy,omitempty"`
CreatedAt time.Time `json:"createdAt"`
UpdatedAt time.Time `json:"updatedAt"`
}
type CreateCardBalanceDTO struct {
PassportNumber string `json:"passportNumber" binding:"required"`
CardNumber string `json:"cardNumber" binding:"required"`
ExpiryMonth int16 `json:"expiryMonth" binding:"required"`
ExpiryYear int16 `json:"expiryYear" binding:"required"`
BalanceAmount *float64 `json:"balanceAmount"`
BalanceCurrency *string `json:"balanceCurrency"`
Status *string `json:"status"`
CheckedAt *shared.FlexibleTime `json:"checkedAt" swaggertype:"string" format:"date-time"`
BranchId *shared.FlexibleInt64 `json:"branchId" swaggertype:"integer"`
CreatedBy *shared.FlexibleInt64 `json:"createdBy" swaggertype:"integer"`
}
type UpdateCardBalanceDTO struct {
PassportNumber string `json:"passportNumber" binding:"required"`
CardNumber string `json:"cardNumber" binding:"required"`
ExpiryMonth int16 `json:"expiryMonth" binding:"required"`
ExpiryYear int16 `json:"expiryYear" binding:"required"`
BalanceAmount *float64 `json:"balanceAmount"`
BalanceCurrency *string `json:"balanceCurrency"`
Status *string `json:"status"`
CheckedAt *shared.FlexibleTime `json:"checkedAt" swaggertype:"string" format:"date-time"`
BranchId *shared.FlexibleInt64 `json:"branchId" swaggertype:"integer"`
CreatedBy *shared.FlexibleInt64 `json:"createdBy" swaggertype:"integer"`
}
type ListFilter struct {
Status *string
PassportNumber string
CreatedBy *int64
BranchId *int64
BranchIds []int64
Page int
Limit int
}
type ListCardBalanceDTO struct {
Count int64 `json:"count"`
CardBalances []CardBalanceDTO `json:"cardBalances"`
}

View File

@@ -0,0 +1,265 @@
package cardbalance
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 = "/card-balances"
type handler struct {
logger *logging.Logger
repository Repository
}
func NewHandler(logger *logging.Logger, repository Repository) handlers.Handler {
return &handler{logger: logger, repository: repository}
}
func (h *handler) Register(router *gin.RouterGroup) {
group := rbac.Group(router, baseURL, rbac.Require(perm.Cards))
group.GET("", h.list)
group.GET("/:id", h.getByID)
group.POST("", h.create)
group.PUT("/:id", h.update)
group.DELETE("/:id", h.delete)
}
// list godoc
// @Summary List card balances
// @Description Returns paginated card balance checks with optional filters
// @Tags card-balances
// @Produce json
// @Security BearerAuth
// @Param status query string false "Filter by status"
// @Param passport_number query string false "Filter by passport number"
// @Param created_by query int false "Filter by creator user ID"
// @Param page query int false "Page number" default(1)
// @Param limit query int false "Items per page" default(10)
// @Param lang query string false "Language of localized fields; all returns the full {en, ru, tm} objects" Enums(tm, ru, en, all) default(tm)
// @Success 200 {object} appresult.AppSuccess
// @Failure 400 {object} appresult.AppError
// @Failure 500 {object} appresult.AppError
// @Router /card-balances [get]
func (h *handler) list(c *gin.Context) {
filter, ok := parseListFilter(c)
if !ok {
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
return
}
result, err := h.repository.List(c.Request.Context(), filter)
if err != nil {
h.logger.Errorf("list card balances failed: %v", err)
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return
}
c.JSON(http.StatusOK, appresult.SuccessWithData(result))
}
// getByID godoc
// @Summary Get card balance by ID
// @Description Returns a single card balance check
// @Tags card-balances
// @Produce json
// @Security BearerAuth
// @Param id path int true "Card balance ID"
// @Param lang query string false "Language of localized fields; all returns the full {en, ru, tm} objects" Enums(tm, ru, en, all) default(tm)
// @Success 200 {object} appresult.AppSuccess
// @Failure 400 {object} appresult.AppError
// @Failure 404 {object} appresult.AppError
// @Failure 500 {object} appresult.AppError
// @Router /card-balances/{id} [get]
func (h *handler) getByID(c *gin.Context) {
id, ok := shared.ParseID(c.Param("id"))
if !ok {
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
return
}
item, err := h.repository.GetByID(c.Request.Context(), id)
if errors.Is(err, pgx.ErrNoRows) {
c.JSON(http.StatusNotFound, appresult.ErrNotFound)
return
}
if err != nil {
h.logger.Errorf("get card balance failed: %v", err)
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return
}
if !rbac.GuardOrder(c, item.CreatedById, item.BranchId) {
return
}
c.JSON(http.StatusOK, appresult.SuccessWithData(item))
}
// create godoc
// @Summary Create card balance
// @Description Creates a new card balance check record
// @Tags card-balances
// @Accept json
// @Produce json
// @Security BearerAuth
// @Param body body CreateCardBalanceDTO true "Card balance payload"
// @Param lang query string false "Language of localized fields; all returns the full {en, ru, tm} objects" Enums(tm, ru, en, all) default(tm)
// @Success 201 {object} appresult.AppSuccess
// @Failure 400 {object} appresult.AppError
// @Failure 500 {object} appresult.AppError
// @Router /card-balances [post]
func (h *handler) create(c *gin.Context) {
var dto CreateCardBalanceDTO
if err := c.ShouldBindJSON(&dto); err != nil {
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
return
}
item, err := h.repository.Create(c.Request.Context(), dto)
if err != nil {
h.logger.Errorf("create card balance failed: %v", err)
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return
}
c.JSON(http.StatusCreated, appresult.SuccessWithData(item))
}
// update godoc
// @Summary Update card balance
// @Description Updates an existing card balance check record
// @Tags card-balances
// @Accept json
// @Produce json
// @Security BearerAuth
// @Param id path int true "Card balance ID"
// @Param body body UpdateCardBalanceDTO true "Card balance payload"
// @Param lang query string false "Language of localized fields; all returns the full {en, ru, tm} objects" Enums(tm, ru, en, all) default(tm)
// @Success 200 {object} appresult.AppSuccess
// @Failure 400 {object} appresult.AppError
// @Failure 404 {object} appresult.AppError
// @Failure 500 {object} appresult.AppError
// @Router /card-balances/{id} [put]
func (h *handler) update(c *gin.Context) {
id, ok := shared.ParseID(c.Param("id"))
if !ok {
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
return
}
if !h.guardCardBalanceByID(c, id) {
return
}
var dto UpdateCardBalanceDTO
if err := c.ShouldBindJSON(&dto); err != nil {
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
return
}
item, err := h.repository.Update(c.Request.Context(), id, dto)
if errors.Is(err, pgx.ErrNoRows) {
c.JSON(http.StatusNotFound, appresult.ErrNotFound)
return
}
if err != nil {
h.logger.Errorf("update card balance failed: %v", err)
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return
}
c.JSON(http.StatusOK, appresult.SuccessWithData(item))
}
// delete godoc
// @Summary Delete card balance
// @Description Soft-deletes a card balance check record
// @Tags card-balances
// @Produce json
// @Security BearerAuth
// @Param id path int true "Card balance ID"
// @Param lang query string false "Language of localized fields; all returns the full {en, ru, tm} objects" Enums(tm, ru, en, all) default(tm)
// @Success 200 {object} appresult.AppSuccess
// @Failure 400 {object} appresult.AppError
// @Failure 404 {object} appresult.AppError
// @Failure 500 {object} appresult.AppError
// @Router /card-balances/{id} [delete]
func (h *handler) delete(c *gin.Context) {
id, ok := shared.ParseID(c.Param("id"))
if !ok {
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
return
}
if !h.guardCardBalanceByID(c, id) {
return
}
if err := h.repository.Delete(c.Request.Context(), id); errors.Is(err, pgx.ErrNoRows) {
c.JSON(http.StatusNotFound, appresult.ErrNotFound)
return
} else if err != nil {
h.logger.Errorf("delete card balance failed: %v", err)
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return
}
c.JSON(http.StatusOK, appresult.SuccessWithData("card balance removed"))
}
func (h *handler) guardCardBalanceByID(c *gin.Context, id int64) bool {
if rbac.SkipRecordGuard(c) {
return true
}
item, err := h.repository.GetByID(c.Request.Context(), id)
if errors.Is(err, pgx.ErrNoRows) {
c.JSON(http.StatusNotFound, appresult.ErrNotFound)
return false
}
if err != nil {
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return false
}
return rbac.GuardOrder(c, item.CreatedById, item.BranchId)
}
func parseListFilter(c *gin.Context) (ListFilter, bool) {
page, limit, ok := shared.ParsePageLimit(c)
if !ok {
return ListFilter{}, false
}
filter := ListFilter{Page: page, Limit: limit}
if raw := shared.QueryValue(c, "status"); raw != "" {
filter.Status = &raw
}
if raw := shared.QueryValue(c, "passport_number", "passportNumber"); raw != "" {
filter.PassportNumber = raw
}
if id, ok := shared.OptionalQueryID(c, "created_by", "createdBy"); !ok {
return ListFilter{}, false
} else if id != nil {
filter.CreatedBy = id
}
if id, ok := shared.OptionalQueryID(c, "branch_id", "branchId"); !ok {
return ListFilter{}, false
} else if id != nil {
filter.BranchId = id
}
rbac.BindBranchIDs(c, &filter.BranchIds)
return filter, true
}

View File

@@ -0,0 +1,11 @@
package cardbalance
import "context"
type Repository interface {
List(ctx context.Context, filter ListFilter) (ListCardBalanceDTO, error)
GetByID(ctx context.Context, id int64) (CardBalanceDTO, error)
Create(ctx context.Context, dto CreateCardBalanceDTO) (CardBalanceDTO, error)
Update(ctx context.Context, id int64, dto UpdateCardBalanceDTO) (CardBalanceDTO, error)
Delete(ctx context.Context, id int64) error
}

View File

@@ -6,6 +6,8 @@ import (
"strings"
"online-back/internal/cards/cardorder"
"online-back/internal/identity/rbac"
"online-back/internal/shared"
"online-back/pkg/client/postgresql"
"online-back/pkg/logging"
"online-back/pkg/repository/genericrepo"
@@ -25,8 +27,6 @@ func NewRepository(client postgresql.Client, logger *logging.Logger) cardorder.R
}
}
// cardOrderWritableColumns lists every card_orders column except id, created_at and
// updated_at, in the exact order CreateCardOrderDTO/UpdateCardOrderDTO fields are read.
var cardOrderWritableColumns = []string{
"unique_id", "card_state_id", "card_type_id", "region", "branch_id",
"customer_name", "customer_surname", "customer_patronic_name", "born_at", "old_surname", "citizenship",
@@ -41,6 +41,22 @@ var cardOrderColumnsSQL = strings.Join(cardOrderColumns, ", ")
var cardOrderWritableColumnsSQL = strings.Join(cardOrderWritableColumns, ", ")
const cardOrderFromClause = ` FROM card_orders co
LEFT JOIN card_states cs ON cs.id = co.card_state_id
LEFT JOIN card_types ct ON ct.id = co.card_type_id
LEFT JOIN branches b ON b.id = co.branch_id
LEFT JOIN users u ON u.id = co.user_id`
var cardOrderSelectColumns = shared.PrefixedColumns("co", cardOrderColumns) + `,
cs.name, ct.name, b.name, ` + shared.UserDisplaySQL + `, COALESCE(u.username, ''), COALESCE(u.phone, ''), COALESCE(u.email, '')`
const cardOrderListFromClause = cardOrderFromClause + `
LEFT JOIN provinces bp ON bp.id = b.province_id`
var cardOrderListColumns = `co.id, co.unique_id, co.customer_name, co.customer_surname, co.customer_patronic_name,
co.phone, co.card_type_id, ct.name, co.card_state_id, cs.name, co.branch_id, b.name, bp.name, co.region,
co.passport_serie, co.passport_id, co.user_id, ` + shared.UserDisplaySQL + `, co.status, co.paid, co.created_at`
func resolveStatus(status *string) *string {
if status == nil || strings.TrimSpace(*status) == "" {
pending := "pending"
@@ -58,77 +74,102 @@ func resolvePaid(paid *bool) bool {
func createArgs(dto cardorder.CreateCardOrderDTO) []interface{} {
return []interface{}{
dto.UniqueId, dto.CardStateId, dto.CardTypeId, dto.Region, dto.BranchId,
dto.CustomerName, dto.CustomerSurname, dto.CustomerPatronicName, dto.BornAt, dto.OldSurname, dto.Citizenship,
dto.PassportSerie, dto.PassportId, dto.PassportGivenAt, dto.PassportGivenBy, dto.BornPlace,
dto.UniqueId, dto.CardStateId.Int64(), dto.CardTypeId.Int64(), dto.Region, dto.BranchId.Int64(),
dto.CustomerName, dto.CustomerSurname, dto.CustomerPatronicName, shared.OptionalTime(dto.BornAt), dto.OldSurname, dto.Citizenship,
dto.PassportSerie, dto.PassportId, dto.PassportGivenAt.Time(), dto.PassportGivenBy, dto.BornPlace,
dto.JobLocation, dto.PassportAddress, dto.RealAddress, dto.Phone, dto.PhoneAdditional,
resolveStatus(dto.Status), dto.PassportOne, dto.PassportTwo, dto.PassportThree, dto.PassportFour, dto.Notes, dto.UserId, resolvePaid(dto.Paid),
resolveStatus(dto.Status), dto.PassportOne, dto.PassportTwo, dto.PassportThree, dto.PassportFour, dto.Notes, shared.OptionalInt64(dto.UserId), resolvePaid(dto.Paid),
}
}
func updateArgs(dto cardorder.UpdateCardOrderDTO) []interface{} {
return []interface{}{
dto.UniqueId, dto.CardStateId, dto.CardTypeId, dto.Region, dto.BranchId,
dto.CustomerName, dto.CustomerSurname, dto.CustomerPatronicName, dto.BornAt, dto.OldSurname, dto.Citizenship,
dto.PassportSerie, dto.PassportId, dto.PassportGivenAt, dto.PassportGivenBy, dto.BornPlace,
dto.UniqueId, dto.CardStateId.Int64(), dto.CardTypeId.Int64(), dto.Region, dto.BranchId.Int64(),
dto.CustomerName, dto.CustomerSurname, dto.CustomerPatronicName, shared.OptionalTime(dto.BornAt), dto.OldSurname, dto.Citizenship,
dto.PassportSerie, dto.PassportId, dto.PassportGivenAt.Time(), dto.PassportGivenBy, dto.BornPlace,
dto.JobLocation, dto.PassportAddress, dto.RealAddress, dto.Phone, dto.PhoneAdditional,
resolveStatus(dto.Status), dto.PassportOne, dto.PassportTwo, dto.PassportThree, dto.PassportFour, dto.Notes, dto.UserId, dto.Paid,
resolveStatus(dto.Status), dto.PassportOne, dto.PassportTwo, dto.PassportThree, dto.PassportFour, dto.Notes, shared.OptionalInt64(dto.UserId), dto.Paid,
}
}
func (r *repository) List(ctx context.Context, filter cardorder.ListFilter) (cardorder.ListCardOrderDTO, error) {
whereClause, args := buildListQuery(filter)
items, count, err := r.generic.List(ctx, whereClause, args, filter.Page, filter.Limit, "id")
var count int64
if err := r.client.QueryRow(ctx, `SELECT COUNT(*) FROM card_orders co`+whereClause, args...).Scan(&count); err != nil {
return cardorder.ListCardOrderDTO{}, err
}
offset := (filter.Page - 1) * filter.Limit
limitPlaceholder := len(args) + 1
offsetPlaceholder := len(args) + 2
query := fmt.Sprintf(
`SELECT %s%s%s ORDER BY co.id LIMIT $%d OFFSET $%d`,
cardOrderListColumns, cardOrderListFromClause, whereClause, limitPlaceholder, offsetPlaceholder,
)
rows, err := r.client.Query(ctx, query, append(args, filter.Limit, offset)...)
if err != nil {
return cardorder.ListCardOrderDTO{}, err
}
defer rows.Close()
items := []cardorder.CardOrderListItemDTO{}
for rows.Next() {
item, err := scanCardOrderListItem(rows)
if err != nil {
return cardorder.ListCardOrderDTO{}, err
}
items = append(items, item)
}
if err := rows.Err(); err != nil {
return cardorder.ListCardOrderDTO{}, err
}
return cardorder.ListCardOrderDTO{Count: count, CardOrders: items}, nil
}
func buildListQuery(filter cardorder.ListFilter) (whereClause string, args []interface{}) {
var conditions []string
conditions := []string{"co.deleted_at IS NULL"}
if filter.Status != nil {
args = append(args, *filter.Status)
conditions = append(conditions, fmt.Sprintf("status = $%d", len(args)))
conditions = append(conditions, fmt.Sprintf("co.status = $%d", len(args)))
}
if filter.BranchId != nil {
if len(filter.BranchIds) > 0 {
conditions, args = rbac.AppendBranchIDs(conditions, args, "co.branch_id", filter.BranchIds)
} else if filter.BranchId != nil {
args = append(args, *filter.BranchId)
conditions = append(conditions, fmt.Sprintf("branch_id = $%d", len(args)))
conditions = append(conditions, fmt.Sprintf("co.branch_id = $%d", len(args)))
}
if filter.UserId != nil {
args = append(args, *filter.UserId)
conditions = append(conditions, fmt.Sprintf("user_id = $%d", len(args)))
conditions = append(conditions, fmt.Sprintf("co.user_id = $%d", len(args)))
}
if filter.CardStateId != nil {
args = append(args, *filter.CardStateId)
conditions = append(conditions, fmt.Sprintf("card_state_id = $%d", len(args)))
conditions = append(conditions, fmt.Sprintf("co.card_state_id = $%d", len(args)))
}
if filter.CardTypeId != nil {
args = append(args, *filter.CardTypeId)
conditions = append(conditions, fmt.Sprintf("card_type_id = $%d", len(args)))
conditions = append(conditions, fmt.Sprintf("co.card_type_id = $%d", len(args)))
}
if filter.Region != "" {
args = append(args, filter.Region)
conditions = append(conditions, fmt.Sprintf("region = $%d", len(args)))
}
if len(conditions) == 0 {
return "", args
conditions = append(conditions, fmt.Sprintf("co.region = $%d", len(args)))
}
return " WHERE " + strings.Join(conditions, " AND "), args
}
func (r *repository) GetByID(ctx context.Context, id int64) (cardorder.CardOrderDTO, error) {
return r.generic.GetByID(ctx, id)
query := `SELECT ` + cardOrderSelectColumns + cardOrderFromClause + ` WHERE co.id = $1 AND co.deleted_at IS NULL`
return scanCardOrderWithJoins(r.client.QueryRow(ctx, query, id))
}
func (r *repository) Create(ctx context.Context, dto cardorder.CreateCardOrderDTO) (cardorder.CardOrderDTO, error) {
@@ -139,12 +180,22 @@ func (r *repository) Create(ctx context.Context, dto cardorder.CreateCardOrderDT
placeholders[i] = fmt.Sprintf("$%d", i+1)
}
query := fmt.Sprintf(
`INSERT INTO card_orders (%s) VALUES (%s) RETURNING %s`,
cardOrderWritableColumnsSQL, strings.Join(placeholders, ", "), cardOrderColumnsSQL,
query := fmt.Sprintf(`
WITH inserted AS (
INSERT INTO card_orders (%s) VALUES (%s)
RETURNING %s
)
SELECT %s
FROM inserted co
LEFT JOIN card_states cs ON cs.id = co.card_state_id
LEFT JOIN card_types ct ON ct.id = co.card_type_id
LEFT JOIN branches b ON b.id = co.branch_id
LEFT JOIN users u ON u.id = co.user_id`,
cardOrderWritableColumnsSQL, strings.Join(placeholders, ", "),
cardOrderColumnsSQL, cardOrderSelectColumns,
)
return scanCardOrder(r.client.QueryRow(ctx, query, args...))
return scanCardOrderWithJoins(r.client.QueryRow(ctx, query, args...))
}
func (r *repository) Update(ctx context.Context, id int64, dto cardorder.UpdateCardOrderDTO) (cardorder.CardOrderDTO, error) {
@@ -156,12 +207,22 @@ func (r *repository) Update(ctx context.Context, id int64, dto cardorder.UpdateC
}
args = append(args, id)
query := fmt.Sprintf(
`UPDATE card_orders SET %s, updated_at = (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') WHERE id = $%d RETURNING %s`,
strings.Join(assignments, ", "), len(args), cardOrderColumnsSQL,
query := fmt.Sprintf(`
WITH updated AS (
UPDATE card_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 co
LEFT JOIN card_states cs ON cs.id = co.card_state_id
LEFT JOIN card_types ct ON ct.id = co.card_type_id
LEFT JOIN branches b ON b.id = co.branch_id
LEFT JOIN users u ON u.id = co.user_id`,
strings.Join(assignments, ", "), len(args), cardOrderColumnsSQL, cardOrderSelectColumns,
)
item, err := scanCardOrder(r.client.QueryRow(ctx, query, args...))
item, err := scanCardOrderWithJoins(r.client.QueryRow(ctx, query, args...))
if err != nil {
return cardorder.CardOrderDTO{}, err
}
@@ -173,17 +234,110 @@ func (r *repository) Delete(ctx context.Context, id int64) error {
}
func scanCardOrder(row genericrepo.Scanner) (cardorder.CardOrderDTO, error) {
return scanCardOrderRow(row, false)
}
func scanCardOrderListItem(row genericrepo.Scanner) (cardorder.CardOrderListItemDTO, error) {
var item cardorder.CardOrderListItemDTO
var cardTypeId, cardStateId, branchId int64
var userId *int64
var cardTypeNameJSON, cardStateNameJSON, branchNameJSON, provinceNameJSON []byte
var userName string
if err := row.Scan(
&item.Id, &item.UniqueId, &item.CustomerName, &item.CustomerSurname, &item.CustomerPatronicName,
&item.Phone, &cardTypeId, &cardTypeNameJSON, &cardStateId, &cardStateNameJSON, &branchId, &branchNameJSON, &provinceNameJSON, &item.Region,
&item.PassportSerie, &item.PassportId, &userId, &userName, &item.Status, &item.Paid, &item.CreatedAt,
); err != nil {
return cardorder.CardOrderListItemDTO{}, err
}
var cardTypeName, cardStateName, branchName shared.LocalizedText
if err := shared.UnmarshalLocalized(cardTypeNameJSON, &cardTypeName); err != nil {
return cardorder.CardOrderListItemDTO{}, err
}
if err := shared.UnmarshalLocalized(cardStateNameJSON, &cardStateName); err != nil {
return cardorder.CardOrderListItemDTO{}, err
}
if err := shared.UnmarshalLocalized(branchNameJSON, &branchName); err != nil {
return cardorder.CardOrderListItemDTO{}, err
}
if err := shared.UnmarshalLocalized(provinceNameJSON, &item.ProvinceName); err != nil {
return cardorder.CardOrderListItemDTO{}, err
}
if cardTypeId != 0 {
item.CardType = &shared.NamedInfo{Id: cardTypeId, Name: cardTypeName}
}
if cardStateId != 0 {
item.CardState = &shared.NamedInfo{Id: cardStateId, Name: cardStateName}
}
if branchId != 0 {
item.Branch = &shared.NamedInfo{Id: branchId, Name: branchName}
}
if userId != nil {
item.User = &cardorder.ListUserDTO{Id: *userId, Name: userName}
}
return item, nil
}
func scanCardOrderWithJoins(row genericrepo.Scanner) (cardorder.CardOrderDTO, error) {
return scanCardOrderRow(row, true)
}
func scanCardOrderRow(row genericrepo.Scanner, withJoins bool) (cardorder.CardOrderDTO, error) {
var item cardorder.CardOrderDTO
err := row.Scan(
dest := []interface{}{
&item.Id, &item.UniqueId, &item.CardStateId, &item.CardTypeId, &item.Region, &item.BranchId,
&item.CustomerName, &item.CustomerSurname, &item.CustomerPatronicName, &item.BornAt, &item.OldSurname, &item.Citizenship,
&item.PassportSerie, &item.PassportId, &item.PassportGivenAt, &item.PassportGivenBy, &item.BornPlace,
&item.JobLocation, &item.PassportAddress, &item.RealAddress, &item.Phone, &item.PhoneAdditional,
&item.Status, &item.PassportOne, &item.PassportTwo, &item.PassportThree, &item.PassportFour, &item.Notes, &item.UserId, &item.Paid,
&item.CreatedAt, &item.UpdatedAt,
)
if err != nil {
}
var cardStateNameJSON, cardTypeNameJSON, branchNameJSON []byte
var userName, userUsername, userPhone, userEmail string
if withJoins {
dest = append(dest,
&cardStateNameJSON, &cardTypeNameJSON, &branchNameJSON,
&userName, &userUsername, &userPhone, &userEmail,
)
}
if err := row.Scan(dest...); err != nil {
return cardorder.CardOrderDTO{}, err
}
if !withJoins {
return item, nil
}
var cardStateName, cardTypeName, branchName shared.LocalizedText
if err := shared.UnmarshalLocalized(cardStateNameJSON, &cardStateName); err != nil {
return cardorder.CardOrderDTO{}, err
}
if err := shared.UnmarshalLocalized(cardTypeNameJSON, &cardTypeName); err != nil {
return cardorder.CardOrderDTO{}, err
}
if err := shared.UnmarshalLocalized(branchNameJSON, &branchName); err != nil {
return cardorder.CardOrderDTO{}, err
}
if item.CardStateId != 0 {
item.CardState = &shared.NamedInfo{Id: item.CardStateId, Name: cardStateName}
}
if item.CardTypeId != 0 {
item.CardType = &shared.NamedInfo{Id: item.CardTypeId, Name: cardTypeName}
}
if item.BranchId != 0 {
item.Branch = &shared.NamedInfo{Id: item.BranchId, Name: branchName}
}
if item.UserId != nil {
item.User = &shared.UserInfo{
Id: *item.UserId,
Name: userName,
Username: userUsername,
Phone: userPhone,
Email: userEmail,
}
}
return item, nil
}

View File

@@ -1,109 +1,118 @@
package cardorder
import "time"
import (
"time"
"online-back/internal/shared"
)
type CardOrderDTO struct {
Id int64 `json:"id"`
UniqueId *string `json:"uniqueId"`
CardStateId int64 `json:"cardStateId"`
CardTypeId int64 `json:"cardTypeId"`
Region string `json:"region"`
BranchId int64 `json:"branchId"`
CustomerName string `json:"customerName"`
CustomerSurname string `json:"customerSurname"`
CustomerPatronicName *string `json:"customerPatronicName"`
BornAt *time.Time `json:"bornAt"`
OldSurname *string `json:"oldSurname"`
Citizenship string `json:"citizenship"`
PassportSerie string `json:"passportSerie"`
PassportId string `json:"passportId"`
PassportGivenAt time.Time `json:"passportGivenAt"`
PassportGivenBy string `json:"passportGivenBy"`
BornPlace string `json:"bornPlace"`
JobLocation *string `json:"jobLocation"`
PassportAddress *string `json:"passportAddress"`
RealAddress *string `json:"realAddress"`
Phone *string `json:"phone"`
PhoneAdditional *string `json:"phoneAdditional"`
Status *string `json:"status"`
PassportOne string `json:"passportOne"`
PassportTwo string `json:"passportTwo"`
PassportThree string `json:"passportThree"`
PassportFour string `json:"passportFour"`
Notes *string `json:"notes"`
UserId *int64 `json:"userId"`
Paid bool `json:"paid"`
CreatedAt time.Time `json:"createdAt"`
UpdatedAt time.Time `json:"updatedAt"`
Id int64 `json:"id"`
UniqueId *string `json:"uniqueId"`
CardStateId int64 `json:"-"`
CardState *shared.NamedInfo `json:"cardState,omitempty"`
CardTypeId int64 `json:"-"`
CardType *shared.NamedInfo `json:"cardType,omitempty"`
Region string `json:"region"`
BranchId int64 `json:"-"`
Branch *shared.NamedInfo `json:"branch,omitempty"`
CustomerName string `json:"customerName"`
CustomerSurname string `json:"customerSurname"`
CustomerPatronicName *string `json:"customerPatronicName"`
BornAt *time.Time `json:"bornAt"`
OldSurname *string `json:"oldSurname"`
Citizenship string `json:"citizenship"`
PassportSerie string `json:"passportSerie"`
PassportId string `json:"passportId"`
PassportGivenAt time.Time `json:"passportGivenAt"`
PassportGivenBy string `json:"passportGivenBy"`
BornPlace string `json:"bornPlace"`
JobLocation *string `json:"jobLocation"`
PassportAddress *string `json:"passportAddress"`
RealAddress *string `json:"realAddress"`
Phone *string `json:"phone"`
PhoneAdditional *string `json:"phoneAdditional"`
Status *string `json:"status"`
PassportOne string `json:"passportOne"`
PassportTwo string `json:"passportTwo"`
PassportThree string `json:"passportThree"`
PassportFour string `json:"passportFour"`
Notes *string `json:"notes"`
UserId *int64 `json:"-"`
User *shared.UserInfo `json:"user,omitempty"`
Paid bool `json:"paid"`
CreatedAt time.Time `json:"createdAt"`
UpdatedAt time.Time `json:"updatedAt"`
}
type CreateCardOrderDTO struct {
UniqueId *string `json:"uniqueId"`
CardStateId int64 `json:"cardStateId" binding:"required"`
CardTypeId int64 `json:"cardTypeId" binding:"required"`
Region string `json:"region" binding:"required"`
BranchId int64 `json:"branchId" binding:"required"`
CustomerName string `json:"customerName" binding:"required"`
CustomerSurname string `json:"customerSurname" binding:"required"`
CustomerPatronicName *string `json:"customerPatronicName"`
BornAt *time.Time `json:"bornAt"`
OldSurname *string `json:"oldSurname"`
Citizenship string `json:"citizenship" binding:"required"`
PassportSerie string `json:"passportSerie" binding:"required"`
PassportId string `json:"passportId" binding:"required"`
PassportGivenAt time.Time `json:"passportGivenAt" binding:"required"`
PassportGivenBy string `json:"passportGivenBy" binding:"required"`
BornPlace string `json:"bornPlace" binding:"required"`
JobLocation *string `json:"jobLocation"`
PassportAddress *string `json:"passportAddress"`
RealAddress *string `json:"realAddress"`
Phone *string `json:"phone"`
PhoneAdditional *string `json:"phoneAdditional"`
Status *string `json:"status"`
PassportOne string `json:"passportOne" binding:"required"`
PassportTwo string `json:"passportTwo" binding:"required"`
PassportThree string `json:"passportThree" binding:"required"`
PassportFour string `json:"passportFour" binding:"required"`
Notes *string `json:"notes"`
UserId *int64 `json:"userId"`
Paid *bool `json:"paid"`
UniqueId *string `json:"uniqueId"`
CardStateId shared.FlexibleInt64 `json:"cardStateId" binding:"required" swaggertype:"integer"`
CardTypeId shared.FlexibleInt64 `json:"cardTypeId" binding:"required" swaggertype:"integer"`
Region string `json:"region" binding:"required"`
BranchId shared.FlexibleInt64 `json:"branchId" binding:"required" swaggertype:"integer"`
CustomerName string `json:"customerName" binding:"required"`
CustomerSurname string `json:"customerSurname" binding:"required"`
CustomerPatronicName *string `json:"customerPatronicName"`
BornAt *shared.FlexibleTime `json:"bornAt" swaggertype:"string" format:"date"`
OldSurname *string `json:"oldSurname"`
Citizenship string `json:"citizenship" binding:"required"`
PassportSerie string `json:"passportSerie" binding:"required"`
PassportId string `json:"passportId" binding:"required"`
PassportGivenAt shared.FlexibleTime `json:"passportGivenAt" swaggertype:"string" format:"date"`
PassportGivenBy string `json:"passportGivenBy" binding:"required"`
BornPlace string `json:"bornPlace" binding:"required"`
JobLocation *string `json:"jobLocation"`
PassportAddress *string `json:"passportAddress"`
RealAddress *string `json:"realAddress"`
Phone *string `json:"phone"`
PhoneAdditional *string `json:"phoneAdditional"`
Status *string `json:"status"`
PassportOne string `json:"passportOne" binding:"required"`
PassportTwo string `json:"passportTwo" binding:"required"`
PassportThree string `json:"passportThree" binding:"required"`
PassportFour string `json:"passportFour" binding:"required"`
Notes *string `json:"notes"`
UserId *shared.FlexibleInt64 `json:"userId" swaggertype:"integer"`
Paid *bool `json:"paid"`
}
type UpdateCardOrderDTO struct {
UniqueId *string `json:"uniqueId"`
CardStateId int64 `json:"cardStateId" binding:"required"`
CardTypeId int64 `json:"cardTypeId" binding:"required"`
Region string `json:"region" binding:"required"`
BranchId int64 `json:"branchId" binding:"required"`
CustomerName string `json:"customerName" binding:"required"`
CustomerSurname string `json:"customerSurname" binding:"required"`
CustomerPatronicName *string `json:"customerPatronicName"`
BornAt *time.Time `json:"bornAt"`
OldSurname *string `json:"oldSurname"`
Citizenship string `json:"citizenship" binding:"required"`
PassportSerie string `json:"passportSerie" binding:"required"`
PassportId string `json:"passportId" binding:"required"`
PassportGivenAt time.Time `json:"passportGivenAt" binding:"required"`
PassportGivenBy string `json:"passportGivenBy" binding:"required"`
BornPlace string `json:"bornPlace" binding:"required"`
JobLocation *string `json:"jobLocation"`
PassportAddress *string `json:"passportAddress"`
RealAddress *string `json:"realAddress"`
Phone *string `json:"phone"`
PhoneAdditional *string `json:"phoneAdditional"`
Status *string `json:"status"`
PassportOne string `json:"passportOne" binding:"required"`
PassportTwo string `json:"passportTwo" binding:"required"`
PassportThree string `json:"passportThree" binding:"required"`
PassportFour string `json:"passportFour" binding:"required"`
Notes *string `json:"notes"`
UserId *int64 `json:"userId"`
Paid bool `json:"paid"`
UniqueId *string `json:"uniqueId"`
CardStateId shared.FlexibleInt64 `json:"cardStateId" binding:"required" swaggertype:"integer"`
CardTypeId shared.FlexibleInt64 `json:"cardTypeId" binding:"required" swaggertype:"integer"`
Region string `json:"region" binding:"required"`
BranchId shared.FlexibleInt64 `json:"branchId" binding:"required" swaggertype:"integer"`
CustomerName string `json:"customerName" binding:"required"`
CustomerSurname string `json:"customerSurname" binding:"required"`
CustomerPatronicName *string `json:"customerPatronicName"`
BornAt *shared.FlexibleTime `json:"bornAt" swaggertype:"string" format:"date"`
OldSurname *string `json:"oldSurname"`
Citizenship string `json:"citizenship" binding:"required"`
PassportSerie string `json:"passportSerie" binding:"required"`
PassportId string `json:"passportId" binding:"required"`
PassportGivenAt shared.FlexibleTime `json:"passportGivenAt" swaggertype:"string" format:"date"`
PassportGivenBy string `json:"passportGivenBy" binding:"required"`
BornPlace string `json:"bornPlace" binding:"required"`
JobLocation *string `json:"jobLocation"`
PassportAddress *string `json:"passportAddress"`
RealAddress *string `json:"realAddress"`
Phone *string `json:"phone"`
PhoneAdditional *string `json:"phoneAdditional"`
Status *string `json:"status"`
PassportOne string `json:"passportOne" binding:"required"`
PassportTwo string `json:"passportTwo" binding:"required"`
PassportThree string `json:"passportThree" binding:"required"`
PassportFour string `json:"passportFour" binding:"required"`
Notes *string `json:"notes"`
UserId *shared.FlexibleInt64 `json:"userId" swaggertype:"integer"`
Paid bool `json:"paid"`
}
type ListFilter struct {
Status *string
BranchId *int64
BranchIds []int64
UserId *int64
CardStateId *int64
CardTypeId *int64
@@ -112,7 +121,35 @@ type ListFilter struct {
Limit int
}
type ListCardOrderDTO struct {
Count int64 `json:"count"`
CardOrders []CardOrderDTO `json:"cardOrders"`
// CardOrderListItemDTO is the list row; addresses, passport issue details
// and scans come from GET /card-orders/:id.
type CardOrderListItemDTO struct {
Id int64 `json:"id"`
UniqueId *string `json:"uniqueId"`
CustomerName string `json:"customerName"`
CustomerSurname string `json:"customerSurname"`
CustomerPatronicName *string `json:"customerPatronicName"`
Phone *string `json:"phone"`
CardType *shared.NamedInfo `json:"cardType,omitempty"`
CardState *shared.NamedInfo `json:"cardState,omitempty"`
Branch *shared.NamedInfo `json:"branch,omitempty"`
// ProvinceName is the branch's province (etrap).
ProvinceName shared.LocalizedText `json:"provinceName"`
Region string `json:"region"`
PassportSerie string `json:"passportSerie"`
PassportId string `json:"passportId"`
User *ListUserDTO `json:"user,omitempty"`
Status *string `json:"status"`
Paid bool `json:"paid"`
CreatedAt time.Time `json:"createdAt"`
}
type ListUserDTO struct {
Id int64 `json:"id"`
Name string `json:"name"`
}
type ListCardOrderDTO struct {
Count int64 `json:"count"`
CardOrders []CardOrderListItemDTO `json:"cardOrders"`
}

View File

@@ -3,11 +3,12 @@ package cardorder
import (
"errors"
"net/http"
"strconv"
"strings"
"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"
@@ -26,7 +27,7 @@ func NewHandler(logger *logging.Logger, repository Repository) handlers.Handler
}
func (h *handler) Register(router *gin.RouterGroup) {
group := router.Group(baseURL, appresult.JwtTokenCheck())
group := rbac.Group(router, baseURL, rbac.Require(perm.Cards))
group.GET("", h.list)
group.GET("/:id", h.getByID)
group.POST("", h.create)
@@ -48,6 +49,7 @@ func (h *handler) Register(router *gin.RouterGroup) {
// @Param region query string false "Filter by region"
// @Param page query int false "Page number" default(1)
// @Param limit query int false "Items per page" default(10)
// @Param lang query string false "Language of localized fields; all returns the full {en, ru, tm} objects" Enums(tm, ru, en, all) default(tm)
// @Success 200 {object} appresult.AppSuccess
// @Failure 400 {object} appresult.AppError
// @Failure 500 {object} appresult.AppError
@@ -76,13 +78,14 @@ func (h *handler) list(c *gin.Context) {
// @Produce json
// @Security BearerAuth
// @Param id path int true "Card order ID"
// @Param lang query string false "Language of localized fields; all returns the full {en, ru, tm} objects" Enums(tm, ru, en, all) default(tm)
// @Success 200 {object} appresult.AppSuccess
// @Failure 400 {object} appresult.AppError
// @Failure 404 {object} appresult.AppError
// @Failure 500 {object} appresult.AppError
// @Router /card-orders/{id} [get]
func (h *handler) getByID(c *gin.Context) {
id, ok := parseID(c.Param("id"))
id, ok := shared.ParseID(c.Param("id"))
if !ok {
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
return
@@ -98,6 +101,9 @@ func (h *handler) getByID(c *gin.Context) {
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return
}
if !rbac.GuardOrder(c, item.UserId, item.BranchId) {
return
}
c.JSON(http.StatusOK, appresult.SuccessWithData(item))
}
@@ -110,13 +116,15 @@ func (h *handler) getByID(c *gin.Context) {
// @Produce json
// @Security BearerAuth
// @Param body body CreateCardOrderDTO true "Card order payload"
// @Param lang query string false "Language of localized fields; all returns the full {en, ru, tm} objects" Enums(tm, ru, en, all) default(tm)
// @Success 201 {object} appresult.AppSuccess
// @Failure 400 {object} appresult.AppError
// @Failure 500 {object} appresult.AppError
// @Router /card-orders [post]
func (h *handler) create(c *gin.Context) {
var dto CreateCardOrderDTO
if err := c.ShouldBindJSON(&dto); err != nil {
if err := c.ShouldBindBodyWithJSON(&dto); err != nil {
h.logger.Errorf("create card order bind failed: %v", err)
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
return
}
@@ -140,20 +148,26 @@ func (h *handler) create(c *gin.Context) {
// @Security BearerAuth
// @Param id path int true "Card order ID"
// @Param body body UpdateCardOrderDTO true "Card order payload"
// @Param lang query string false "Language of localized fields; all returns the full {en, ru, tm} objects" Enums(tm, ru, en, all) default(tm)
// @Success 200 {object} appresult.AppSuccess
// @Failure 400 {object} appresult.AppError
// @Failure 404 {object} appresult.AppError
// @Failure 500 {object} appresult.AppError
// @Router /card-orders/{id} [put]
func (h *handler) update(c *gin.Context) {
id, ok := parseID(c.Param("id"))
id, ok := shared.ParseID(c.Param("id"))
if !ok {
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
return
}
if !h.guardBranchByID(c, id) {
return
}
var dto UpdateCardOrderDTO
if err := c.ShouldBindJSON(&dto); err != nil {
if err := c.ShouldBindBodyWithJSON(&dto); err != nil {
h.logger.Errorf("update card order bind failed: %v", err)
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
return
}
@@ -179,18 +193,23 @@ func (h *handler) update(c *gin.Context) {
// @Produce json
// @Security BearerAuth
// @Param id path int true "Card order ID"
// @Param lang query string false "Language of localized fields; all returns the full {en, ru, tm} objects" Enums(tm, ru, en, all) default(tm)
// @Success 200 {object} appresult.AppSuccess
// @Failure 400 {object} appresult.AppError
// @Failure 404 {object} appresult.AppError
// @Failure 500 {object} appresult.AppError
// @Router /card-orders/{id} [delete]
func (h *handler) delete(c *gin.Context) {
id, ok := parseID(c.Param("id"))
id, ok := shared.ParseID(c.Param("id"))
if !ok {
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
return
}
if !h.guardBranchByID(c, id) {
return
}
if err := h.repository.Delete(c.Request.Context(), id); errors.Is(err, pgx.ErrNoRows) {
c.JSON(http.StatusNotFound, appresult.ErrNotFound)
return
@@ -203,81 +222,61 @@ func (h *handler) delete(c *gin.Context) {
c.JSON(http.StatusOK, appresult.SuccessWithData("card order removed"))
}
func parseID(raw string) (int64, bool) {
id, err := strconv.ParseInt(raw, 10, 64)
if err != nil || id <= 0 {
return 0, false
}
return id, true
}
const (
defaultPage = 1
defaultLimit = 10
maxLimit = 100
)
func parseListFilter(c *gin.Context) (ListFilter, bool) {
filter := ListFilter{
Page: defaultPage,
Limit: defaultLimit,
page, limit, ok := shared.ParsePageLimit(c)
if !ok {
return ListFilter{}, false
}
filter := ListFilter{Page: page, Limit: limit}
if id, ok := shared.OptionalQueryID(c, "branch_id", "branchId"); !ok {
return ListFilter{}, false
} else if id != nil {
filter.BranchId = id
}
if raw := c.Query("branch_id"); raw != "" {
id, ok := parseID(raw)
if !ok {
return ListFilter{}, false
}
filter.BranchId = &id
if id, ok := shared.OptionalQueryID(c, "user_id", "userId"); !ok {
return ListFilter{}, false
} else if id != nil {
filter.UserId = id
}
if raw := c.Query("user_id"); raw != "" {
id, ok := parseID(raw)
if !ok {
return ListFilter{}, false
}
filter.UserId = &id
if id, ok := shared.OptionalQueryID(c, "card_state_id", "cardStateId"); !ok {
return ListFilter{}, false
} else if id != nil {
filter.CardStateId = id
}
if raw := c.Query("card_state_id"); raw != "" {
id, ok := parseID(raw)
if !ok {
return ListFilter{}, false
}
filter.CardStateId = &id
if id, ok := shared.OptionalQueryID(c, "card_type_id", "cardTypeId"); !ok {
return ListFilter{}, false
} else if id != nil {
filter.CardTypeId = id
}
if raw := c.Query("card_type_id"); raw != "" {
id, ok := parseID(raw)
if !ok {
return ListFilter{}, false
}
filter.CardTypeId = &id
}
if raw := c.Query("page"); raw != "" {
page, err := strconv.Atoi(raw)
if err != nil || page < 1 {
return ListFilter{}, false
}
filter.Page = page
}
if raw := c.Query("limit"); raw != "" {
limit, err := strconv.Atoi(raw)
if err != nil || limit < 1 || limit > maxLimit {
return ListFilter{}, false
}
filter.Limit = limit
}
if raw := strings.TrimSpace(c.Query("status")); raw != "" {
if raw := shared.QueryValue(c, "status"); raw != "" {
filter.Status = &raw
}
if raw := strings.TrimSpace(c.Query("region")); raw != "" {
if raw := shared.QueryValue(c, "region"); raw != "" {
filter.Region = raw
}
rbac.BindBranchIDs(c, &filter.BranchIds)
return filter, true
}
func (h *handler) guardBranchByID(c *gin.Context, id int64) bool {
if rbac.SkipRecordGuard(c) {
return true
}
item, err := h.repository.GetByID(c.Request.Context(), id)
if errors.Is(err, pgx.ErrNoRows) {
c.JSON(http.StatusNotFound, appresult.ErrNotFound)
return false
}
if err != nil {
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return false
}
return rbac.GuardOrder(c, item.UserId, item.BranchId)
}

View File

@@ -6,6 +6,8 @@ import (
"strings"
"online-back/internal/cards/cardpinorders"
"online-back/internal/identity/rbac"
"online-back/internal/shared"
"online-back/pkg/client/postgresql"
"online-back/pkg/logging"
"online-back/pkg/repository/genericrepo"
@@ -25,8 +27,6 @@ func NewRepository(client postgresql.Client, logger *logging.Logger) cardpinorde
}
}
// cardPinOrderWritableColumns lists every card_pin_orders column except id, created_at and
// updated_at, in the exact order CreateCardPinOrderDTO/UpdateCardPinOrderDTO fields are read.
var cardPinOrderWritableColumns = []string{
"unique_id", "user_id", "card_type_id", "card_number", "region", "branch_id",
"customer_name", "customer_surname", "customer_patronic_name", "born_at", "phone",
@@ -40,10 +40,18 @@ var cardPinOrderColumnsSQL = strings.Join(cardPinOrderColumns, ", ")
var cardPinOrderWritableColumnsSQL = strings.Join(cardPinOrderWritableColumns, ", ")
const cardPinOrderFromClause = ` FROM card_pin_orders cpo
LEFT JOIN card_types ct ON ct.id = cpo.card_type_id
LEFT JOIN branches b ON b.id = cpo.branch_id
LEFT JOIN users u ON u.id = cpo.user_id`
var cardPinOrderSelectColumns = shared.PrefixedColumns("cpo", cardPinOrderColumns) + `,
ct.name, b.name, ` + shared.UserDisplaySQL + `, COALESCE(u.username, ''), COALESCE(u.phone, ''), COALESCE(u.email, '')`
func createArgs(dto cardpinorders.CreateCardPinOrderDTO) []interface{} {
return []interface{}{
dto.UniqueId, dto.UserId, dto.CardTypeId, dto.CardNumber, dto.Region, dto.BranchId,
dto.CustomerName, dto.CustomerSurname, dto.CustomerPatronicName, dto.BornAt, dto.Phone,
dto.UniqueId, shared.OptionalInt64(dto.UserId), dto.CardTypeId.Int64(), dto.CardNumber, dto.Region, dto.BranchId.Int64(),
dto.CustomerName, dto.CustomerSurname, dto.CustomerPatronicName, shared.OptionalTime(dto.BornAt), dto.Phone,
dto.PassportSerie, dto.PassportId, dto.PassportOne, dto.PassportTwo, dto.PassportThree, dto.PassportFour,
dto.Status, dto.Notes,
}
@@ -51,8 +59,8 @@ func createArgs(dto cardpinorders.CreateCardPinOrderDTO) []interface{} {
func updateArgs(dto cardpinorders.UpdateCardPinOrderDTO) []interface{} {
return []interface{}{
dto.UniqueId, dto.UserId, dto.CardTypeId, dto.CardNumber, dto.Region, dto.BranchId,
dto.CustomerName, dto.CustomerSurname, dto.CustomerPatronicName, dto.BornAt, dto.Phone,
dto.UniqueId, shared.OptionalInt64(dto.UserId), dto.CardTypeId.Int64(), dto.CardNumber, dto.Region, dto.BranchId.Int64(),
dto.CustomerName, dto.CustomerSurname, dto.CustomerPatronicName, shared.OptionalTime(dto.BornAt), dto.Phone,
dto.PassportSerie, dto.PassportId, dto.PassportOne, dto.PassportTwo, dto.PassportThree, dto.PassportFour,
dto.Status, dto.Notes,
}
@@ -61,51 +69,87 @@ func updateArgs(dto cardpinorders.UpdateCardPinOrderDTO) []interface{} {
func (r *repository) List(ctx context.Context, filter cardpinorders.ListFilter) (cardpinorders.ListCardPinOrderDTO, error) {
whereClause, args := buildListQuery(filter)
items, count, err := r.generic.List(ctx, whereClause, args, filter.Page, filter.Limit, "id")
var count int64
if err := r.client.QueryRow(ctx, `SELECT COUNT(*) FROM card_pin_orders cpo`+whereClause, args...).Scan(&count); err != nil {
return cardpinorders.ListCardPinOrderDTO{}, err
}
offset := (filter.Page - 1) * filter.Limit
limitPlaceholder := len(args) + 1
offsetPlaceholder := len(args) + 2
query := fmt.Sprintf(
`SELECT cpo.id, cpo.unique_id, cpo.card_number, cpo.customer_name, cpo.customer_surname,
cpo.region, bp.name, cpo.phone, cpo.status, cpo.created_at
FROM card_pin_orders cpo
LEFT JOIN branches b ON b.id = cpo.branch_id
LEFT JOIN provinces bp ON bp.id = b.province_id%s ORDER BY cpo.id LIMIT $%d OFFSET $%d`,
whereClause, limitPlaceholder, offsetPlaceholder,
)
rows, err := r.client.Query(ctx, query, append(args, filter.Limit, offset)...)
if err != nil {
return cardpinorders.ListCardPinOrderDTO{}, err
}
defer rows.Close()
items := []cardpinorders.CardPinOrderListItemDTO{}
for rows.Next() {
var item cardpinorders.CardPinOrderListItemDTO
var provinceNameJSON []byte
if err := rows.Scan(
&item.Id, &item.UniqueId, &item.CardNumber, &item.CustomerName, &item.CustomerSurname,
&item.Region, &provinceNameJSON, &item.Phone, &item.Status, &item.CreatedAt,
); err != nil {
return cardpinorders.ListCardPinOrderDTO{}, err
}
if err := shared.UnmarshalLocalized(provinceNameJSON, &item.ProvinceName); err != nil {
return cardpinorders.ListCardPinOrderDTO{}, err
}
items = append(items, item)
}
if err := rows.Err(); err != nil {
return cardpinorders.ListCardPinOrderDTO{}, err
}
return cardpinorders.ListCardPinOrderDTO{Count: count, CardPinOrders: items}, nil
}
func buildListQuery(filter cardpinorders.ListFilter) (whereClause string, args []interface{}) {
var conditions []string
conditions := []string{"cpo.deleted_at IS NULL"}
if filter.Status != nil {
args = append(args, *filter.Status)
conditions = append(conditions, fmt.Sprintf("status = $%d", len(args)))
conditions = append(conditions, fmt.Sprintf("cpo.status = $%d", len(args)))
}
if filter.BranchId != nil {
if len(filter.BranchIds) > 0 {
conditions, args = rbac.AppendBranchIDs(conditions, args, "cpo.branch_id", filter.BranchIds)
} else if filter.BranchId != nil {
args = append(args, *filter.BranchId)
conditions = append(conditions, fmt.Sprintf("branch_id = $%d", len(args)))
conditions = append(conditions, fmt.Sprintf("cpo.branch_id = $%d", len(args)))
}
if filter.UserId != nil {
args = append(args, *filter.UserId)
conditions = append(conditions, fmt.Sprintf("user_id = $%d", len(args)))
conditions = append(conditions, fmt.Sprintf("cpo.user_id = $%d", len(args)))
}
if filter.CardTypeId != nil {
args = append(args, *filter.CardTypeId)
conditions = append(conditions, fmt.Sprintf("card_type_id = $%d", len(args)))
conditions = append(conditions, fmt.Sprintf("cpo.card_type_id = $%d", len(args)))
}
if filter.Region != "" {
args = append(args, filter.Region)
conditions = append(conditions, fmt.Sprintf("region = $%d", len(args)))
}
if len(conditions) == 0 {
return "", args
conditions = append(conditions, fmt.Sprintf("cpo.region = $%d", len(args)))
}
return " WHERE " + strings.Join(conditions, " AND "), args
}
func (r *repository) GetByID(ctx context.Context, id int64) (cardpinorders.CardPinOrderDTO, error) {
return r.generic.GetByID(ctx, id)
query := `SELECT ` + cardPinOrderSelectColumns + cardPinOrderFromClause + ` WHERE cpo.id = $1 AND cpo.deleted_at IS NULL`
return scanCardPinOrderWithJoins(r.client.QueryRow(ctx, query, id))
}
func (r *repository) Create(ctx context.Context, dto cardpinorders.CreateCardPinOrderDTO) (cardpinorders.CardPinOrderDTO, error) {
@@ -116,12 +160,21 @@ func (r *repository) Create(ctx context.Context, dto cardpinorders.CreateCardPin
placeholders[i] = fmt.Sprintf("$%d", i+1)
}
query := fmt.Sprintf(
`INSERT INTO card_pin_orders (%s) VALUES (%s) RETURNING %s`,
cardPinOrderWritableColumnsSQL, strings.Join(placeholders, ", "), cardPinOrderColumnsSQL,
query := fmt.Sprintf(`
WITH inserted AS (
INSERT INTO card_pin_orders (%s) VALUES (%s)
RETURNING %s
)
SELECT %s
FROM inserted cpo
LEFT JOIN card_types ct ON ct.id = cpo.card_type_id
LEFT JOIN branches b ON b.id = cpo.branch_id
LEFT JOIN users u ON u.id = cpo.user_id`,
cardPinOrderWritableColumnsSQL, strings.Join(placeholders, ", "),
cardPinOrderColumnsSQL, cardPinOrderSelectColumns,
)
return scanCardPinOrder(r.client.QueryRow(ctx, query, args...))
return scanCardPinOrderWithJoins(r.client.QueryRow(ctx, query, args...))
}
func (r *repository) Update(ctx context.Context, id int64, dto cardpinorders.UpdateCardPinOrderDTO) (cardpinorders.CardPinOrderDTO, error) {
@@ -133,12 +186,21 @@ func (r *repository) Update(ctx context.Context, id int64, dto cardpinorders.Upd
}
args = append(args, id)
query := fmt.Sprintf(
`UPDATE card_pin_orders SET %s, updated_at = (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') WHERE id = $%d RETURNING %s`,
strings.Join(assignments, ", "), len(args), cardPinOrderColumnsSQL,
query := fmt.Sprintf(`
WITH updated AS (
UPDATE card_pin_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 cpo
LEFT JOIN card_types ct ON ct.id = cpo.card_type_id
LEFT JOIN branches b ON b.id = cpo.branch_id
LEFT JOIN users u ON u.id = cpo.user_id`,
strings.Join(assignments, ", "), len(args), cardPinOrderColumnsSQL, cardPinOrderSelectColumns,
)
item, err := scanCardPinOrder(r.client.QueryRow(ctx, query, args...))
item, err := scanCardPinOrderWithJoins(r.client.QueryRow(ctx, query, args...))
if err != nil {
return cardpinorders.CardPinOrderDTO{}, err
}
@@ -150,16 +212,57 @@ func (r *repository) Delete(ctx context.Context, id int64) error {
}
func scanCardPinOrder(row genericrepo.Scanner) (cardpinorders.CardPinOrderDTO, error) {
return scanCardPinOrderRow(row, false)
}
func scanCardPinOrderWithJoins(row genericrepo.Scanner) (cardpinorders.CardPinOrderDTO, error) {
return scanCardPinOrderRow(row, true)
}
func scanCardPinOrderRow(row genericrepo.Scanner, withJoins bool) (cardpinorders.CardPinOrderDTO, error) {
var item cardpinorders.CardPinOrderDTO
err := row.Scan(
dest := []interface{}{
&item.Id, &item.UniqueId, &item.UserId, &item.CardTypeId, &item.CardNumber, &item.Region, &item.BranchId,
&item.CustomerName, &item.CustomerSurname, &item.CustomerPatronicName, &item.BornAt, &item.Phone,
&item.PassportSerie, &item.PassportId, &item.PassportOne, &item.PassportTwo, &item.PassportThree, &item.PassportFour,
&item.Status, &item.Notes,
&item.CreatedAt, &item.UpdatedAt,
)
if err != nil {
}
var cardTypeNameJSON, branchNameJSON []byte
var userName, userUsername, userPhone, userEmail string
if withJoins {
dest = append(dest, &cardTypeNameJSON, &branchNameJSON, &userName, &userUsername, &userPhone, &userEmail)
}
if err := row.Scan(dest...); err != nil {
return cardpinorders.CardPinOrderDTO{}, err
}
if !withJoins {
return item, nil
}
var cardTypeName, branchName shared.LocalizedText
if err := shared.UnmarshalLocalized(cardTypeNameJSON, &cardTypeName); err != nil {
return cardpinorders.CardPinOrderDTO{}, err
}
if err := shared.UnmarshalLocalized(branchNameJSON, &branchName); err != nil {
return cardpinorders.CardPinOrderDTO{}, err
}
if item.CardTypeId != 0 {
item.CardType = &shared.NamedInfo{Id: item.CardTypeId, Name: cardTypeName}
}
if item.BranchId != 0 {
item.Branch = &shared.NamedInfo{Id: item.BranchId, Name: branchName}
}
if item.UserId != nil {
item.User = &shared.UserInfo{
Id: *item.UserId,
Name: userName,
Username: userUsername,
Phone: userPhone,
Email: userEmail,
}
}
return item, nil
}

View File

@@ -1,79 +1,87 @@
package cardpinorders
import "time"
import (
"time"
"online-back/internal/shared"
)
type CardPinOrderDTO struct {
Id int64 `json:"id"`
UniqueId *string `json:"uniqueId"`
UserId *int64 `json:"userId"`
CardTypeId int64 `json:"cardTypeId"`
CardNumber *string `json:"cardNumber"`
Region string `json:"region"`
BranchId int64 `json:"branchId"`
CustomerName string `json:"customerName"`
CustomerSurname string `json:"customerSurname"`
CustomerPatronicName *string `json:"customerPatronicName"`
BornAt *time.Time `json:"bornAt"`
Phone *string `json:"phone"`
PassportSerie string `json:"passportSerie"`
PassportId string `json:"passportId"`
PassportOne string `json:"passportOne"`
PassportTwo string `json:"passportTwo"`
PassportThree string `json:"passportThree"`
PassportFour string `json:"passportFour"`
Status *string `json:"status"`
Notes *string `json:"notes"`
CreatedAt time.Time `json:"createdAt"`
UpdatedAt time.Time `json:"updatedAt"`
Id int64 `json:"id"`
UniqueId *string `json:"uniqueId"`
UserId *int64 `json:"-"`
User *shared.UserInfo `json:"user,omitempty"`
CardTypeId int64 `json:"-"`
CardType *shared.NamedInfo `json:"cardType,omitempty"`
CardNumber *string `json:"cardNumber"`
Region string `json:"region"`
BranchId int64 `json:"-"`
Branch *shared.NamedInfo `json:"branch,omitempty"`
CustomerName string `json:"customerName"`
CustomerSurname string `json:"customerSurname"`
CustomerPatronicName *string `json:"customerPatronicName"`
BornAt *time.Time `json:"bornAt"`
Phone *string `json:"phone"`
PassportSerie string `json:"passportSerie"`
PassportId string `json:"passportId"`
PassportOne string `json:"passportOne"`
PassportTwo string `json:"passportTwo"`
PassportThree string `json:"passportThree"`
PassportFour string `json:"passportFour"`
Status *string `json:"status"`
Notes *string `json:"notes"`
CreatedAt time.Time `json:"createdAt"`
UpdatedAt time.Time `json:"updatedAt"`
}
type CreateCardPinOrderDTO struct {
UniqueId *string `json:"uniqueId"`
UserId *int64 `json:"userId"`
CardTypeId int64 `json:"cardTypeId" binding:"required"`
CardNumber *string `json:"cardNumber"`
Region string `json:"region" binding:"required"`
BranchId int64 `json:"branchId" binding:"required"`
CustomerName string `json:"customerName" binding:"required"`
CustomerSurname string `json:"customerSurname" binding:"required"`
CustomerPatronicName *string `json:"customerPatronicName"`
BornAt *time.Time `json:"bornAt"`
Phone *string `json:"phone"`
PassportSerie string `json:"passportSerie" binding:"required"`
PassportId string `json:"passportId" binding:"required"`
PassportOne string `json:"passportOne" binding:"required"`
PassportTwo string `json:"passportTwo" binding:"required"`
PassportThree string `json:"passportThree" binding:"required"`
PassportFour string `json:"passportFour" binding:"required"`
Status *string `json:"status"`
Notes *string `json:"notes"`
UniqueId *string `json:"uniqueId"`
UserId *shared.FlexibleInt64 `json:"userId" swaggertype:"integer"`
CardTypeId shared.FlexibleInt64 `json:"cardTypeId" binding:"required" swaggertype:"integer"`
CardNumber *string `json:"cardNumber"`
Region string `json:"region" binding:"required"`
BranchId shared.FlexibleInt64 `json:"branchId" binding:"required" swaggertype:"integer"`
CustomerName string `json:"customerName" binding:"required"`
CustomerSurname string `json:"customerSurname" binding:"required"`
CustomerPatronicName *string `json:"customerPatronicName"`
BornAt *shared.FlexibleTime `json:"bornAt" swaggertype:"string" format:"date"`
Phone *string `json:"phone"`
PassportSerie string `json:"passportSerie" binding:"required"`
PassportId string `json:"passportId" binding:"required"`
PassportOne string `json:"passportOne" binding:"required"`
PassportTwo string `json:"passportTwo" binding:"required"`
PassportThree string `json:"passportThree" binding:"required"`
PassportFour string `json:"passportFour" binding:"required"`
Status *string `json:"status"`
Notes *string `json:"notes"`
}
type UpdateCardPinOrderDTO struct {
UniqueId *string `json:"uniqueId"`
UserId *int64 `json:"userId"`
CardTypeId int64 `json:"cardTypeId" binding:"required"`
CardNumber *string `json:"cardNumber"`
Region string `json:"region" binding:"required"`
BranchId int64 `json:"branchId" binding:"required"`
CustomerName string `json:"customerName" binding:"required"`
CustomerSurname string `json:"customerSurname" binding:"required"`
CustomerPatronicName *string `json:"customerPatronicName"`
BornAt *time.Time `json:"bornAt"`
Phone *string `json:"phone"`
PassportSerie string `json:"passportSerie" binding:"required"`
PassportId string `json:"passportId" binding:"required"`
PassportOne string `json:"passportOne" binding:"required"`
PassportTwo string `json:"passportTwo" binding:"required"`
PassportThree string `json:"passportThree" binding:"required"`
PassportFour string `json:"passportFour" binding:"required"`
Status *string `json:"status"`
Notes *string `json:"notes"`
UniqueId *string `json:"uniqueId"`
UserId *shared.FlexibleInt64 `json:"userId" swaggertype:"integer"`
CardTypeId shared.FlexibleInt64 `json:"cardTypeId" binding:"required" swaggertype:"integer"`
CardNumber *string `json:"cardNumber"`
Region string `json:"region" binding:"required"`
BranchId shared.FlexibleInt64 `json:"branchId" binding:"required" swaggertype:"integer"`
CustomerName string `json:"customerName" binding:"required"`
CustomerSurname string `json:"customerSurname" binding:"required"`
CustomerPatronicName *string `json:"customerPatronicName"`
BornAt *shared.FlexibleTime `json:"bornAt" swaggertype:"string" format:"date"`
Phone *string `json:"phone"`
PassportSerie string `json:"passportSerie" binding:"required"`
PassportId string `json:"passportId" binding:"required"`
PassportOne string `json:"passportOne" binding:"required"`
PassportTwo string `json:"passportTwo" binding:"required"`
PassportThree string `json:"passportThree" binding:"required"`
PassportFour string `json:"passportFour" binding:"required"`
Status *string `json:"status"`
Notes *string `json:"notes"`
}
type ListFilter struct {
Status *string
BranchId *int64
BranchIds []int64
UserId *int64
CardTypeId *int64
Region string
@@ -81,7 +89,23 @@ type ListFilter struct {
Limit int
}
type ListCardPinOrderDTO struct {
Count int64 `json:"count"`
CardPinOrders []CardPinOrderDTO `json:"cardPinOrders"`
// CardPinOrderListItemDTO is the list row; card type, branch, passport and
// scans come from GET /card-pin-orders/:id.
type CardPinOrderListItemDTO struct {
Id int64 `json:"id"`
UniqueId *string `json:"uniqueId"`
CardNumber *string `json:"cardNumber"`
CustomerName string `json:"customerName"`
CustomerSurname string `json:"customerSurname"`
Region string `json:"region"`
// ProvinceName is the branch's province (etrap).
ProvinceName shared.LocalizedText `json:"provinceName"`
Phone *string `json:"phone"`
Status *string `json:"status"`
CreatedAt time.Time `json:"createdAt"`
}
type ListCardPinOrderDTO struct {
Count int64 `json:"count"`
CardPinOrders []CardPinOrderListItemDTO `json:"cardPinOrders"`
}

View File

@@ -3,11 +3,12 @@ package cardpinorders
import (
"errors"
"net/http"
"strconv"
"strings"
"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"
@@ -26,7 +27,7 @@ func NewHandler(logger *logging.Logger, repository Repository) handlers.Handler
}
func (h *handler) Register(router *gin.RouterGroup) {
group := router.Group(baseURL, appresult.JwtTokenCheck())
group := rbac.Group(router, baseURL, rbac.Require(perm.Cards))
group.GET("", h.list)
group.GET("/:id", h.getByID)
group.POST("", h.create)
@@ -47,6 +48,7 @@ func (h *handler) Register(router *gin.RouterGroup) {
// @Param region query string false "Filter by region"
// @Param page query int false "Page number" default(1)
// @Param limit query int false "Items per page" default(10)
// @Param lang query string false "Language of localized fields; all returns the full {en, ru, tm} objects" Enums(tm, ru, en, all) default(tm)
// @Success 200 {object} appresult.AppSuccess
// @Failure 400 {object} appresult.AppError
// @Failure 500 {object} appresult.AppError
@@ -75,13 +77,14 @@ func (h *handler) list(c *gin.Context) {
// @Produce json
// @Security BearerAuth
// @Param id path int true "Card pin order ID"
// @Param lang query string false "Language of localized fields; all returns the full {en, ru, tm} objects" Enums(tm, ru, en, all) default(tm)
// @Success 200 {object} appresult.AppSuccess
// @Failure 400 {object} appresult.AppError
// @Failure 404 {object} appresult.AppError
// @Failure 500 {object} appresult.AppError
// @Router /card-pin-orders/{id} [get]
func (h *handler) getByID(c *gin.Context) {
id, ok := parseID(c.Param("id"))
id, ok := shared.ParseID(c.Param("id"))
if !ok {
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
return
@@ -97,6 +100,9 @@ func (h *handler) getByID(c *gin.Context) {
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return
}
if !rbac.GuardOrder(c, item.UserId, item.BranchId) {
return
}
c.JSON(http.StatusOK, appresult.SuccessWithData(item))
}
@@ -109,6 +115,7 @@ func (h *handler) getByID(c *gin.Context) {
// @Produce json
// @Security BearerAuth
// @Param body body CreateCardPinOrderDTO true "Card pin order payload"
// @Param lang query string false "Language of localized fields; all returns the full {en, ru, tm} objects" Enums(tm, ru, en, all) default(tm)
// @Success 201 {object} appresult.AppSuccess
// @Failure 400 {object} appresult.AppError
// @Failure 500 {object} appresult.AppError
@@ -139,18 +146,23 @@ func (h *handler) create(c *gin.Context) {
// @Security BearerAuth
// @Param id path int true "Card pin order ID"
// @Param body body UpdateCardPinOrderDTO true "Card pin order payload"
// @Param lang query string false "Language of localized fields; all returns the full {en, ru, tm} objects" Enums(tm, ru, en, all) default(tm)
// @Success 200 {object} appresult.AppSuccess
// @Failure 400 {object} appresult.AppError
// @Failure 404 {object} appresult.AppError
// @Failure 500 {object} appresult.AppError
// @Router /card-pin-orders/{id} [put]
func (h *handler) update(c *gin.Context) {
id, ok := parseID(c.Param("id"))
id, ok := shared.ParseID(c.Param("id"))
if !ok {
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
return
}
if !h.guardBranchByID(c, id) {
return
}
var dto UpdateCardPinOrderDTO
if err := c.ShouldBindJSON(&dto); err != nil {
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
@@ -178,18 +190,23 @@ func (h *handler) update(c *gin.Context) {
// @Produce json
// @Security BearerAuth
// @Param id path int true "Card pin order ID"
// @Param lang query string false "Language of localized fields; all returns the full {en, ru, tm} objects" Enums(tm, ru, en, all) default(tm)
// @Success 200 {object} appresult.AppSuccess
// @Failure 400 {object} appresult.AppError
// @Failure 404 {object} appresult.AppError
// @Failure 500 {object} appresult.AppError
// @Router /card-pin-orders/{id} [delete]
func (h *handler) delete(c *gin.Context) {
id, ok := parseID(c.Param("id"))
id, ok := shared.ParseID(c.Param("id"))
if !ok {
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
return
}
if !h.guardBranchByID(c, id) {
return
}
if err := h.repository.Delete(c.Request.Context(), id); errors.Is(err, pgx.ErrNoRows) {
c.JSON(http.StatusNotFound, appresult.ErrNotFound)
return
@@ -202,73 +219,55 @@ func (h *handler) delete(c *gin.Context) {
c.JSON(http.StatusOK, appresult.SuccessWithData("card pin order removed"))
}
func parseID(raw string) (int64, bool) {
id, err := strconv.ParseInt(raw, 10, 64)
if err != nil || id <= 0 {
return 0, false
}
return id, true
}
const (
defaultPage = 1
defaultLimit = 10
maxLimit = 100
)
func parseListFilter(c *gin.Context) (ListFilter, bool) {
filter := ListFilter{
Page: defaultPage,
Limit: defaultLimit,
page, limit, ok := shared.ParsePageLimit(c)
if !ok {
return ListFilter{}, false
}
filter := ListFilter{Page: page, Limit: limit}
if id, ok := shared.OptionalQueryID(c, "branch_id", "branchId"); !ok {
return ListFilter{}, false
} else if id != nil {
filter.BranchId = id
}
if raw := c.Query("branch_id"); raw != "" {
id, ok := parseID(raw)
if !ok {
return ListFilter{}, false
}
filter.BranchId = &id
if id, ok := shared.OptionalQueryID(c, "user_id", "userId"); !ok {
return ListFilter{}, false
} else if id != nil {
filter.UserId = id
}
if raw := c.Query("user_id"); raw != "" {
id, ok := parseID(raw)
if !ok {
return ListFilter{}, false
}
filter.UserId = &id
if id, ok := shared.OptionalQueryID(c, "card_type_id", "cardTypeId"); !ok {
return ListFilter{}, false
} else if id != nil {
filter.CardTypeId = id
}
if raw := c.Query("card_type_id"); raw != "" {
id, ok := parseID(raw)
if !ok {
return ListFilter{}, false
}
filter.CardTypeId = &id
}
if raw := c.Query("page"); raw != "" {
page, err := strconv.Atoi(raw)
if err != nil || page < 1 {
return ListFilter{}, false
}
filter.Page = page
}
if raw := c.Query("limit"); raw != "" {
limit, err := strconv.Atoi(raw)
if err != nil || limit < 1 || limit > maxLimit {
return ListFilter{}, false
}
filter.Limit = limit
}
if raw := strings.TrimSpace(c.Query("status")); raw != "" {
if raw := shared.QueryValue(c, "status"); raw != "" {
filter.Status = &raw
}
if raw := strings.TrimSpace(c.Query("region")); raw != "" {
if raw := shared.QueryValue(c, "region"); raw != "" {
filter.Region = raw
}
rbac.BindBranchIDs(c, &filter.BranchIds)
return filter, true
}
func (h *handler) guardBranchByID(c *gin.Context, id int64) bool {
if rbac.SkipRecordGuard(c) {
return true
}
item, err := h.repository.GetByID(c.Request.Context(), id)
if errors.Is(err, pgx.ErrNoRows) {
c.JSON(http.StatusNotFound, appresult.ErrNotFound)
return false
}
if err != nil {
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return false
}
return rbac.GuardOrder(c, item.UserId, item.BranchId)
}

View File

@@ -0,0 +1,316 @@
package db
import (
"context"
"fmt"
"strings"
"online-back/internal/cards/cardrekwizit"
"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[cardrekwizit.CardRekwizitOrderDTO]
logger *logging.Logger
}
func NewRepository(client postgresql.Client, logger *logging.Logger) cardrekwizit.Repository {
return &repository{
client: client,
generic: genericrepo.New(client, "card_rekwizit_orders", cardRekwizitOrderColumnsSQL, scanCardRekwizitOrder),
logger: logger,
}
}
var cardRekwizitOrderWritableColumns = []string{
"unique_id", "user_id", "card_type_id", "card_number", "card_month", "card_year",
"region", "branch_id",
"customer_name", "customer_surname", "customer_patronic_name", "born_at", "phone",
"passport_serie", "passport_id", "passport_one", "passport_two", "passport_three", "passport_four",
"status", "notes",
}
var cardRekwizitOrderColumns = append(append([]string{"id"}, cardRekwizitOrderWritableColumns...), "created_at", "updated_at")
var cardRekwizitOrderColumnsSQL = strings.Join(cardRekwizitOrderColumns, ", ")
var cardRekwizitOrderWritableColumnsSQL = strings.Join(cardRekwizitOrderWritableColumns, ", ")
const cardRekwizitOrderFromClause = ` FROM card_rekwizit_orders cro
LEFT JOIN card_types ct ON ct.id = cro.card_type_id
LEFT JOIN branches b ON b.id = cro.branch_id
LEFT JOIN users u ON u.id = cro.user_id`
var cardRekwizitOrderSelectColumns = shared.PrefixedColumns("cro", cardRekwizitOrderColumns) + `,
ct.name, b.name, ` + shared.UserDisplaySQL + `, COALESCE(u.username, ''), COALESCE(u.phone, ''), COALESCE(u.email, '')`
const cardRekwizitOrderListFromClause = cardRekwizitOrderFromClause + `
LEFT JOIN provinces bp ON bp.id = b.province_id`
var cardRekwizitOrderListColumns = `cro.id, cro.unique_id, cro.card_type_id, ct.name,
cro.customer_name, cro.customer_surname, cro.user_id, ` + shared.UserDisplaySQL + `,
cro.region, cro.branch_id, b.name, bp.name, cro.status`
func resolveStatus(status *string) *string {
if status == nil || strings.TrimSpace(*status) == "" {
pending := "pending"
return &pending
}
return status
}
func createArgs(dto cardrekwizit.CreateCardRekwizitOrderDTO) []interface{} {
return []interface{}{
dto.UniqueId, shared.OptionalInt64(dto.UserId), dto.CardTypeId.Int64(),
dto.CardNumber, dto.CardMonth, dto.CardYear,
dto.Region, dto.BranchId.Int64(),
dto.CustomerName, dto.CustomerSurname, dto.CustomerPatronicName, dto.BornAt.Time(), dto.Phone,
dto.PassportSerie, dto.PassportId, dto.PassportOne, dto.PassportTwo, dto.PassportThree, dto.PassportFour,
resolveStatus(dto.Status), dto.Notes,
}
}
func updateArgs(dto cardrekwizit.UpdateCardRekwizitOrderDTO) []interface{} {
return []interface{}{
dto.UniqueId, shared.OptionalInt64(dto.UserId), dto.CardTypeId.Int64(),
dto.CardNumber, dto.CardMonth, dto.CardYear,
dto.Region, dto.BranchId.Int64(),
dto.CustomerName, dto.CustomerSurname, dto.CustomerPatronicName, dto.BornAt.Time(), dto.Phone,
dto.PassportSerie, dto.PassportId, dto.PassportOne, dto.PassportTwo, dto.PassportThree, dto.PassportFour,
resolveStatus(dto.Status), dto.Notes,
}
}
func (r *repository) List(ctx context.Context, filter cardrekwizit.ListFilter) (cardrekwizit.ListCardRekwizitOrderDTO, error) {
whereClause, args := buildListQuery(filter)
var count int64
if err := r.client.QueryRow(ctx, `SELECT COUNT(*) FROM card_rekwizit_orders cro`+whereClause, args...).Scan(&count); err != nil {
return cardrekwizit.ListCardRekwizitOrderDTO{}, err
}
offset := (filter.Page - 1) * filter.Limit
limitPlaceholder := len(args) + 1
offsetPlaceholder := len(args) + 2
query := fmt.Sprintf(
`SELECT %s%s%s ORDER BY cro.id LIMIT $%d OFFSET $%d`,
cardRekwizitOrderListColumns, cardRekwizitOrderListFromClause, whereClause, limitPlaceholder, offsetPlaceholder,
)
rows, err := r.client.Query(ctx, query, append(args, filter.Limit, offset)...)
if err != nil {
return cardrekwizit.ListCardRekwizitOrderDTO{}, err
}
defer rows.Close()
items := []cardrekwizit.CardRekwizitOrderListItemDTO{}
for rows.Next() {
item, err := scanCardRekwizitOrderListItem(rows)
if err != nil {
return cardrekwizit.ListCardRekwizitOrderDTO{}, err
}
items = append(items, item)
}
if err := rows.Err(); err != nil {
return cardrekwizit.ListCardRekwizitOrderDTO{}, err
}
return cardrekwizit.ListCardRekwizitOrderDTO{Count: count, CardRekwizitOrders: items}, nil
}
func buildListQuery(filter cardrekwizit.ListFilter) (whereClause string, args []interface{}) {
conditions := []string{"cro.deleted_at IS NULL"}
if filter.Status != nil {
args = append(args, *filter.Status)
conditions = append(conditions, fmt.Sprintf("cro.status = $%d", len(args)))
}
if len(filter.BranchIds) > 0 {
conditions, args = rbac.AppendBranchIDs(conditions, args, "cro.branch_id", filter.BranchIds)
} else if filter.BranchId != nil {
args = append(args, *filter.BranchId)
conditions = append(conditions, fmt.Sprintf("cro.branch_id = $%d", len(args)))
}
if filter.UserId != nil {
args = append(args, *filter.UserId)
conditions = append(conditions, fmt.Sprintf("cro.user_id = $%d", len(args)))
}
if filter.CardTypeId != nil {
args = append(args, *filter.CardTypeId)
conditions = append(conditions, fmt.Sprintf("cro.card_type_id = $%d", len(args)))
}
if filter.Region != "" {
args = append(args, filter.Region)
conditions = append(conditions, fmt.Sprintf("cro.region = $%d", len(args)))
}
return " WHERE " + strings.Join(conditions, " AND "), args
}
func (r *repository) GetByID(ctx context.Context, id int64) (cardrekwizit.CardRekwizitOrderDTO, error) {
query := `SELECT ` + cardRekwizitOrderSelectColumns + cardRekwizitOrderFromClause + ` WHERE cro.id = $1 AND cro.deleted_at IS NULL`
return scanCardRekwizitOrderWithJoins(r.client.QueryRow(ctx, query, id))
}
func (r *repository) Create(ctx context.Context, dto cardrekwizit.CreateCardRekwizitOrderDTO) (cardrekwizit.CardRekwizitOrderDTO, 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 card_rekwizit_orders (%s) VALUES (%s)
RETURNING %s
)
SELECT %s
FROM inserted cro
LEFT JOIN card_types ct ON ct.id = cro.card_type_id
LEFT JOIN branches b ON b.id = cro.branch_id
LEFT JOIN users u ON u.id = cro.user_id`,
cardRekwizitOrderWritableColumnsSQL, strings.Join(placeholders, ", "),
cardRekwizitOrderColumnsSQL, cardRekwizitOrderSelectColumns,
)
return scanCardRekwizitOrderWithJoins(r.client.QueryRow(ctx, query, args...))
}
func (r *repository) Update(ctx context.Context, id int64, dto cardrekwizit.UpdateCardRekwizitOrderDTO) (cardrekwizit.CardRekwizitOrderDTO, error) {
args := updateArgs(dto)
assignments := make([]string, len(cardRekwizitOrderWritableColumns))
for i, column := range cardRekwizitOrderWritableColumns {
assignments[i] = fmt.Sprintf("%s = $%d", column, i+1)
}
args = append(args, id)
query := fmt.Sprintf(`
WITH updated AS (
UPDATE card_rekwizit_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 cro
LEFT JOIN card_types ct ON ct.id = cro.card_type_id
LEFT JOIN branches b ON b.id = cro.branch_id
LEFT JOIN users u ON u.id = cro.user_id`,
strings.Join(assignments, ", "), len(args), cardRekwizitOrderColumnsSQL, cardRekwizitOrderSelectColumns,
)
item, err := scanCardRekwizitOrderWithJoins(r.client.QueryRow(ctx, query, args...))
if err != nil {
return cardrekwizit.CardRekwizitOrderDTO{}, err
}
return item, nil
}
func (r *repository) Delete(ctx context.Context, id int64) error {
return r.generic.Delete(ctx, id)
}
func scanCardRekwizitOrder(row genericrepo.Scanner) (cardrekwizit.CardRekwizitOrderDTO, error) {
return scanCardRekwizitOrderRow(row, false)
}
func scanCardRekwizitOrderListItem(row genericrepo.Scanner) (cardrekwizit.CardRekwizitOrderListItemDTO, error) {
var item cardrekwizit.CardRekwizitOrderListItemDTO
var cardTypeId, branchId int64
var userId *int64
var cardTypeNameJSON, branchNameJSON, provinceNameJSON []byte
var userName string
if err := row.Scan(
&item.Id, &item.UniqueId, &cardTypeId, &cardTypeNameJSON,
&item.CustomerName, &item.CustomerSurname, &userId, &userName,
&item.Region, &branchId, &branchNameJSON, &provinceNameJSON, &item.Status,
); err != nil {
return cardrekwizit.CardRekwizitOrderListItemDTO{}, err
}
var cardTypeName, branchName shared.LocalizedText
if err := shared.UnmarshalLocalized(cardTypeNameJSON, &cardTypeName); err != nil {
return cardrekwizit.CardRekwizitOrderListItemDTO{}, err
}
if err := shared.UnmarshalLocalized(branchNameJSON, &branchName); err != nil {
return cardrekwizit.CardRekwizitOrderListItemDTO{}, err
}
if err := shared.UnmarshalLocalized(provinceNameJSON, &item.ProvinceName); err != nil {
return cardrekwizit.CardRekwizitOrderListItemDTO{}, err
}
if cardTypeId != 0 {
item.CardType = &shared.NamedInfo{Id: cardTypeId, Name: cardTypeName}
}
if branchId != 0 {
item.Branch = &shared.NamedInfo{Id: branchId, Name: branchName}
}
if userId != nil {
item.User = &cardrekwizit.ListUserDTO{Id: *userId, Name: userName}
}
return item, nil
}
func scanCardRekwizitOrderWithJoins(row genericrepo.Scanner) (cardrekwizit.CardRekwizitOrderDTO, error) {
return scanCardRekwizitOrderRow(row, true)
}
func scanCardRekwizitOrderRow(row genericrepo.Scanner, withJoins bool) (cardrekwizit.CardRekwizitOrderDTO, error) {
var item cardrekwizit.CardRekwizitOrderDTO
dest := []interface{}{
&item.Id, &item.UniqueId, &item.UserId, &item.CardTypeId,
&item.CardNumber, &item.CardMonth, &item.CardYear,
&item.Region, &item.BranchId,
&item.CustomerName, &item.CustomerSurname, &item.CustomerPatronicName, &item.BornAt, &item.Phone,
&item.PassportSerie, &item.PassportId, &item.PassportOne, &item.PassportTwo, &item.PassportThree, &item.PassportFour,
&item.Status, &item.Notes,
&item.CreatedAt, &item.UpdatedAt,
}
var cardTypeNameJSON, branchNameJSON []byte
var userName, userUsername, userPhone, userEmail string
if withJoins {
dest = append(dest, &cardTypeNameJSON, &branchNameJSON, &userName, &userUsername, &userPhone, &userEmail)
}
if err := row.Scan(dest...); err != nil {
return cardrekwizit.CardRekwizitOrderDTO{}, err
}
if !withJoins {
return item, nil
}
var cardTypeName, branchName shared.LocalizedText
if err := shared.UnmarshalLocalized(cardTypeNameJSON, &cardTypeName); err != nil {
return cardrekwizit.CardRekwizitOrderDTO{}, err
}
if err := shared.UnmarshalLocalized(branchNameJSON, &branchName); err != nil {
return cardrekwizit.CardRekwizitOrderDTO{}, err
}
if item.CardTypeId != 0 {
item.CardType = &shared.NamedInfo{Id: item.CardTypeId, Name: cardTypeName}
}
if item.BranchId != 0 {
item.Branch = &shared.NamedInfo{Id: item.BranchId, Name: branchName}
}
if item.UserId != nil {
item.User = &shared.UserInfo{
Id: *item.UserId,
Name: userName,
Username: userUsername,
Phone: userPhone,
Email: userEmail,
}
}
return item, nil
}

View File

@@ -0,0 +1,122 @@
package cardrekwizit
import (
"time"
"online-back/internal/shared"
)
type CardRekwizitOrderDTO struct {
Id int64 `json:"id"`
UniqueId *string `json:"uniqueId"`
UserId *int64 `json:"-"`
User *shared.UserInfo `json:"user,omitempty"`
CardTypeId int64 `json:"-"`
CardType *shared.NamedInfo `json:"cardType,omitempty"`
CardNumber string `json:"cardNumber"`
CardMonth string `json:"cardMonth"`
CardYear string `json:"cardYear"`
Region string `json:"region"`
BranchId int64 `json:"-"`
Branch *shared.NamedInfo `json:"branch,omitempty"`
CustomerName string `json:"customerName"`
CustomerSurname string `json:"customerSurname"`
CustomerPatronicName *string `json:"customerPatronicName"`
BornAt time.Time `json:"bornAt"`
Phone string `json:"phone"`
PassportSerie string `json:"passportSerie"`
PassportId string `json:"passportId"`
PassportOne string `json:"passportOne"`
PassportTwo string `json:"passportTwo"`
PassportThree string `json:"passportThree"`
PassportFour string `json:"passportFour"`
Status *string `json:"status"`
Notes *string `json:"notes"`
CreatedAt time.Time `json:"createdAt"`
UpdatedAt time.Time `json:"updatedAt"`
}
type CreateCardRekwizitOrderDTO struct {
UniqueId *string `json:"uniqueId"`
UserId *shared.FlexibleInt64 `json:"userId" swaggertype:"integer"`
CardTypeId shared.FlexibleInt64 `json:"cardTypeId" binding:"required" swaggertype:"integer"`
CardNumber string `json:"cardNumber" binding:"required"`
CardMonth string `json:"cardMonth" binding:"required"`
CardYear string `json:"cardYear" binding:"required"`
Region string `json:"region" binding:"required"`
BranchId shared.FlexibleInt64 `json:"branchId" binding:"required" swaggertype:"integer"`
CustomerName string `json:"customerName" binding:"required"`
CustomerSurname string `json:"customerSurname" binding:"required"`
CustomerPatronicName *string `json:"customerPatronicName"`
BornAt shared.FlexibleTime `json:"bornAt" binding:"required" swaggertype:"string" format:"date"`
Phone string `json:"phone" binding:"required"`
PassportSerie string `json:"passportSerie" binding:"required"`
PassportId string `json:"passportId" binding:"required"`
PassportOne string `json:"passportOne" binding:"required"`
PassportTwo string `json:"passportTwo" binding:"required"`
PassportThree string `json:"passportThree" binding:"required"`
PassportFour string `json:"passportFour" binding:"required"`
Status *string `json:"status"`
Notes *string `json:"notes"`
}
type UpdateCardRekwizitOrderDTO struct {
UniqueId *string `json:"uniqueId"`
UserId *shared.FlexibleInt64 `json:"userId" swaggertype:"integer"`
CardTypeId shared.FlexibleInt64 `json:"cardTypeId" binding:"required" swaggertype:"integer"`
CardNumber string `json:"cardNumber" binding:"required"`
CardMonth string `json:"cardMonth" binding:"required"`
CardYear string `json:"cardYear" binding:"required"`
Region string `json:"region" binding:"required"`
BranchId shared.FlexibleInt64 `json:"branchId" binding:"required" swaggertype:"integer"`
CustomerName string `json:"customerName" binding:"required"`
CustomerSurname string `json:"customerSurname" binding:"required"`
CustomerPatronicName *string `json:"customerPatronicName"`
BornAt shared.FlexibleTime `json:"bornAt" binding:"required" swaggertype:"string" format:"date"`
Phone string `json:"phone" binding:"required"`
PassportSerie string `json:"passportSerie" binding:"required"`
PassportId string `json:"passportId" binding:"required"`
PassportOne string `json:"passportOne" binding:"required"`
PassportTwo string `json:"passportTwo" binding:"required"`
PassportThree string `json:"passportThree" binding:"required"`
PassportFour string `json:"passportFour" binding:"required"`
Status *string `json:"status"`
Notes *string `json:"notes"`
}
type ListFilter struct {
Status *string
BranchId *int64
BranchIds []int64
UserId *int64
CardTypeId *int64
Region string
Page int
Limit int
}
// CardRekwizitOrderListItemDTO is the list row; card number, passport and
// scans come from GET /card-rekwizit-orders/:id.
type CardRekwizitOrderListItemDTO struct {
Id int64 `json:"id"`
UniqueId *string `json:"uniqueId"`
CardType *shared.NamedInfo `json:"cardType,omitempty"`
CustomerName string `json:"customerName"`
CustomerSurname string `json:"customerSurname"`
User *ListUserDTO `json:"user,omitempty"`
Region string `json:"region"`
Branch *shared.NamedInfo `json:"branch,omitempty"`
// ProvinceName is the branch's province (etrap).
ProvinceName shared.LocalizedText `json:"provinceName"`
Status *string `json:"status"`
}
type ListUserDTO struct {
Id int64 `json:"id"`
Name string `json:"name"`
}
type ListCardRekwizitOrderDTO struct {
Count int64 `json:"count"`
CardRekwizitOrders []CardRekwizitOrderListItemDTO `json:"cardRekwizitOrders"`
}

View File

@@ -0,0 +1,273 @@
package cardrekwizit
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 = "/card-rekwizit-orders"
type handler struct {
logger *logging.Logger
repository Repository
}
func NewHandler(logger *logging.Logger, repository Repository) handlers.Handler {
return &handler{logger: logger, repository: repository}
}
func (h *handler) Register(router *gin.RouterGroup) {
group := rbac.Group(router, baseURL, rbac.Require(perm.Cards))
group.GET("", h.list)
group.GET("/:id", h.getByID)
group.POST("", h.create)
group.PUT("/:id", h.update)
group.DELETE("/:id", h.delete)
}
// list godoc
// @Summary List card rekwizit orders
// @Description Returns paginated card rekwizit (card details) orders with optional filters
// @Tags card-rekwizit-orders
// @Produce json
// @Security BearerAuth
// @Param status query string false "Filter by status"
// @Param branch_id query int false "Filter by branch ID"
// @Param user_id query int false "Filter by user ID"
// @Param card_type_id query int false "Filter by card type ID"
// @Param region query string false "Filter by region"
// @Param page query int false "Page number" default(1)
// @Param limit query int false "Items per page" default(10)
// @Param lang query string false "Language of localized fields; all returns the full {en, ru, tm} objects" Enums(tm, ru, en, all) default(tm)
// @Success 200 {object} appresult.AppSuccess
// @Failure 400 {object} appresult.AppError
// @Failure 500 {object} appresult.AppError
// @Router /card-rekwizit-orders [get]
func (h *handler) list(c *gin.Context) {
filter, ok := parseListFilter(c)
if !ok {
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
return
}
result, err := h.repository.List(c.Request.Context(), filter)
if err != nil {
h.logger.Errorf("list card rekwizit orders failed: %v", err)
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return
}
c.JSON(http.StatusOK, appresult.SuccessWithData(result))
}
// getByID godoc
// @Summary Get card rekwizit order by ID
// @Description Returns a single card rekwizit order
// @Tags card-rekwizit-orders
// @Produce json
// @Security BearerAuth
// @Param id path int true "Card rekwizit order ID"
// @Param lang query string false "Language of localized fields; all returns the full {en, ru, tm} objects" Enums(tm, ru, en, all) default(tm)
// @Success 200 {object} appresult.AppSuccess
// @Failure 400 {object} appresult.AppError
// @Failure 404 {object} appresult.AppError
// @Failure 500 {object} appresult.AppError
// @Router /card-rekwizit-orders/{id} [get]
func (h *handler) getByID(c *gin.Context) {
id, ok := shared.ParseID(c.Param("id"))
if !ok {
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
return
}
item, err := h.repository.GetByID(c.Request.Context(), id)
if errors.Is(err, pgx.ErrNoRows) {
c.JSON(http.StatusNotFound, appresult.ErrNotFound)
return
}
if err != nil {
h.logger.Errorf("get card rekwizit order failed: %v", err)
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return
}
if !rbac.GuardOrder(c, item.UserId, item.BranchId) {
return
}
c.JSON(http.StatusOK, appresult.SuccessWithData(item))
}
// create godoc
// @Summary Create card rekwizit order
// @Description Creates a new card rekwizit (card details) order
// @Tags card-rekwizit-orders
// @Accept json
// @Produce json
// @Security BearerAuth
// @Param body body CreateCardRekwizitOrderDTO true "Card rekwizit order payload"
// @Param lang query string false "Language of localized fields; all returns the full {en, ru, tm} objects" Enums(tm, ru, en, all) default(tm)
// @Success 201 {object} appresult.AppSuccess
// @Failure 400 {object} appresult.AppError
// @Failure 500 {object} appresult.AppError
// @Router /card-rekwizit-orders [post]
func (h *handler) create(c *gin.Context) {
var dto CreateCardRekwizitOrderDTO
if err := c.ShouldBindJSON(&dto); err != nil {
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
return
}
item, err := h.repository.Create(c.Request.Context(), dto)
if err != nil {
h.logger.Errorf("create card rekwizit order failed: %v", err)
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return
}
c.JSON(http.StatusCreated, appresult.SuccessWithData(item))
}
// update godoc
// @Summary Update card rekwizit order
// @Description Updates an existing card rekwizit order
// @Tags card-rekwizit-orders
// @Accept json
// @Produce json
// @Security BearerAuth
// @Param id path int true "Card rekwizit order ID"
// @Param body body UpdateCardRekwizitOrderDTO true "Card rekwizit order payload"
// @Param lang query string false "Language of localized fields; all returns the full {en, ru, tm} objects" Enums(tm, ru, en, all) default(tm)
// @Success 200 {object} appresult.AppSuccess
// @Failure 400 {object} appresult.AppError
// @Failure 404 {object} appresult.AppError
// @Failure 500 {object} appresult.AppError
// @Router /card-rekwizit-orders/{id} [put]
func (h *handler) update(c *gin.Context) {
id, ok := shared.ParseID(c.Param("id"))
if !ok {
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
return
}
if !h.guardBranchByID(c, id) {
return
}
var dto UpdateCardRekwizitOrderDTO
if err := c.ShouldBindJSON(&dto); err != nil {
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
return
}
item, err := h.repository.Update(c.Request.Context(), id, dto)
if errors.Is(err, pgx.ErrNoRows) {
c.JSON(http.StatusNotFound, appresult.ErrNotFound)
return
}
if err != nil {
h.logger.Errorf("update card rekwizit order failed: %v", err)
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return
}
c.JSON(http.StatusOK, appresult.SuccessWithData(item))
}
// delete godoc
// @Summary Delete card rekwizit order
// @Description Deletes a card rekwizit order
// @Tags card-rekwizit-orders
// @Produce json
// @Security BearerAuth
// @Param id path int true "Card rekwizit order ID"
// @Param lang query string false "Language of localized fields; all returns the full {en, ru, tm} objects" Enums(tm, ru, en, all) default(tm)
// @Success 200 {object} appresult.AppSuccess
// @Failure 400 {object} appresult.AppError
// @Failure 404 {object} appresult.AppError
// @Failure 500 {object} appresult.AppError
// @Router /card-rekwizit-orders/{id} [delete]
func (h *handler) delete(c *gin.Context) {
id, ok := shared.ParseID(c.Param("id"))
if !ok {
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
return
}
if !h.guardBranchByID(c, id) {
return
}
if err := h.repository.Delete(c.Request.Context(), id); errors.Is(err, pgx.ErrNoRows) {
c.JSON(http.StatusNotFound, appresult.ErrNotFound)
return
} else if err != nil {
h.logger.Errorf("delete card rekwizit order failed: %v", err)
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return
}
c.JSON(http.StatusOK, appresult.SuccessWithData("card rekwizit order removed"))
}
func parseListFilter(c *gin.Context) (ListFilter, bool) {
page, limit, ok := shared.ParsePageLimit(c)
if !ok {
return ListFilter{}, false
}
filter := ListFilter{Page: page, Limit: limit}
if id, ok := shared.OptionalQueryID(c, "branch_id", "branchId"); !ok {
return ListFilter{}, false
} else if id != nil {
filter.BranchId = id
}
if id, ok := shared.OptionalQueryID(c, "user_id", "userId"); !ok {
return ListFilter{}, false
} else if id != nil {
filter.UserId = id
}
if id, ok := shared.OptionalQueryID(c, "card_type_id", "cardTypeId"); !ok {
return ListFilter{}, false
} else if id != nil {
filter.CardTypeId = id
}
if raw := shared.QueryValue(c, "status"); raw != "" {
filter.Status = &raw
}
if raw := shared.QueryValue(c, "region"); raw != "" {
filter.Region = raw
}
rbac.BindBranchIDs(c, &filter.BranchIds)
return filter, true
}
func (h *handler) guardBranchByID(c *gin.Context, id int64) bool {
if rbac.SkipRecordGuard(c) {
return true
}
item, err := h.repository.GetByID(c.Request.Context(), id)
if errors.Is(err, pgx.ErrNoRows) {
c.JSON(http.StatusNotFound, appresult.ErrNotFound)
return false
}
if err != nil {
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return false
}
return rbac.GuardOrder(c, item.UserId, item.BranchId)
}

View File

@@ -0,0 +1,11 @@
package cardrekwizit
import "context"
type Repository interface {
List(ctx context.Context, filter ListFilter) (ListCardRekwizitOrderDTO, error)
GetByID(ctx context.Context, id int64) (CardRekwizitOrderDTO, error)
Create(ctx context.Context, dto CreateCardRekwizitOrderDTO) (CardRekwizitOrderDTO, error)
Update(ctx context.Context, id int64, dto UpdateCardRekwizitOrderDTO) (CardRekwizitOrderDTO, error)
Delete(ctx context.Context, id int64) error
}

View File

@@ -3,9 +3,12 @@ package db
import (
"context"
"fmt"
"strconv"
"strings"
"online-back/internal/cards/cards"
"online-back/internal/identity/rbac"
"online-back/internal/shared"
"online-back/pkg/client/postgresql"
"online-back/pkg/logging"
"online-back/pkg/repository/genericrepo"
@@ -37,6 +40,13 @@ var cardColumnsSQL = strings.Join(cardColumns, ", ")
var cardWritableColumnsSQL = strings.Join(cardWritableColumns, ", ")
const cardFromClause = ` FROM cards c
LEFT JOIN card_types ct ON ct.id::text = c.type
LEFT JOIN users u ON u.id = c.user_id`
var cardSelectColumns = shared.PrefixedColumns("c", cardColumns) + `,
ct.name, ` + shared.UserDisplaySQL + `, COALESCE(u.username, ''), COALESCE(u.phone, ''), COALESCE(u.email, '')`
func createArgs(dto cards.CreateCardDTO) []interface{} {
return []interface{}{
dto.UserId, dto.Number, dto.Name, dto.Month, dto.Year, dto.Type,
@@ -52,36 +62,64 @@ func updateArgs(dto cards.UpdateCardDTO) []interface{} {
func (r *repository) List(ctx context.Context, filter cards.ListFilter) (cards.ListCardDTO, error) {
whereClause, args := buildListQuery(filter)
items, count, err := r.generic.List(ctx, whereClause, args, filter.Page, filter.Limit, "id")
var count int64
if err := r.client.QueryRow(ctx, `SELECT COUNT(*) FROM cards c`+whereClause, args...).Scan(&count); err != nil {
return cards.ListCardDTO{}, err
}
offset := (filter.Page - 1) * filter.Limit
limitPlaceholder := len(args) + 1
offsetPlaceholder := len(args) + 2
query := fmt.Sprintf(
`SELECT %s%s%s ORDER BY c.id LIMIT $%d OFFSET $%d`,
cardSelectColumns, cardFromClause, whereClause, limitPlaceholder, offsetPlaceholder,
)
rows, err := r.client.Query(ctx, query, append(args, filter.Limit, offset)...)
if err != nil {
return cards.ListCardDTO{}, err
}
defer rows.Close()
var items []cards.CardDTO
for rows.Next() {
item, err := scanCardWithUser(rows)
if err != nil {
return cards.ListCardDTO{}, err
}
items = append(items, item)
}
if err := rows.Err(); err != nil {
return cards.ListCardDTO{}, err
}
return cards.ListCardDTO{Count: count, Cards: items}, nil
}
func buildListQuery(filter cards.ListFilter) (whereClause string, args []interface{}) {
var conditions []string
conditions := []string{"c.deleted_at IS NULL"}
if filter.UserId != nil {
args = append(args, *filter.UserId)
conditions = append(conditions, fmt.Sprintf("user_id = $%d", len(args)))
conditions = append(conditions, fmt.Sprintf("c.user_id = $%d", len(args)))
}
if len(filter.BranchIds) > 0 {
args = append(args, filter.BranchIds)
conditions = append(conditions, rbac.UserInBranchSQL("c.user_id", len(args)))
}
if filter.Type != nil {
args = append(args, *filter.Type)
conditions = append(conditions, fmt.Sprintf("type = $%d", len(args)))
}
if len(conditions) == 0 {
return "", args
conditions = append(conditions, fmt.Sprintf("c.type = $%d", len(args)))
}
return " WHERE " + strings.Join(conditions, " AND "), args
}
func (r *repository) GetByID(ctx context.Context, id int64) (cards.CardDTO, error) {
return r.generic.GetByID(ctx, id)
query := `SELECT ` + cardSelectColumns + cardFromClause + ` WHERE c.id = $1 AND c.deleted_at IS NULL`
return scanCardWithUser(r.client.QueryRow(ctx, query, id))
}
func (r *repository) Create(ctx context.Context, dto cards.CreateCardDTO) (cards.CardDTO, error) {
@@ -92,12 +130,20 @@ func (r *repository) Create(ctx context.Context, dto cards.CreateCardDTO) (cards
placeholders[i] = fmt.Sprintf("$%d", i+1)
}
query := fmt.Sprintf(
`INSERT INTO cards (%s) VALUES (%s) RETURNING %s`,
cardWritableColumnsSQL, strings.Join(placeholders, ", "), cardColumnsSQL,
query := fmt.Sprintf(`
WITH inserted AS (
INSERT INTO cards (%s) VALUES (%s)
RETURNING %s
)
SELECT %s
FROM inserted c
LEFT JOIN card_types ct ON ct.id::text = c.type
LEFT JOIN users u ON u.id = c.user_id`,
cardWritableColumnsSQL, strings.Join(placeholders, ", "),
cardColumnsSQL, cardSelectColumns,
)
return scanCard(r.client.QueryRow(ctx, query, args...))
return scanCardWithUser(r.client.QueryRow(ctx, query, args...))
}
func (r *repository) Update(ctx context.Context, id int64, dto cards.UpdateCardDTO) (cards.CardDTO, error) {
@@ -109,12 +155,20 @@ func (r *repository) Update(ctx context.Context, id int64, dto cards.UpdateCardD
}
args = append(args, id)
query := fmt.Sprintf(
`UPDATE cards SET %s, updated_at = (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') WHERE id = $%d RETURNING %s`,
strings.Join(assignments, ", "), len(args), cardColumnsSQL,
query := fmt.Sprintf(`
WITH updated AS (
UPDATE cards SET %s, updated_at = (CURRENT_TIMESTAMP AT TIME ZONE 'UTC')
WHERE id = $%d AND deleted_at IS NULL
RETURNING %s
)
SELECT %s
FROM updated c
LEFT JOIN card_types ct ON ct.id::text = c.type
LEFT JOIN users u ON u.id = c.user_id`,
strings.Join(assignments, ", "), len(args), cardColumnsSQL, cardSelectColumns,
)
item, err := scanCard(r.client.QueryRow(ctx, query, args...))
item, err := scanCardWithUser(r.client.QueryRow(ctx, query, args...))
if err != nil {
return cards.CardDTO{}, err
}
@@ -126,13 +180,57 @@ func (r *repository) Delete(ctx context.Context, id int64) error {
}
func scanCard(row genericrepo.Scanner) (cards.CardDTO, error) {
return scanCardRow(row, false)
}
func scanCardWithUser(row genericrepo.Scanner) (cards.CardDTO, error) {
return scanCardRow(row, true)
}
func scanCardRow(row genericrepo.Scanner, withUser bool) (cards.CardDTO, error) {
var item cards.CardDTO
err := row.Scan(
dest := []interface{}{
&item.Id, &item.UserId, &item.Number, &item.Name, &item.Month, &item.Year, &item.Type,
&item.CreatedAt, &item.UpdatedAt,
)
if err != nil {
}
var cardTypeNameJSON []byte
var userName, userUsername, userPhone, userEmail string
if withUser {
dest = append(dest, &cardTypeNameJSON, &userName, &userUsername, &userPhone, &userEmail)
}
if err := row.Scan(dest...); err != nil {
return cards.CardDTO{}, err
}
if withUser {
var cardTypeName shared.LocalizedText
if err := shared.UnmarshalLocalized(cardTypeNameJSON, &cardTypeName); err != nil {
return cards.CardDTO{}, err
}
if id := parseCardTypeID(item.Type); id != 0 {
item.CardType = &shared.NamedInfo{Id: id, Name: cardTypeName}
}
if item.UserId != nil {
item.User = &shared.UserInfo{
Id: *item.UserId,
Name: userName,
Username: userUsername,
Phone: userPhone,
Email: userEmail,
}
}
}
return item, nil
}
func parseCardTypeID(raw *string) int64 {
if raw == nil {
return 0
}
id, err := strconv.ParseInt(strings.TrimSpace(*raw), 10, 64)
if err != nil {
return 0
}
return id
}

View File

@@ -1,17 +1,23 @@
package cards
import "time"
import (
"time"
"online-back/internal/shared"
)
type CardDTO struct {
Id int64 `json:"id"`
UserId *int64 `json:"userId"`
Number string `json:"number"`
Name string `json:"name"`
Month string `json:"month"`
Year *string `json:"year"`
Type *string `json:"type"`
CreatedAt time.Time `json:"createdAt"`
UpdatedAt time.Time `json:"updatedAt"`
Id int64 `json:"id"`
UserId *int64 `json:"-"`
User *shared.UserInfo `json:"user,omitempty"`
Number string `json:"number"`
Name string `json:"name"`
Month string `json:"month"`
Year *string `json:"year"`
Type *string `json:"-"`
CardType *shared.NamedInfo `json:"cardType,omitempty"`
CreatedAt time.Time `json:"createdAt"`
UpdatedAt time.Time `json:"updatedAt"`
}
type CreateCardDTO struct {
@@ -33,10 +39,11 @@ type UpdateCardDTO struct {
}
type ListFilter struct {
UserId *int64
Type *string
Page int
Limit int
UserId *int64
BranchIds []int64
Type *string
Page int
Limit int
}
type ListCardDTO struct {

View File

@@ -3,11 +3,12 @@ package cards
import (
"errors"
"net/http"
"strconv"
"strings"
"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"
@@ -26,7 +27,7 @@ func NewHandler(logger *logging.Logger, repository Repository) handlers.Handler
}
func (h *handler) Register(router *gin.RouterGroup) {
group := router.Group(baseURL, appresult.JwtTokenCheck())
group := rbac.Group(router, baseURL, rbac.Require(perm.Cards))
group.GET("", h.list)
group.GET("/:id", h.getByID)
group.POST("", h.create)
@@ -44,6 +45,7 @@ func (h *handler) Register(router *gin.RouterGroup) {
// @Param type query string false "Filter by card type"
// @Param page query int false "Page number" default(1)
// @Param limit query int false "Items per page" default(10)
// @Param lang query string false "Language of localized fields; all returns the full {en, ru, tm} objects" Enums(tm, ru, en, all) default(tm)
// @Success 200 {object} appresult.AppSuccess
// @Failure 400 {object} appresult.AppError
// @Failure 500 {object} appresult.AppError
@@ -72,13 +74,14 @@ func (h *handler) list(c *gin.Context) {
// @Produce json
// @Security BearerAuth
// @Param id path int true "Card ID"
// @Param lang query string false "Language of localized fields; all returns the full {en, ru, tm} objects" Enums(tm, ru, en, all) default(tm)
// @Success 200 {object} appresult.AppSuccess
// @Failure 400 {object} appresult.AppError
// @Failure 404 {object} appresult.AppError
// @Failure 500 {object} appresult.AppError
// @Router /cards/{id} [get]
func (h *handler) getByID(c *gin.Context) {
id, ok := parseID(c.Param("id"))
id, ok := shared.ParseID(c.Param("id"))
if !ok {
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
return
@@ -94,6 +97,16 @@ func (h *handler) getByID(c *gin.Context) {
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return
}
if !rbac.GuardOwned(c, item.UserId) {
return
}
if item.UserId != nil && !rbac.GuardUser(c, *item.UserId) {
return
}
if item.UserId == nil && rbac.HasBranchScope(c) {
c.JSON(http.StatusForbidden, appresult.ErrForbidden)
return
}
c.JSON(http.StatusOK, appresult.SuccessWithData(item))
}
@@ -106,6 +119,7 @@ func (h *handler) getByID(c *gin.Context) {
// @Produce json
// @Security BearerAuth
// @Param body body CreateCardDTO true "Card payload"
// @Param lang query string false "Language of localized fields; all returns the full {en, ru, tm} objects" Enums(tm, ru, en, all) default(tm)
// @Success 201 {object} appresult.AppSuccess
// @Failure 400 {object} appresult.AppError
// @Failure 500 {object} appresult.AppError
@@ -136,18 +150,23 @@ func (h *handler) create(c *gin.Context) {
// @Security BearerAuth
// @Param id path int true "Card ID"
// @Param body body UpdateCardDTO true "Card payload"
// @Param lang query string false "Language of localized fields; all returns the full {en, ru, tm} objects" Enums(tm, ru, en, all) default(tm)
// @Success 200 {object} appresult.AppSuccess
// @Failure 400 {object} appresult.AppError
// @Failure 404 {object} appresult.AppError
// @Failure 500 {object} appresult.AppError
// @Router /cards/{id} [put]
func (h *handler) update(c *gin.Context) {
id, ok := parseID(c.Param("id"))
id, ok := shared.ParseID(c.Param("id"))
if !ok {
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
return
}
if !h.guardCardByID(c, id) {
return
}
var dto UpdateCardDTO
if err := c.ShouldBindJSON(&dto); err != nil {
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
@@ -175,18 +194,23 @@ func (h *handler) update(c *gin.Context) {
// @Produce json
// @Security BearerAuth
// @Param id path int true "Card ID"
// @Param lang query string false "Language of localized fields; all returns the full {en, ru, tm} objects" Enums(tm, ru, en, all) default(tm)
// @Success 200 {object} appresult.AppSuccess
// @Failure 400 {object} appresult.AppError
// @Failure 404 {object} appresult.AppError
// @Failure 500 {object} appresult.AppError
// @Router /cards/{id} [delete]
func (h *handler) delete(c *gin.Context) {
id, ok := parseID(c.Param("id"))
id, ok := shared.ParseID(c.Param("id"))
if !ok {
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
return
}
if !h.guardCardByID(c, id) {
return
}
if err := h.repository.Delete(c.Request.Context(), id); errors.Is(err, pgx.ErrNoRows) {
c.JSON(http.StatusNotFound, appresult.ErrNotFound)
return
@@ -199,53 +223,43 @@ func (h *handler) delete(c *gin.Context) {
c.JSON(http.StatusOK, appresult.SuccessWithData("card removed"))
}
func parseID(raw string) (int64, bool) {
id, err := strconv.ParseInt(raw, 10, 64)
if err != nil || id <= 0 {
return 0, false
}
return id, true
}
const (
defaultPage = 1
defaultLimit = 10
maxLimit = 100
)
func parseListFilter(c *gin.Context) (ListFilter, bool) {
filter := ListFilter{
Page: defaultPage,
Limit: defaultLimit,
page, limit, ok := shared.ParsePageLimit(c)
if !ok {
return ListFilter{}, false
}
filter := ListFilter{Page: page, Limit: limit}
if id, ok := shared.OptionalQueryID(c, "user_id", "userId"); !ok {
return ListFilter{}, false
} else if id != nil {
filter.UserId = id
}
if raw := c.Query("user_id"); raw != "" {
id, ok := parseID(raw)
if !ok {
return ListFilter{}, false
}
filter.UserId = &id
}
if raw := strings.TrimSpace(c.Query("type")); raw != "" {
if raw := shared.QueryValue(c, "type"); raw != "" {
filter.Type = &raw
}
if raw := c.Query("page"); raw != "" {
page, err := strconv.Atoi(raw)
if err != nil || page < 1 {
return ListFilter{}, false
}
filter.Page = page
}
if raw := c.Query("limit"); raw != "" {
limit, err := strconv.Atoi(raw)
if err != nil || limit < 1 || limit > maxLimit {
return ListFilter{}, false
}
filter.Limit = limit
}
rbac.BindBranchIDs(c, &filter.BranchIds)
return filter, true
}
func (h *handler) guardCardByID(c *gin.Context, id int64) bool {
if rbac.SkipRecordGuard(c) {
return true
}
item, err := h.repository.GetByID(c.Request.Context(), id)
if errors.Is(err, pgx.ErrNoRows) {
c.JSON(http.StatusNotFound, appresult.ErrNotFound)
return false
}
if err != nil {
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return false
}
if item.UserId == nil {
c.JSON(http.StatusForbidden, appresult.ErrForbidden)
return false
}
return rbac.GuardUser(c, *item.UserId)
}

View File

@@ -8,6 +8,7 @@ import (
"strings"
"online-back/internal/cards/paymentcard"
"online-back/internal/shared"
"online-back/pkg/client/postgresql"
"online-back/pkg/logging"
"online-back/pkg/repository/genericrepo"
@@ -48,7 +49,7 @@ func buildListQuery(filter paymentcard.ListFilter) (whereClause string, args []i
var conditions []string
if filter.CardName != "" {
args = append(args, likePattern(filter.CardName))
args = append(args, shared.LikePattern(filter.CardName))
n := len(args)
conditions = append(conditions, fmt.Sprintf(`(
c.name->>'en' ILIKE $%[1]d OR c.name->>'ru' ILIKE $%[1]d OR c.name->>'tm' ILIKE $%[1]d
@@ -67,13 +68,6 @@ func buildListQuery(filter paymentcard.ListFilter) (whereClause string, args []i
return " WHERE " + strings.Join(conditions, " AND "), args
}
func likePattern(term string) string {
term = strings.ReplaceAll(term, `\`, `\\`)
term = strings.ReplaceAll(term, `%`, `\%`)
term = strings.ReplaceAll(term, `_`, `\_`)
return "%" + term + "%"
}
func (r *repository) GetByID(ctx context.Context, id int64) (paymentcard.PaymentCardDTO, error) {
return r.generic.GetByID(ctx, id)
}
@@ -106,7 +100,7 @@ func (r *repository) Update(ctx context.Context, id int64, dto paymentcard.Updat
query := fmt.Sprintf(`
UPDATE card_types SET
price = $1, name = $2, notes = $3, active = $4
WHERE id = $5
WHERE id = $5 AND deleted_at IS NULL
RETURNING %s`, cardReturningColumns)
item, err := scanPaymentCard(r.client.QueryRow(ctx, query, dto.Price, name, dto.Notes, dto.Active, id))
@@ -119,7 +113,7 @@ func (r *repository) Update(ctx context.Context, id int64, dto paymentcard.Updat
func (r *repository) UpdateActive(ctx context.Context, id int64, active bool) (paymentcard.PaymentCardDTO, error) {
query := fmt.Sprintf(`
UPDATE card_types SET active = $1
WHERE id = $2
WHERE id = $2 AND deleted_at IS NULL
RETURNING %s`, cardReturningColumns)
item, err := scanPaymentCard(r.client.QueryRow(ctx, query, active, id))
@@ -133,7 +127,7 @@ func (r *repository) Delete(ctx context.Context, id int64) error {
return r.generic.Delete(ctx, id)
}
func marshalName(title paymentcard.LocalizedText) ([]byte, error) {
func marshalName(title shared.LocalizedText) ([]byte, error) {
return json.Marshal(title)
}

View File

@@ -1,31 +1,27 @@
package paymentcard
type LocalizedText struct {
En string `json:"en"`
Ru string `json:"ru"`
Tm string `json:"tm"`
}
import "online-back/internal/shared"
type PaymentCardDTO struct {
Id int64 `json:"id"`
Price string `json:"price"`
Title LocalizedText `json:"title"`
Notes string `json:"notes"`
Active bool `json:"active"`
Id int64 `json:"id"`
Price string `json:"price"`
Title shared.LocalizedText `json:"title"`
Notes string `json:"notes"`
Active bool `json:"active"`
}
type CreatePaymentCardDTO struct {
Price string `json:"price" binding:"required"`
Title LocalizedText `json:"title" binding:"required"`
Notes string `json:"notes"`
Active *bool `json:"active"`
Price string `json:"price" binding:"required"`
Title shared.LocalizedText `json:"title" binding:"required"`
Notes string `json:"notes"`
Active *bool `json:"active"`
}
type UpdatePaymentCardDTO struct {
Price string `json:"price" binding:"required"`
Title LocalizedText `json:"title" binding:"required"`
Notes string `json:"notes"`
Active bool `json:"active"`
Price string `json:"price" binding:"required"`
Title shared.LocalizedText `json:"title" binding:"required"`
Notes string `json:"notes"`
Active bool `json:"active"`
}
type UpdatePaymentCardActiveDTO struct {

View File

@@ -4,10 +4,12 @@ import (
"errors"
"net/http"
"strconv"
"strings"
"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"
@@ -26,7 +28,7 @@ func NewHandler(logger *logging.Logger, repository Repository) handlers.Handler
}
func (h *handler) Register(router *gin.RouterGroup) {
group := router.Group(baseURL, appresult.JwtTokenCheck())
group := rbac.Group(router, baseURL, rbac.Catalog(perm.Cards))
group.GET("", h.list)
group.GET("/:id", h.getByID)
group.POST("", h.create)
@@ -45,6 +47,7 @@ func (h *handler) Register(router *gin.RouterGroup) {
// @Param active query bool false "Filter by active"
// @Param page query int false "Page number" default(1)
// @Param limit query int false "Items per page" default(10)
// @Param lang query string false "Language of localized fields; all returns the full {en, ru, tm} objects" Enums(tm, ru, en, all) default(tm)
// @Success 200 {object} appresult.AppSuccess
// @Failure 400 {object} appresult.AppError
// @Failure 500 {object} appresult.AppError
@@ -73,13 +76,14 @@ func (h *handler) list(c *gin.Context) {
// @Produce json
// @Security BearerAuth
// @Param id path int true "Payment card ID"
// @Param lang query string false "Language of localized fields; all returns the full {en, ru, tm} objects" Enums(tm, ru, en, all) default(tm)
// @Success 200 {object} appresult.AppSuccess
// @Failure 400 {object} appresult.AppError
// @Failure 404 {object} appresult.AppError
// @Failure 500 {object} appresult.AppError
// @Router /payment-cards/{id} [get]
func (h *handler) getByID(c *gin.Context) {
id, ok := parseID(c.Param("id"))
id, ok := shared.ParseID(c.Param("id"))
if !ok {
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
return
@@ -107,6 +111,7 @@ func (h *handler) getByID(c *gin.Context) {
// @Produce json
// @Security BearerAuth
// @Param body body CreatePaymentCardDTO true "Payment card payload"
// @Param lang query string false "Language of localized fields; all returns the full {en, ru, tm} objects" Enums(tm, ru, en, all) default(tm)
// @Success 201 {object} appresult.AppSuccess
// @Failure 400 {object} appresult.AppError
// @Failure 500 {object} appresult.AppError
@@ -137,13 +142,14 @@ func (h *handler) create(c *gin.Context) {
// @Security BearerAuth
// @Param id path int true "Payment card ID"
// @Param body body UpdatePaymentCardDTO true "Payment card payload"
// @Param lang query string false "Language of localized fields; all returns the full {en, ru, tm} objects" Enums(tm, ru, en, all) default(tm)
// @Success 200 {object} appresult.AppSuccess
// @Failure 400 {object} appresult.AppError
// @Failure 404 {object} appresult.AppError
// @Failure 500 {object} appresult.AppError
// @Router /payment-cards/{id} [put]
func (h *handler) update(c *gin.Context) {
id, ok := parseID(c.Param("id"))
id, ok := shared.ParseID(c.Param("id"))
if !ok {
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
return
@@ -178,13 +184,14 @@ func (h *handler) update(c *gin.Context) {
// @Security BearerAuth
// @Param id path int true "Payment card ID"
// @Param body body UpdatePaymentCardActiveDTO true "Active payload"
// @Param lang query string false "Language of localized fields; all returns the full {en, ru, tm} objects" Enums(tm, ru, en, all) default(tm)
// @Success 200 {object} appresult.AppSuccess
// @Failure 400 {object} appresult.AppError
// @Failure 404 {object} appresult.AppError
// @Failure 500 {object} appresult.AppError
// @Router /payment-cards/{id}/active [put]
func (h *handler) updateActive(c *gin.Context) {
id, ok := parseID(c.Param("id"))
id, ok := shared.ParseID(c.Param("id"))
if !ok {
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
return
@@ -217,13 +224,14 @@ func (h *handler) updateActive(c *gin.Context) {
// @Produce json
// @Security BearerAuth
// @Param id path int true "Payment card ID"
// @Param lang query string false "Language of localized fields; all returns the full {en, ru, tm} objects" Enums(tm, ru, en, all) default(tm)
// @Success 200 {object} appresult.AppSuccess
// @Failure 400 {object} appresult.AppError
// @Failure 404 {object} appresult.AppError
// @Failure 500 {object} appresult.AppError
// @Router /payment-cards/{id} [delete]
func (h *handler) delete(c *gin.Context) {
id, ok := parseID(c.Param("id"))
id, ok := shared.ParseID(c.Param("id"))
if !ok {
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
return
@@ -241,47 +249,18 @@ func (h *handler) delete(c *gin.Context) {
c.JSON(http.StatusOK, appresult.SuccessWithData("payment card removed"))
}
func parseID(raw string) (int64, bool) {
id, err := strconv.ParseInt(raw, 10, 64)
if err != nil || id <= 0 {
return 0, false
}
return id, true
}
const (
defaultPage = 1
defaultLimit = 10
maxLimit = 100
)
func parseListFilter(c *gin.Context) (ListFilter, bool) {
filter := ListFilter{
Page: defaultPage,
Limit: defaultLimit,
page, limit, ok := shared.ParsePageLimit(c)
if !ok {
return ListFilter{}, false
}
filter := ListFilter{Page: page, Limit: limit}
if raw := c.Query("page"); raw != "" {
page, err := strconv.Atoi(raw)
if err != nil || page < 1 {
return ListFilter{}, false
}
filter.Page = page
}
if raw := c.Query("limit"); raw != "" {
limit, err := strconv.Atoi(raw)
if err != nil || limit < 1 || limit > maxLimit {
return ListFilter{}, false
}
filter.Limit = limit
}
if raw := strings.TrimSpace(c.Query("card_name")); raw != "" {
if raw := shared.QueryValue(c, "card_name", "cardName"); raw != "" {
filter.CardName = raw
}
if raw := c.Query("active"); raw != "" {
if raw := shared.QueryValue(c, "active"); raw != "" {
active, err := strconv.ParseBool(raw)
if err != nil {
return ListFilter{}, false

View File

@@ -8,6 +8,7 @@ import (
"strings"
"online-back/internal/cards/reasonscard"
"online-back/internal/shared"
"online-back/pkg/client/postgresql"
"online-back/pkg/logging"
"online-back/pkg/repository/genericrepo"
@@ -47,7 +48,7 @@ func (r *repository) List(ctx context.Context, filter reasonscard.ListFilter) (r
func buildListQuery(filter reasonscard.ListFilter) (whereClause string, args []interface{}) {
var conditions []string
if filter.ReasonName != "" {
args = append(args, likePattern(filter.ReasonName))
args = append(args, shared.LikePattern(filter.ReasonName))
n := len(args)
conditions = append(conditions, fmt.Sprintf(`(
r.name->>'en' ILIKE $%[1]d OR r.name->>'ru' ILIKE $%[1]d OR r.name->>'tm' ILIKE $%[1]d
@@ -61,13 +62,6 @@ func buildListQuery(filter reasonscard.ListFilter) (whereClause string, args []i
return " WHERE " + strings.Join(conditions, " AND "), args
}
func likePattern(term string) string {
term = strings.ReplaceAll(term, `\`, `\\`)
term = strings.ReplaceAll(term, `%`, `\%`)
term = strings.ReplaceAll(term, `_`, `\_`)
return "%" + term + "%"
}
func (r *repository) GetByID(ctx context.Context, id int64) (reasonscard.ReasonCardDTO, error) {
return r.generic.GetByID(ctx, id)
}
@@ -101,7 +95,7 @@ func (r *repository) Update(ctx context.Context, id int64, dto reasonscard.Updat
UPDATE card_states SET
price = $1, name = $2, notes = $3, active = $4,
updated_at = (CURRENT_TIMESTAMP AT TIME ZONE 'UTC')
WHERE id = $5
WHERE id = $5 AND deleted_at IS NULL
RETURNING %s`, reasonReturningColumns)
item, err := scanReasonCard(r.client.QueryRow(ctx, query, dto.Price, name, dto.Notes, dto.Active, id))
@@ -115,7 +109,7 @@ func (r *repository) Delete(ctx context.Context, id int64) error {
return r.generic.Delete(ctx, id)
}
func marshalName(title reasonscard.LocalizedText) ([]byte, error) {
func marshalName(title shared.LocalizedText) ([]byte, error) {
return json.Marshal(title)
}

View File

@@ -1,35 +1,33 @@
package reasonscard
import "time"
import (
"time"
type LocalizedText struct {
En string `json:"en"`
Ru string `json:"ru"`
Tm string `json:"tm"`
}
"online-back/internal/shared"
)
type ReasonCardDTO struct {
Id int64 `json:"id"`
Title LocalizedText `json:"title"`
Price string `json:"price"`
Notes string `json:"notes"`
Active bool `json:"active"`
CreatedAt time.Time `json:"createdAt"`
UpdatedAt time.Time `json:"updatedAt"`
Id int64 `json:"id"`
Title shared.LocalizedText `json:"title"`
Price string `json:"price"`
Notes string `json:"notes"`
Active bool `json:"active"`
CreatedAt time.Time `json:"createdAt"`
UpdatedAt time.Time `json:"updatedAt"`
}
type CreateReasonCardDTO struct {
Title LocalizedText `json:"title" binding:"required"`
Price string `json:"price" binding:"required"`
Notes string `json:"notes"`
Active *bool `json:"active"`
Title shared.LocalizedText `json:"title" binding:"required"`
Price string `json:"price" binding:"required"`
Notes string `json:"notes"`
Active *bool `json:"active"`
}
type UpdateReasonCardDTO struct {
Title LocalizedText `json:"title" binding:"required"`
Price string `json:"price" binding:"required"`
Notes string `json:"notes"`
Active bool `json:"active"`
Title shared.LocalizedText `json:"title" binding:"required"`
Price string `json:"price" binding:"required"`
Notes string `json:"notes"`
Active bool `json:"active"`
}
type ListFilter struct {

View File

@@ -3,11 +3,12 @@ package reasonscard
import (
"errors"
"net/http"
"strconv"
"strings"
"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"
@@ -26,7 +27,7 @@ func NewHandler(logger *logging.Logger, repository Repository) handlers.Handler
}
func (h *handler) Register(router *gin.RouterGroup) {
group := router.Group(baseURL, appresult.JwtTokenCheck())
group := rbac.Group(router, baseURL, rbac.Catalog(perm.Cards))
group.GET("", h.list)
group.GET("/:id", h.getByID)
group.POST("", h.create)
@@ -43,6 +44,7 @@ func (h *handler) Register(router *gin.RouterGroup) {
// @Param reason_name query string false "Filter by title (en, ru, tm)"
// @Param page query int false "Page number" default(1)
// @Param limit query int false "Items per page" default(10)
// @Param lang query string false "Language of localized fields; all returns the full {en, ru, tm} objects" Enums(tm, ru, en, all) default(tm)
// @Success 200 {object} appresult.AppSuccess
// @Failure 400 {object} appresult.AppError
// @Failure 500 {object} appresult.AppError
@@ -71,13 +73,14 @@ func (h *handler) list(c *gin.Context) {
// @Produce json
// @Security BearerAuth
// @Param id path int true "Reason card ID"
// @Param lang query string false "Language of localized fields; all returns the full {en, ru, tm} objects" Enums(tm, ru, en, all) default(tm)
// @Success 200 {object} appresult.AppSuccess
// @Failure 400 {object} appresult.AppError
// @Failure 404 {object} appresult.AppError
// @Failure 500 {object} appresult.AppError
// @Router /reasons-cards/{id} [get]
func (h *handler) getByID(c *gin.Context) {
id, ok := parseID(c.Param("id"))
id, ok := shared.ParseID(c.Param("id"))
if !ok {
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
return
@@ -105,6 +108,7 @@ func (h *handler) getByID(c *gin.Context) {
// @Produce json
// @Security BearerAuth
// @Param body body CreateReasonCardDTO true "Reason card payload"
// @Param lang query string false "Language of localized fields; all returns the full {en, ru, tm} objects" Enums(tm, ru, en, all) default(tm)
// @Success 201 {object} appresult.AppSuccess
// @Failure 400 {object} appresult.AppError
// @Failure 500 {object} appresult.AppError
@@ -135,13 +139,14 @@ func (h *handler) create(c *gin.Context) {
// @Security BearerAuth
// @Param id path int true "Reason card ID"
// @Param body body UpdateReasonCardDTO true "Reason card payload"
// @Param lang query string false "Language of localized fields; all returns the full {en, ru, tm} objects" Enums(tm, ru, en, all) default(tm)
// @Success 200 {object} appresult.AppSuccess
// @Failure 400 {object} appresult.AppError
// @Failure 404 {object} appresult.AppError
// @Failure 500 {object} appresult.AppError
// @Router /reasons-cards/{id} [put]
func (h *handler) update(c *gin.Context) {
id, ok := parseID(c.Param("id"))
id, ok := shared.ParseID(c.Param("id"))
if !ok {
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
return
@@ -174,13 +179,14 @@ func (h *handler) update(c *gin.Context) {
// @Produce json
// @Security BearerAuth
// @Param id path int true "Reason card ID"
// @Param lang query string false "Language of localized fields; all returns the full {en, ru, tm} objects" Enums(tm, ru, en, all) default(tm)
// @Success 200 {object} appresult.AppSuccess
// @Failure 400 {object} appresult.AppError
// @Failure 404 {object} appresult.AppError
// @Failure 500 {object} appresult.AppError
// @Router /reasons-cards/{id} [delete]
func (h *handler) delete(c *gin.Context) {
id, ok := parseID(c.Param("id"))
id, ok := shared.ParseID(c.Param("id"))
if !ok {
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
return
@@ -198,43 +204,14 @@ func (h *handler) delete(c *gin.Context) {
c.JSON(http.StatusOK, appresult.SuccessWithData("reason card removed"))
}
func parseID(raw string) (int64, bool) {
id, err := strconv.ParseInt(raw, 10, 64)
if err != nil || id <= 0 {
return 0, false
}
return id, true
}
const (
defaultPage = 1
defaultLimit = 10
maxLimit = 100
)
func parseListFilter(c *gin.Context) (ListFilter, bool) {
filter := ListFilter{
Page: defaultPage,
Limit: defaultLimit,
page, limit, ok := shared.ParsePageLimit(c)
if !ok {
return ListFilter{}, false
}
filter := ListFilter{Page: page, Limit: limit}
if raw := c.Query("page"); raw != "" {
page, err := strconv.Atoi(raw)
if err != nil || page < 1 {
return ListFilter{}, false
}
filter.Page = page
}
if raw := c.Query("limit"); raw != "" {
limit, err := strconv.Atoi(raw)
if err != nil || limit < 1 || limit > maxLimit {
return ListFilter{}, false
}
filter.Limit = limit
}
if raw := strings.TrimSpace(c.Query("reason_name")); raw != "" {
if raw := shared.QueryValue(c, "reason_name", "reasonName"); raw != "" {
filter.ReasonName = raw
}

View File

@@ -1,19 +1,28 @@
// Package cards groups payment cards, card orders, PIN orders, and their
// reference data (reasons, payment card types) under one bounded context,
// replacing the flat internal/admin/* listing.
// Package cards groups payment cards, card orders, PIN orders, rekwizit
// (card details) orders, visa/master payment orders, and their reference
// data (reasons, payment card types) under one bounded context, replacing
// the flat internal/admin/* listing.
package cards
import (
"online-back/internal/cards/cardbalance"
cardbalancedb "online-back/internal/cards/cardbalance/db"
"online-back/internal/cards/cardorder"
cardorderdb "online-back/internal/cards/cardorder/db"
"online-back/internal/cards/cardpinorders"
cardpinordersdb "online-back/internal/cards/cardpinorders/db"
"online-back/internal/cards/cardrekwizit"
cardrekwizitdb "online-back/internal/cards/cardrekwizit/db"
cardentity "online-back/internal/cards/cards"
cardentitydb "online-back/internal/cards/cards/db"
"online-back/internal/cards/paymentcard"
paymentcarddb "online-back/internal/cards/paymentcard/db"
"online-back/internal/cards/reasonscard"
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"
@@ -30,10 +39,14 @@ func Register(router *gin.RouterGroup, client postgresql.Client, logger *logging
func Handlers(client postgresql.Client, logger *logging.Logger) []handlers.Handler {
return []handlers.Handler{
cardbalance.NewHandler(logger, cardbalancedb.NewRepository(client, logger)),
cardentity.NewHandler(logger, cardentitydb.NewRepository(client, logger)),
cardorder.NewHandler(logger, cardorderdb.NewRepository(client, logger)),
cardpinorders.NewHandler(logger, cardpinordersdb.NewRepository(client, logger)),
cardrekwizit.NewHandler(logger, cardrekwizitdb.NewRepository(client, logger)),
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

@@ -0,0 +1,483 @@
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
}

View File

@@ -0,0 +1,154 @@
package visamaster
import (
"encoding/json"
"time"
"online-back/internal/shared"
)
type BranchInfo struct {
Id int64 `json:"id"`
UniqueCode string `json:"uniqueCode"`
Name shared.LocalizedText `json:"name"`
Region string `json:"region"`
ProvinceId *int64 `json:"provinceId"`
ProvinceName shared.LocalizedText `json:"provinceName"`
}
type VisaMasterPaymentOrderDTO struct {
Id int64 `json:"id"`
UniqueId *string `json:"uniqueId"`
Type *string `json:"type"`
PassportName string `json:"passportName"`
PassportSurname string `json:"passportSurname"`
Phone string `json:"phone"`
Email *string `json:"email"`
Region string `json:"region"`
RegionName shared.LocalizedText `json:"regionName,omitempty"`
BranchId int64 `json:"-"`
Branch BranchInfo `json:"branch"`
UserId *int64 `json:"-"`
User *shared.UserInfo `json:"user,omitempty"`
Address string `json:"address"`
SenderDatas json.RawMessage `json:"senderDatas" swaggertype:"object"`
PaymentReciever json.RawMessage `json:"paymentReciever" swaggertype:"array,object"`
Documents json.RawMessage `json:"documents" swaggertype:"object"`
Status *string `json:"status"`
Notes *string `json:"notes"`
SenderFullName string `json:"senderFullName"`
SenderPassportSerie string `json:"senderPassportSerie"`
SenderPassportNumber string `json:"senderPassportNumber"`
SenderDepositAccount string `json:"senderDepositAccount"`
RecieverFullName *string `json:"recieverFullName"`
RecieverPassportSerie *string `json:"recieverPassportSerie"`
RecieverPassportNumber *string `json:"recieverPassportNumber"`
RecieverDepositAccount *string `json:"recieverDepositAccount"`
AmountUsd *float64 `json:"amountUsd"`
Paid bool `json:"paid"`
CreatedAt time.Time `json:"createdAt"`
UpdatedAt time.Time `json:"updatedAt"`
}
type CreateVisaMasterPaymentOrderDTO struct {
UniqueId *string `json:"uniqueId"`
Type *string `json:"type"`
PassportName string `json:"passportName" binding:"required"`
PassportSurname string `json:"passportSurname" binding:"required"`
Phone string `json:"phone" binding:"required"`
Email *string `json:"email"`
Region string `json:"region" binding:"required"`
BranchId int64 `json:"branchId" binding:"required"`
UserId *int64 `json:"userId"`
Address string `json:"address" binding:"required"`
SenderDatas json.RawMessage `json:"senderDatas" swaggertype:"object"`
PaymentReciever json.RawMessage `json:"paymentReciever" swaggertype:"array,object"`
Documents json.RawMessage `json:"documents" swaggertype:"object"`
Status *string `json:"status"`
Notes *string `json:"notes"`
SenderFullName string `json:"senderFullName" binding:"required"`
SenderPassportSerie string `json:"senderPassportSerie" binding:"required"`
SenderPassportNumber string `json:"senderPassportNumber" binding:"required"`
SenderDepositAccount string `json:"senderDepositAccount" binding:"required"`
RecieverFullName *string `json:"recieverFullName"`
RecieverPassportSerie *string `json:"recieverPassportSerie"`
RecieverPassportNumber *string `json:"recieverPassportNumber"`
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 {
UniqueId *string `json:"uniqueId"`
Type *string `json:"type"`
PassportName string `json:"passportName" binding:"required"`
PassportSurname string `json:"passportSurname" binding:"required"`
Phone string `json:"phone" binding:"required"`
Email *string `json:"email"`
Region string `json:"region" binding:"required"`
BranchId int64 `json:"branchId" binding:"required"`
UserId *int64 `json:"userId"`
Address string `json:"address" binding:"required"`
SenderDatas json.RawMessage `json:"senderDatas" swaggertype:"object"`
PaymentReciever json.RawMessage `json:"paymentReciever" swaggertype:"array,object"`
Documents json.RawMessage `json:"documents" swaggertype:"object"`
Status *string `json:"status"`
Notes *string `json:"notes"`
SenderFullName string `json:"senderFullName" binding:"required"`
SenderPassportSerie string `json:"senderPassportSerie" binding:"required"`
SenderPassportNumber string `json:"senderPassportNumber" binding:"required"`
SenderDepositAccount string `json:"senderDepositAccount" binding:"required"`
RecieverFullName *string `json:"recieverFullName"`
RecieverPassportSerie *string `json:"recieverPassportSerie"`
RecieverPassportNumber *string `json:"recieverPassportNumber"`
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 {
Name string
// Type narrows to one order type; ExcludeType drops one (the Visa/Master
// page hides sber, which has its own page).
Type string
ExcludeType string
Status *string
BranchId *int64
BranchIds []int64
UserId *int64
Region string
Page int
Limit int
}
// VisaMasterPaymentOrderListItemDTO is the list row (visa/master and sber);
// sender, receiver, documents and amounts come from GET /visa-master-payment-orders/:id.
type VisaMasterPaymentOrderListItemDTO struct {
Id int64 `json:"id"`
UniqueId *string `json:"uniqueId"`
Type *string `json:"type"`
CreatedAt time.Time `json:"createdAt"`
Region string `json:"region"`
// RegionName is the welaýat of the branch's province (Mary, Lebap, ...).
RegionName shared.LocalizedText `json:"regionName"`
Branch *shared.NamedInfo `json:"branch,omitempty"`
// ProvinceName is the branch's province (etrap).
ProvinceName shared.LocalizedText `json:"provinceName"`
PassportName string `json:"passportName"`
PassportSurname string `json:"passportSurname"`
Phone string `json:"phone"`
Status *string `json:"status"`
Paid bool `json:"paid"`
// PaidThisMonth: a successful payment exists for the current month's
// payment period (Ashgabat time).
PaidThisMonth bool `json:"paidThisMonth"`
}
type ListVisaMasterPaymentOrderDTO struct {
Count int64 `json:"count"`
VisaMasterPaymentOrders []VisaMasterPaymentOrderListItemDTO `json:"visaMasterPaymentOrders"`
}

View File

@@ -0,0 +1,324 @@
package visamaster
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"
)
// orderTypeSber is the type value of Sber orders, matched case-insensitively
// like visamasterpay does when it picks Sber fees and credentials.
const orderTypeSber = "sber"
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}
}
func (h *handler) Register(router *gin.RouterGroup) {
group := rbac.Group(router, baseURL, rbac.Require(perm.Cards))
group.GET("", h.list)
group.GET("/sber", h.listSber)
group.GET("/:id", h.getByID)
group.POST("", h.create)
group.PUT("/:id", h.update)
group.DELETE("/:id", h.delete)
}
// list godoc
// @Summary List visa/master payment orders
// @Description Returns paginated visa/master payment orders; sber orders are excluded (see /visa-master-payment-orders/sber)
// @Tags visa-master-orders
// @Produce json
// @Security BearerAuth
// @Param name query string false "Filter by passport name or surname"
// @Param type query string false "Filter by order type (e.g. student), case-insensitive"
// @Param status query string false "Filter by status"
// @Param branch_id query int false "Filter by branch ID"
// @Param user_id query int false "Filter by user ID"
// @Param region query string false "Filter by region"
// @Param page query int false "Page number" default(1)
// @Param limit query int false "Items per page" default(10)
// @Param lang query string false "Language of localized fields; all returns the full {en, ru, tm} objects" Enums(tm, ru, en, all) default(tm)
// @Success 200 {object} appresult.AppSuccess
// @Failure 400 {object} appresult.AppError
// @Failure 500 {object} appresult.AppError
// @Router /visa-master-payment-orders [get]
func (h *handler) list(c *gin.Context) {
filter, ok := parseListFilter(c)
if !ok {
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
return
}
filter.ExcludeType = orderTypeSber
h.respondList(c, filter)
}
// listSber godoc
// @Summary List sber payment orders
// @Description Returns paginated payment orders of type sber
// @Tags visa-master-orders
// @Produce json
// @Security BearerAuth
// @Param name query string false "Filter by passport name or surname"
// @Param status query string false "Filter by status"
// @Param branch_id query int false "Filter by branch ID"
// @Param user_id query int false "Filter by user ID"
// @Param region query string false "Filter by region"
// @Param page query int false "Page number" default(1)
// @Param limit query int false "Items per page" default(10)
// @Param lang query string false "Language of localized fields; all returns the full {en, ru, tm} objects" Enums(tm, ru, en, all) default(tm)
// @Success 200 {object} appresult.AppSuccess
// @Failure 400 {object} appresult.AppError
// @Failure 500 {object} appresult.AppError
// @Router /visa-master-payment-orders/sber [get]
func (h *handler) listSber(c *gin.Context) {
filter, ok := parseListFilter(c)
if !ok {
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
return
}
filter.Type = orderTypeSber
h.respondList(c, filter)
}
func (h *handler) respondList(c *gin.Context, filter ListFilter) {
result, err := h.repository.List(c.Request.Context(), filter)
if err != nil {
h.logger.Errorf("list visa master payment orders failed: %v", err)
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return
}
c.JSON(http.StatusOK, appresult.SuccessWithData(result))
}
// getByID godoc
// @Summary Get visa/master payment order by ID
// @Description Returns a single visa/master payment order with branch and user details
// @Tags visa-master-orders
// @Produce json
// @Security BearerAuth
// @Param id path int true "Visa/master payment order ID"
// @Param lang query string false "Language of localized fields; all returns the full {en, ru, tm} objects" Enums(tm, ru, en, all) default(tm)
// @Success 200 {object} appresult.AppSuccess
// @Failure 400 {object} appresult.AppError
// @Failure 404 {object} appresult.AppError
// @Failure 500 {object} appresult.AppError
// @Router /visa-master-payment-orders/{id} [get]
func (h *handler) getByID(c *gin.Context) {
id, ok := shared.ParseID(c.Param("id"))
if !ok {
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
return
}
item, err := h.repository.GetByID(c.Request.Context(), id)
if errors.Is(err, pgx.ErrNoRows) {
c.JSON(http.StatusNotFound, appresult.ErrNotFound)
return
}
if err != nil {
h.logger.Errorf("get visa master payment order failed: %v", err)
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return
}
if !rbac.GuardOrder(c, item.UserId, item.BranchId) {
return
}
c.JSON(http.StatusOK, appresult.SuccessWithData(item))
}
// create godoc
// @Summary Create visa/master payment order
// @Description Creates a new visa/master payment order
// @Tags visa-master-orders
// @Accept json
// @Produce json
// @Security BearerAuth
// @Param body body CreateVisaMasterPaymentOrderDTO true "Visa/master payment order payload"
// @Param lang query string false "Language of localized fields; all returns the full {en, ru, tm} objects" Enums(tm, ru, en, all) default(tm)
// @Success 201 {object} appresult.AppSuccess
// @Failure 400 {object} appresult.AppError
// @Failure 500 {object} appresult.AppError
// @Router /visa-master-payment-orders [post]
func (h *handler) create(c *gin.Context) {
var dto CreateVisaMasterPaymentOrderDTO
if err := c.ShouldBindJSON(&dto); err != nil {
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 {
h.logger.Errorf("create visa master payment order failed: %v", err)
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return
}
c.JSON(http.StatusCreated, appresult.SuccessWithData(item))
}
// update godoc
// @Summary Update visa/master payment order
// @Description Updates an existing visa/master payment order
// @Tags visa-master-orders
// @Accept json
// @Produce json
// @Security BearerAuth
// @Param id path int true "Visa/master payment order ID"
// @Param body body UpdateVisaMasterPaymentOrderDTO true "Visa/master payment order payload"
// @Param lang query string false "Language of localized fields; all returns the full {en, ru, tm} objects" Enums(tm, ru, en, all) default(tm)
// @Success 200 {object} appresult.AppSuccess
// @Failure 400 {object} appresult.AppError
// @Failure 404 {object} appresult.AppError
// @Failure 500 {object} appresult.AppError
// @Router /visa-master-payment-orders/{id} [put]
func (h *handler) update(c *gin.Context) {
id, ok := shared.ParseID(c.Param("id"))
if !ok {
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
return
}
if !h.guardBranchByID(c, id) {
return
}
var dto UpdateVisaMasterPaymentOrderDTO
if err := c.ShouldBindJSON(&dto); err != nil {
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) {
c.JSON(http.StatusNotFound, appresult.ErrNotFound)
return
}
if err != nil {
h.logger.Errorf("update visa master payment order failed: %v", err)
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return
}
c.JSON(http.StatusOK, appresult.SuccessWithData(item))
}
// delete godoc
// @Summary Delete visa/master payment order
// @Description Deletes a visa/master payment order
// @Tags visa-master-orders
// @Produce json
// @Security BearerAuth
// @Param id path int true "Visa/master payment order ID"
// @Param lang query string false "Language of localized fields; all returns the full {en, ru, tm} objects" Enums(tm, ru, en, all) default(tm)
// @Success 200 {object} appresult.AppSuccess
// @Failure 400 {object} appresult.AppError
// @Failure 404 {object} appresult.AppError
// @Failure 500 {object} appresult.AppError
// @Router /visa-master-payment-orders/{id} [delete]
func (h *handler) delete(c *gin.Context) {
id, ok := shared.ParseID(c.Param("id"))
if !ok {
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
return
}
if !h.guardBranchByID(c, id) {
return
}
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 {
h.logger.Errorf("delete visa master payment order failed: %v", err)
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return
}
c.JSON(http.StatusOK, appresult.SuccessWithData("visa master payment order removed"))
}
func parseListFilter(c *gin.Context) (ListFilter, bool) {
page, limit, ok := shared.ParsePageLimit(c)
if !ok {
return ListFilter{}, false
}
filter := ListFilter{Page: page, Limit: limit}
if raw := shared.QueryValue(c, "name"); raw != "" {
filter.Name = raw
}
if raw := shared.QueryValue(c, "type"); raw != "" {
filter.Type = raw
}
if raw := shared.QueryValue(c, "status"); raw != "" {
filter.Status = &raw
}
if raw := shared.QueryValue(c, "region"); raw != "" {
filter.Region = raw
}
if id, ok := shared.OptionalQueryID(c, "branch_id", "branchId"); !ok {
return ListFilter{}, false
} else if id != nil {
filter.BranchId = id
}
if id, ok := shared.OptionalQueryID(c, "user_id", "userId"); !ok {
return ListFilter{}, false
} else if id != nil {
filter.UserId = id
}
rbac.BindBranchIDs(c, &filter.BranchIds)
return filter, true
}
func (h *handler) guardBranchByID(c *gin.Context, id int64) bool {
if rbac.SkipRecordGuard(c) {
return true
}
item, err := h.repository.GetByID(c.Request.Context(), id)
if errors.Is(err, pgx.ErrNoRows) {
c.JSON(http.StatusNotFound, appresult.ErrNotFound)
return false
}
if err != nil {
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return false
}
return rbac.GuardOrder(c, item.UserId, item.BranchId)
}

View File

@@ -0,0 +1,13 @@
package visamaster
import "context"
type Repository interface {
List(ctx context.Context, filter ListFilter) (ListVisaMasterPaymentOrderDTO, error)
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 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

@@ -16,6 +16,7 @@ type Config struct {
Port string `yaml:"port" env-default:"8080"`
} `yaml:"listen"`
PublicFilePath string `yaml:"public_file_path" env-required:"true"`
PublicBaseURL string `yaml:"public_base_url" env-required:"true"`
Storage StorageConfig `yaml:"storage"`
Minio MinioConfig `yaml:"minio"`
JwtKey string `yaml:"jwt_key" env-required:"true"`

View File

@@ -0,0 +1,242 @@
package db
import (
"context"
"errors"
"fmt"
"strings"
"online-back/internal/currency"
"online-back/internal/shared"
"online-back/pkg/client/postgresql"
"online-back/pkg/logging"
"online-back/pkg/repository/genericrepo"
"github.com/jackc/pgconn"
"github.com/jackc/pgx/v4"
)
type repository struct {
client postgresql.Client
generic *genericrepo.Repository[currency.CurrencyDTO]
logger *logging.Logger
}
func NewRepository(client postgresql.Client, logger *logging.Logger) currency.Repository {
return &repository{
client: client,
generic: genericrepo.New(client, "currencies", currencyColumnsSQL, scanCurrency),
logger: logger,
}
}
var currencyColumns = []string{
"id", "currency_from", "currency_to", "value",
"created_by", "updated_by", "created_at", "updated_at",
}
var currencyColumnsSQL = strings.Join(currencyColumns, ", ")
const userDisplaySQL = `COALESCE(NULLIF(TRIM(CONCAT_WS(' ', %s.first_name, %s.last_name)), ''), NULLIF(%s.name, ''), %s.username, '')`
const currencyFromClause = ` FROM currencies c
LEFT JOIN users cu ON cu.id = c.created_by
LEFT JOIN users uu ON uu.id = c.updated_by`
var currencySelectColumns = shared.PrefixedColumns("c", currencyColumns) + `,
` + fmt.Sprintf(userDisplaySQL, "cu", "cu", "cu", "cu") + `, COALESCE(cu.username, ''), COALESCE(cu.phone, ''), COALESCE(cu.email, ''),
` + fmt.Sprintf(userDisplaySQL, "uu", "uu", "uu", "uu") + `, COALESCE(uu.username, ''), COALESCE(uu.phone, ''), COALESCE(uu.email, '')`
func (r *repository) List(ctx context.Context, filter currency.ListFilter) (currency.ListCurrencyDTO, error) {
whereClause, args := buildListQuery(filter)
var count int64
if err := r.client.QueryRow(ctx, `SELECT COUNT(*) FROM currencies c`+whereClause, args...).Scan(&count); err != nil {
return currency.ListCurrencyDTO{}, err
}
offset := (filter.Page - 1) * filter.Limit
limitPlaceholder := len(args) + 1
offsetPlaceholder := len(args) + 2
query := fmt.Sprintf(
`SELECT %s%s%s ORDER BY c.id DESC LIMIT $%d OFFSET $%d`,
currencySelectColumns, currencyFromClause, whereClause, limitPlaceholder, offsetPlaceholder,
)
rows, err := r.client.Query(ctx, query, append(args, filter.Limit, offset)...)
if err != nil {
return currency.ListCurrencyDTO{}, err
}
defer rows.Close()
var items []currency.CurrencyDTO
for rows.Next() {
item, err := scanCurrencyWithUsers(rows)
if err != nil {
return currency.ListCurrencyDTO{}, err
}
items = append(items, item)
}
if err := rows.Err(); err != nil {
return currency.ListCurrencyDTO{}, err
}
return currency.ListCurrencyDTO{Count: count, Currencies: items}, nil
}
func buildListQuery(filter currency.ListFilter) (whereClause string, args []interface{}) {
conditions := []string{"c.deleted_at IS NULL"}
if filter.Search != "" {
args = append(args, shared.LikePattern(filter.Search))
n := len(args)
conditions = append(conditions, fmt.Sprintf(`(
c.currency_from ILIKE $%[1]d ESCAPE '\' OR c.currency_to ILIKE $%[1]d ESCAPE '\'
)`, n))
}
if filter.CurrencyFrom != "" {
args = append(args, filter.CurrencyFrom)
conditions = append(conditions, fmt.Sprintf("c.currency_from = $%d", len(args)))
}
if filter.CurrencyTo != "" {
args = append(args, filter.CurrencyTo)
conditions = append(conditions, fmt.Sprintf("c.currency_to = $%d", len(args)))
}
return " WHERE " + strings.Join(conditions, " AND "), args
}
func (r *repository) GetByID(ctx context.Context, id int64) (currency.CurrencyDTO, error) {
query := `SELECT ` + currencySelectColumns + currencyFromClause + ` WHERE c.id = $1 AND c.deleted_at IS NULL`
return scanCurrencyWithUsers(r.client.QueryRow(ctx, query, id))
}
func (r *repository) Create(ctx context.Context, dto currency.CreateCurrencyDTO) (currency.CurrencyDTO, error) {
from, to, value := normalizeRate(dto.CurrencyFrom, dto.CurrencyTo, dto.Value)
query := `
WITH inserted AS (
INSERT INTO currencies (currency_from, currency_to, value, created_by, updated_by)
VALUES ($1, $2, $3::numeric, $4, $4)
RETURNING ` + currencyColumnsSQL + `
)
SELECT ` + currencySelectColumns + `
FROM inserted c
LEFT JOIN users cu ON cu.id = c.created_by
LEFT JOIN users uu ON uu.id = c.updated_by`
item, err := scanCurrencyWithUsers(r.client.QueryRow(ctx, query, from, to, value, dto.CreatedBy))
if isUniqueViolation(err) {
return currency.CurrencyDTO{}, currency.ErrDuplicate
}
return item, err
}
func (r *repository) Update(ctx context.Context, id int64, dto currency.UpdateCurrencyDTO) (currency.CurrencyDTO, error) {
from, to, value := normalizeRate(dto.CurrencyFrom, dto.CurrencyTo, dto.Value)
query := `
WITH updated AS (
UPDATE currencies SET
currency_from = $1, currency_to = $2, value = $3::numeric,
updated_by = $4,
updated_at = (CURRENT_TIMESTAMP AT TIME ZONE 'UTC')
WHERE id = $5 AND deleted_at IS NULL
RETURNING ` + currencyColumnsSQL + `
)
SELECT ` + currencySelectColumns + `
FROM updated c
LEFT JOIN users cu ON cu.id = c.created_by
LEFT JOIN users uu ON uu.id = c.updated_by`
item, err := scanCurrencyWithUsers(r.client.QueryRow(ctx, query, from, to, value, dto.UpdatedBy, id))
if errors.Is(err, pgx.ErrNoRows) {
return currency.CurrencyDTO{}, err
}
if isUniqueViolation(err) {
return currency.CurrencyDTO{}, currency.ErrDuplicate
}
return item, err
}
func (r *repository) Delete(ctx context.Context, id int64) error {
return r.generic.Delete(ctx, id)
}
// isUniqueViolation reports whether err is a Postgres unique-constraint
// violation (e.g. the currencies_from_to_idx partial unique index rejecting
// a duplicate active currency_from/currency_to pair), so callers can map it
// to a clean 409 instead of letting it fall through as a generic 500.
func isUniqueViolation(err error) bool {
var pgErr *pgconn.PgError
return errors.As(err, &pgErr) && pgErr.Code == "23505"
}
func normalizeRate(from, to string, value currency.RateValue) (string, string, string) {
return strings.ToUpper(strings.TrimSpace(from)),
strings.ToUpper(strings.TrimSpace(to)),
strings.TrimSpace(value.String())
}
func scanCurrency(row genericrepo.Scanner) (currency.CurrencyDTO, error) {
return scanCurrencyRow(row, false)
}
func scanCurrencyWithUsers(row genericrepo.Scanner) (currency.CurrencyDTO, error) {
return scanCurrencyRow(row, true)
}
func scanCurrencyRow(row genericrepo.Scanner, withUsers bool) (currency.CurrencyDTO, error) {
var item currency.CurrencyDTO
var value string
dest := []interface{}{
&item.Id, &item.CurrencyFrom, &item.CurrencyTo, &value,
&item.CreatedById, &item.UpdatedById, &item.CreatedAt, &item.UpdatedAt,
}
var createdName, createdUsername, createdPhone, createdEmail string
var updatedName, updatedUsername, updatedPhone, updatedEmail string
if withUsers {
dest = append(dest,
&createdName, &createdUsername, &createdPhone, &createdEmail,
&updatedName, &updatedUsername, &updatedPhone, &updatedEmail,
)
}
if err := row.Scan(dest...); err != nil {
return currency.CurrencyDTO{}, err
}
item.Value = currency.RateValue(trimNumeric(value))
if withUsers {
item.CreatedBy = userInfo(item.CreatedById, createdName, createdUsername, createdPhone, createdEmail)
item.UpdatedBy = userInfo(item.UpdatedById, updatedName, updatedUsername, updatedPhone, updatedEmail)
}
return item, nil
}
func userInfo(id *int64, name, username, phone, email string) *currency.UserInfo {
if id == nil {
return nil
}
return &currency.UserInfo{
Id: *id,
Name: name,
Username: username,
Phone: phone,
Email: email,
}
}
func trimNumeric(raw string) string {
raw = strings.TrimSpace(raw)
if !strings.Contains(raw, ".") {
return raw
}
raw = strings.TrimRight(raw, "0")
raw = strings.TrimRight(raw, ".")
if raw == "" {
return "0"
}
return raw
}

88
internal/currency/dto.go Normal file
View File

@@ -0,0 +1,88 @@
package currency
import (
"encoding/json"
"strings"
"time"
)
type RateValue string
func (v RateValue) String() string { return string(v) }
func (v RateValue) MarshalJSON() ([]byte, error) {
s := strings.TrimSpace(string(v))
if s == "" {
return []byte("0"), nil
}
return []byte(s), nil
}
func (v *RateValue) UnmarshalJSON(b []byte) error {
raw := strings.TrimSpace(string(b))
if raw == "" || raw == "null" {
*v = ""
return nil
}
var n json.Number
if err := json.Unmarshal(b, &n); err == nil {
*v = RateValue(n.String())
return nil
}
var s string
if err := json.Unmarshal(b, &s); err != nil {
return err
}
*v = RateValue(strings.TrimSpace(s))
return nil
}
type CurrencyDTO struct {
Id int64 `json:"id"`
CurrencyFrom string `json:"currencyFrom"`
CurrencyTo string `json:"currencyTo"`
Value RateValue `json:"value" swaggertype:"number"`
CreatedById *int64 `json:"-"`
CreatedBy *UserInfo `json:"createdBy,omitempty"`
UpdatedById *int64 `json:"-"`
UpdatedBy *UserInfo `json:"updatedBy,omitempty"`
CreatedAt time.Time `json:"createdAt"`
UpdatedAt time.Time `json:"updatedAt"`
}
type UserInfo struct {
Id int64 `json:"id"`
Name string `json:"name"`
Username string `json:"username"`
Phone string `json:"phone"`
Email string `json:"email"`
}
type CreateCurrencyDTO struct {
CurrencyFrom string `json:"currencyFrom" binding:"required"`
CurrencyTo string `json:"currencyTo" binding:"required"`
Value RateValue `json:"value" binding:"required" swaggertype:"number"`
CreatedBy *int64 `json:"-"`
}
type UpdateCurrencyDTO struct {
CurrencyFrom string `json:"currencyFrom" binding:"required"`
CurrencyTo string `json:"currencyTo" binding:"required"`
Value RateValue `json:"value" binding:"required" swaggertype:"number"`
UpdatedBy *int64 `json:"-"`
}
type ListFilter struct {
Search string
CurrencyFrom string
CurrencyTo string
Page int
Limit int
}
type ListCurrencyDTO struct {
Count int64 `json:"count"`
Currencies []CurrencyDTO `json:"currencies"`
}

View File

@@ -0,0 +1,284 @@
package currency
import (
"errors"
"net/http"
"strconv"
"strings"
"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 = "/currencies"
type handler struct {
logger *logging.Logger
repository Repository
}
func NewHandler(logger *logging.Logger, repository Repository) handlers.Handler {
return &handler{logger: logger, repository: repository}
}
func (h *handler) Register(router *gin.RouterGroup) {
group := rbac.Group(router, baseURL, rbac.Catalog(perm.Currencies))
group.GET("", h.list)
group.GET("/:id", h.getByID)
group.POST("", h.create)
group.PUT("/:id", h.update)
group.DELETE("/:id", h.delete)
}
// list godoc
// @Summary List currency rates
// @Description Returns paginated currency exchange rates
// @Tags currencies
// @Produce json
// @Security BearerAuth
// @Param search query string false "Filter by currency code"
// @Param currency_from query string false "Filter by source currency"
// @Param currency_to query string false "Filter by target currency"
// @Param page query int false "Page number" default(1)
// @Param limit query int false "Items per page" default(10)
// @Param lang query string false "Language of localized fields; all returns the full {en, ru, tm} objects" Enums(tm, ru, en, all) default(tm)
// @Success 200 {object} ListCurrencyDTO
// @Failure 400 {object} appresult.AppError
// @Failure 500 {object} appresult.AppError
// @Router /currencies [get]
func (h *handler) list(c *gin.Context) {
filter, ok := parseListFilter(c)
if !ok {
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
return
}
result, err := h.repository.List(c.Request.Context(), filter)
if err != nil {
h.logger.Errorf("list currencies failed: %v", err)
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return
}
c.JSON(http.StatusOK, appresult.SuccessWithData(result))
}
// getByID godoc
// @Summary Get currency rate by ID
// @Description Returns a single currency exchange rate
// @Tags currencies
// @Produce json
// @Security BearerAuth
// @Param id path int true "Currency ID"
// @Param lang query string false "Language of localized fields; all returns the full {en, ru, tm} objects" Enums(tm, ru, en, all) default(tm)
// @Success 200 {object} CurrencyDTO
// @Failure 400 {object} appresult.AppError
// @Failure 404 {object} appresult.AppError
// @Failure 500 {object} appresult.AppError
// @Router /currencies/{id} [get]
func (h *handler) getByID(c *gin.Context) {
id, ok := shared.ParseID(c.Param("id"))
if !ok {
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
return
}
item, err := h.repository.GetByID(c.Request.Context(), id)
if errors.Is(err, pgx.ErrNoRows) {
c.JSON(http.StatusNotFound, appresult.ErrNotFound)
return
}
if err != nil {
h.logger.Errorf("get currency failed: %v", err)
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return
}
c.JSON(http.StatusOK, appresult.SuccessWithData(item))
}
// create godoc
// @Summary Create currency rate
// @Description Creates a new currency exchange rate
// @Tags currencies
// @Accept json
// @Produce json
// @Security BearerAuth
// @Param body body CreateCurrencyDTO true "Currency rate payload"
// @Param lang query string false "Language of localized fields; all returns the full {en, ru, tm} objects" Enums(tm, ru, en, all) default(tm)
// @Success 201 {object} CurrencyDTO
// @Failure 400 {object} appresult.AppError
// @Failure 409 {object} appresult.AppError
// @Failure 500 {object} appresult.AppError
// @Router /currencies [post]
func (h *handler) create(c *gin.Context) {
var dto CreateCurrencyDTO
if err := c.ShouldBindJSON(&dto); err != nil {
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
return
}
dto.CreatedBy = currentUserID(c)
item, err := h.repository.Create(c.Request.Context(), dto)
if errors.Is(err, ErrDuplicate) {
c.JSON(http.StatusConflict, appresult.ErrDuplicate)
return
}
if err != nil {
h.logger.Errorf("create currency failed: %v", err)
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return
}
c.JSON(http.StatusCreated, appresult.SuccessWithData(item))
}
// update godoc
// @Summary Update currency rate
// @Description Updates an existing currency exchange rate
// @Tags currencies
// @Accept json
// @Produce json
// @Security BearerAuth
// @Param id path int true "Currency ID"
// @Param body body UpdateCurrencyDTO true "Currency rate payload"
// @Param lang query string false "Language of localized fields; all returns the full {en, ru, tm} objects" Enums(tm, ru, en, all) default(tm)
// @Success 200 {object} CurrencyDTO
// @Failure 400 {object} appresult.AppError
// @Failure 404 {object} appresult.AppError
// @Failure 409 {object} appresult.AppError
// @Failure 500 {object} appresult.AppError
// @Router /currencies/{id} [put]
func (h *handler) update(c *gin.Context) {
id, ok := shared.ParseID(c.Param("id"))
if !ok {
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
return
}
var dto UpdateCurrencyDTO
if err := c.ShouldBindJSON(&dto); err != nil {
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
return
}
dto.UpdatedBy = currentUserID(c)
item, err := h.repository.Update(c.Request.Context(), id, dto)
if errors.Is(err, pgx.ErrNoRows) {
c.JSON(http.StatusNotFound, appresult.ErrNotFound)
return
}
if errors.Is(err, ErrDuplicate) {
c.JSON(http.StatusConflict, appresult.ErrDuplicate)
return
}
if err != nil {
h.logger.Errorf("update currency failed: %v", err)
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return
}
c.JSON(http.StatusOK, appresult.SuccessWithData(item))
}
// delete godoc
// @Summary Delete currency rate
// @Description Deletes a currency exchange rate
// @Tags currencies
// @Produce json
// @Security BearerAuth
// @Param id path int true "Currency ID"
// @Param lang query string false "Language of localized fields; all returns the full {en, ru, tm} objects" Enums(tm, ru, en, all) default(tm)
// @Success 200 {object} appresult.AppSuccess
// @Failure 400 {object} appresult.AppError
// @Failure 404 {object} appresult.AppError
// @Failure 500 {object} appresult.AppError
// @Router /currencies/{id} [delete]
func (h *handler) delete(c *gin.Context) {
id, ok := shared.ParseID(c.Param("id"))
if !ok {
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
return
}
if err := h.repository.Delete(c.Request.Context(), id); errors.Is(err, pgx.ErrNoRows) {
c.JSON(http.StatusNotFound, appresult.ErrNotFound)
return
} else if err != nil {
h.logger.Errorf("delete currency failed: %v", err)
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return
}
c.JSON(http.StatusOK, appresult.SuccessWithData("currency removed"))
}
func parseListFilter(c *gin.Context) (ListFilter, bool) {
filter := ListFilter{Page: shared.DefaultPage, Limit: shared.DefaultLimit}
if raw := queryValue(c, "page"); raw != "" {
page, err := strconv.Atoi(raw)
if err != nil || page < 1 {
return ListFilter{}, false
}
filter.Page = page
}
if raw := queryValue(c, "limit"); raw != "" {
limit, err := strconv.Atoi(raw)
if err != nil || limit < 1 {
return ListFilter{}, false
}
if limit > shared.MaxLimit {
limit = shared.MaxLimit
}
filter.Limit = limit
}
filter.Search = queryValue(c, "search", "q")
filter.CurrencyFrom = strings.ToUpper(queryValue(c, "currency_from", "currencyFrom"))
filter.CurrencyTo = strings.ToUpper(queryValue(c, "currency_to", "currencyTo"))
return filter, true
}
func queryValue(c *gin.Context, keys ...string) string {
for _, key := range keys {
if raw := strings.TrimSpace(c.Query(key)); raw != "" && raw != "undefined" && raw != "null" {
return raw
}
}
return ""
}
func currentUserID(c *gin.Context) *int64 {
rawID, exists := c.Get("id")
if !exists {
return nil
}
switch id := rawID.(type) {
case int64:
if id > 0 {
return &id
}
case int:
if id > 0 {
v := int64(id)
return &v
}
case string:
parsed, err := strconv.ParseInt(id, 10, 64)
if err == nil && parsed > 0 {
return &parsed
}
}
return nil
}

View File

@@ -0,0 +1,19 @@
package currency
import (
"context"
"errors"
)
// ErrDuplicate is returned by Repository.Create/Update when the
// currency_from/currency_to pair already exists among active (non-deleted)
// rows, so the handler can respond with a clean 409 instead of a raw 500.
var ErrDuplicate = errors.New("currency pair already exists")
type Repository interface {
List(ctx context.Context, filter ListFilter) (ListCurrencyDTO, error)
GetByID(ctx context.Context, id int64) (CurrencyDTO, error)
Create(ctx context.Context, dto CreateCurrencyDTO) (CurrencyDTO, error)
Update(ctx context.Context, id int64, dto UpdateCurrencyDTO) (CurrencyDTO, error)
Delete(ctx context.Context, id int64) error
}

View File

@@ -0,0 +1,393 @@
package db
import (
"context"
"fmt"
"math"
"strings"
"time"
"online-back/internal/dashboard"
"online-back/pkg/client/postgresql"
"online-back/pkg/logging"
)
type repository struct {
client postgresql.Client
logger *logging.Logger
}
func NewRepository(client postgresql.Client, logger *logging.Logger) dashboard.Repository {
return &repository{client: client, logger: logger}
}
func (r *repository) Overview(ctx context.Context, filter dashboard.OverviewFilter) (dashboard.OverviewDTO, error) {
now := time.Now().UTC()
win := currentPeriodWindow(now)
loanOrders, err := r.loanOrdersMetric(ctx, filter.BranchIds, win)
if err != nil {
return dashboard.OverviewDTO{}, err
}
activeCards, err := r.activeCardsMetric(ctx, filter.BranchIds, win)
if err != nil {
return dashboard.OverviewDTO{}, err
}
activeCustomers, err := r.activeCustomersMetric(ctx, filter.BranchIds, win)
if err != nil {
return dashboard.OverviewDTO{}, err
}
onlinePayments, err := r.onlinePaymentsMetric(ctx, filter.BranchIds, win)
if err != nil {
return dashboard.OverviewDTO{}, err
}
trendPoints, err := r.monthlyTrend(ctx, filter.BranchIds, filter.Year)
if err != nil {
return dashboard.OverviewDTO{}, err
}
loanStatus, err := r.loanStatusBreakdown(ctx, filter.BranchIds)
if err != nil {
return dashboard.OverviewDTO{}, err
}
weeklyOrders, err := r.weeklyOrders(ctx, filter.BranchIds, now)
if err != nil {
return dashboard.OverviewDTO{}, err
}
recentActivity, err := r.recentActivity(ctx, filter.BranchIds, filter.RecentLimit)
if err != nil {
return dashboard.OverviewDTO{}, err
}
return dashboard.OverviewDTO{
Stats: dashboard.StatsDTO{
LoanOrders: loanOrders,
ActiveCards: activeCards,
ActiveCustomers: activeCustomers,
OnlinePayments: onlinePayments,
},
Trend: dashboard.TrendDTO{Year: filter.Year, Points: trendPoints},
LoanStatus: loanStatus,
WeeklyOrders: weeklyOrders,
RecentActivity: recentActivity,
}, nil
}
// periodWindow holds the current-month-to-date range plus the same elapsed
// window one month earlier, so a KPI's "vs last month" change compares like
// with like instead of a partial month against a full one.
type periodWindow struct {
curStart, curEnd time.Time
prevStart, prevEnd time.Time
}
func currentPeriodWindow(now time.Time) periodWindow {
curStart := time.Date(now.Year(), now.Month(), 1, 0, 0, 0, 0, time.UTC)
prevAnchor := curStart.AddDate(0, -1, 0)
prevStart := time.Date(prevAnchor.Year(), prevAnchor.Month(), 1, 0, 0, 0, 0, time.UTC)
return periodWindow{
curStart: curStart,
curEnd: now,
prevStart: prevStart,
prevEnd: prevStart.Add(now.Sub(curStart)),
}
}
func percentChange(cur, prev int64) *float64 {
if prev == 0 {
return nil
}
pct := round2((float64(cur) - float64(prev)) / float64(prev) * 100)
return &pct
}
func round2(v float64) float64 {
return math.Round(v*100) / 100
}
// scanMetric runs a query shaped as "total, current-window count,
// previous-window count" and turns it into a StatMetricDTO.
func (r *repository) scanMetric(ctx context.Context, query string, args ...interface{}) (dashboard.StatMetricDTO, error) {
var total, cur, prev int64
if err := r.client.QueryRow(ctx, query, args...).Scan(&total, &cur, &prev); err != nil {
return dashboard.StatMetricDTO{}, err
}
return dashboard.StatMetricDTO{Count: total, ChangePercent: percentChange(cur, prev)}, nil
}
func metricSQL(fromAndWhere string) string {
return fmt.Sprintf(`
SELECT
COUNT(*),
COUNT(*) FILTER (WHERE created_at >= $1 AND created_at < $2),
COUNT(*) FILTER (WHERE created_at >= $3 AND created_at < $4)
%s`, fromAndWhere)
}
func (r *repository) loanOrdersMetric(ctx context.Context, branchIds []int64, win periodWindow) (dashboard.StatMetricDTO, error) {
where := ""
var extra []interface{}
if len(branchIds) > 0 {
extra = append(extra, branchIds)
where = fmt.Sprintf(" AND branch_id = ANY($%d)", len(extra)+4)
}
query := metricSQL(`FROM loan_orders WHERE deleted_at IS NULL` + where)
return r.scanMetric(ctx, query, append(dateArgs(win), extra...)...)
}
func (r *repository) activeCardsMetric(ctx context.Context, branchIds []int64, win periodWindow) (dashboard.StatMetricDTO, error) {
where := ""
var extra []interface{}
if len(branchIds) > 0 {
extra = append(extra, branchIds)
where = fmt.Sprintf(" AND EXISTS (SELECT 1 FROM branch_user bu WHERE bu.user_id = c.user_id AND bu.branch_id = ANY($%d) AND bu.deleted_at IS NULL)", len(extra)+4)
}
query := metricSQL(`FROM cards c WHERE c.deleted_at IS NULL` + where)
return r.scanMetric(ctx, query, append(dateArgs(win), extra...)...)
}
func (r *repository) activeCustomersMetric(ctx context.Context, branchIds []int64, win periodWindow) (dashboard.StatMetricDTO, error) {
where := " AND u.role_id = (SELECT id FROM roles WHERE code = 'user' AND deleted_at IS NULL) AND u.active = true"
var extra []interface{}
if len(branchIds) > 0 {
extra = append(extra, branchIds)
where += fmt.Sprintf(" AND EXISTS (SELECT 1 FROM branch_user bu WHERE bu.user_id = u.id AND bu.branch_id = ANY($%d) AND bu.deleted_at IS NULL)", len(extra)+4)
}
query := metricSQL(`FROM users u WHERE u.deleted_at IS NULL` + where)
return r.scanMetric(ctx, query, append(dateArgs(win), extra...)...)
}
func (r *repository) onlinePaymentsMetric(ctx context.Context, branchIds []int64, win periodWindow) (dashboard.StatMetricDTO, error) {
where := ""
var extra []interface{}
if len(branchIds) > 0 {
extra = append(extra, branchIds)
where = fmt.Sprintf(" AND branch_id = ANY($%d)", len(extra)+4)
}
query := metricSQL(`FROM visa_master_payment_orders WHERE deleted_at IS NULL` + where)
return r.scanMetric(ctx, query, append(dateArgs(win), extra...)...)
}
func dateArgs(win periodWindow) []interface{} {
return []interface{}{win.curStart, win.curEnd, win.prevStart, win.prevEnd}
}
// monthlyTrend groups loan_orders and card_orders (both "sargytlar" —
// orders raised by customers) by calendar month for the requested year.
func (r *repository) monthlyTrend(ctx context.Context, branchIds []int64, year int) ([]dashboard.TrendPointDTO, error) {
loanCounts, err := r.monthlyCounts(ctx, "loan_orders", branchIds, year)
if err != nil {
return nil, err
}
cardCounts, err := r.monthlyCounts(ctx, "card_orders", branchIds, year)
if err != nil {
return nil, err
}
points := make([]dashboard.TrendPointDTO, 12)
for month := 1; month <= 12; month++ {
points[month-1] = dashboard.TrendPointDTO{
Month: month,
Loans: loanCounts[month],
Cards: cardCounts[month],
}
}
return points, nil
}
func (r *repository) monthlyCounts(ctx context.Context, table string, branchIds []int64, year int) (map[int]int64, error) {
args := []interface{}{year}
where := ""
if len(branchIds) > 0 {
args = append(args, branchIds)
where = " AND branch_id = ANY($2)"
}
query := fmt.Sprintf(`
SELECT EXTRACT(MONTH FROM created_at)::int, COUNT(*)
FROM %s
WHERE EXTRACT(YEAR FROM created_at) = $1 AND deleted_at IS NULL%s
GROUP BY 1`, table, where)
rows, err := r.client.Query(ctx, query, args...)
if err != nil {
return nil, err
}
defer rows.Close()
counts := make(map[int]int64, 12)
for rows.Next() {
var month int
var count int64
if err := rows.Scan(&month, &count); err != nil {
return nil, err
}
counts[month] = count
}
return counts, rows.Err()
}
// weeklyOrders covers the last 7 calendar days including today.
func (r *repository) weeklyOrders(ctx context.Context, branchIds []int64, now time.Time) ([]dashboard.WeeklyPointDTO, error) {
today := time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, time.UTC)
start := today.AddDate(0, 0, -6)
loanCounts, err := r.dailyCounts(ctx, "loan_orders", branchIds, start)
if err != nil {
return nil, err
}
cardCounts, err := r.dailyCounts(ctx, "card_orders", branchIds, start)
if err != nil {
return nil, err
}
points := make([]dashboard.WeeklyPointDTO, 7)
for i := 0; i < 7; i++ {
day := start.AddDate(0, 0, i)
key := day.Format("2006-01-02")
points[i] = dashboard.WeeklyPointDTO{
Date: key,
Weekday: int(day.Weekday()+6)%7 + 1, // Monday=1 .. Sunday=7
Loans: loanCounts[key],
Cards: cardCounts[key],
}
}
return points, nil
}
func (r *repository) dailyCounts(ctx context.Context, table string, branchIds []int64, start time.Time) (map[string]int64, error) {
args := []interface{}{start}
where := ""
if len(branchIds) > 0 {
args = append(args, branchIds)
where = " AND branch_id = ANY($2)"
}
query := fmt.Sprintf(`
SELECT created_at::date, COUNT(*)
FROM %s
WHERE created_at >= $1 AND deleted_at IS NULL%s
GROUP BY 1`, table, where)
rows, err := r.client.Query(ctx, query, args...)
if err != nil {
return nil, err
}
defer rows.Close()
counts := make(map[string]int64, 7)
for rows.Next() {
var day time.Time
var count int64
if err := rows.Scan(&day, &count); err != nil {
return nil, err
}
counts[day.Format("2006-01-02")] = count
}
return counts, rows.Err()
}
var loanStatusOrder = []string{
dashboard.LoanStatusSatisfied,
dashboard.LoanStatusPending,
dashboard.LoanStatusProcessing,
dashboard.LoanStatusCancelled,
dashboard.LoanStatusRegistered,
}
// loanStatusBucketSQL folds the free-text loan_orders.status column into
// the five buckets the dashboard donut chart renders. Anything unrecognized
// (including NULL, i.e. a freshly created order) falls into "registered".
const loanStatusBucketSQL = `
CASE
WHEN lower(coalesce(status, '')) IN ('approved', 'satisfied', 'completed') THEN 'satisfied'
WHEN lower(coalesce(status, '')) = 'pending' THEN 'pending'
WHEN lower(coalesce(status, '')) IN ('review', 'processing', 'in_process', 'in-process') THEN 'processing'
WHEN lower(coalesce(status, '')) IN ('rejected', 'cancelled', 'canceled', 'declined') THEN 'cancelled'
ELSE 'registered'
END`
func (r *repository) loanStatusBreakdown(ctx context.Context, branchIds []int64) ([]dashboard.LoanStatusShareDTO, error) {
args := []interface{}{}
where := ""
if len(branchIds) > 0 {
args = append(args, branchIds)
where = " AND branch_id = ANY($1)"
}
query := fmt.Sprintf(`
SELECT %s, COUNT(*)
FROM loan_orders
WHERE deleted_at IS NULL%s
GROUP BY 1`, loanStatusBucketSQL, where)
rows, err := r.client.Query(ctx, query, args...)
if err != nil {
return nil, err
}
defer rows.Close()
counts := make(map[string]int64, len(loanStatusOrder))
var total int64
for rows.Next() {
var bucket string
var count int64
if err := rows.Scan(&bucket, &count); err != nil {
return nil, err
}
counts[bucket] = count
total += count
}
if err := rows.Err(); err != nil {
return nil, err
}
shares := make([]dashboard.LoanStatusShareDTO, 0, len(loanStatusOrder))
for _, bucket := range loanStatusOrder {
count := counts[bucket]
var pct float64
if total > 0 {
pct = round2(float64(count) / float64(total) * 100)
}
shares = append(shares, dashboard.LoanStatusShareDTO{Status: bucket, Count: count, Percent: pct})
}
return shares, nil
}
func (r *repository) recentActivity(ctx context.Context, branchIds []int64, limit int) ([]dashboard.RecentActivityDTO, error) {
args := []interface{}{}
where := ""
if len(branchIds) > 0 {
args = append(args, branchIds)
where = fmt.Sprintf(" AND branch_id = ANY($%d)", len(args))
}
args = append(args, limit)
query := fmt.Sprintf(`
SELECT id, unique_id, customer_name, customer_surname, loan_amount, status, created_at
FROM loan_orders
WHERE deleted_at IS NULL%s
ORDER BY created_at DESC, id DESC
LIMIT $%d`, where, len(args))
rows, err := r.client.Query(ctx, query, args...)
if err != nil {
return nil, err
}
defer rows.Close()
var items []dashboard.RecentActivityDTO
for rows.Next() {
var item dashboard.RecentActivityDTO
var firstName, lastName string
if err := rows.Scan(&item.Id, &item.UniqueId, &firstName, &lastName, &item.Amount, &item.Status, &item.CreatedAt); err != nil {
return nil, err
}
item.CustomerName = strings.TrimSpace(firstName + " " + lastName)
items = append(items, item)
}
return items, rows.Err()
}

78
internal/dashboard/dto.go Normal file
View File

@@ -0,0 +1,78 @@
package dashboard
import "time"
// StatMetricDTO is a single KPI card: a running total plus the percent
// change of new records this calendar month-to-date versus the same
// elapsed window last month. ChangePercent is nil when last month's
// window has zero records, since a percent change against zero is
// undefined.
type StatMetricDTO struct {
Count int64 `json:"count"`
ChangePercent *float64 `json:"changePercent"`
}
type StatsDTO struct {
LoanOrders StatMetricDTO `json:"loanOrders"`
ActiveCards StatMetricDTO `json:"activeCards"`
ActiveCustomers StatMetricDTO `json:"activeCustomers"`
OnlinePayments StatMetricDTO `json:"onlinePayments"`
}
type TrendPointDTO struct {
Month int `json:"month"`
Loans int64 `json:"loans"`
Cards int64 `json:"cards"`
}
type TrendDTO struct {
Year int `json:"year"`
Points []TrendPointDTO `json:"points"`
}
// LoanStatusShareDTO buckets loan_orders.status into one of five
// normalized states so the UI can render a stable donut chart regardless
// of the raw status text stored on the row.
type LoanStatusShareDTO struct {
Status string `json:"status"`
Count int64 `json:"count"`
Percent float64 `json:"percent"`
}
const (
LoanStatusSatisfied = "satisfied"
LoanStatusPending = "pending"
LoanStatusProcessing = "processing"
LoanStatusCancelled = "cancelled"
LoanStatusRegistered = "registered"
)
type WeeklyPointDTO struct {
Date string `json:"date"`
Weekday int `json:"weekday"`
Loans int64 `json:"loans"`
Cards int64 `json:"cards"`
}
type RecentActivityDTO struct {
Id int64 `json:"id"`
UniqueId *string `json:"uniqueId"`
CustomerName string `json:"customerName"`
Amount *string `json:"amount"`
Status *string `json:"status"`
CreatedAt time.Time `json:"createdAt"`
}
type OverviewDTO struct {
Stats StatsDTO `json:"stats"`
Trend TrendDTO `json:"trend"`
LoanStatus []LoanStatusShareDTO `json:"loanStatus"`
WeeklyOrders []WeeklyPointDTO `json:"weeklyOrders"`
RecentActivity []RecentActivityDTO `json:"recentActivity"`
}
type OverviewFilter struct {
BranchIds []int64
Year int
RecentLimit int
}

View File

@@ -0,0 +1,151 @@
package dashboard
import (
"net/http"
"strconv"
"time"
"online-back/internal/appresult"
"online-back/internal/handlers"
"online-back/internal/identity/rbac"
"online-back/internal/identity/rbac/perm"
"online-back/pkg/logging"
"online-back/pkg/sysstats"
"github.com/gin-gonic/gin"
)
const baseURL = "/dashboard"
const (
defaultRecentLimit = 10
maxRecentLimit = 50
)
type handler struct {
logger *logging.Logger
repository Repository
// diskPaths are the mount points reported by /server-stats.
diskPaths []string
}
func NewHandler(logger *logging.Logger, repository Repository, diskPaths []string) handlers.Handler {
return &handler{logger: logger, repository: repository, diskPaths: diskPaths}
}
func (h *handler) Register(router *gin.RouterGroup) {
group := rbac.Group(router, baseURL, rbac.RequireStaff(perm.Dashboard))
group.GET("/overview", h.overview)
group.GET("/server-stats", h.serverStats)
}
// overview godoc
// @Summary Dashboard overview
// @Description Returns the KPI cards, loan/card trend, loan status breakdown, weekly order counts, and recent activity feed for the admin dashboard
// @Tags dashboard
// @Produce json
// @Security BearerAuth
// @Param year query int false "Year for the monthly trend chart" default(current year)
// @Param recent_limit query int false "Number of recent activity items to return" default(10)
// @Param lang query string false "Language of localized fields; all returns the full {en, ru, tm} objects" Enums(tm, ru, en, all) default(tm)
// @Success 200 {object} appresult.AppSuccess
// @Failure 400 {object} appresult.AppError
// @Failure 500 {object} appresult.AppError
// @Router /dashboard/overview [get]
func (h *handler) overview(c *gin.Context) {
filter, ok := parseOverviewFilter(c)
if !ok {
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
return
}
result, err := h.repository.Overview(c.Request.Context(), filter)
if err != nil {
h.logger.Errorf("dashboard overview failed: %v", err)
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return
}
redactByPermission(&result, rbac.Can(c, perm.Cards), rbac.Can(c, perm.Loans))
c.JSON(http.StatusOK, appresult.SuccessWithData(result))
}
// serverStats godoc
// @Summary Server statistics
// @Description Returns host CPU, RAM and disk usage plus the API process's own memory and uptime. CPU usage is sampled over ~250ms; host fields are null when the OS cannot report them.
// @Tags dashboard
// @Produce json
// @Security BearerAuth
// @Param lang query string false "Language of localized fields; all returns the full {en, ru, tm} objects" Enums(tm, ru, en, all) default(tm)
// @Success 200 {object} appresult.AppSuccess{data=sysstats.Stats}
// @Failure 500 {object} appresult.AppError
// @Router /dashboard/server-stats [get]
func (h *handler) serverStats(c *gin.Context) {
stats, err := sysstats.Collect(c.Request.Context(), h.diskPaths)
if err != nil {
h.logger.Errorf("dashboard server stats failed: %v", err)
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return
}
c.JSON(http.StatusOK, appresult.SuccessWithData(stats))
}
func parseOverviewFilter(c *gin.Context) (OverviewFilter, bool) {
filter := OverviewFilter{
Year: time.Now().Year(),
RecentLimit: defaultRecentLimit,
}
if raw := c.Query("year"); raw != "" {
year, err := strconv.Atoi(raw)
if err != nil || year < 2000 || year > 2100 {
return OverviewFilter{}, false
}
filter.Year = year
}
if raw := c.Query("recent_limit"); raw != "" {
limit, err := strconv.Atoi(raw)
if err != nil || limit < 1 {
return OverviewFilter{}, false
}
if limit > maxRecentLimit {
limit = maxRecentLimit
}
filter.RecentLimit = limit
}
rbac.BindBranchIDs(c, &filter.BranchIds)
return filter, true
}
// redactByPermission blanks the widgets of modules the caller cannot open, so
// e.g. a head of loans sees every branch's loan numbers but no card numbers.
func redactByPermission(o *OverviewDTO, cards, loans bool) {
if !cards {
o.Stats.ActiveCards = StatMetricDTO{}
o.Stats.OnlinePayments = StatMetricDTO{}
}
if !loans {
o.Stats.LoanOrders = StatMetricDTO{}
o.LoanStatus = []LoanStatusShareDTO{}
o.RecentActivity = []RecentActivityDTO{}
}
for i := range o.Trend.Points {
if !cards {
o.Trend.Points[i].Cards = 0
}
if !loans {
o.Trend.Points[i].Loans = 0
}
}
for i := range o.WeeklyOrders {
if !cards {
o.WeeklyOrders[i].Cards = 0
}
if !loans {
o.WeeklyOrders[i].Loans = 0
}
}
}

View File

@@ -0,0 +1,7 @@
package dashboard
import "context"
type Repository interface {
Overview(ctx context.Context, filter OverviewFilter) (OverviewDTO, error)
}

View File

@@ -1,16 +1,31 @@
package handlermanager
import (
"context"
"net/http"
"path/filepath"
"online-back/internal/analytics"
analyticsdb "online-back/internal/analytics/db"
"online-back/internal/appresult"
"online-back/internal/backup"
backupdb "online-back/internal/backup/db"
"online-back/internal/cards"
"online-back/internal/config"
"online-back/internal/currency"
currencydb "online-back/internal/currency/db"
"online-back/internal/dashboard"
dashboarddb "online-back/internal/dashboard/db"
"online-back/internal/identity"
"online-back/internal/identity/activitylog"
activitylogdb "online-back/internal/identity/activitylog/db"
"online-back/internal/identity/rbac"
"online-back/internal/identity/rbac/perm"
"online-back/internal/lending"
"online-back/internal/org"
"online-back/internal/payment"
"online-back/pkg/logging"
"online-back/pkg/paymentgateway"
"github.com/gin-contrib/cors"
"github.com/gin-gonic/gin"
@@ -47,18 +62,59 @@ func New(cfg *config.Config, client *pgxpool.Pool, logger *logging.Logger) *gin.
"Authorization",
"Cache-Control",
},
ExposeHeaders: []string{"Content-Length"},
ExposeHeaders: []string{"Content-Length", "Content-Disposition"},
}))
adminGroup := router.Group(adminAPIPrefix)
// First, so it sees every admin response; /swagger stays outside it.
adminGroup.Use(appresult.Localize())
adminGroup.Use(activitylog.Record(activitylogdb.NewRepository(client, logger), logger))
if err := perm.Sync(context.Background(), client); err != nil {
logger.Fatalf("rbac: sync permission catalog: %v", err)
}
adminGroup.Use(rbac.Guard(rbac.NewService(client)))
// Each bounded context registers its own modules' handlers.
// Add new modules inside the relevant context's router.go rather than here.
identity.Register(adminGroup, client, logger)
org.Register(adminGroup, client, logger)
lending.Register(adminGroup, client, logger)
cards.Register(adminGroup, client, logger)
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)
org.Register(adminGroup, client, logger)
lending.Register(adminGroup, client, logger)
cards.Register(adminGroup, client, logger)
currencyRepo := currencydb.NewRepository(client, logger)
payment.Register(adminGroup, client, logger, currencyRepo, paymentGatewayClient(cfg, logger), cfg.PublicBaseURL)
currency.NewHandler(logger, currencyRepo).Register(adminGroup)
dashboard.NewHandler(logger, dashboarddb.NewRepository(client, logger), []string{"/", cfg.PublicFilePath}).Register(adminGroup)
analytics.NewHandler(logger, analyticsdb.NewRepository(client, logger)).Register(adminGroup)
backupDir := filepath.Join(cfg.PublicFilePath, "backups")
backupSvc := backup.NewService(
backupdb.NewRepository(client, logger),
backup.NewPgDumper(cfg.Storage),
backupDir,
logger,
)
backup.NewHandler(logger, backupSvc).Register(adminGroup)
}
// paymentGatewayClient picks the real GBÜS client outside debug mode, and
// the logging stub in debug mode, so local/dev runs never hit the live
// bank gateway by accident.
func paymentGatewayClient(cfg *config.Config, logger *logging.Logger) paymentgateway.Client {
if cfg.IsDebug != nil && *cfg.IsDebug {
return paymentgateway.NewLogClient(logger)
}
return paymentgateway.NewHTTPClient(logger)
}

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

@@ -12,16 +12,14 @@ import (
)
type repository struct {
client postgresql.Client
generic *genericrepo.Repository[activitylog.ActivityLogDTO]
logger *logging.Logger
client postgresql.Client
logger *logging.Logger
}
func NewRepository(client postgresql.Client, logger *logging.Logger) activitylog.Repository {
return &repository{
client: client,
generic: genericrepo.New(client, "activity_logs", activityLogColumnsSQL, scanActivityLog),
logger: logger,
client: client,
logger: logger,
}
}
@@ -31,13 +29,45 @@ var activityLogColumns = []string{
var activityLogColumnsSQL = strings.Join(activityLogColumns, ", ")
const activityLogFromClause = ` FROM activity_logs al
LEFT JOIN users u ON u.id = al.user_id
LEFT JOIN roles r ON r.id = u.role_id`
const activityLogSelectColumns = `al.id, al.user_id, al.method, al.path, al.module, al.action, al.status_code, al.request_body, al.ip, al.created_at, COALESCE(u.username, ''), COALESCE(r.code, '')`
func (r *repository) List(ctx context.Context, filter activitylog.ListFilter) (activitylog.ListActivityLogDTO, error) {
whereClause, args := buildListQuery(filter)
items, count, err := r.generic.List(ctx, whereClause, args, filter.Page, filter.Limit, "id DESC")
var count int64
if err := r.client.QueryRow(ctx, `SELECT COUNT(*) FROM activity_logs al`+whereClause, args...).Scan(&count); err != nil {
return activitylog.ListActivityLogDTO{}, err
}
offset := (filter.Page - 1) * filter.Limit
limitPlaceholder := len(args) + 1
offsetPlaceholder := len(args) + 2
query := fmt.Sprintf(
`SELECT %s%s%s ORDER BY al.id DESC LIMIT $%d OFFSET $%d`,
activityLogSelectColumns, activityLogFromClause, whereClause, limitPlaceholder, offsetPlaceholder,
)
rows, err := r.client.Query(ctx, query, append(args, filter.Limit, offset)...)
if err != nil {
return activitylog.ListActivityLogDTO{}, err
}
defer rows.Close()
var items []activitylog.ActivityLogDTO
for rows.Next() {
item, err := scanActivityLog(rows)
if err != nil {
return activitylog.ListActivityLogDTO{}, err
}
items = append(items, item)
}
if err := rows.Err(); err != nil {
return activitylog.ListActivityLogDTO{}, err
}
return activitylog.ListActivityLogDTO{Count: count, Logs: items}, nil
}
@@ -47,17 +77,17 @@ func buildListQuery(filter activitylog.ListFilter) (whereClause string, args []i
if filter.UserId != nil {
args = append(args, *filter.UserId)
conditions = append(conditions, fmt.Sprintf("user_id = $%d", len(args)))
conditions = append(conditions, fmt.Sprintf("al.user_id = $%d", len(args)))
}
if filter.Module != "" {
args = append(args, filter.Module)
conditions = append(conditions, fmt.Sprintf("module = $%d", len(args)))
conditions = append(conditions, fmt.Sprintf("al.module = $%d", len(args)))
}
if filter.Action != "" {
args = append(args, filter.Action)
conditions = append(conditions, fmt.Sprintf("action = $%d", len(args)))
conditions = append(conditions, fmt.Sprintf("al.action = $%d", len(args)))
}
if len(conditions) == 0 {
@@ -68,12 +98,21 @@ func buildListQuery(filter activitylog.ListFilter) (whereClause string, args []i
}
func (r *repository) GetByID(ctx context.Context, id int64) (activitylog.ActivityLogDTO, error) {
return r.generic.GetByID(ctx, id)
query := `SELECT ` + activityLogSelectColumns + activityLogFromClause + ` WHERE al.id = $1`
return scanActivityLog(r.client.QueryRow(ctx, query, id))
}
func (r *repository) Create(ctx context.Context, dto activitylog.CreateActivityLogDTO) (activitylog.ActivityLogDTO, error) {
query := `INSERT INTO activity_logs (user_id, method, path, module, action, status_code, request_body, ip)
VALUES ($1,$2,$3,$4,$5,$6,$7,$8) RETURNING ` + activityLogColumnsSQL
query := `
WITH inserted AS (
INSERT INTO activity_logs (user_id, method, path, module, action, status_code, request_body, ip)
VALUES ($1,$2,$3,$4,$5,$6,$7,$8)
RETURNING ` + activityLogColumnsSQL + `
)
SELECT ` + activityLogSelectColumns + `
FROM inserted al
LEFT JOIN users u ON u.id = al.user_id
LEFT JOIN roles r ON r.id = u.role_id`
row := r.client.QueryRow(ctx, query,
dto.UserId, dto.Method, dto.Path, dto.Module, dto.Action, dto.StatusCode, dto.RequestBody, dto.Ip,
@@ -84,14 +123,23 @@ func (r *repository) Create(ctx context.Context, dto activitylog.CreateActivityL
func scanActivityLog(row genericrepo.Scanner) (activitylog.ActivityLogDTO, error) {
var item activitylog.ActivityLogDTO
var requestBody []byte
var username, role string
err := row.Scan(
&item.Id, &item.UserId, &item.Method, &item.Path, &item.Module, &item.Action,
&item.StatusCode, &requestBody, &item.Ip, &item.CreatedAt,
&username, &role,
)
if err != nil {
return activitylog.ActivityLogDTO{}, err
}
item.RequestBody = requestBody
if item.UserId != nil {
item.User = &activitylog.UserInfo{
Id: *item.UserId,
Username: username,
Role: role,
}
}
return item, nil
}

View File

@@ -5,9 +5,16 @@ import (
"time"
)
type UserInfo struct {
Id int64 `json:"id"`
Username string `json:"username"`
Role string `json:"role"`
}
type ActivityLogDTO struct {
Id int64 `json:"id"`
UserId *int64 `json:"userId"`
User *UserInfo `json:"user"`
Method string `json:"method"`
Path string `json:"path"`
Module string `json:"module"`

View File

@@ -4,9 +4,13 @@ import (
"errors"
"net/http"
"strconv"
"strings"
"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"
@@ -27,14 +31,14 @@ func NewHandler(logger *logging.Logger, repository Repository) handlers.Handler
// Register only wires read endpoints: activity log entries are written by
// the Record middleware, never through the API.
func (h *handler) Register(router *gin.RouterGroup) {
group := router.Group(baseURL, appresult.JwtTokenCheck())
group := rbac.Group(router, baseURL, rbac.RequireStaff(perm.ActivityLogs))
group.GET("", h.list)
group.GET("/:id", h.getByID)
}
// list godoc
// @Summary List activity logs
// @Description Returns a paginated audit trail of user actions (create/update/delete)
// @Description Returns a paginated audit trail of user actions (create/update/delete). Each log includes the actor's username and role code.
// @Tags activity-logs
// @Produce json
// @Security BearerAuth
@@ -43,6 +47,7 @@ func (h *handler) Register(router *gin.RouterGroup) {
// @Param action query string false "Filter by action (create, update, delete)"
// @Param page query int false "Page number" default(1)
// @Param limit query int false "Items per page" default(10)
// @Param lang query string false "Language of localized fields; all returns the full {en, ru, tm} objects" Enums(tm, ru, en, all) default(tm)
// @Success 200 {object} appresult.AppSuccess
// @Failure 400 {object} appresult.AppError
// @Failure 500 {object} appresult.AppError
@@ -71,15 +76,22 @@ func (h *handler) list(c *gin.Context) {
// @Produce json
// @Security BearerAuth
// @Param id path int true "Activity log ID"
// @Param lang query string false "Language of localized fields; all returns the full {en, ru, tm} objects" Enums(tm, ru, en, all) default(tm)
// @Success 200 {object} appresult.AppSuccess
// @Failure 400 {object} appresult.AppError
// @Failure 404 {object} appresult.AppError
// @Failure 500 {object} appresult.AppError
// @Router /activity-logs/{id} [get]
func (h *handler) getByID(c *gin.Context) {
id, ok := parseID(c.Param("id"))
id, ok := shared.ParseID(c.Param("id"))
if !ok {
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
// GET /activity-logs/card-orders → list that module instead of 400.
q := c.Request.URL.Query()
if q.Get("module") == "" {
q.Set("module", c.Param("id"))
c.Request.URL.RawQuery = q.Encode()
}
h.list(c)
return
}
@@ -97,38 +109,22 @@ func (h *handler) getByID(c *gin.Context) {
c.JSON(http.StatusOK, appresult.SuccessWithData(item))
}
func parseID(raw string) (int64, bool) {
id, err := strconv.ParseInt(raw, 10, 64)
if err != nil || id <= 0 {
return 0, false
}
return id, true
}
const (
defaultPage = 1
defaultLimit = 10
maxLimit = 100
)
func parseListFilter(c *gin.Context) (ListFilter, bool) {
filter := ListFilter{
Page: defaultPage,
Limit: defaultLimit,
Page: shared.DefaultPage,
Limit: shared.DefaultLimit,
}
if raw := c.Query("user_id"); raw != "" {
id, ok := parseID(raw)
if !ok {
return ListFilter{}, false
}
filter.UserId = &id
if id, ok := optionalQueryID(c, "user_id", "userId"); !ok {
return ListFilter{}, false
} else if id != nil {
filter.UserId = id
}
filter.Module = c.Query("module")
filter.Action = c.Query("action")
filter.Module = queryValue(c, "module")
filter.Action = queryValue(c, "action")
if raw := c.Query("page"); raw != "" {
if raw := queryValue(c, "page"); raw != "" {
page, err := strconv.Atoi(raw)
if err != nil || page < 1 {
return ListFilter{}, false
@@ -136,13 +132,37 @@ func parseListFilter(c *gin.Context) (ListFilter, bool) {
filter.Page = page
}
if raw := c.Query("limit"); raw != "" {
if raw := queryValue(c, "limit"); raw != "" {
limit, err := strconv.Atoi(raw)
if err != nil || limit < 1 || limit > maxLimit {
if err != nil || limit < 1 {
return ListFilter{}, false
}
if limit > shared.MaxLimit {
limit = shared.MaxLimit
}
filter.Limit = limit
}
return filter, true
}
func queryValue(c *gin.Context, keys ...string) string {
for _, key := range keys {
if raw := strings.TrimSpace(c.Query(key)); raw != "" && raw != "undefined" && raw != "null" {
return raw
}
}
return ""
}
func optionalQueryID(c *gin.Context, keys ...string) (*int64, bool) {
raw := queryValue(c, keys...)
if raw == "" {
return nil, true
}
id, ok := shared.ParseID(raw)
if !ok {
return nil, false
}
return &id, true
}

View File

@@ -0,0 +1,97 @@
package activitylog
import (
"context"
"net/http"
"net/http/httptest"
"sync"
"testing"
"online-back/internal/shared"
"online-back/pkg/logging"
"github.com/gin-gonic/gin"
)
type stubRepository struct {
mu sync.Mutex
listFilter ListFilter
listResult ListActivityLogDTO
created []CreateActivityLogDTO
}
func (s *stubRepository) List(_ context.Context, filter ListFilter) (ListActivityLogDTO, error) {
s.listFilter = filter
return s.listResult, nil
}
func (s *stubRepository) GetByID(_ context.Context, _ int64) (ActivityLogDTO, error) {
return ActivityLogDTO{}, nil
}
func (s *stubRepository) Create(_ context.Context, dto CreateActivityLogDTO) (ActivityLogDTO, error) {
s.mu.Lock()
defer s.mu.Unlock()
s.created = append(s.created, dto)
return ActivityLogDTO{Id: 1}, nil
}
func (s *stubRepository) createdEntries() []CreateActivityLogDTO {
s.mu.Lock()
defer s.mu.Unlock()
out := make([]CreateActivityLogDTO, len(s.created))
copy(out, s.created)
return out
}
func TestParseListFilterIgnoresUndefinedAndCapsLimit(t *testing.T) {
gin.SetMode(gin.TestMode)
w := httptest.NewRecorder()
c, _ := gin.CreateTestContext(w)
req := httptest.NewRequest(http.MethodGet, "/activity-logs?user_id=undefined&module=card-orders&limit=1000&page=2", nil)
c.Request = req
filter, ok := parseListFilter(c)
if !ok {
t.Fatal("expected filter to parse")
}
if filter.UserId != nil {
t.Fatalf("user_id should be ignored, got %v", *filter.UserId)
}
if filter.Module != "card-orders" {
t.Fatalf("module=%q", filter.Module)
}
if filter.Limit != shared.MaxLimit {
t.Fatalf("limit=%d", filter.Limit)
}
if filter.Page != 2 {
t.Fatalf("page=%d", filter.Page)
}
}
func TestGetByIDListsModuleWhenPathIsNotNumeric(t *testing.T) {
gin.SetMode(gin.TestMode)
repo := &stubRepository{listResult: ListActivityLogDTO{Count: 0, Logs: []ActivityLogDTO{}}}
h := &handler{logger: logging.GetLogger(), repository: repo}
r := gin.New()
group := r.Group("/activity-logs")
group.GET("", h.list)
group.GET("/:id", h.getByID)
w := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodGet, "/activity-logs/card-orders?limit=1000", nil)
r.ServeHTTP(w, req)
if w.Code != http.StatusOK {
t.Fatalf("status=%d body=%s", w.Code, w.Body.String())
}
if repo.listFilter.Module != "card-orders" {
t.Fatalf("module=%q", repo.listFilter.Module)
}
if repo.listFilter.Limit != shared.MaxLimit {
t.Fatalf("limit=%d", repo.listFilter.Limit)
}
}

View File

@@ -15,53 +15,87 @@ import (
"github.com/gin-gonic/gin"
)
// sensitiveFieldSubstrings marks request body keys that must never be
// persisted verbatim (login passwords, branch billing credentials, etc).
var sensitiveFieldSubstrings = []string{"password", "token", "secret"}
const writeTimeout = 5 * time.Second
const (
writeTimeout = 5 * time.Second
queueSize = 1024
workers = 2
)
type recorder struct {
repository Repository
logger *logging.Logger
queue chan CreateActivityLogDTO
}
// Record returns a global gin middleware that persists every mutating
// (POST/PUT/PATCH/DELETE) request made by an authenticated user into
// activity_logs - e.g. creating a card or attaching a user to a branch.
// Read-only (GET) requests are not recorded. It must run after
// appresult.JwtTokenCheck has set "id" in the context, which happens
// naturally here since c.Next() runs the rest of the chain first.
// Read-only (GET) requests are not recorded. After the handler finishes
// the entry is queued (the client is not blocked) and a small worker
// pool writes it. JwtTokenCheck sets "id" during c.Next(), which is why
// the user is read afterwards.
func Record(repository Repository, logger *logging.Logger) gin.HandlerFunc {
return func(c *gin.Context) {
if !shouldRecord(c.Request.Method) {
c.Next()
return
}
return newRecorder(repository, logger).handle
}
body := readAndRestoreBody(c)
func newRecorder(repository Repository, logger *logging.Logger) *recorder {
r := &recorder{
repository: repository,
logger: logger,
queue: make(chan CreateActivityLogDTO, queueSize),
}
for i := 0; i < workers; i++ {
go r.worker()
}
return r
}
func (r *recorder) handle(c *gin.Context) {
if !shouldRecord(c.Request.Method) {
c.Next()
return
}
userID := currentUserID(c)
if userID == nil {
return
body := readAndRestoreBody(c)
c.Next()
userID := currentUserID(c)
if userID == nil {
return
}
id := *userID
module, action := describeRoute(c)
r.enqueue(CreateActivityLogDTO{
UserId: &id,
Method: c.Request.Method,
Path: c.Request.URL.Path,
Module: module,
Action: action,
StatusCode: c.Writer.Status(),
RequestBody: redact(body),
Ip: c.ClientIP(),
})
}
func (r *recorder) enqueue(entry CreateActivityLogDTO) {
select {
case r.queue <- entry:
default:
r.logger.Errorf("activity log queue full, dropping %s %s", entry.Method, entry.Path)
}
}
func (r *recorder) worker() {
for entry := range r.queue {
ctx, cancel := context.WithTimeout(context.Background(), writeTimeout)
if _, err := r.repository.Create(ctx, entry); err != nil {
r.logger.Errorf("record activity log failed: %v", err)
}
module, action := describeRoute(c)
entry := CreateActivityLogDTO{
UserId: userID,
Method: c.Request.Method,
Path: c.Request.URL.Path,
Module: module,
Action: action,
StatusCode: c.Writer.Status(),
RequestBody: redact(body),
Ip: c.ClientIP(),
}
go func() {
ctx, cancel := context.WithTimeout(context.Background(), writeTimeout)
defer cancel()
if _, err := repository.Create(ctx, entry); err != nil {
logger.Errorf("record activity log failed: %v", err)
}
}()
cancel()
}
}
@@ -80,9 +114,13 @@ func readAndRestoreBody(c *gin.Context) []byte {
}
data, err := io.ReadAll(c.Request.Body)
if err != nil {
c.Request.Body = io.NopCloser(bytes.NewReader(nil))
return nil
}
// Restore Body for ShouldBindJSON and cache it so ShouldBindBodyWithJSON
// still works after this middleware has already consumed the stream.
c.Request.Body = io.NopCloser(bytes.NewReader(data))
c.Set(gin.BodyBytesKey, data)
return data
}

View File

@@ -0,0 +1,71 @@
package activitylog
import (
"bytes"
"encoding/json"
"net/http"
"net/http/httptest"
"testing"
"time"
"online-back/pkg/logging"
"github.com/gin-gonic/gin"
)
func TestRecordLeavesJSONBodyForHandler(t *testing.T) {
gin.SetMode(gin.TestMode)
repo := &stubRepository{}
r := gin.New()
r.Use(Record(repo, logging.GetLogger()))
r.POST("/api/admin/card-orders", func(c *gin.Context) {
c.Set("id", "3")
var dto struct {
CustomerName string `json:"customerName" binding:"required"`
Region string `json:"region" binding:"required"`
}
if err := c.ShouldBindBodyWithJSON(&dto); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusCreated, dto)
})
body := `{"customerName":"Simple","region":"Aşgabat"}`
w := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodPost, "/api/admin/card-orders", bytes.NewBufferString(body))
req.Header.Set("Content-Type", "application/json")
r.ServeHTTP(w, req)
if w.Code != http.StatusCreated {
t.Fatalf("status=%d body=%s", w.Code, w.Body.String())
}
deadline := time.Now().Add(time.Second)
var created []CreateActivityLogDTO
for time.Now().Before(deadline) {
created = repo.createdEntries()
if len(created) > 0 {
break
}
time.Sleep(10 * time.Millisecond)
}
if len(created) == 0 {
t.Fatal("expected activity log to be recorded")
}
if created[0].Module != "card-orders" {
t.Fatalf("module=%q", created[0].Module)
}
if created[0].StatusCode != http.StatusCreated {
t.Fatalf("statusCode=%d", created[0].StatusCode)
}
var logged map[string]interface{}
if err := json.Unmarshal(created[0].RequestBody, &logged); err != nil {
t.Fatalf("request body: %v", err)
}
if logged["customerName"] != "Simple" {
t.Fatalf("logged body=%v", logged)
}
}

View File

@@ -2,13 +2,18 @@ package db
import (
"context"
"database/sql"
"encoding/json"
"errors"
"sort"
"strings"
"unicode"
"online-back/internal/identity/auth"
"online-back/internal/identity/rbac/perm"
"online-back/pkg/client/postgresql"
"online-back/pkg/logging"
"online-back/pkg/repository/genericrepo"
"github.com/jackc/pgconn"
"github.com/jackc/pgx/v4"
@@ -29,19 +34,50 @@ func NewRepository(client postgresql.Client, logger *logging.Logger) auth.Reposi
const (
loginByNameQuery = `
SELECT id, password FROM users
WHERE LOWER(TRIM(name)) = LOWER(TRIM($1))
OR LOWER(TRIM(username)) = LOWER(TRIM($1))
WHERE (LOWER(TRIM(name)) = LOWER(TRIM($1))
OR LOWER(TRIM(username)) = LOWER(TRIM($1)))
AND deleted_at IS NULL
LIMIT 1`
loginByPhoneQuery = `
SELECT id, password FROM users
WHERE phone = $1
OR ($2 <> '' AND regexp_replace(phone, '[^0-9]', '', 'g') = $2)
WHERE (phone = $1
OR ($2 <> '' AND regexp_replace(phone, '[^0-9]', '', 'g') = $2))
AND deleted_at IS NULL
LIMIT 1`
userByIDQuery = `SELECT id, password FROM users WHERE id = $1`
profileQuery = `SELECT id, name, first_name, last_name, phone, avatar, created_at
FROM users WHERE id = $1`
userByIDQuery = `SELECT id, password FROM users WHERE id = $1 AND deleted_at IS NULL`
)
const profileFromClause = ` FROM users u
LEFT JOIN roles r ON r.id = u.role_id AND r.deleted_at IS NULL`
const profileBranchesJSON = `COALESCE((
SELECT json_agg(jsonb_build_object(
'id', b.id,
'uniqueCode', COALESCE(b.unique_code, ''),
'name', b.name
) ORDER BY b.id)
FROM (
SELECT DISTINCT ON (b.id) b.id, b.unique_code, b.name
FROM branch_user bu
JOIN branches b ON b.id = bu.branch_id
WHERE bu.user_id = u.id AND bu.deleted_at IS NULL AND b.deleted_at IS NULL
ORDER BY b.id
) b
), '[]'::json)`
// profilePermissionsJSON: every permission for an is_super role, else the
// role's own; ordered as rbac/perm.All by the caller.
const profilePermissionsJSON = `COALESCE((
SELECT json_agg(jsonb_build_object('code', p.code, 'name', p.name))
FROM permissions p
WHERE r.is_super OR EXISTS (
SELECT 1 FROM role_permissions rp WHERE rp.role_id = r.id AND rp.permission_code = p.code
)
), '[]'::json)`
const profileQuery = `SELECT u.id, u.name, u.first_name, u.last_name, u.phone, u.avatar, u.created_at,
r.id, r.code, r.name, r.scope, COALESCE(r.is_super, false), ` + profileBranchesJSON + `, ` + profilePermissionsJSON + profileFromClause + ` WHERE u.id = $1 AND u.deleted_at IS NULL`
func (r *repository) Login(ctx context.Context, dto auth.LoginDTO) (auth.UserCredentials, error) {
phone := strings.TrimSpace(dto.Phone)
if phone != "" {
@@ -66,31 +102,37 @@ func (r *repository) GetUserByID(ctx context.Context, id int) (auth.UserCredenti
}
func (r *repository) GetProfile(ctx context.Context, id int) (auth.UserProfileDTO, error) {
var profile auth.UserProfileDTO
err := r.client.QueryRow(ctx, profileQuery, id).Scan(
&profile.Id,
&profile.Name,
&profile.FirstName,
&profile.LastName,
&profile.Phone,
&profile.Avatar,
&profile.CreatedAt,
)
return profile, err
return scanProfile(r.client.QueryRow(ctx, profileQuery, id))
}
const updateProfileQuery = `
UPDATE users SET
name = $1, first_name = $2, last_name = $3, phone = $4, avatar = $5,
updated_at = (CURRENT_TIMESTAMP AT TIME ZONE 'UTC')
WHERE id = $6
RETURNING id, name, first_name, last_name, phone, avatar, created_at`
WHERE id = $6 AND deleted_at IS NULL`
func (r *repository) UpdateProfile(ctx context.Context, id int, dto auth.UpdateProfileDTO) (auth.UserProfileDTO, error) {
var profile auth.UserProfileDTO
err := r.client.QueryRow(ctx, updateProfileQuery,
tag, err := r.client.Exec(ctx, updateProfileQuery,
dto.Name, dto.FirstName, dto.LastName, dto.Phone, dto.Avatar, id,
).Scan(
)
if err != nil {
return auth.UserProfileDTO{}, err
}
if tag.RowsAffected() == 0 {
return auth.UserProfileDTO{}, pgx.ErrNoRows
}
return r.GetProfile(ctx, id)
}
func scanProfile(row genericrepo.Scanner) (auth.UserProfileDTO, error) {
var profile auth.UserProfileDTO
var roleID sql.NullInt64
var roleCode, roleName, roleScope sql.NullString
var roleSuper bool
var branchesJSON []byte
var permissionsJSON []byte
err := row.Scan(
&profile.Id,
&profile.Name,
&profile.FirstName,
@@ -98,19 +140,52 @@ func (r *repository) UpdateProfile(ctx context.Context, id int, dto auth.UpdateP
&profile.Phone,
&profile.Avatar,
&profile.CreatedAt,
&roleID,
&roleCode,
&roleName,
&roleScope,
&roleSuper,
&branchesJSON,
&permissionsJSON,
)
if errors.Is(err, pgx.ErrNoRows) {
if err != nil {
return auth.UserProfileDTO{}, err
}
return profile, err
if roleID.Valid {
profile.Role = &auth.ProfileRoleDTO{
Id: roleID.Int64,
Code: roleCode.String,
Name: roleName.String,
Scope: roleScope.String,
IsSuper: roleSuper,
}
}
profile.Branches = []auth.ProfileBranchDTO{}
if len(branchesJSON) > 0 && string(branchesJSON) != "null" {
if err := json.Unmarshal(branchesJSON, &profile.Branches); err != nil {
return auth.UserProfileDTO{}, err
}
}
profile.Permissions = []auth.ProfilePermissionDTO{}
if len(permissionsJSON) > 0 && string(permissionsJSON) != "null" {
if err := json.Unmarshal(permissionsJSON, &profile.Permissions); err != nil {
return auth.UserProfileDTO{}, err
}
}
sortByCatalog(profile.Permissions)
return profile, nil
}
func (r *repository) UserExists(ctx context.Context, username, phone string) (bool, error) {
const query = `
SELECT EXISTS (
SELECT 1 FROM users
WHERE LOWER(username) = LOWER($1)
OR regexp_replace(phone, '[^0-9]', '', 'g') = $2
WHERE (LOWER(username) = LOWER($1)
OR regexp_replace(phone, '[^0-9]', '', 'g') = $2)
AND deleted_at IS NULL
)`
var exists bool
err := r.client.QueryRow(ctx, query, username, digitString(phone)).Scan(&exists)
@@ -177,8 +252,8 @@ func (r *repository) CompleteRegistration(ctx context.Context, v auth.Verificati
var userID int
err = tx.QueryRow(ctx, `
INSERT INTO users (name, username, phone, password, role, active, email)
VALUES ($1, $2, $3, $4, 'user', true, '')
INSERT INTO users (name, username, phone, password, role_id, active, email)
VALUES ($1, $2, $3, $4, (SELECT id FROM roles WHERE code = 'user' AND deleted_at IS NULL), true, '')
RETURNING id`,
v.Name, v.Username, v.Phone, v.Password,
).Scan(&userID)
@@ -203,7 +278,7 @@ func (r *repository) CompleteRegistration(ctx context.Context, v auth.Verificati
func (r *repository) GetUserByName(ctx context.Context, name string) (auth.UserIdentity, error) {
const query = `
SELECT id, name, username, phone FROM users
WHERE LOWER(TRIM(name)) = LOWER(TRIM($1))
WHERE LOWER(TRIM(name)) = LOWER(TRIM($1)) AND deleted_at IS NULL
LIMIT 1`
var user auth.UserIdentity
@@ -225,7 +300,7 @@ func (r *repository) CompletePasswordReset(ctx context.Context, userID int, veri
UPDATE users SET
password = $1,
updated_at = (CURRENT_TIMESTAMP AT TIME ZONE 'UTC')
WHERE id = $2`, passwordHash, userID)
WHERE id = $2 AND deleted_at IS NULL`, passwordHash, userID)
if err != nil {
return err
}
@@ -249,3 +324,13 @@ func digitString(s string) string {
}
return b.String()
}
func sortByCatalog(perms []auth.ProfilePermissionDTO) {
order := make(map[perm.Code]int, len(perm.All))
for i, d := range perm.All {
order[d.Code] = i
}
sort.SliceStable(perms, func(i, j int) bool {
return order[perm.Code(perms[i].Code)] < order[perm.Code(perms[j].Code)]
})
}

View File

@@ -1,6 +1,10 @@
package auth
import "time"
import (
"time"
"online-back/internal/shared"
)
type LoginDTO struct {
Name string `json:"name"`
@@ -12,14 +16,38 @@ type RefreshTokenDTO struct {
RefreshToken string `json:"refreshToken" binding:"required"`
}
type ProfileRoleDTO struct {
Id int64 `json:"id"`
Code string `json:"code"`
Name string `json:"name"`
Scope string `json:"scope"`
IsSuper bool `json:"isSuper"`
}
type ProfileBranchDTO struct {
Id int64 `json:"id"`
UniqueCode string `json:"uniqueCode"`
Name shared.LocalizedText `json:"name"`
}
// ProfilePermissionDTO is one module the caller can open; the front-end
// builds its menu from this list.
type ProfilePermissionDTO struct {
Code string `json:"code"`
Name string `json:"name"`
}
type UserProfileDTO struct {
Id int `json:"id"`
Name string `json:"name"`
FirstName string `json:"firstName"`
LastName string `json:"lastName"`
Phone string `json:"phone"`
Avatar string `json:"avatar"`
CreatedAt time.Time `json:"createdAt"`
Id int `json:"id"`
Name string `json:"name"`
FirstName string `json:"firstName"`
LastName string `json:"lastName"`
Phone string `json:"phone"`
Avatar string `json:"avatar"`
Role *ProfileRoleDTO `json:"role"`
Branches []ProfileBranchDTO `json:"branches"`
Permissions []ProfilePermissionDTO `json:"permissions"`
CreatedAt time.Time `json:"createdAt"`
}
type UpdateProfileDTO struct {

View File

@@ -7,6 +7,7 @@ import (
"online-back/internal/appresult"
"online-back/internal/handlers"
"online-back/internal/identity/rbac"
"online-back/pkg/logging"
"online-back/pkg/sms"
@@ -35,16 +36,16 @@ func NewHandler(logger *logging.Logger, repository Repository, sender sms.Sender
}
func (h *handler) Register(router *gin.RouterGroup) {
router.POST(loginURL, h.login)
router.POST(tokenURL, h.refreshToken)
router.POST(registerURL, h.register)
router.POST(verifyURL, h.verify)
router.POST(forgotPasswordURL, h.forgotPassword)
router.POST(resetPasswordURL, h.resetPassword)
rbac.Group(router, loginURL, rbac.Public()).POST("", h.login)
rbac.Group(router, tokenURL, rbac.Public()).POST("", h.refreshToken)
rbac.Group(router, registerURL, rbac.Public()).POST("", h.register)
rbac.Group(router, verifyURL, rbac.Public()).POST("", h.verify)
rbac.Group(router, forgotPasswordURL, rbac.Public()).POST("", h.forgotPassword)
rbac.Group(router, resetPasswordURL, rbac.Public()).POST("", h.resetPassword)
protected := router.Group("", appresult.JwtTokenCheck())
protected.GET(profileURL, h.getProfile)
protected.PUT(profileURL, h.updateProfile)
profile := rbac.Group(router, profileURL, rbac.Authenticated())
profile.GET("", h.getProfile)
profile.PUT("", h.updateProfile)
}
// login godoc
@@ -54,6 +55,7 @@ func (h *handler) Register(router *gin.RouterGroup) {
// @Accept json
// @Produce json
// @Param body body LoginDTO true "Login payload"
// @Param lang query string false "Language of localized fields; all returns the full {en, ru, tm} objects" Enums(tm, ru, en, all) default(tm)
// @Success 200 {object} appresult.AppSuccess
// @Failure 400 {object} appresult.AppError
// @Failure 401 {object} appresult.AppError
@@ -90,6 +92,7 @@ func (h *handler) login(c *gin.Context) {
// @Accept json
// @Produce json
// @Param body body RegisterDTO true "Registration payload"
// @Param lang query string false "Language of localized fields; all returns the full {en, ru, tm} objects" Enums(tm, ru, en, all) default(tm)
// @Success 200 {object} appresult.AppSuccess
// @Failure 400 {object} appresult.AppError
// @Failure 409 {object} appresult.AppError
@@ -117,6 +120,7 @@ func (h *handler) register(c *gin.Context) {
// @Accept json
// @Produce json
// @Param body body VerifyDTO true "Verification payload"
// @Param lang query string false "Language of localized fields; all returns the full {en, ru, tm} objects" Enums(tm, ru, en, all) default(tm)
// @Success 200 {object} appresult.AppSuccess
// @Failure 400 {object} appresult.AppError
// @Failure 409 {object} appresult.AppError
@@ -144,6 +148,7 @@ func (h *handler) verify(c *gin.Context) {
// @Accept json
// @Produce json
// @Param body body ForgotPasswordDTO true "Forgot password payload"
// @Param lang query string false "Language of localized fields; all returns the full {en, ru, tm} objects" Enums(tm, ru, en, all) default(tm)
// @Success 200 {object} appresult.AppSuccess
// @Failure 400 {object} appresult.AppError
// @Failure 404 {object} appresult.AppError
@@ -171,6 +176,7 @@ func (h *handler) forgotPassword(c *gin.Context) {
// @Accept json
// @Produce json
// @Param body body ResetPasswordDTO true "Reset password payload"
// @Param lang query string false "Language of localized fields; all returns the full {en, ru, tm} objects" Enums(tm, ru, en, all) default(tm)
// @Success 200 {object} appresult.AppSuccess
// @Failure 400 {object} appresult.AppError
// @Failure 404 {object} appresult.AppError
@@ -216,6 +222,7 @@ func (h *handler) respondRegisterError(c *gin.Context, err error) {
// @Accept json
// @Produce json
// @Param body body RefreshTokenDTO true "Refresh token payload"
// @Param lang query string false "Language of localized fields; all returns the full {en, ru, tm} objects" Enums(tm, ru, en, all) default(tm)
// @Success 200 {object} appresult.AppSuccess
// @Failure 400 {object} appresult.AppError
// @Failure 401 {object} appresult.AppError
@@ -242,10 +249,11 @@ func (h *handler) refreshToken(c *gin.Context) {
// getProfile godoc
// @Summary Get profile
// @Description Returns the authenticated user's profile
// @Description Returns the authenticated user's profile with role, branches, and permissions grouped by saha (module)
// @Tags auth
// @Produce json
// @Security BearerAuth
// @Param lang query string false "Language of localized fields; all returns the full {en, ru, tm} objects" Enums(tm, ru, en, all) default(tm)
// @Success 200 {object} appresult.AppSuccess
// @Failure 400 {object} appresult.AppError
// @Failure 401 {object} appresult.AppError
@@ -276,6 +284,7 @@ func (h *handler) getProfile(c *gin.Context) {
// @Produce json
// @Security BearerAuth
// @Param body body UpdateProfileDTO true "Profile payload"
// @Param lang query string false "Language of localized fields; all returns the full {en, ru, tm} objects" Enums(tm, ru, en, all) default(tm)
// @Success 200 {object} appresult.AppSuccess
// @Failure 400 {object} appresult.AppError
// @Failure 401 {object} appresult.AppError

View File

@@ -1,48 +0,0 @@
package auth
import "testing"
func TestNormalizePhone(t *testing.T) {
tests := []struct {
in, want string
}{
{"+99361531216", "+993 61 53 12 16"},
{"+993 61 92 92 48", "+993 61 92 92 48"},
{"+99361929248", "+993 61 92 92 48"},
{"99361929248", "+993 61 92 92 48"},
{"61929248", "+993 61 92 92 48"},
{"8 61929248", "+993 61 92 92 48"},
{"61 92 92 48", "+993 61 92 92 48"},
}
for _, tt := range tests {
got, err := NormalizePhone(tt.in)
if err != nil {
t.Fatalf("NormalizePhone(%q) unexpected error: %v", tt.in, err)
}
if got != tt.want {
t.Errorf("NormalizePhone(%q) = %q, want %q", tt.in, got, tt.want)
}
}
if _, err := NormalizePhone("123"); err != ErrInvalidPhone {
t.Errorf("NormalizePhone(123) error = %v, want ErrInvalidPhone", err)
}
validPrefixes := []string{"61", "62", "63", "64", "65", "71", "72"}
for _, prefix := range validPrefixes {
in := prefix + "929248"
if _, err := NormalizePhone(in); err != nil {
t.Errorf("NormalizePhone(%q) unexpected error: %v", in, err)
}
}
invalid := []string{
"60929248", "66929248", "70929248", "73929248", "81929248",
"+99366531216", "+99360929248",
}
for _, in := range invalid {
if _, err := NormalizePhone(in); err != ErrInvalidPhone {
t.Errorf("NormalizePhone(%q) error = %v, want ErrInvalidPhone", in, err)
}
}
}

View File

@@ -1,293 +0,0 @@
package auth
import (
"context"
"errors"
"strings"
"testing"
"time"
"golang.org/x/crypto/bcrypt"
)
type fakeRepo struct {
exists bool
usernameTaken bool
verification Verification
getErr error
userID int
userByName UserIdentity
userByNameErr error
loginUser UserCredentials
loginErr error
lastLogin LoginDTO
}
func (f *fakeRepo) Login(_ context.Context, dto LoginDTO) (UserCredentials, error) {
f.lastLogin = dto
if f.loginErr != nil {
return UserCredentials{}, f.loginErr
}
return f.loginUser, nil
}
func (f *fakeRepo) GetUserByID(context.Context, int) (UserCredentials, error) {
return UserCredentials{}, errors.New("not implemented")
}
func (f *fakeRepo) GetProfile(context.Context, int) (UserProfileDTO, error) {
return UserProfileDTO{}, errors.New("not implemented")
}
func (f *fakeRepo) UpdateProfile(context.Context, int, UpdateProfileDTO) (UserProfileDTO, error) {
return UserProfileDTO{}, errors.New("not implemented")
}
func (f *fakeRepo) UserExists(context.Context, string, string) (bool, error) {
return f.exists, nil
}
func (f *fakeRepo) UsernameTaken(context.Context, string, string) (bool, error) {
return f.usernameTaken, nil
}
func (f *fakeRepo) UpsertVerification(_ context.Context, v Verification) error {
f.verification = v
return nil
}
func (f *fakeRepo) GetVerificationByPhone(context.Context, string) (Verification, error) {
return f.verification, f.getErr
}
func (f *fakeRepo) IncrementVerifyAttempts(context.Context, int64) error {
f.verification.Attempts++
return nil
}
func (f *fakeRepo) CompleteRegistration(context.Context, Verification) (int, error) {
return f.userID, nil
}
func (f *fakeRepo) GetUserByName(context.Context, string) (UserIdentity, error) {
if f.userByNameErr != nil {
return UserIdentity{}, f.userByNameErr
}
return f.userByName, nil
}
func (f *fakeRepo) CompletePasswordReset(context.Context, int, int64, string) error {
return nil
}
type fakeSMS struct {
phone, message string
err error
}
func (f *fakeSMS) Send(_ context.Context, phone, message string) error {
f.phone = phone
f.message = message
return f.err
}
func validRegisterDTO() RegisterDTO {
return RegisterDTO{
Name: "Berdi Berdiyew",
Phone: "+993 61 92 92 48",
Username: "berdi",
Password: "secret1",
PasswordConfirm: "secret1",
}
}
func TestLoginRequiresNameOrPhone(t *testing.T) {
_, err := NewService(&fakeRepo{}, &fakeSMS{}).Login(context.Background(), LoginDTO{
Password: "secret1",
})
if !errors.Is(err, ErrInvalidInput) {
t.Fatalf("error = %v, want ErrInvalidInput", err)
}
}
func TestLoginIgnoresInvalidPhoneWhenNamePresent(t *testing.T) {
repo := &fakeRepo{loginErr: errors.New("stop after lookup")}
_, _ = NewService(repo, &fakeSMS{}).Login(context.Background(), LoginDTO{
Name: "admin",
Phone: "string",
Password: "Test1234!",
})
if repo.lastLogin.Name != "admin" {
t.Fatalf("name = %q, want admin", repo.lastLogin.Name)
}
if repo.lastLogin.Phone != "" {
t.Fatalf("phone = %q, want empty", repo.lastLogin.Phone)
}
}
func TestLoginInvalidPhoneWithoutName(t *testing.T) {
_, err := NewService(&fakeRepo{}, &fakeSMS{}).Login(context.Background(), LoginDTO{
Phone: "string",
Password: "secret1",
})
if !errors.Is(err, ErrInvalidInput) {
t.Fatalf("error = %v, want ErrInvalidInput", err)
}
}
func TestLoginWrongPassword(t *testing.T) {
hash, err := bcrypt.GenerateFromPassword([]byte("secret1"), bcrypt.MinCost)
if err != nil {
t.Fatal(err)
}
_, err = NewService(&fakeRepo{loginUser: UserCredentials{Id: 7, Password: string(hash)}}, &fakeSMS{}).Login(context.Background(), LoginDTO{
Name: "Berdi Berdiyew",
Password: "wrong",
})
if !errors.Is(err, ErrInvalidCredentials) {
t.Fatalf("error = %v, want ErrInvalidCredentials", err)
}
}
func TestRegisterPasswordMismatch(t *testing.T) {
dto := validRegisterDTO()
dto.PasswordConfirm = "other"
_, err := NewService(&fakeRepo{}, &fakeSMS{}).Register(context.Background(), dto)
if !errors.Is(err, ErrPasswordMismatch) {
t.Fatalf("error = %v, want ErrPasswordMismatch", err)
}
}
func TestRegisterConflict(t *testing.T) {
_, err := NewService(&fakeRepo{exists: true}, &fakeSMS{}).Register(context.Background(), validRegisterDTO())
if !errors.Is(err, ErrConflict) {
t.Fatalf("error = %v, want ErrConflict", err)
}
}
func TestRegisterSendsSMS(t *testing.T) {
repo := &fakeRepo{}
sender := &fakeSMS{}
result, err := NewService(repo, sender).Register(context.Background(), validRegisterDTO())
if err != nil {
t.Fatalf("Register: %v", err)
}
if result.Phone != "+993 61 92 92 48" {
t.Errorf("phone = %q", result.Phone)
}
if result.ExpiresIn != 60 {
t.Errorf("expiresIn = %d", result.ExpiresIn)
}
if sender.phone != result.Phone {
t.Errorf("sms phone = %q", sender.phone)
}
if !strings.Contains(sender.message, "123456") {
t.Errorf("sms message = %q", sender.message)
}
if repo.verification.Password == "secret1" {
t.Fatal("password stored in plaintext")
}
}
func TestVerifyWrongCode(t *testing.T) {
hash, err := bcrypt.GenerateFromPassword([]byte("123456"), bcrypt.MinCost)
if err != nil {
t.Fatal(err)
}
repo := &fakeRepo{verification: Verification{
ID: 1,
Phone: "+993 61 92 92 48",
CodeHash: string(hash),
ExpiresAt: time.Now().UTC().Add(time.Minute),
}}
_, err = NewService(repo, &fakeSMS{}).Verify(context.Background(), VerifyDTO{
Phone: "+993 61 92 92 48",
Code: "000000",
})
if !errors.Is(err, ErrInvalidCode) {
t.Fatalf("error = %v, want ErrInvalidCode", err)
}
if repo.verification.Attempts != 1 {
t.Errorf("attempts = %d, want 1", repo.verification.Attempts)
}
}
func TestVerifyExpiredCode(t *testing.T) {
repo := &fakeRepo{verification: Verification{
ExpiresAt: time.Now().UTC().Add(-time.Minute),
}}
_, err := NewService(repo, &fakeSMS{}).Verify(context.Background(), VerifyDTO{
Phone: "+993 61 92 92 48",
Code: "123456",
})
if !errors.Is(err, ErrInvalidCode) {
t.Fatalf("error = %v, want ErrInvalidCode", err)
}
}
func TestForgotPasswordRequiresName(t *testing.T) {
_, err := NewService(&fakeRepo{}, &fakeSMS{}).ForgotPassword(context.Background(), ForgotPasswordDTO{})
if !errors.Is(err, ErrInvalidInput) {
t.Fatalf("error = %v, want ErrInvalidInput", err)
}
}
func TestForgotPasswordNotFound(t *testing.T) {
_, err := NewService(&fakeRepo{userByNameErr: ErrNotFound}, &fakeSMS{}).ForgotPassword(context.Background(), ForgotPasswordDTO{
Name: "Berdi Berdiyew",
})
if !errors.Is(err, ErrNotFound) {
t.Fatalf("error = %v, want ErrNotFound", err)
}
}
func TestForgotPasswordSendsSMS(t *testing.T) {
repo := &fakeRepo{userByName: UserIdentity{
Id: 7,
Name: "Berdi Berdiyew",
Username: "berdi",
Phone: "+993 61 92 92 48",
}}
sender := &fakeSMS{}
result, err := NewService(repo, sender).ForgotPassword(context.Background(), ForgotPasswordDTO{
Name: "Berdi Berdiyew",
})
if err != nil {
t.Fatalf("ForgotPassword: %v", err)
}
if result.Phone != "+993 61 92 92 48" {
t.Errorf("phone = %q", result.Phone)
}
if sender.phone != result.Phone {
t.Errorf("sms phone = %q", sender.phone)
}
if !strings.Contains(sender.message, "123456") {
t.Errorf("sms message = %q", sender.message)
}
}
func TestResetPasswordMismatch(t *testing.T) {
_, err := NewService(&fakeRepo{}, &fakeSMS{}).ResetPassword(context.Background(), ResetPasswordDTO{
Name: "Berdi Berdiyew",
Code: "123456",
Password: "secret1",
PasswordConfirm: "other",
})
if !errors.Is(err, ErrPasswordMismatch) {
t.Fatalf("error = %v, want ErrPasswordMismatch", err)
}
}
func TestResetPasswordWrongCode(t *testing.T) {
hash, err := bcrypt.GenerateFromPassword([]byte("123456"), bcrypt.MinCost)
if err != nil {
t.Fatal(err)
}
repo := &fakeRepo{
userByName: UserIdentity{Id: 7, Phone: "+993 61 92 92 48"},
verification: Verification{
ID: 1,
Phone: "+993 61 92 92 48",
CodeHash: string(hash),
ExpiresAt: time.Now().UTC().Add(time.Minute),
},
}
_, err = NewService(repo, &fakeSMS{}).ResetPassword(context.Background(), ResetPasswordDTO{
Name: "Berdi Berdiyew",
Code: "000000",
Password: "secret1",
PasswordConfirm: "secret1",
})
if !errors.Is(err, ErrInvalidCode) {
t.Fatalf("error = %v, want ErrInvalidCode", err)
}
}

View File

@@ -1,108 +0,0 @@
package db
import (
"context"
"errors"
"fmt"
"strings"
"online-back/internal/identity/permission"
"online-back/pkg/client/postgresql"
"online-back/pkg/logging"
"online-back/pkg/repository/genericrepo"
"github.com/jackc/pgx/v4"
)
type repository struct {
client postgresql.Client
generic *genericrepo.Repository[permission.PermissionDTO]
logger *logging.Logger
}
func NewRepository(client postgresql.Client, logger *logging.Logger) permission.Repository {
return &repository{
client: client,
generic: genericrepo.New(client, "permissions p", permissionColumns, scanPermission),
logger: logger,
}
}
const permissionColumns = `p.id, p.code, p.name, p.guard_name, p.created_at, p.updated_at`
const permissionReturningColumns = `id, code, name, guard_name, created_at, updated_at`
func (r *repository) List(ctx context.Context, filter permission.ListFilter) (permission.ListPermissionDTO, error) {
whereClause, args := buildListQuery(filter)
items, count, err := r.generic.List(ctx, whereClause, args, filter.Page, filter.Limit, "id")
if err != nil {
return permission.ListPermissionDTO{}, err
}
return permission.ListPermissionDTO{Count: count, Permissions: items}, nil
}
func buildListQuery(filter permission.ListFilter) (whereClause string, args []interface{}) {
var conditions []string
if filter.PermissionName != "" {
args = append(args, likePattern(filter.PermissionName))
n := len(args)
conditions = append(conditions, fmt.Sprintf(`p.name ILIKE $%d`, n))
}
if len(conditions) == 0 {
return "", args
}
return " WHERE " + strings.Join(conditions, " AND "), args
}
func likePattern(term string) string {
term = strings.ReplaceAll(term, `\`, `\\`)
term = strings.ReplaceAll(term, `%`, `\%`)
term = strings.ReplaceAll(term, `_`, `\_`)
return "%" + term + "%"
}
func (r *repository) GetByID(ctx context.Context, id int64) (permission.PermissionDTO, error) {
return r.generic.GetByID(ctx, id)
}
func (r *repository) Create(ctx context.Context, dto permission.CreatePermissionDTO) (permission.PermissionDTO, error) {
query := fmt.Sprintf(`
INSERT INTO permissions (code, name, guard_name)
VALUES ($1, $2, $3)
RETURNING %s`, permissionReturningColumns)
return scanPermission(r.client.QueryRow(ctx, query, dto.Code, dto.Name, dto.GuardName))
}
func (r *repository) Update(ctx context.Context, id int64, dto permission.UpdatePermissionDTO) (permission.PermissionDTO, error) {
query := fmt.Sprintf(`
UPDATE permissions SET
code = $1, name = $2, guard_name = $3,
updated_at = (CURRENT_TIMESTAMP AT TIME ZONE 'UTC')
WHERE id = $4
RETURNING %s`, permissionReturningColumns)
item, err := scanPermission(r.client.QueryRow(ctx, query, dto.Code, dto.Name, dto.GuardName, id))
if errors.Is(err, pgx.ErrNoRows) {
return permission.PermissionDTO{}, err
}
return item, err
}
func (r *repository) Delete(ctx context.Context, id int64) error {
return r.generic.Delete(ctx, id)
}
func scanPermission(row genericrepo.Scanner) (permission.PermissionDTO, error) {
var item permission.PermissionDTO
if err := row.Scan(
&item.Id, &item.Code, &item.Name, &item.GuardName, &item.CreatedAt, &item.UpdatedAt,
); err != nil {
return permission.PermissionDTO{}, err
}
return item, nil
}

Some files were not shown because too many files have changed in this diff Show More