Compare commits
56
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
72a5ac52b0 | ||
|
|
c6540a658b | ||
|
|
f067872cd7 | ||
|
|
6dd6110914 | ||
|
|
a3cbb52f4b | ||
|
|
ef3a1baee2 | ||
|
|
ae6bf0b7e3 | ||
|
|
c209f338c2 | ||
|
|
a715cd23ea | ||
|
|
e5f01d0e94 | ||
|
|
965b00dba5 | ||
|
|
29867561d1 | ||
|
|
ebedeba009 | ||
|
|
7e403dab13 | ||
|
|
60787c8149 | ||
|
|
3b33e25703 | ||
|
|
0de3900ed1 | ||
|
|
94eb2aa4e9 | ||
|
|
27ad42528c | ||
|
|
15774d2bc4 | ||
|
|
69d1495b1f | ||
|
|
a44c10d445 | ||
|
|
68ead82827 | ||
|
|
4f3631c70d | ||
|
|
6f54e9c20b | ||
|
|
5ab17b1539 | ||
|
|
19a1f70588 | ||
|
|
8b73df4435 | ||
|
|
0058411cdd | ||
|
|
e47e8c24d0 | ||
|
|
c01429d2a4 | ||
|
|
323e131216 | ||
|
|
f0ecf23879 | ||
|
|
d6a1053003 | ||
|
|
205aaafc63 | ||
|
|
f2b55f9896 | ||
|
|
ac94e0dd8a | ||
|
|
235ef5ec9e | ||
|
|
febd190d6e | ||
|
|
99788a853f | ||
|
|
23d208769c | ||
|
|
f42ad01828 | ||
|
|
87e4b33322 | ||
|
|
45378559ca | ||
|
|
599c12ef87 | ||
|
|
6c7c402390 | ||
|
|
848a07324f | ||
|
|
c6b9cb7462 | ||
|
|
b8455625b5 | ||
|
|
0971158e98 | ||
|
|
d3e188affe | ||
|
|
e0d03730de | ||
|
|
d1a6fcaadc | ||
|
|
28509eb4ca | ||
|
|
0d000f9af6 | ||
|
|
6683826662 |
No files matched your search
+11
-1
@@ -1,16 +1,26 @@
|
||||
.git
|
||||
.github
|
||||
.cursor
|
||||
.claude
|
||||
.DS_Store
|
||||
logs
|
||||
tmp
|
||||
temp
|
||||
vendor
|
||||
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
|
||||
@@ -82,3 +82,35 @@ jobs:
|
||||
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' }}
|
||||
@@ -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/
|
||||
@@ -74,3 +77,6 @@ bank_db_schema.drawio
|
||||
# Debug
|
||||
__debug_bin
|
||||
debug
|
||||
|
||||
# Docker image bundles (make docker-bundle)
|
||||
dist/
|
||||
+25
-16
@@ -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"]
|
||||
@@ -12,10 +12,54 @@ migrate:
|
||||
migrate-rollback:
|
||||
migrate -database 'postgres://bank_admin:bank%40%2323%23%40_password@localhost:5424/bank_db?sslmode=disable' -path db/migrations down
|
||||
seed:
|
||||
docker exec -i main-db psql -U bank_admin -d bank_db -f - < db/mock/seed.sql
|
||||
docker exec -i main-db psql -U bank_admin -d bank_db -f - < db/seed.sql
|
||||
|
||||
# ---- for linux
|
||||
# migrate:
|
||||
# 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
|
||||
@@ -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
|
||||
|
||||
+1
-1
@@ -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 | |
|
||||
|
||||
@@ -21,7 +21,7 @@ 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
|
||||
@@ -46,17 +46,23 @@ 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-payment-orders
|
||||
// @tag.description Visa/Master student-transfer payment orders
|
||||
// @tag.name backups
|
||||
// @tag.description Database SQL backups
|
||||
// @tag.name currencies
|
||||
// @tag.description Currency exchange rates
|
||||
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"}
|
||||
|
||||
+2
-1
@@ -18,4 +18,5 @@ minio:
|
||||
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)
|
||||
@@ -1,3 +1,51 @@
|
||||
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;
|
||||
@@ -13,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_role;
|
||||
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;
|
||||
@@ -1,3 +1,57 @@
|
||||
-- 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 '',
|
||||
@@ -10,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,
|
||||
@@ -37,57 +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
|
||||
);
|
||||
|
||||
INSERT INTO roles (code, name, guard_name)
|
||||
SELECT 'user', 'User', 'web'
|
||||
WHERE NOT EXISTS (SELECT 1 FROM roles WHERE code = 'user');
|
||||
|
||||
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_role (
|
||||
id bigserial PRIMARY KEY,
|
||||
permission_id bigint REFERENCES permissions(id),
|
||||
role_id bigint REFERENCES roles(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,
|
||||
CONSTRAINT permission_role_permission_id_role_id_key UNIQUE (permission_id, role_id)
|
||||
);
|
||||
|
||||
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 '',
|
||||
@@ -104,18 +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
|
||||
);
|
||||
|
||||
-- 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,
|
||||
@@ -123,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 (
|
||||
@@ -133,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 (
|
||||
@@ -144,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 (
|
||||
@@ -153,7 +186,8 @@ 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
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS cards (
|
||||
@@ -166,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)
|
||||
);
|
||||
@@ -203,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
|
||||
@@ -236,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
|
||||
@@ -250,7 +287,7 @@ CREATE TABLE IF NOT EXISTS loan_orders (
|
||||
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,6 +390,7 @@ 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
|
||||
@@ -383,8 +423,10 @@ CREATE TABLE IF NOT EXISTS visa_master_payment_orders (
|
||||
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
|
||||
@@ -409,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();
|
||||
@@ -1,3 +0,0 @@
|
||||
ALTER TABLE card_pin_orders
|
||||
ALTER COLUMN region TYPE character varying(2)
|
||||
USING LEFT(region, 2);
|
||||
@@ -1,2 +0,0 @@
|
||||
ALTER TABLE card_pin_orders
|
||||
ALTER COLUMN region TYPE character varying(255);
|
||||
@@ -0,0 +1 @@
|
||||
DROP INDEX IF EXISTS idx_visa_master_order_payments_status_id;
|
||||
@@ -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;
|
||||
@@ -0,0 +1 @@
|
||||
DROP INDEX IF EXISTS visa_master_payment_logs_order_step_idx;
|
||||
@@ -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);
|
||||
@@ -1,711 +0,0 @@
|
||||
-- Dev / staging mock data. Re-runnable: wipes app tables then reloads.
|
||||
-- Usage: PGPASSWORD='bank@#23#@_password' psql -h localhost -p 5424 -U bank_admin -d bank_db -f db/mock/seed.sql
|
||||
-- Login (password = test1234):
|
||||
-- superadmin@bank.tm / +993 61 92 92 48
|
||||
-- admin@bank.tm
|
||||
-- manager@bank.tm
|
||||
-- operator@bank.tm
|
||||
-- serdar@bank.tm … leyla@bank.tm (role=user)
|
||||
|
||||
BEGIN;
|
||||
|
||||
TRUNCATE TABLE
|
||||
activity_logs,
|
||||
visa_master_payment_orders,
|
||||
loan_paid_off_letters,
|
||||
loans,
|
||||
loan_orders,
|
||||
card_pin_orders,
|
||||
card_orders,
|
||||
cards,
|
||||
loan_order_required_docs,
|
||||
loan_types,
|
||||
card_states,
|
||||
card_types,
|
||||
branch_user,
|
||||
branches,
|
||||
provinces,
|
||||
permission_role,
|
||||
role_user,
|
||||
permissions,
|
||||
roles,
|
||||
registration_verifications,
|
||||
users
|
||||
RESTART IDENTITY CASCADE;
|
||||
|
||||
-- ---------------------------------------------------------------------------
|
||||
-- Users (10): superadmin, admin, manager, operator,
|
||||
-- 1 branch-assigned user (serdar), 5 users (gulnar…leyla).
|
||||
-- Password = test1234 for all. Phone unique (idx_users_phone).
|
||||
-- ---------------------------------------------------------------------------
|
||||
INSERT INTO users (email, password, name, first_name, last_name, username, phone, role, active) VALUES
|
||||
(
|
||||
'superadmin@bank.tm',
|
||||
'$2a$12$.9KVj6x7wxUMdPcBJ6UpweYbzW4Mka0d2mQj7O20YHXpBKlb3ypdC',
|
||||
'Super Admin', 'Myrat', 'Nazarow', 'superadmin',
|
||||
'+993 61 92 92 48', 'superadmin', true
|
||||
),
|
||||
(
|
||||
'admin@bank.tm',
|
||||
'$2a$12$.9KVj6x7wxUMdPcBJ6UpweYbzW4Mka0d2mQj7O20YHXpBKlb3ypdC',
|
||||
'Admin', 'Nurmuhammet', 'Allanow', 'admin',
|
||||
'+993 61 92 92 41', 'admin', true
|
||||
),
|
||||
(
|
||||
'manager@bank.tm',
|
||||
'$2a$12$.9KVj6x7wxUMdPcBJ6UpweYbzW4Mka0d2mQj7O20YHXpBKlb3ypdC',
|
||||
'Branch Manager', 'Mergen', 'Berdiyew', 'manager',
|
||||
'+993 61 92 92 42', 'manager', true
|
||||
),
|
||||
(
|
||||
'operator@bank.tm',
|
||||
'$2a$12$.9KVj6x7wxUMdPcBJ6UpweYbzW4Mka0d2mQj7O20YHXpBKlb3ypdC',
|
||||
'Operator', 'Aygul', 'Hojayeva', 'operator',
|
||||
'+993 61 92 92 43', 'operator', true
|
||||
),
|
||||
(
|
||||
'serdar@bank.tm',
|
||||
'$2a$12$.9KVj6x7wxUMdPcBJ6UpweYbzW4Mka0d2mQj7O20YHXpBKlb3ypdC',
|
||||
'Serdar Myradow', 'Serdar', 'Myradow', 'serdar',
|
||||
'+993 61 92 92 44', 'user', true
|
||||
),
|
||||
(
|
||||
'gulnar@bank.tm',
|
||||
'$2a$12$.9KVj6x7wxUMdPcBJ6UpweYbzW4Mka0d2mQj7O20YHXpBKlb3ypdC',
|
||||
'Gulnar Orazowa', 'Gulnar', 'Orazowa', 'gulnar',
|
||||
'+993 61 92 92 45', 'user', true
|
||||
),
|
||||
(
|
||||
'dovran@bank.tm',
|
||||
'$2a$12$.9KVj6x7wxUMdPcBJ6UpweYbzW4Mka0d2mQj7O20YHXpBKlb3ypdC',
|
||||
'Dovran Annayew', 'Dovran', 'Annayew', 'dovran',
|
||||
'+993 61 92 92 46', 'user', true
|
||||
),
|
||||
(
|
||||
'maya@bank.tm',
|
||||
'$2a$12$.9KVj6x7wxUMdPcBJ6UpweYbzW4Mka0d2mQj7O20YHXpBKlb3ypdC',
|
||||
'Maya Halylowa', 'Maya', 'Halylowa', 'maya',
|
||||
'+993 61 92 92 47', 'user', true
|
||||
),
|
||||
(
|
||||
'kerim@bank.tm',
|
||||
'$2a$12$.9KVj6x7wxUMdPcBJ6UpweYbzW4Mka0d2mQj7O20YHXpBKlb3ypdC',
|
||||
'Kerim Atayew', 'Kerim', 'Atayew', 'kerim',
|
||||
'+993 61 92 92 49', 'user', true
|
||||
),
|
||||
(
|
||||
'leyla@bank.tm',
|
||||
'$2a$12$.9KVj6x7wxUMdPcBJ6UpweYbzW4Mka0d2mQj7O20YHXpBKlb3ypdC',
|
||||
'Leyla Gurbanowa', 'Leyla', 'Gurbanowa', 'leyla',
|
||||
'+993 61 92 92 40', 'user', true
|
||||
);
|
||||
|
||||
-- ---------------------------------------------------------------------------
|
||||
-- Roles & permissions
|
||||
-- ---------------------------------------------------------------------------
|
||||
INSERT INTO roles (code, name, guard_name) VALUES
|
||||
('superadmin', 'Super Administrator', 'admin'),
|
||||
('admin', 'Administrator', 'admin'),
|
||||
('manager', 'Branch Manager', 'admin'),
|
||||
('operator', 'Operator', 'admin'),
|
||||
('user', 'User', 'web');
|
||||
|
||||
INSERT INTO permissions (code, name, guard_name) VALUES
|
||||
('users.view', 'View users', 'admin'),
|
||||
('users.manage', 'Manage users', 'admin'),
|
||||
('roles.view', 'View roles', 'admin'),
|
||||
('roles.manage', 'Manage roles', 'admin'),
|
||||
('branches.view', 'View branches', 'admin'),
|
||||
('branches.manage', 'Manage branches', 'admin'),
|
||||
('provinces.view', 'View provinces', 'admin'),
|
||||
('provinces.manage', 'Manage provinces', 'admin'),
|
||||
('cards.view', 'View cards', 'admin'),
|
||||
('cards.manage', 'Manage cards', 'admin'),
|
||||
('card-orders.view', 'View card orders', 'admin'),
|
||||
('card-orders.manage', 'Manage card orders', 'admin'),
|
||||
('loans.view', 'View loans', 'admin'),
|
||||
('loans.manage', 'Manage loans', 'admin'),
|
||||
('activity-logs.view', 'View activity logs', 'admin');
|
||||
|
||||
INSERT INTO role_user (role_id, user_id)
|
||||
SELECT r.id, u.id
|
||||
FROM users u
|
||||
JOIN roles r ON r.code = u.role;
|
||||
|
||||
INSERT INTO permission_role (permission_id, role_id)
|
||||
SELECT p.id, r.id
|
||||
FROM permissions p
|
||||
JOIN roles r ON r.code IN ('superadmin', 'admin');
|
||||
|
||||
INSERT INTO permission_role (permission_id, role_id)
|
||||
SELECT p.id, r.id
|
||||
FROM permissions p
|
||||
JOIN roles r ON r.code = 'manager'
|
||||
WHERE p.code IN (
|
||||
'branches.view', 'provinces.view', 'cards.view',
|
||||
'card-orders.view', 'card-orders.manage', 'loans.view', 'loans.manage'
|
||||
);
|
||||
|
||||
INSERT INTO permission_role (permission_id, role_id)
|
||||
SELECT p.id, r.id
|
||||
FROM permissions p
|
||||
JOIN roles r ON r.code = 'operator'
|
||||
WHERE p.code IN (
|
||||
'card-orders.view', 'loans.view', 'cards.view', 'branches.view'
|
||||
);
|
||||
|
||||
-- ---------------------------------------------------------------------------
|
||||
-- Provinces (Turkmenistan) — name = etrap, region = welaýat
|
||||
-- ---------------------------------------------------------------------------
|
||||
INSERT INTO provinces (name, region, active) VALUES
|
||||
-- Paýtagt
|
||||
(
|
||||
'{"en":"Ashgabat","ru":"Ашхабад","tm":"Aşgabat"}'::json,
|
||||
'{"en":"Capital","ru":"Столица","tm":"Paýtagt"}'::json,
|
||||
true
|
||||
),
|
||||
-- Ahal welaýaty
|
||||
(
|
||||
'{"en":"Anew","ru":"Анев","tm":"Änew"}'::json,
|
||||
'{"en":"Ahal Region","ru":"Ахалский велаят","tm":"Ahal welaýaty"}'::json,
|
||||
true
|
||||
),
|
||||
(
|
||||
'{"en":"Gokdepe","ru":"Гокдепе","tm":"Gökdepe"}'::json,
|
||||
'{"en":"Ahal Region","ru":"Ахалский велаят","tm":"Ahal welaýaty"}'::json,
|
||||
true
|
||||
),
|
||||
(
|
||||
'{"en":"Tejen","ru":"Теджен","tm":"Tejen"}'::json,
|
||||
'{"en":"Ahal Region","ru":"Ахалский велаят","tm":"Ahal welaýaty"}'::json,
|
||||
true
|
||||
),
|
||||
-- Balkan welaýaty
|
||||
(
|
||||
'{"en":"Balkanabat","ru":"Балканабад","tm":"Balkanabat"}'::json,
|
||||
'{"en":"Balkan Region","ru":"Балканский велаят","tm":"Balkan welaýaty"}'::json,
|
||||
true
|
||||
),
|
||||
(
|
||||
'{"en":"Turkmenbashy","ru":"Туркменбаши","tm":"Türkmenbaşy"}'::json,
|
||||
'{"en":"Balkan Region","ru":"Балканский велаят","tm":"Balkan welaýaty"}'::json,
|
||||
true
|
||||
),
|
||||
(
|
||||
'{"en":"Serdar","ru":"Сердар","tm":"Serdar"}'::json,
|
||||
'{"en":"Balkan Region","ru":"Балканский велаят","tm":"Balkan welaýaty"}'::json,
|
||||
true
|
||||
),
|
||||
-- Daşoguz welaýaty
|
||||
(
|
||||
'{"en":"Dashoguz","ru":"Дашогуз","tm":"Daşoguz"}'::json,
|
||||
'{"en":"Dashoguz Region","ru":"Дашогузский велаят","tm":"Daşoguz welaýaty"}'::json,
|
||||
true
|
||||
),
|
||||
(
|
||||
'{"en":"Koneurgench","ru":"Кёнеургенч","tm":"Köneürgenç"}'::json,
|
||||
'{"en":"Dashoguz Region","ru":"Дашогузский велаят","tm":"Daşoguz welaýaty"}'::json,
|
||||
true
|
||||
),
|
||||
-- Lebap welaýaty
|
||||
(
|
||||
'{"en":"Turkmenabat","ru":"Туркменабад","tm":"Türkmenabat"}'::json,
|
||||
'{"en":"Lebap Region","ru":"Лебапский велаят","tm":"Lebap welaýaty"}'::json,
|
||||
true
|
||||
),
|
||||
(
|
||||
'{"en":"Farap","ru":"Фарап","tm":"Farap"}'::json,
|
||||
'{"en":"Lebap Region","ru":"Лебапский велаят","tm":"Lebap welaýaty"}'::json,
|
||||
true
|
||||
),
|
||||
-- Mary welaýaty
|
||||
(
|
||||
'{"en":"Mary","ru":"Мары","tm":"Mary"}'::json,
|
||||
'{"en":"Mary Region","ru":"Марыйский велаят","tm":"Mary welaýaty"}'::json,
|
||||
true
|
||||
),
|
||||
(
|
||||
'{"en":"Bayramaly","ru":"Байрамали","tm":"Baýramaly"}'::json,
|
||||
'{"en":"Mary Region","ru":"Марыйский велаят","tm":"Mary welaýaty"}'::json,
|
||||
true
|
||||
),
|
||||
(
|
||||
'{"en":"Yoloten","ru":"Ёлётен","tm":"Ýolöten"}'::json,
|
||||
'{"en":"Mary Region","ru":"Марыйский велаят","tm":"Mary welaýaty"}'::json,
|
||||
true
|
||||
);
|
||||
|
||||
-- ---------------------------------------------------------------------------
|
||||
-- Branches
|
||||
-- ---------------------------------------------------------------------------
|
||||
INSERT INTO branches (
|
||||
unique_code, name, address, region, province_id, phone_numbers,
|
||||
billing_username, billing_password, active
|
||||
) VALUES
|
||||
(
|
||||
'AGB-01',
|
||||
'{"en":"Ashgabat Central Branch","ru":"Центральный филиал Ашхабад","tm":"Aşgabat Merkezi şahamça"}'::json,
|
||||
'{"en":"Archabil Ave 1","ru":"пр. Арчабиль 1","tm":"Arçabil şaýoly 1"}'::json,
|
||||
'AG', 1, '+993 61 92 92 48', 'billing_agb', 'billing_pass', true
|
||||
),
|
||||
(
|
||||
'AGB-02',
|
||||
'{"en":"Ashgabat Kopetdag Branch","ru":"Филиал Копетдаг","tm":"Köpetdag şahamçasy"}'::json,
|
||||
'{"en":"Turkmenbashy Ave 45","ru":"пр. Туркменбаши 45","tm":"Türkmenbaşy şaýoly 45"}'::json,
|
||||
'AG', 1, '+993 61 92 92 48', 'billing_agb2', 'billing_pass', true
|
||||
),
|
||||
(
|
||||
'AHL-01',
|
||||
'{"en":"Ahal Branch","ru":"Ахалский филиал","tm":"Ahal şahamçasy"}'::json,
|
||||
'{"en":"Anew, Main St 10","ru":"Анев, ул. Главная 10","tm":"Änew, Baş köçe 10"}'::json,
|
||||
'AH', 2, '+993 61 92 92 48', 'billing_ahl', 'billing_pass', true
|
||||
),
|
||||
(
|
||||
'BLK-01',
|
||||
'{"en":"Balkanabat Branch","ru":"Филиал Балканабад","tm":"Balkanabat şahamçasy"}'::json,
|
||||
'{"en":"Garaşsyzlyk St 7","ru":"ул. Гарашсызлык 7","tm":"Garaşsyzlyk köçesi 7"}'::json,
|
||||
'BL', 5, '+993 61 92 92 48', 'billing_blk', 'billing_pass', true
|
||||
),
|
||||
(
|
||||
'DSZ-01',
|
||||
'{"en":"Dashoguz Branch","ru":"Филиал Дашогуз","tm":"Daşoguz şahamçasy"}'::json,
|
||||
'{"en":"Galkynyş St 3","ru":"ул. Галкыныш 3","tm":"Galkynyş köçesi 3"}'::json,
|
||||
'DZ', 8, '+993 61 92 92 48', 'billing_dsz', 'billing_pass', true
|
||||
),
|
||||
(
|
||||
'LBP-01',
|
||||
'{"en":"Turkmenabat Branch","ru":"Филиал Туркменабад","tm":"Türkmenabat şahamçasy"}'::json,
|
||||
'{"en":"Magtymguly Ave 12","ru":"пр. Махтумкули 12","tm":"Magtymguly şaýoly 12"}'::json,
|
||||
'LB', 10, '+993 61 92 92 48', 'billing_lbp', 'billing_pass', true
|
||||
),
|
||||
(
|
||||
'MRY-01',
|
||||
'{"en":"Mary Branch","ru":"Марыйский филиал","tm":"Mary şahamçasy"}'::json,
|
||||
'{"en":"Mollanepes St 8","ru":"ул. Молланепес 8","tm":"Mollanepes köçesi 8"}'::json,
|
||||
'MR', 12, '+993 61 92 92 48', 'billing_mry', 'billing_pass', true
|
||||
),
|
||||
(
|
||||
'MRY-02',
|
||||
'{"en":"Bayramaly Branch (inactive)","ru":"Филиал Байрамали (неактивен)","tm":"Baýramaly şahamçasy (işjeň däl)"}'::json,
|
||||
'{"en":"Bayramaly, Central 1","ru":"Байрамали, Центральная 1","tm":"Baýramaly, Merkezi 1"}'::json,
|
||||
'MR', 13, '+993 61 92 92 48', 'billing_mry2', 'billing_pass', false
|
||||
);
|
||||
|
||||
INSERT INTO branch_user (branch_id, user_id) VALUES
|
||||
(1, 1),
|
||||
(1, 2),
|
||||
(1, 3),
|
||||
(7, 4),
|
||||
(2, 5);
|
||||
|
||||
-- ---------------------------------------------------------------------------
|
||||
-- Card types (payment-cards) & card states (reasons-cards)
|
||||
-- ---------------------------------------------------------------------------
|
||||
INSERT INTO card_types (name, price, notes, active) VALUES
|
||||
(
|
||||
'{"en":"Visa Classic","ru":"Visa Classic","tm":"Visa Classic"}'::json,
|
||||
'50', 'Standard debit card', true
|
||||
),
|
||||
(
|
||||
'{"en":"Visa Gold","ru":"Visa Gold","tm":"Visa Gold"}'::json,
|
||||
'150', 'Premium debit card', true
|
||||
),
|
||||
(
|
||||
'{"en":"MasterCard Standard","ru":"MasterCard Standard","tm":"MasterCard Standard"}'::json,
|
||||
'50', 'Standard debit card', true
|
||||
),
|
||||
(
|
||||
'{"en":"Altyn Asyr","ru":"Алтын Асыр","tm":"Altyn Asyr"}'::json,
|
||||
'30', 'Local payment card', true
|
||||
),
|
||||
(
|
||||
'{"en":"Visa Platinum (inactive)","ru":"Visa Platinum","tm":"Visa Platinum"}'::json,
|
||||
'300', 'Temporarily unavailable', false
|
||||
);
|
||||
|
||||
INSERT INTO card_states (name, price, notes, active) VALUES
|
||||
(
|
||||
'{"en":"New card","ru":"Новая карта","tm":"Täze kart"}'::json,
|
||||
'0', 'First-time issue', true
|
||||
),
|
||||
(
|
||||
'{"en":"Lost / stolen","ru":"Утеря / кража","tm":"Ýiten / ogurlanan"}'::json,
|
||||
'20', 'Reissue after loss', true
|
||||
),
|
||||
(
|
||||
'{"en":"Damaged","ru":"Повреждена","tm":"Zaýalanan"}'::json,
|
||||
'15', 'Reissue after damage', true
|
||||
),
|
||||
(
|
||||
'{"en":"Expired","ru":"Истёк срок","tm":"Möhleti gutaran"}'::json,
|
||||
'10', 'Renewal', true
|
||||
),
|
||||
(
|
||||
'{"en":"Name change","ru":"Смена имени","tm":"At üýtgetmek"}'::json,
|
||||
'25', 'Reissue after name change', false
|
||||
);
|
||||
|
||||
-- ---------------------------------------------------------------------------
|
||||
-- Loan types & required docs
|
||||
-- ---------------------------------------------------------------------------
|
||||
INSERT INTO loan_types (name, tax, maturity, notes, active) VALUES
|
||||
(
|
||||
'{"en":"Consumer loan","ru":"Потребительский кредит","tm":"Sarp ediş karzy"}'::json,
|
||||
12.50, '12',
|
||||
'{"en":"Up to 12 months","ru":"До 12 месяцев","tm":"12 aýa çenli"}'::json,
|
||||
true
|
||||
),
|
||||
(
|
||||
'{"en":"Mortgage","ru":"Ипотека","tm":"Ipoteka"}'::json,
|
||||
8.00, '120',
|
||||
'{"en":"Housing loan up to 10 years","ru":"Жилищный кредит до 10 лет","tm":"Ýaşaýyş karzy 10 ýyla çenli"}'::json,
|
||||
true
|
||||
),
|
||||
(
|
||||
'{"en":"Auto loan","ru":"Автокредит","tm":"Awto karzy"}'::json,
|
||||
10.00, '36',
|
||||
'{"en":"Vehicle purchase","ru":"Покупка автомобиля","tm":"Ulag satyn almak"}'::json,
|
||||
true
|
||||
),
|
||||
(
|
||||
'{"en":"Business loan","ru":"Бизнес-кредит","tm":"Işewürlik karzy"}'::json,
|
||||
14.00, '24',
|
||||
'{"en":"SME financing","ru":"Финансирование МСБ","tm":"Kiçi we orta biznes"}'::json,
|
||||
true
|
||||
),
|
||||
(
|
||||
'{"en":"Education loan (inactive)","ru":"Образовательный","tm":"Bilim karzy"}'::json,
|
||||
6.00, '48',
|
||||
'{"en":"Currently paused","ru":"Временно приостановлен","tm":"Wagtlaýyn duruzylan"}'::json,
|
||||
false
|
||||
);
|
||||
|
||||
INSERT INTO loan_order_required_docs (name, value, active) VALUES
|
||||
('Passport copy', 'passport', true),
|
||||
('Income certificate', 'income', true),
|
||||
('Employment letter', 'employment', true),
|
||||
('Property documents', 'property', true),
|
||||
('Guarantor passport', 'guarantor_passport', true),
|
||||
('Old checklist (inactive)', 'legacy', false);
|
||||
|
||||
-- ---------------------------------------------------------------------------
|
||||
-- Cards belonging to users
|
||||
-- ---------------------------------------------------------------------------
|
||||
INSERT INTO cards (user_id, number, name, month, year, type) VALUES
|
||||
(5, '4169740012345678', 'SERDAR MYRADOW', '12', '28', 'visa'),
|
||||
(6, '4169740087654321', 'GULNAR ORAZOWA', '06', '27', 'visa'),
|
||||
(8, '5536910011223344', 'MAYA HALYLOWA', '03', '29', 'mastercard'),
|
||||
(7, '9860010055667788', 'DOVRAN ANNAYEW', '09', '26', 'altyn'),
|
||||
(9, '4169740011112222', 'KERIM ATAYEW', '08', '28', 'visa'),
|
||||
(10, '5536910055556666', 'LEYLA GURBANOWA', '11', '29', 'mastercard');
|
||||
|
||||
-- ---------------------------------------------------------------------------
|
||||
-- Card orders
|
||||
-- ---------------------------------------------------------------------------
|
||||
INSERT INTO card_orders (
|
||||
unique_id, card_state_id, card_type_id, region, branch_id,
|
||||
customer_name, customer_surname, customer_patronic_name, born_at,
|
||||
citizenship, passport_serie, passport_id, passport_given_at, passport_given_by,
|
||||
born_place, job_location, passport_address, real_address, phone, phone_additional,
|
||||
status, passport_one, passport_two, passport_three, passport_four,
|
||||
notes, user_id, paid
|
||||
) VALUES
|
||||
(
|
||||
'CO-2026-0001', 1, 1, 'AG', 1,
|
||||
'Serdar', 'Myradow', 'Gurbanowicz', '1990-05-12',
|
||||
'TM', 'I-AG', '123456', '2015-03-20', 'Ashgabat City Police',
|
||||
'Ashgabat', 'Bank employee', 'Ashgabat, 10ýyl Abadanlyk 5', 'Ashgabat, 10ýyl Abadanlyk 5',
|
||||
'+993 61 92 92 48', '+993 61 92 92 48',
|
||||
'pending', 'pass1.jpg', 'pass2.jpg', 'pass3.jpg', 'pass4.jpg',
|
||||
'First Visa Classic order', 5, false
|
||||
),
|
||||
(
|
||||
'CO-2026-0002', 2, 2, 'AG', 1,
|
||||
'Gulnar', 'Orazowa', 'Batyrowna', '1988-11-03',
|
||||
'TM', 'I-AG', '654321', '2014-08-11', 'Ashgabat City Police',
|
||||
'Ashgabat', 'Teacher', 'Ashgabat, Andalyp 12', 'Ashgabat, Andalyp 12',
|
||||
'+993 61 92 92 48', NULL,
|
||||
'approved', 'pass1.jpg', 'pass2.jpg', 'pass3.jpg', 'pass4.jpg',
|
||||
'Lost card reissue — Gold', 6, true
|
||||
),
|
||||
(
|
||||
'CO-2026-0003', 1, 4, 'MR', 7,
|
||||
'Dovran', 'Annayew', 'Hojamyradowiç', '1995-01-25',
|
||||
'TM', 'I-MR', '112233', '2018-06-01', 'Mary Police',
|
||||
'Mary', 'Farmer', 'Mary, Garaşsyzlyk 3', 'Mary, Garaşsyzlyk 3',
|
||||
'+993 61 92 92 48', NULL,
|
||||
'rejected', 'pass1.jpg', 'pass2.jpg', 'pass3.jpg', 'pass4.jpg',
|
||||
'Incomplete documents', 7, false
|
||||
),
|
||||
(
|
||||
'CO-2026-0004', 3, 3, 'BL', 4,
|
||||
'Maya', 'Halylowa', 'Saparowna', '1992-07-19',
|
||||
'TM', 'I-BL', '445566', '2016-02-14', 'Balkanabat Police',
|
||||
'Balkanabat', 'Nurse', 'Balkanabat, Magtymguly 9', 'Balkanabat, Magtymguly 9',
|
||||
'+993 61 92 92 48', NULL,
|
||||
'pending', 'pass1.jpg', 'pass2.jpg', 'pass3.jpg', 'pass4.jpg',
|
||||
'Damaged MasterCard', 8, false
|
||||
);
|
||||
|
||||
-- ---------------------------------------------------------------------------
|
||||
-- Card PIN orders
|
||||
-- ---------------------------------------------------------------------------
|
||||
INSERT INTO card_pin_orders (
|
||||
unique_id, user_id, card_type_id, card_number, 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
|
||||
) VALUES
|
||||
(
|
||||
'CPO-2026-0001', 5, 1, '4169740012345678', 'AG', 1,
|
||||
'Serdar', 'Myradow', 'Gurbanowicz', '1990-05-12', '+993 61 92 92 48',
|
||||
'I-AG', '123456',
|
||||
'pin1.jpg', 'pin2.jpg', 'pin3.jpg', 'pin4.jpg',
|
||||
'pending', 'PIN reset request'
|
||||
),
|
||||
(
|
||||
'CPO-2026-0002', 7, 4, '9860010055667788', 'MR', 7,
|
||||
'Dovran', 'Annayew', 'Hojamyradowiç', '1995-01-25', '+993 61 92 92 48',
|
||||
'I-MR', '112233',
|
||||
'pin1.jpg', 'pin2.jpg', 'pin3.jpg', 'pin4.jpg',
|
||||
'completed', 'PIN issued'
|
||||
),
|
||||
(
|
||||
'CPO-2026-0003', NULL, 2, '4169740099990000', 'AH', 3,
|
||||
'Batyr', 'Saparow', 'Orazowicz', '1991-12-01', '+993 61 92 92 48',
|
||||
'I-AH', '334455',
|
||||
'pin1.jpg', 'pin2.jpg', 'pin3.jpg', 'pin4.jpg',
|
||||
'rejected', 'Passport mismatch'
|
||||
);
|
||||
|
||||
-- ---------------------------------------------------------------------------
|
||||
-- Loan orders
|
||||
-- ---------------------------------------------------------------------------
|
||||
INSERT INTO loan_orders (
|
||||
unique_id, source, user_id, loan_type, region, branch_id,
|
||||
customer_name, customer_surname, customer_patronic_name,
|
||||
passport_address, real_address, passport_serie, passport_id,
|
||||
passport_given_at, passport_given_by, born_place, born_at,
|
||||
email, phone, phone_additional, phone_home,
|
||||
work_region, work_province_id, work_company, work_company_accountant_number,
|
||||
work_started_at, work_salary, work_position,
|
||||
education, marriage_status,
|
||||
passport_one, passport_two, passport_three, passport_four,
|
||||
loan_amount, card_number, card_name, card_month, card_year,
|
||||
guarantor_name, guarantor_surname, guarantor_patronic_name,
|
||||
guarantor_passport_serie, guarantor_passport_id,
|
||||
guarantor_card_number, guarantor_card_name, guarantor_card_month, guarantor_card_year,
|
||||
guarantor_note,
|
||||
loan_order_required_doc_id, status, satisfiable, notes
|
||||
) VALUES
|
||||
(
|
||||
'0001', 'mobile', 9, 1, 'AG', 1,
|
||||
'Kerim', 'Atayew', 'Begliýewiç',
|
||||
'Ashgabat, Bitaraplyk 20', 'Ashgabat, Bitaraplyk 20', 'I-AG', '101010',
|
||||
'2017-01-15', 'Ashgabat City Police', 'Ashgabat', '1989-03-21',
|
||||
'kerim@bank.tm', '+993 61 92 92 48', NULL, '+993 61 92 92 48',
|
||||
'AG', 1, 'Türkmen Poçta', 'ACC-1001',
|
||||
'2019-05-01', '4500', 'Specialist',
|
||||
'higher', 'married',
|
||||
'lo1.jpg', 'lo2.jpg', 'lo3.jpg', 'lo4.jpg',
|
||||
'20000', '4169740011112222', 'KERIM ATAYEW', '08', '28',
|
||||
'Myrat', 'Atayew', 'Begliýewiç',
|
||||
'I-AG', '202020',
|
||||
'4169740033334444', 'MYRAT ATAYEW', '08', '27',
|
||||
'Brother',
|
||||
1, 'pending', 'yes', 'Consumer loan application'
|
||||
),
|
||||
(
|
||||
'0002', 'mobile', 10, 3, 'AG', 2,
|
||||
'Leyla', 'Gurbanowa', 'Saparowna',
|
||||
'Ashgabat, Andalyp 8', 'Ashgabat, Andalyp 8', 'I-AG', '303030',
|
||||
'2016-09-10', 'Ashgabat City Police', 'Ashgabat', '1994-08-02',
|
||||
'leyla@bank.tm', '+993 61 92 92 48', '+993 61 92 92 48', NULL,
|
||||
'AG', 1, 'Altyn Asyr', 'ACC-2002',
|
||||
'2020-02-15', '3800', 'Accountant',
|
||||
'higher', 'single',
|
||||
'lo1.jpg', 'lo2.jpg', 'lo3.jpg', 'lo4.jpg',
|
||||
'80000', '5536910055556666', 'LEYLA GURBANOWA', '11', '29',
|
||||
NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
|
||||
2, 'approved', 'yes', 'Auto loan approved'
|
||||
),
|
||||
(
|
||||
'0003', 'mobile', 7, 2, 'MR', 7,
|
||||
'Dovran', 'Annayew', 'Hojamyradowiç',
|
||||
'Mary, Galkynyş 15', 'Mary, Galkynyş 15', 'I-MR', '112233',
|
||||
'2012-04-22', 'Mary Police', 'Mary', '1995-01-25',
|
||||
'dovran@bank.tm', '+993 61 92 92 48', NULL, NULL,
|
||||
'MR', 12, 'Mary Textile', 'ACC-3003',
|
||||
'2015-01-10', '5200', 'Engineer',
|
||||
'higher', 'married',
|
||||
'lo1.jpg', 'lo2.jpg', 'lo3.jpg', 'lo4.jpg',
|
||||
'250000', NULL, NULL, NULL, NULL,
|
||||
'Hatyja', 'Jumaýewa', 'Berdiýewna',
|
||||
'I-MR', '505050',
|
||||
'9860010077778888', 'HATYJA JUMAYEWA', '01', '28',
|
||||
'Spouse',
|
||||
4, 'review', 'pending', 'Mortgage under review'
|
||||
),
|
||||
(
|
||||
'0004', 'mobile', NULL, 4, 'LB', 6,
|
||||
'Oguljenan', 'Çaryýewa', 'Myradowna',
|
||||
'Turkmenabat, Magtymguly 2', 'Turkmenabat, Magtymguly 2', 'I-LB', '606060',
|
||||
'2019-11-05', 'Turkmenabat Police', 'Turkmenabat', '1996-12-12',
|
||||
'ogul@mail.tm', '+993 61 92 92 48', NULL, NULL,
|
||||
'LB', 10, 'Self-employed', NULL,
|
||||
'2021-03-01', '6000', 'Entrepreneur',
|
||||
'secondary', 'single',
|
||||
'lo1.jpg', 'lo2.jpg', 'lo3.jpg', 'lo4.jpg',
|
||||
'50000', '4169740099998888', 'OGULJENAN CARYYEWA', '04', '27',
|
||||
NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
|
||||
3, 'rejected', 'no', 'Insufficient income proof'
|
||||
);
|
||||
|
||||
-- ---------------------------------------------------------------------------
|
||||
-- Loans (repayment accounts)
|
||||
-- ---------------------------------------------------------------------------
|
||||
INSERT INTO loans (user_id, passport_serie, passport_id, account_number) VALUES
|
||||
(9, 'I-AG', '101010', 'ACC-LOAN-10001'),
|
||||
(10, 'I-AG', '303030', 'ACC-LOAN-10002'),
|
||||
(7, 'I-MR', '112233', 'ACC-LOAN-10003'),
|
||||
(5, 'I-AG', '123456', 'ACC-LOAN-10004'),
|
||||
(6, 'I-AG', '654321', 'ACC-LOAN-10005');
|
||||
|
||||
-- ---------------------------------------------------------------------------
|
||||
-- Loan paid-off letters
|
||||
-- ---------------------------------------------------------------------------
|
||||
INSERT INTO loan_paid_off_letters (
|
||||
unique_id, region, branch_id, user_id,
|
||||
customer_name, customer_surname, customer_patronic_name, born_at, phone,
|
||||
passport_serie, passport_id, status, notes,
|
||||
loan_contract_number, loan_contract_date, loan_amount, loan_reason, loan_file
|
||||
) VALUES
|
||||
(
|
||||
'LPL-2026-0001', 'AG', 1, 9,
|
||||
'Kerim', 'Atayew', 'Begliýewiç', '1989-03-21', '+993 61 92 92 48',
|
||||
'I-AG', '101010', 'pending', 'Waiting for branch confirmation',
|
||||
'CTR-2024-1001', '2024-01-15', '15000', 'Consumer loan closed', 'letter1.pdf'
|
||||
),
|
||||
(
|
||||
'LPL-2026-0002', 'AG', 2, 10,
|
||||
'Leyla', 'Gurbanowa', 'Saparowna', '1994-08-02', '+993 61 92 92 48',
|
||||
'I-AG', '303030', 'approved', 'Paid off confirmed',
|
||||
'CTR-2023-2202', '2023-06-01', '8000', 'Early repayment', 'letter2.pdf'
|
||||
),
|
||||
(
|
||||
'LPL-2026-0003', 'AG', 1, NULL,
|
||||
'Batyr', 'Saparow', 'Orazowicz', '1991-12-01', '+993 61 92 92 48',
|
||||
'I-AH', '334455', 'rejected', 'Outstanding balance remains',
|
||||
'CTR-2025-3303', '2025-02-10', '20000', 'Requested too early', NULL
|
||||
);
|
||||
|
||||
-- ---------------------------------------------------------------------------
|
||||
-- Visa / Master payment orders (student transfers)
|
||||
-- documents JSON keys match the admin upload slots (student + sender).
|
||||
-- ---------------------------------------------------------------------------
|
||||
INSERT INTO visa_master_payment_orders (
|
||||
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,
|
||||
paid
|
||||
) VALUES
|
||||
(
|
||||
'VMP-2026-0001', 'student', 'Serdar', 'Myradow', '+993 61 92 92 48', 'serdar@bank.tm',
|
||||
'AG', 1, 5, 'Aşgabat, Parahat 7',
|
||||
'{"fullName":"Myradow Serdar Orazowiç","passportSerie":"I-AG","passportNumber":"123456","depositAccount":"23202984200012345678"}'::json,
|
||||
'[{"fullName":"Orazowa Gulnar Myradowna","passportSerie":"I-AG","passportNumber":"654321"}]'::json,
|
||||
'{
|
||||
"student_visa_card_details":["visa-card-1.pdf"],
|
||||
"student_enrollment_certificate":["enrollment-1.pdf"],
|
||||
"student_ticket_copy":["ticket-1.pdf"],
|
||||
"student_internal_passport":["student-internal-1.pdf"],
|
||||
"student_foreign_passport":["student-foreign-1.pdf"],
|
||||
"student_visa_page":["student-visa-page-1.pdf"],
|
||||
"student_stamp_page":["student-stamp-1.pdf"],
|
||||
"student_enrollment_clarification":[],
|
||||
"sender_internal_passport":["sender-internal-1.pdf"],
|
||||
"sender_foreign_passport":["sender-foreign-1.pdf"],
|
||||
"sender_stamp_page":["sender-stamp-1.pdf"],
|
||||
"kinship_documents":["kinship-1.pdf"],
|
||||
"first_passport_series_info":[],
|
||||
"police_passport_series_info":[]
|
||||
}'::json,
|
||||
'pending', 'Garaşylýar',
|
||||
'Myradow Serdar Orazowiç', 'I-AG', '123456', '23202984200012345678',
|
||||
'Orazowa Gulnar Myradowna', 'I-AG', '654321', NULL,
|
||||
false
|
||||
),
|
||||
(
|
||||
'VMP-2026-0002', 'student', 'Kerim', 'Atayew', '+993 61 92 92 48', NULL,
|
||||
'AG', 2, 9, 'Aşgabat, 10 ýyl Abadançylyk',
|
||||
'{"fullName":"Atayew Kerim Begliýewiç","passportSerie":"I-AG","passportNumber":"101010","depositAccount":"23202984200010101011"}'::json,
|
||||
'[{"fullName":"Gurbanowa Leyla Saparowna","passportSerie":"I-AG","passportNumber":"303030"}]'::json,
|
||||
'{
|
||||
"student_visa_card_details":["visa-card-2.pdf"],
|
||||
"student_enrollment_certificate":[],
|
||||
"student_ticket_copy":[],
|
||||
"student_internal_passport":["student-internal-2.pdf"],
|
||||
"student_foreign_passport":[],
|
||||
"student_visa_page":[],
|
||||
"student_stamp_page":[],
|
||||
"student_enrollment_clarification":[],
|
||||
"sender_internal_passport":["sender-internal-2.pdf"],
|
||||
"sender_foreign_passport":[],
|
||||
"sender_stamp_page":["sender-stamp-2.pdf"],
|
||||
"kinship_documents":[],
|
||||
"first_passport_series_info":["old-passport-series-2.pdf"],
|
||||
"police_passport_series_info":[]
|
||||
}'::json,
|
||||
'approved', NULL,
|
||||
'Atayew Kerim Begliýewiç', 'I-AG', '101010', '23202984200010101011',
|
||||
'Gurbanowa Leyla Saparowna', 'I-AG', '303030', NULL,
|
||||
true
|
||||
);
|
||||
|
||||
-- ---------------------------------------------------------------------------
|
||||
-- Activity logs
|
||||
-- ---------------------------------------------------------------------------
|
||||
INSERT INTO activity_logs (user_id, method, path, module, action, status_code, request_body, ip) VALUES
|
||||
(1, 'POST', '/api/admin/login', 'auth', 'login', 200, '{"email":"superadmin@bank.tm"}'::jsonb, '127.0.0.1'),
|
||||
(2, 'POST', '/api/admin/login', 'auth', 'login', 200, '{"email":"admin@bank.tm"}'::jsonb, '10.0.0.5'),
|
||||
(2, 'GET', '/api/admin/users', 'users', 'list', 200, NULL, '10.0.0.5'),
|
||||
(1, 'POST', '/api/admin/provinces', 'provinces', 'create', 200, '{"name":{"tm":"Aşgabat"}}'::jsonb, '127.0.0.1'),
|
||||
(3, 'GET', '/api/admin/card-orders', 'card-orders', 'list', 200, NULL, '10.0.0.12'),
|
||||
(3, 'PUT', '/api/admin/card-orders/2', 'card-orders', 'update', 200, '{"status":"approved"}'::jsonb, '10.0.0.12'),
|
||||
(4, 'GET', '/api/admin/loan-orders', 'loan-orders', 'list', 200, NULL, '10.0.0.20'),
|
||||
(4, 'POST', '/api/admin/loan-orders', 'loan-orders', 'create', 400, '{"loanAmount":"0"}'::jsonb, '10.0.0.20'),
|
||||
(1, 'DELETE', '/api/admin/roles/99', 'roles', 'delete', 404, NULL, '127.0.0.1'),
|
||||
(3, 'GET', '/api/admin/branches', 'branches', 'list', 200, NULL, '10.0.0.12'),
|
||||
(2, 'PUT', '/api/admin/profile', 'auth', 'update', 200, '{"firstName":"Nurmuhammet"}'::jsonb, '10.0.0.5'),
|
||||
(5, 'GET', '/api/admin/cards', 'cards', 'list', 200, NULL, '10.0.0.30');
|
||||
|
||||
COMMIT;
|
||||
|
||||
-- Quick counts
|
||||
SELECT 'users' AS table_name, count(*) FROM users
|
||||
UNION ALL SELECT 'roles', count(*) FROM roles
|
||||
UNION ALL SELECT 'role_user', count(*) FROM role_user
|
||||
UNION ALL SELECT 'permission_role', count(*) FROM permission_role
|
||||
UNION ALL SELECT 'branch_user', count(*) FROM branch_user
|
||||
UNION ALL SELECT 'permissions', count(*) FROM permissions
|
||||
UNION ALL SELECT 'provinces', count(*) FROM provinces
|
||||
UNION ALL SELECT 'branches', count(*) FROM branches
|
||||
UNION ALL SELECT 'card_types', count(*) FROM card_types
|
||||
UNION ALL SELECT 'card_states', count(*) FROM card_states
|
||||
UNION ALL SELECT 'loan_types', count(*) FROM loan_types
|
||||
UNION ALL SELECT 'loan_order_required_docs', count(*) FROM loan_order_required_docs
|
||||
UNION ALL SELECT 'cards', count(*) FROM cards
|
||||
UNION ALL SELECT 'card_orders', count(*) FROM card_orders
|
||||
UNION ALL SELECT 'card_pin_orders', count(*) FROM card_pin_orders
|
||||
UNION ALL SELECT 'loan_orders', count(*) FROM loan_orders
|
||||
UNION ALL SELECT 'loans', count(*) FROM loans
|
||||
UNION ALL SELECT 'loan_paid_off_letters', count(*) FROM loan_paid_off_letters
|
||||
UNION ALL SELECT 'visa_master_payment_orders', count(*) FROM visa_master_payment_orders
|
||||
UNION ALL SELECT 'registration_verifications', count(*) FROM registration_verifications
|
||||
UNION ALL SELECT 'activity_logs', count(*) FROM activity_logs
|
||||
ORDER BY 1;
|
||||
|
||||
@@ -1,57 +0,0 @@
|
||||
-- Additive seed: one branch (şahamça) per etrap.
|
||||
-- Constructed from provinces — run db/mock/seed_provinces.sql first.
|
||||
-- Resolves province_id by tm name+region (does not hard-code ids).
|
||||
-- Does not truncate. Safe to re-run (skips existing unique_code or province_id).
|
||||
-- Usage:
|
||||
-- PGPASSWORD='bank@#23#@_password' psql -h localhost -p 5424 -U bank_admin -d bank_db -f db/mock/seed_provinces.sql
|
||||
-- PGPASSWORD='bank@#23#@_password' psql -h localhost -p 5424 -U bank_admin -d bank_db -f db/mock/seed_branches.sql
|
||||
|
||||
DO $$
|
||||
BEGIN
|
||||
IF NOT EXISTS (SELECT 1 FROM provinces) THEN
|
||||
RAISE EXCEPTION 'provinces is empty — run db/mock/seed_provinces.sql first';
|
||||
END IF;
|
||||
END $$;
|
||||
|
||||
INSERT INTO branches (unique_code, name, address, region, province_id, phone_numbers, active)
|
||||
SELECT
|
||||
s.region_code || '-' || s.name_slug,
|
||||
json_build_object(
|
||||
'en', (s.name->>'en') || ' branch',
|
||||
'ru', (s.name->>'ru') || ' филиал',
|
||||
'tm', (s.name->>'tm') || ' şahamçasy'
|
||||
),
|
||||
json_build_object(
|
||||
'en', s.name->>'en',
|
||||
'ru', s.name->>'ru',
|
||||
'tm', s.name->>'tm'
|
||||
),
|
||||
s.region_code,
|
||||
s.id,
|
||||
'+993 61 92 92 48',
|
||||
true
|
||||
FROM (
|
||||
SELECT
|
||||
p.id,
|
||||
p.name,
|
||||
CASE p.region->>'tm'
|
||||
WHEN 'Aşgabat' THEN 'AG'
|
||||
WHEN 'Ahal' THEN 'AH'
|
||||
WHEN 'Balkan' THEN 'BL'
|
||||
WHEN 'Daşoguz' THEN 'DZ'
|
||||
WHEN 'Lebap' THEN 'LB'
|
||||
WHEN 'Mary' THEN 'MR'
|
||||
ELSE 'XX'
|
||||
END AS region_code,
|
||||
trim(both '-' FROM upper(regexp_replace(
|
||||
translate(p.name->>'tm', 'ÄäÇçŇňÖöŞşÜüÝý', 'AaCcNnOoSsUuYy'),
|
||||
'[^A-Za-z0-9]+', '-', 'g'
|
||||
))) AS name_slug
|
||||
FROM provinces p
|
||||
WHERE p.active
|
||||
) s
|
||||
WHERE NOT EXISTS (
|
||||
SELECT 1 FROM branches b
|
||||
WHERE b.unique_code = s.region_code || '-' || s.name_slug
|
||||
OR b.province_id = s.id
|
||||
);
|
||||
@@ -1,54 +0,0 @@
|
||||
-- Additive seed for card issuance reasons from the admin "Kartyň çykarylmagynyň sebäpleri" list.
|
||||
-- Does not truncate users or other tables. Safe to re-run (skips existing tm names).
|
||||
-- Usage:
|
||||
-- PGPASSWORD='bank@#23#@_password' psql -h localhost -p 5424 -U bank_admin -d bank_db -f db/mock/seed_card_states.sql
|
||||
|
||||
INSERT INTO card_states (name, price, notes, active)
|
||||
SELECT name, price, notes, active
|
||||
FROM (VALUES
|
||||
(
|
||||
'{"en":"New","ru":"Новая","tm":"Täze"}'::json,
|
||||
'32',
|
||||
'',
|
||||
true
|
||||
),
|
||||
(
|
||||
'{"en":"Broken / damaged","ru":"Сломанная / повреждённая","tm":"Döwülen/Zaýalanan"}'::json,
|
||||
'32',
|
||||
'',
|
||||
true
|
||||
),
|
||||
(
|
||||
'{"en":"Usage period expired","ru":"Истёк срок использования","tm":"Ulanylyş möhleti geçen"}'::json,
|
||||
'32',
|
||||
'',
|
||||
true
|
||||
),
|
||||
(
|
||||
'{"en":"Surname change","ru":"Смена фамилии","tm":"Familiýasy üýtgeýär"}'::json,
|
||||
'32',
|
||||
'',
|
||||
true
|
||||
),
|
||||
(
|
||||
'{"en":"Lost","ru":"Утеряна","tm":"Ýiten"}'::json,
|
||||
'37.75',
|
||||
'',
|
||||
true
|
||||
),
|
||||
(
|
||||
'{"en":"PIN envelope (blocked)","ru":"PIN-конверт (заблокирован)","tm":"Pin bukja (bloklanan)"}'::json,
|
||||
'3.02',
|
||||
'',
|
||||
false
|
||||
),
|
||||
(
|
||||
'{"en":"Requisites","ru":"Реквизиты","tm":"Rekwizit"}'::json,
|
||||
'2.30',
|
||||
'',
|
||||
false
|
||||
)
|
||||
) AS t(name, price, notes, active)
|
||||
WHERE NOT EXISTS (
|
||||
SELECT 1 FROM card_states cs WHERE cs.name->>'tm' = t.name->>'tm'
|
||||
);
|
||||
@@ -1,54 +0,0 @@
|
||||
-- Additive seed for card types from the admin "Kart görnüşleri" list.
|
||||
-- Does not truncate users or other tables. Safe to re-run (skips existing tm names).
|
||||
-- Usage:
|
||||
-- PGPASSWORD='bank@#23#@_password' psql -h localhost -p 5424 -U bank_admin -d bank_db -f db/mock/seed_card_types.sql
|
||||
|
||||
INSERT INTO card_types (name, price, notes, active)
|
||||
SELECT name, price, notes, active
|
||||
FROM (VALUES
|
||||
(
|
||||
'{"en":"Altyn Asyr","ru":"Алтын Асыр","tm":"Altyn Asyr"}'::json,
|
||||
'32',
|
||||
'',
|
||||
true
|
||||
),
|
||||
(
|
||||
'{"en":"Family","ru":"Семейная","tm":"Maşgala"}'::json,
|
||||
'32',
|
||||
'',
|
||||
true
|
||||
),
|
||||
(
|
||||
'{"en":"Deposit","ru":"Депозитная","tm":"Goýum"}'::json,
|
||||
'32',
|
||||
'',
|
||||
true
|
||||
),
|
||||
(
|
||||
'{"en":"Pension","ru":"Пенсионная","tm":"Pensiýa"}'::json,
|
||||
'32',
|
||||
'',
|
||||
true
|
||||
),
|
||||
(
|
||||
'{"en":"Entrepreneur","ru":"Предпринимательская","tm":"Telekeçi"}'::json,
|
||||
'32',
|
||||
'',
|
||||
true
|
||||
),
|
||||
(
|
||||
'{"en":"Credit","ru":"Кредитная","tm":"Karz"}'::json,
|
||||
'32',
|
||||
'',
|
||||
false
|
||||
),
|
||||
(
|
||||
'{"en":"Overdraft","ru":"Овердрафт","tm":"Owerdraft"}'::json,
|
||||
'32',
|
||||
'',
|
||||
true
|
||||
)
|
||||
) AS t(name, price, notes, active)
|
||||
WHERE NOT EXISTS (
|
||||
SELECT 1 FROM card_types ct WHERE ct.name->>'tm' = t.name->>'tm'
|
||||
);
|
||||
@@ -1,22 +0,0 @@
|
||||
-- Additive seed for required loan documents from the admin "Karz gerekli resminamalary" list.
|
||||
-- Does not truncate users or other tables. Safe to re-run (skips existing names).
|
||||
-- Usage:
|
||||
-- PGPASSWORD='bank@#23#@_password' psql -h localhost -p 5424 -U bank_admin -d bank_db -f db/mock/seed_loan_order_required_docs.sql
|
||||
|
||||
INSERT INTO loan_order_required_docs (name, value, active)
|
||||
SELECT name, value, active
|
||||
FROM (VALUES
|
||||
(
|
||||
'Hormatly müşderi! Siziň ýüztutmaňyz kanagatlandyryldy!',
|
||||
'approved',
|
||||
true
|
||||
),
|
||||
(
|
||||
'Hormatly müşderi! Siziň ýüztutmaňyz kanagatlandyrylmady!',
|
||||
'rejected',
|
||||
true
|
||||
)
|
||||
) AS t(name, value, active)
|
||||
WHERE NOT EXISTS (
|
||||
SELECT 1 FROM loan_order_required_docs d WHERE d.name = t.name
|
||||
);
|
||||
@@ -1,47 +0,0 @@
|
||||
-- Additive seed for loan types from the admin "Karz görnüşleri" list.
|
||||
-- Does not truncate users or other tables. Safe to re-run (skips existing tm names).
|
||||
-- Usage:
|
||||
-- PGPASSWORD='bank@#23#@_password' psql -h localhost -p 5424 -U bank_admin -d bank_db -f db/mock/seed_loan_types.sql
|
||||
|
||||
INSERT INTO loan_types (name, tax, maturity, notes, active)
|
||||
SELECT name, tax, maturity, notes, active
|
||||
FROM (VALUES
|
||||
(
|
||||
'{"en":"Youth / newlyweds loan","ru":"Кредит для молодожёнов","tm":"Ýaş çatynjalara"}'::json,
|
||||
1.00,
|
||||
'30',
|
||||
'{}'::json,
|
||||
true
|
||||
),
|
||||
(
|
||||
'{"en":"Consumer loan secured by guarantor","ru":"Потребительский кредит под поручительство","tm":"Üpjünçiligine zamunlyk bolan sarp ediş karzy"}'::json,
|
||||
1.00,
|
||||
'30',
|
||||
'{}'::json,
|
||||
true
|
||||
),
|
||||
(
|
||||
'{"en":"Small loans","ru":"Кредиты малого объёма","tm":"Kiçi göwrümli karzlar"}'::json,
|
||||
1.00,
|
||||
'30',
|
||||
'{}'::json,
|
||||
true
|
||||
),
|
||||
(
|
||||
'{"en":"Consumer loan secured by collateral","ru":"Потребительский кредит под залог имущества","tm":"Üpjünçiligine girew emlägi bolan sarp ediş karzy"}'::json,
|
||||
1.00,
|
||||
'30',
|
||||
'{}'::json,
|
||||
true
|
||||
),
|
||||
(
|
||||
'{"en":"Student loan","ru":"Студенческий кредит","tm":"Talyp karzy"}'::json,
|
||||
1.00,
|
||||
'30',
|
||||
'{"en":"Note","ru":"Примечание","tm":"Bellik"}'::json,
|
||||
true
|
||||
)
|
||||
) AS t(name, tax, maturity, notes, active)
|
||||
WHERE NOT EXISTS (
|
||||
SELECT 1 FROM loan_types lt WHERE lt.name->>'tm' = t.name->>'tm'
|
||||
);
|
||||
@@ -1,280 +0,0 @@
|
||||
-- Additive seed for districts (etraps) from the admin location list (WELAÝAT / ADY).
|
||||
-- Does not truncate users or other tables. Safe to re-run (skips existing tm name+region).
|
||||
-- Usage:
|
||||
-- PGPASSWORD='bank@#23#@_password' psql -h localhost -p 5424 -U bank_admin -d bank_db -f db/mock/seed_provinces.sql
|
||||
|
||||
INSERT INTO provinces (name, region, active)
|
||||
SELECT name, region, active
|
||||
FROM (VALUES
|
||||
-- Aşgabat
|
||||
(
|
||||
'{"en":"Ashgabat","ru":"Ашхабад","tm":"Aşgabat"}'::json,
|
||||
'{"en":"Ashgabat","ru":"Ашхабад","tm":"Aşgabat"}'::json,
|
||||
true
|
||||
),
|
||||
-- Ahal
|
||||
(
|
||||
'{"en":"Ak bugday","ru":"Ак бугдай","tm":"Ak bugdaý"}'::json,
|
||||
'{"en":"Ahal","ru":"Ахал","tm":"Ahal"}'::json,
|
||||
true
|
||||
),
|
||||
(
|
||||
'{"en":"Babadayhan","ru":"Бабадайхан","tm":"Babadaýhan"}'::json,
|
||||
'{"en":"Ahal","ru":"Ахал","tm":"Ahal"}'::json,
|
||||
true
|
||||
),
|
||||
(
|
||||
'{"en":"Baherden","ru":"Бахерден","tm":"Bäherden"}'::json,
|
||||
'{"en":"Ahal","ru":"Ахал","tm":"Ahal"}'::json,
|
||||
true
|
||||
),
|
||||
(
|
||||
'{"en":"Gokdepe","ru":"Гокдепе","tm":"Gökdepe"}'::json,
|
||||
'{"en":"Ahal","ru":"Ахал","tm":"Ahal"}'::json,
|
||||
true
|
||||
),
|
||||
(
|
||||
'{"en":"Kaka","ru":"Кака","tm":"Kaka"}'::json,
|
||||
'{"en":"Ahal","ru":"Ахал","tm":"Ahal"}'::json,
|
||||
true
|
||||
),
|
||||
(
|
||||
'{"en":"Sarahs","ru":"Серахс","tm":"Sarahs"}'::json,
|
||||
'{"en":"Ahal","ru":"Ахал","tm":"Ahal"}'::json,
|
||||
true
|
||||
),
|
||||
(
|
||||
'{"en":"Tejen","ru":"Теджен","tm":"Tejen"}'::json,
|
||||
'{"en":"Ahal","ru":"Ахал","tm":"Ahal"}'::json,
|
||||
true
|
||||
),
|
||||
-- Balkan
|
||||
(
|
||||
'{"en":"Balkanabat","ru":"Балканабад","tm":"Balkanabat"}'::json,
|
||||
'{"en":"Balkan","ru":"Балкан","tm":"Balkan"}'::json,
|
||||
true
|
||||
),
|
||||
(
|
||||
'{"en":"Bereket","ru":"Берекет","tm":"Bereket"}'::json,
|
||||
'{"en":"Balkan","ru":"Балкан","tm":"Balkan"}'::json,
|
||||
true
|
||||
),
|
||||
(
|
||||
'{"en":"Esenguly","ru":"Эсенгулы","tm":"Esenguly"}'::json,
|
||||
'{"en":"Balkan","ru":"Балкан","tm":"Balkan"}'::json,
|
||||
true
|
||||
),
|
||||
(
|
||||
'{"en":"Etrek","ru":"Этрек","tm":"Etrek"}'::json,
|
||||
'{"en":"Balkan","ru":"Балкан","tm":"Balkan"}'::json,
|
||||
true
|
||||
),
|
||||
(
|
||||
'{"en":"Garabogaz","ru":"Гарабогаз","tm":"Garabogaz"}'::json,
|
||||
'{"en":"Balkan","ru":"Балкан","tm":"Balkan"}'::json,
|
||||
true
|
||||
),
|
||||
(
|
||||
'{"en":"Gyzylarbat","ru":"Кызыларбат","tm":"Gyzylarbat"}'::json,
|
||||
'{"en":"Balkan","ru":"Балкан","tm":"Balkan"}'::json,
|
||||
true
|
||||
),
|
||||
(
|
||||
'{"en":"Hazar","ru":"Хазар","tm":"Hazar"}'::json,
|
||||
'{"en":"Balkan","ru":"Балкан","tm":"Balkan"}'::json,
|
||||
true
|
||||
),
|
||||
(
|
||||
'{"en":"Magtymguly","ru":"Махтумкули","tm":"Magtymguly"}'::json,
|
||||
'{"en":"Balkan","ru":"Балкан","tm":"Balkan"}'::json,
|
||||
true
|
||||
),
|
||||
(
|
||||
'{"en":"Turkmenbashy","ru":"Туркменбашы","tm":"Türkmenbaşy"}'::json,
|
||||
'{"en":"Balkan","ru":"Балкан","tm":"Balkan"}'::json,
|
||||
true
|
||||
),
|
||||
-- Daşoguz
|
||||
(
|
||||
'{"en":"Akdepe","ru":"Акдепе","tm":"Akdepe"}'::json,
|
||||
'{"en":"Dashoguz","ru":"Дашогуз","tm":"Daşoguz"}'::json,
|
||||
true
|
||||
),
|
||||
(
|
||||
'{"en":"Boldumsaz","ru":"Болдумсаз","tm":"Boldumsaz"}'::json,
|
||||
'{"en":"Dashoguz","ru":"Дашогуз","tm":"Daşoguz"}'::json,
|
||||
true
|
||||
),
|
||||
(
|
||||
'{"en":"Dashoguz","ru":"Дашогуз","tm":"Daşoguz"}'::json,
|
||||
'{"en":"Dashoguz","ru":"Дашогуз","tm":"Daşoguz"}'::json,
|
||||
true
|
||||
),
|
||||
(
|
||||
'{"en":"Gorogly","ru":"Гёроглы","tm":"Görogly"}'::json,
|
||||
'{"en":"Dashoguz","ru":"Дашогуз","tm":"Daşoguz"}'::json,
|
||||
true
|
||||
),
|
||||
(
|
||||
'{"en":"Gubadag","ru":"Губадаг","tm":"Gubadag"}'::json,
|
||||
'{"en":"Dashoguz","ru":"Дашогуз","tm":"Daşoguz"}'::json,
|
||||
true
|
||||
),
|
||||
(
|
||||
'{"en":"Gurbansoltan Eje","ru":"Гурбансолтан эдже","tm":"Gurbansoltan eje ad."}'::json,
|
||||
'{"en":"Dashoguz","ru":"Дашогуз","tm":"Daşoguz"}'::json,
|
||||
true
|
||||
),
|
||||
(
|
||||
'{"en":"Koneurgench","ru":"Кёнеургенч","tm":"Köneürgenç"}'::json,
|
||||
'{"en":"Dashoguz","ru":"Дашогуз","tm":"Daşoguz"}'::json,
|
||||
true
|
||||
),
|
||||
(
|
||||
'{"en":"Ruhubelent","ru":"Рухубелент","tm":"Ruhubelent"}'::json,
|
||||
'{"en":"Dashoguz","ru":"Дашогуз","tm":"Daşoguz"}'::json,
|
||||
true
|
||||
),
|
||||
(
|
||||
'{"en":"S. Turkmenbashy","ru":"С. Туркменбашы","tm":"S. Türkmenbaşy ad."}'::json,
|
||||
'{"en":"Dashoguz","ru":"Дашогуз","tm":"Daşoguz"}'::json,
|
||||
true
|
||||
),
|
||||
(
|
||||
'{"en":"Shawat","ru":"Шават","tm":"Şawat"}'::json,
|
||||
'{"en":"Dashoguz","ru":"Дашогуз","tm":"Daşoguz"}'::json,
|
||||
true
|
||||
),
|
||||
-- Lebap
|
||||
(
|
||||
'{"en":"Charjew","ru":"Чарджев","tm":"Çärjew"}'::json,
|
||||
'{"en":"Lebap","ru":"Лебап","tm":"Lebap"}'::json,
|
||||
true
|
||||
),
|
||||
(
|
||||
'{"en":"Danew","ru":"Данев","tm":"Dänew"}'::json,
|
||||
'{"en":"Lebap","ru":"Лебап","tm":"Lebap"}'::json,
|
||||
true
|
||||
),
|
||||
(
|
||||
'{"en":"Darganata","ru":"Дарганата","tm":"Darganata"}'::json,
|
||||
'{"en":"Lebap","ru":"Лебап","tm":"Lebap"}'::json,
|
||||
true
|
||||
),
|
||||
(
|
||||
'{"en":"Dowletli","ru":"Довлетли","tm":"Döwletli"}'::json,
|
||||
'{"en":"Lebap","ru":"Лебап","tm":"Lebap"}'::json,
|
||||
true
|
||||
),
|
||||
(
|
||||
'{"en":"Farap","ru":"Фарап","tm":"Farap"}'::json,
|
||||
'{"en":"Lebap","ru":"Лебап","tm":"Lebap"}'::json,
|
||||
true
|
||||
),
|
||||
(
|
||||
'{"en":"Garabekewul","ru":"Гарабекевюль","tm":"Garabekewül"}'::json,
|
||||
'{"en":"Lebap","ru":"Лебап","tm":"Lebap"}'::json,
|
||||
true
|
||||
),
|
||||
(
|
||||
'{"en":"Halach","ru":"Халач","tm":"Halaç"}'::json,
|
||||
'{"en":"Lebap","ru":"Лебап","tm":"Lebap"}'::json,
|
||||
true
|
||||
),
|
||||
(
|
||||
'{"en":"Hojambaz","ru":"Ходжамбаз","tm":"Hojambaz"}'::json,
|
||||
'{"en":"Lebap","ru":"Лебап","tm":"Lebap"}'::json,
|
||||
true
|
||||
),
|
||||
(
|
||||
'{"en":"Kerki","ru":"Керки","tm":"Kerki"}'::json,
|
||||
'{"en":"Lebap","ru":"Лебап","tm":"Lebap"}'::json,
|
||||
true
|
||||
),
|
||||
(
|
||||
'{"en":"Koytendag","ru":"Койтендаг","tm":"Köýtendag"}'::json,
|
||||
'{"en":"Lebap","ru":"Лебап","tm":"Lebap"}'::json,
|
||||
true
|
||||
),
|
||||
(
|
||||
'{"en":"Magdanly","ru":"Магданлы","tm":"Magdanly"}'::json,
|
||||
'{"en":"Lebap","ru":"Лебап","tm":"Lebap"}'::json,
|
||||
true
|
||||
),
|
||||
(
|
||||
'{"en":"Sayat","ru":"Саят","tm":"Saýat"}'::json,
|
||||
'{"en":"Lebap","ru":"Лебап","tm":"Lebap"}'::json,
|
||||
true
|
||||
),
|
||||
(
|
||||
'{"en":"Seydi","ru":"Сейди","tm":"Seýdi"}'::json,
|
||||
'{"en":"Lebap","ru":"Лебап","tm":"Lebap"}'::json,
|
||||
true
|
||||
),
|
||||
(
|
||||
'{"en":"Turkmenabat","ru":"Туркменабад","tm":"Türkmenabat"}'::json,
|
||||
'{"en":"Lebap","ru":"Лебап","tm":"Lebap"}'::json,
|
||||
true
|
||||
),
|
||||
-- Mary
|
||||
(
|
||||
'{"en":"Bayramaly","ru":"Байрамали","tm":"Baýramaly"}'::json,
|
||||
'{"en":"Mary","ru":"Мары","tm":"Mary"}'::json,
|
||||
true
|
||||
),
|
||||
(
|
||||
'{"en":"Garagum","ru":"Гарагум","tm":"Garagum"}'::json,
|
||||
'{"en":"Mary","ru":"Мары","tm":"Mary"}'::json,
|
||||
true
|
||||
),
|
||||
(
|
||||
'{"en":"Mary","ru":"Мары","tm":"Mary"}'::json,
|
||||
'{"en":"Mary","ru":"Мары","tm":"Mary"}'::json,
|
||||
true
|
||||
),
|
||||
(
|
||||
'{"en":"Murgap","ru":"Мургап","tm":"Murgap"}'::json,
|
||||
'{"en":"Mary","ru":"Мары","tm":"Mary"}'::json,
|
||||
true
|
||||
),
|
||||
(
|
||||
'{"en":"Oguzhan","ru":"Огузхан","tm":"Oguzhan"}'::json,
|
||||
'{"en":"Mary","ru":"Мары","tm":"Mary"}'::json,
|
||||
true
|
||||
),
|
||||
(
|
||||
'{"en":"Sakarchage","ru":"Сакарчаге","tm":"Sakarçäge"}'::json,
|
||||
'{"en":"Mary","ru":"Мары","tm":"Mary"}'::json,
|
||||
true
|
||||
),
|
||||
(
|
||||
'{"en":"Serhetabat","ru":"Серхетабад","tm":"Serhetabat"}'::json,
|
||||
'{"en":"Mary","ru":"Мары","tm":"Mary"}'::json,
|
||||
true
|
||||
),
|
||||
(
|
||||
'{"en":"Tagtabazar","ru":"Тагтабазар","tm":"Tagtabazar"}'::json,
|
||||
'{"en":"Mary","ru":"Мары","tm":"Mary"}'::json,
|
||||
true
|
||||
),
|
||||
(
|
||||
'{"en":"Turkmengala","ru":"Туркменгала","tm":"Türkmengala"}'::json,
|
||||
'{"en":"Mary","ru":"Мары","tm":"Mary"}'::json,
|
||||
true
|
||||
),
|
||||
(
|
||||
'{"en":"Vekilbazar","ru":"Векильбазар","tm":"Wekilbazar"}'::json,
|
||||
'{"en":"Mary","ru":"Мары","tm":"Mary"}'::json,
|
||||
true
|
||||
),
|
||||
(
|
||||
'{"en":"Yoloten","ru":"Ёлётен","tm":"Ýolöten"}'::json,
|
||||
'{"en":"Mary","ru":"Мары","tm":"Mary"}'::json,
|
||||
true
|
||||
)
|
||||
) AS t(name, region, active)
|
||||
WHERE NOT EXISTS (
|
||||
SELECT 1 FROM provinces p
|
||||
WHERE p.name->>'tm' = t.name->>'tm'
|
||||
AND p.region->>'tm' = t.region->>'tm'
|
||||
);
|
||||
+947
@@ -0,0 +1,947 @@
|
||||
-- Dev / staging mock data. Re-runnable: wipes app tables then reloads.
|
||||
-- Usage: make seed
|
||||
-- or: PGPASSWORD='bank@#23#@_password' psql -h localhost -p 5424 -U bank_admin -d bank_db -f db/seed.sql
|
||||
-- Login (password = test1234):
|
||||
-- superadmin@bank.tm / +993 61 92 92 48 (is_super: ähli permission awtomatik)
|
||||
-- admin@bank.tm (scope=all, roles we backups-dan başga ähli)
|
||||
-- manager@bank.tm (scope=branch: cards, loans, users, dashboard)
|
||||
-- operator@bank.tm (scope=branch: cards)
|
||||
-- loanop@bank.tm (scope=branch: loans)
|
||||
-- bothop@bank.tm (scope=branch: cards + loans)
|
||||
-- loanhead@bank.tm (scope=all: loans — ähli filiallaryň karz bölümi)
|
||||
-- currency@bank.tm (scope=all: diňe walýuta)
|
||||
-- serdar@bank.tm … leyla@bank.tm (role=user, scope=own)
|
||||
|
||||
BEGIN;
|
||||
|
||||
TRUNCATE TABLE
|
||||
activity_logs,
|
||||
backups,
|
||||
currencies,
|
||||
visa_master_payment_logs,
|
||||
visa_master_order_payments,
|
||||
visa_master_payment_orders,
|
||||
loan_paid_off_letters,
|
||||
loans,
|
||||
loan_orders,
|
||||
card_rekwizit_orders,
|
||||
card_pin_orders,
|
||||
card_orders,
|
||||
card_balances,
|
||||
cards,
|
||||
loan_order_required_docs,
|
||||
loan_types,
|
||||
card_states,
|
||||
card_types,
|
||||
branch_user,
|
||||
branches,
|
||||
provinces,
|
||||
role_permissions,
|
||||
roles,
|
||||
registration_verifications,
|
||||
users
|
||||
RESTART IDENTITY CASCADE;
|
||||
|
||||
-- ---------------------------------------------------------------------------
|
||||
-- Roles & permissions. Permission katalogy (permissions tablisasy) app
|
||||
-- tarapyndan başlanda sinhronlanýar (rbac/perm); bu ýerde diňe rollar.
|
||||
-- ---------------------------------------------------------------------------
|
||||
INSERT INTO roles (code, name, scope, is_super, is_system) VALUES
|
||||
('user', 'User', 'own', false, true),
|
||||
('operator', 'Operator', 'branch', false, false),
|
||||
('loan_operator', 'Loan Operator', 'branch', false, false),
|
||||
('full_operator', 'Full Operator (cards + loans)','branch', false, false),
|
||||
('admin', 'Admin', 'all', false, false),
|
||||
('superadmin', 'Superadmin', 'all', true, true),
|
||||
('manager', 'Branch Manager', 'branch', false, false),
|
||||
('loan_head', 'Karz bölüminiň başlygy', 'all', false, false),
|
||||
('currency_maintainer', 'Walyuta kursy operator', 'all', false, false);
|
||||
|
||||
INSERT INTO role_permissions (role_id, permission_code)
|
||||
SELECT r.id, x.code
|
||||
FROM (VALUES
|
||||
('user', 'cards'),
|
||||
('user', 'loans'),
|
||||
('operator', 'cards'),
|
||||
('operator', 'dashboard'),
|
||||
('loan_operator', 'loans'),
|
||||
('loan_operator', 'dashboard'),
|
||||
('full_operator', 'cards'),
|
||||
('full_operator', 'loans'),
|
||||
('full_operator', 'dashboard'),
|
||||
('admin', 'dashboard'),
|
||||
('admin', 'cards'),
|
||||
('admin', 'loans'),
|
||||
('admin', 'users'),
|
||||
('admin', 'branches'),
|
||||
('admin', 'provinces'),
|
||||
('admin', 'currencies'),
|
||||
('admin', 'payment-settings'),
|
||||
('admin', 'activity-logs'),
|
||||
('manager', 'cards'),
|
||||
('manager', 'loans'),
|
||||
('manager', 'users'),
|
||||
('manager', 'dashboard'),
|
||||
('loan_head', 'loans'),
|
||||
('loan_head', 'dashboard'),
|
||||
('currency_maintainer', 'currencies')
|
||||
) AS x(role, code)
|
||||
JOIN roles r ON r.code = x.role;
|
||||
|
||||
-- ---------------------------------------------------------------------------
|
||||
-- Users (14): superadmin, admin, manager, operator,
|
||||
-- 1 branch-assigned user (serdar), 5 users (gulnar…leyla),
|
||||
-- 1 currency maintainer, 1 loan operator, 1 cards+loans operator,
|
||||
-- 1 head of loans (all branches).
|
||||
-- Password = test1234 for all. Phone unique (idx_users_phone).
|
||||
-- ---------------------------------------------------------------------------
|
||||
INSERT INTO users (email, password, name, first_name, last_name, username, phone, role_id, active) VALUES
|
||||
(
|
||||
'superadmin@bank.tm',
|
||||
'$2a$12$.9KVj6x7wxUMdPcBJ6UpweYbzW4Mka0d2mQj7O20YHXpBKlb3ypdC',
|
||||
'Super Admin', 'Myrat', 'Nazarow', 'superadmin',
|
||||
'+993 61 92 92 48', (SELECT id FROM roles WHERE code = 'superadmin'), true
|
||||
),
|
||||
(
|
||||
'admin@bank.tm',
|
||||
'$2a$12$.9KVj6x7wxUMdPcBJ6UpweYbzW4Mka0d2mQj7O20YHXpBKlb3ypdC',
|
||||
'Admin', 'Nurmuhammet', 'Allanow', 'admin',
|
||||
'+993 61 92 92 41', (SELECT id FROM roles WHERE code = 'admin'), true
|
||||
),
|
||||
(
|
||||
'manager@bank.tm',
|
||||
'$2a$12$.9KVj6x7wxUMdPcBJ6UpweYbzW4Mka0d2mQj7O20YHXpBKlb3ypdC',
|
||||
'Branch Manager', 'Mergen', 'Berdiyew', 'manager',
|
||||
'+993 61 92 92 42', (SELECT id FROM roles WHERE code = 'manager'), true
|
||||
),
|
||||
(
|
||||
'operator@bank.tm',
|
||||
'$2a$12$.9KVj6x7wxUMdPcBJ6UpweYbzW4Mka0d2mQj7O20YHXpBKlb3ypdC',
|
||||
'Operator', 'Aygul', 'Hojayeva', 'operator',
|
||||
'+993 61 92 92 43', (SELECT id FROM roles WHERE code = 'operator'), true
|
||||
),
|
||||
(
|
||||
'serdar@bank.tm',
|
||||
'$2a$12$.9KVj6x7wxUMdPcBJ6UpweYbzW4Mka0d2mQj7O20YHXpBKlb3ypdC',
|
||||
'Serdar Myradow', 'Serdar', 'Myradow', 'serdar',
|
||||
'+993 61 92 92 44', (SELECT id FROM roles WHERE code = 'user'), true
|
||||
),
|
||||
(
|
||||
'gulnar@bank.tm',
|
||||
'$2a$12$.9KVj6x7wxUMdPcBJ6UpweYbzW4Mka0d2mQj7O20YHXpBKlb3ypdC',
|
||||
'Gulnar Orazowa', 'Gulnar', 'Orazowa', 'gulnar',
|
||||
'+993 61 92 92 45', (SELECT id FROM roles WHERE code = 'user'), true
|
||||
),
|
||||
(
|
||||
'dovran@bank.tm',
|
||||
'$2a$12$.9KVj6x7wxUMdPcBJ6UpweYbzW4Mka0d2mQj7O20YHXpBKlb3ypdC',
|
||||
'Dovran Annayew', 'Dovran', 'Annayew', 'dovran',
|
||||
'+993 61 92 92 46', (SELECT id FROM roles WHERE code = 'user'), true
|
||||
),
|
||||
(
|
||||
'maya@bank.tm',
|
||||
'$2a$12$.9KVj6x7wxUMdPcBJ6UpweYbzW4Mka0d2mQj7O20YHXpBKlb3ypdC',
|
||||
'Maya Halylowa', 'Maya', 'Halylowa', 'maya',
|
||||
'+993 61 92 92 47', (SELECT id FROM roles WHERE code = 'user'), true
|
||||
),
|
||||
(
|
||||
'kerim@bank.tm',
|
||||
'$2a$12$.9KVj6x7wxUMdPcBJ6UpweYbzW4Mka0d2mQj7O20YHXpBKlb3ypdC',
|
||||
'Kerim Atayew', 'Kerim', 'Atayew', 'kerim',
|
||||
'+993 61 92 92 49', (SELECT id FROM roles WHERE code = 'user'), true
|
||||
),
|
||||
(
|
||||
'leyla@bank.tm',
|
||||
'$2a$12$.9KVj6x7wxUMdPcBJ6UpweYbzW4Mka0d2mQj7O20YHXpBKlb3ypdC',
|
||||
'Leyla Gurbanowa', 'Leyla', 'Gurbanowa', 'leyla',
|
||||
'+993 61 92 92 40', (SELECT id FROM roles WHERE code = 'user'), true
|
||||
),
|
||||
(
|
||||
'currency@bank.tm',
|
||||
'$2a$12$.9KVj6x7wxUMdPcBJ6UpweYbzW4Mka0d2mQj7O20YHXpBKlb3ypdC',
|
||||
'Walýuta operator', 'Berdi', 'Hojayew', 'currency',
|
||||
'+993 61 92 92 38', (SELECT id FROM roles WHERE code = 'currency_maintainer'), true
|
||||
),
|
||||
(
|
||||
'loanop@bank.tm',
|
||||
'$2a$12$.9KVj6x7wxUMdPcBJ6UpweYbzW4Mka0d2mQj7O20YHXpBKlb3ypdC',
|
||||
'Loan Operator', 'Jeren', 'Atayeva', 'loanop',
|
||||
'+993 61 92 92 37', (SELECT id FROM roles WHERE code = 'loan_operator'), true
|
||||
),
|
||||
(
|
||||
'bothop@bank.tm',
|
||||
'$2a$12$.9KVj6x7wxUMdPcBJ6UpweYbzW4Mka0d2mQj7O20YHXpBKlb3ypdC',
|
||||
'Full Operator', 'Batyr', 'Myradow', 'bothop',
|
||||
'+993 61 92 92 36', (SELECT id FROM roles WHERE code = 'full_operator'), true
|
||||
),
|
||||
(
|
||||
'loanhead@bank.tm',
|
||||
'$2a$12$.9KVj6x7wxUMdPcBJ6UpweYbzW4Mka0d2mQj7O20YHXpBKlb3ypdC',
|
||||
'Loan Head', 'Aman', 'Orazow', 'loanhead',
|
||||
'+993 61 92 92 35', (SELECT id FROM roles WHERE code = 'loan_head'), true
|
||||
);
|
||||
|
||||
-- ---------------------------------------------------------------------------
|
||||
-- Provinces — name = etrap, region = welaýat (admin location list)
|
||||
-- ---------------------------------------------------------------------------
|
||||
INSERT INTO provinces (name, region, active) VALUES
|
||||
('{"en":"Ashgabat","ru":"Ашхабад","tm":"Aşgabat"}'::json, '{"en":"Ashgabat","ru":"Ашхабад","tm":"Aşgabat"}'::json, true),
|
||||
('{"en":"Ak bugday","ru":"Ак бугдай","tm":"Ak bugdaý"}'::json, '{"en":"Ahal","ru":"Ахал","tm":"Ahal"}'::json, true),
|
||||
('{"en":"Babadayhan","ru":"Бабадайхан","tm":"Babadaýhan"}'::json, '{"en":"Ahal","ru":"Ахал","tm":"Ahal"}'::json, true),
|
||||
('{"en":"Baherden","ru":"Бахерден","tm":"Bäherden"}'::json, '{"en":"Ahal","ru":"Ахал","tm":"Ahal"}'::json, true),
|
||||
('{"en":"Gokdepe","ru":"Гокдепе","tm":"Gökdepe"}'::json, '{"en":"Ahal","ru":"Ахал","tm":"Ahal"}'::json, true),
|
||||
('{"en":"Kaka","ru":"Кака","tm":"Kaka"}'::json, '{"en":"Ahal","ru":"Ахал","tm":"Ahal"}'::json, true),
|
||||
('{"en":"Sarahs","ru":"Серахс","tm":"Sarahs"}'::json, '{"en":"Ahal","ru":"Ахал","tm":"Ahal"}'::json, true),
|
||||
('{"en":"Tejen","ru":"Теджен","tm":"Tejen"}'::json, '{"en":"Ahal","ru":"Ахал","tm":"Ahal"}'::json, true),
|
||||
('{"en":"Balkanabat","ru":"Балканабад","tm":"Balkanabat"}'::json, '{"en":"Balkan","ru":"Балкан","tm":"Balkan"}'::json, true),
|
||||
('{"en":"Bereket","ru":"Берекет","tm":"Bereket"}'::json, '{"en":"Balkan","ru":"Балкан","tm":"Balkan"}'::json, true),
|
||||
('{"en":"Esenguly","ru":"Эсенгулы","tm":"Esenguly"}'::json, '{"en":"Balkan","ru":"Балкан","tm":"Balkan"}'::json, true),
|
||||
('{"en":"Etrek","ru":"Этрек","tm":"Etrek"}'::json, '{"en":"Balkan","ru":"Балкан","tm":"Balkan"}'::json, true),
|
||||
('{"en":"Garabogaz","ru":"Гарабогаз","tm":"Garabogaz"}'::json, '{"en":"Balkan","ru":"Балкан","tm":"Balkan"}'::json, true),
|
||||
('{"en":"Gyzylarbat","ru":"Кызыларбат","tm":"Gyzylarbat"}'::json, '{"en":"Balkan","ru":"Балкан","tm":"Balkan"}'::json, true),
|
||||
('{"en":"Hazar","ru":"Хазар","tm":"Hazar"}'::json, '{"en":"Balkan","ru":"Балкан","tm":"Balkan"}'::json, true),
|
||||
('{"en":"Magtymguly","ru":"Махтумкули","tm":"Magtymguly"}'::json, '{"en":"Balkan","ru":"Балкан","tm":"Balkan"}'::json, true),
|
||||
('{"en":"Turkmenbashy","ru":"Туркменбашы","tm":"Türkmenbaşy"}'::json, '{"en":"Balkan","ru":"Балкан","tm":"Balkan"}'::json, true),
|
||||
('{"en":"Akdepe","ru":"Акдепе","tm":"Akdepe"}'::json, '{"en":"Dashoguz","ru":"Дашогуз","tm":"Daşoguz"}'::json, true),
|
||||
('{"en":"Boldumsaz","ru":"Болдумсаз","tm":"Boldumsaz"}'::json, '{"en":"Dashoguz","ru":"Дашогуз","tm":"Daşoguz"}'::json, true),
|
||||
('{"en":"Dashoguz","ru":"Дашогуз","tm":"Daşoguz"}'::json, '{"en":"Dashoguz","ru":"Дашогуз","tm":"Daşoguz"}'::json, true),
|
||||
('{"en":"Gorogly","ru":"Гёроглы","tm":"Görogly"}'::json, '{"en":"Dashoguz","ru":"Дашогуз","tm":"Daşoguz"}'::json, true),
|
||||
('{"en":"Gubadag","ru":"Губадаг","tm":"Gubadag"}'::json, '{"en":"Dashoguz","ru":"Дашогуз","tm":"Daşoguz"}'::json, true),
|
||||
('{"en":"Gurbansoltan Eje","ru":"Гурбансолтан эдже","tm":"Gurbansoltan eje ad."}'::json, '{"en":"Dashoguz","ru":"Дашогуз","tm":"Daşoguz"}'::json, true),
|
||||
('{"en":"Koneurgench","ru":"Кёнеургенч","tm":"Köneürgenç"}'::json, '{"en":"Dashoguz","ru":"Дашогуз","tm":"Daşoguz"}'::json, true),
|
||||
('{"en":"Ruhubelent","ru":"Рухубелент","tm":"Ruhubelent"}'::json, '{"en":"Dashoguz","ru":"Дашогуз","tm":"Daşoguz"}'::json, true),
|
||||
('{"en":"S. Turkmenbashy","ru":"С. Туркменбашы","tm":"S. Türkmenbaşy ad."}'::json, '{"en":"Dashoguz","ru":"Дашогуз","tm":"Daşoguz"}'::json, true),
|
||||
('{"en":"Shawat","ru":"Шават","tm":"Şawat"}'::json, '{"en":"Dashoguz","ru":"Дашогуз","tm":"Daşoguz"}'::json, true),
|
||||
('{"en":"Charjew","ru":"Чарджев","tm":"Çärjew"}'::json, '{"en":"Lebap","ru":"Лебап","tm":"Lebap"}'::json, true),
|
||||
('{"en":"Danew","ru":"Данев","tm":"Dänew"}'::json, '{"en":"Lebap","ru":"Лебап","tm":"Lebap"}'::json, true),
|
||||
('{"en":"Darganata","ru":"Дарганата","tm":"Darganata"}'::json, '{"en":"Lebap","ru":"Лебап","tm":"Lebap"}'::json, true),
|
||||
('{"en":"Dowletli","ru":"Довлетли","tm":"Döwletli"}'::json, '{"en":"Lebap","ru":"Лебап","tm":"Lebap"}'::json, true),
|
||||
('{"en":"Farap","ru":"Фарап","tm":"Farap"}'::json, '{"en":"Lebap","ru":"Лебап","tm":"Lebap"}'::json, true),
|
||||
('{"en":"Garabekewul","ru":"Гарабекевюль","tm":"Garabekewül"}'::json, '{"en":"Lebap","ru":"Лебап","tm":"Lebap"}'::json, true),
|
||||
('{"en":"Halach","ru":"Халач","tm":"Halaç"}'::json, '{"en":"Lebap","ru":"Лебап","tm":"Lebap"}'::json, true),
|
||||
('{"en":"Hojambaz","ru":"Ходжамбаз","tm":"Hojambaz"}'::json, '{"en":"Lebap","ru":"Лебап","tm":"Lebap"}'::json, true),
|
||||
('{"en":"Kerki","ru":"Керки","tm":"Kerki"}'::json, '{"en":"Lebap","ru":"Лебап","tm":"Lebap"}'::json, true),
|
||||
('{"en":"Koytendag","ru":"Койтендаг","tm":"Köýtendag"}'::json, '{"en":"Lebap","ru":"Лебап","tm":"Lebap"}'::json, true),
|
||||
('{"en":"Magdanly","ru":"Магданлы","tm":"Magdanly"}'::json, '{"en":"Lebap","ru":"Лебап","tm":"Lebap"}'::json, true),
|
||||
('{"en":"Sayat","ru":"Саят","tm":"Saýat"}'::json, '{"en":"Lebap","ru":"Лебап","tm":"Lebap"}'::json, true),
|
||||
('{"en":"Seydi","ru":"Сейди","tm":"Seýdi"}'::json, '{"en":"Lebap","ru":"Лебап","tm":"Lebap"}'::json, true),
|
||||
('{"en":"Turkmenabat","ru":"Туркменабад","tm":"Türkmenabat"}'::json, '{"en":"Lebap","ru":"Лебап","tm":"Lebap"}'::json, true),
|
||||
('{"en":"Bayramaly","ru":"Байрамали","tm":"Baýramaly"}'::json, '{"en":"Mary","ru":"Мары","tm":"Mary"}'::json, true),
|
||||
('{"en":"Garagum","ru":"Гарагум","tm":"Garagum"}'::json, '{"en":"Mary","ru":"Мары","tm":"Mary"}'::json, true),
|
||||
('{"en":"Mary","ru":"Мары","tm":"Mary"}'::json, '{"en":"Mary","ru":"Мары","tm":"Mary"}'::json, true),
|
||||
('{"en":"Murgap","ru":"Мургап","tm":"Murgap"}'::json, '{"en":"Mary","ru":"Мары","tm":"Mary"}'::json, true),
|
||||
('{"en":"Oguzhan","ru":"Огузхан","tm":"Oguzhan"}'::json, '{"en":"Mary","ru":"Мары","tm":"Mary"}'::json, true),
|
||||
('{"en":"Sakarchage","ru":"Сакарчаге","tm":"Sakarçäge"}'::json, '{"en":"Mary","ru":"Мары","tm":"Mary"}'::json, true),
|
||||
('{"en":"Serhetabat","ru":"Серхетабад","tm":"Serhetabat"}'::json, '{"en":"Mary","ru":"Мары","tm":"Mary"}'::json, true),
|
||||
('{"en":"Tagtabazar","ru":"Тагтабазар","tm":"Tagtabazar"}'::json, '{"en":"Mary","ru":"Мары","tm":"Mary"}'::json, true),
|
||||
('{"en":"Turkmengala","ru":"Туркменгала","tm":"Türkmengala"}'::json, '{"en":"Mary","ru":"Мары","tm":"Mary"}'::json, true),
|
||||
('{"en":"Vekilbazar","ru":"Векильбазар","tm":"Wekilbazar"}'::json, '{"en":"Mary","ru":"Мары","tm":"Mary"}'::json, true),
|
||||
('{"en":"Yoloten","ru":"Ёлётен","tm":"Ýolöten"}'::json, '{"en":"Mary","ru":"Мары","tm":"Mary"}'::json, true);
|
||||
|
||||
-- ---------------------------------------------------------------------------
|
||||
-- Branches — 8 named mock şahamça first (ids 1–8 for order FKs),
|
||||
-- then one şahamça per remaining etrap.
|
||||
-- ---------------------------------------------------------------------------
|
||||
INSERT INTO branches (
|
||||
unique_code, name, address, region, province_id, phone_numbers,
|
||||
billing_username, billing_password,
|
||||
billing_visa_master_username, billing_visa_master_password,
|
||||
billing_sber_username, billing_sber_password, active
|
||||
)
|
||||
SELECT v.unique_code, v.name::json, v.address::json, v.region, p.id, '+993 61 92 92 48', v.billing_username, 'billing_pass',
|
||||
replace(v.billing_username, 'billing_', 'vm_'), 'vm_pass',
|
||||
replace(v.billing_username, 'billing_', 'sber_'), 'sber_pass', v.active
|
||||
FROM (VALUES
|
||||
('AGB-01', '{"en":"Ashgabat Central Branch","ru":"Центральный филиал Ашхабад","tm":"Aşgabat Merkezi şahamça"}', '{"en":"Archabil Ave 1","ru":"пр. Арчабиль 1","tm":"Arçabil şaýoly 1"}', 'AG', 'Aşgabat', 'billing_agb', true),
|
||||
('AGB-02', '{"en":"Ashgabat Kopetdag Branch","ru":"Филиал Копетдаг","tm":"Köpetdag şahamçasy"}', '{"en":"Turkmenbashy Ave 45","ru":"пр. Туркменбаши 45","tm":"Türkmenbaşy şaýoly 45"}', 'AG', 'Aşgabat', 'billing_agb2', true),
|
||||
('AHL-01', '{"en":"Ahal Branch","ru":"Ахалский филиал","tm":"Ahal şahamçasy"}', '{"en":"Ak bugday, Main St 10","ru":"Ак бугдай, ул. Главная 10","tm":"Ak bugdaý, Baş köçe 10"}', 'AH', 'Ak bugdaý', 'billing_ahl', true),
|
||||
('BLK-01', '{"en":"Balkanabat Branch","ru":"Филиал Балканабад","tm":"Balkanabat şahamçasy"}', '{"en":"Garaşsyzlyk St 7","ru":"ул. Гарашсызлык 7","tm":"Garaşsyzlyk köçesi 7"}', 'BL', 'Balkanabat', 'billing_blk', true),
|
||||
('DSZ-01', '{"en":"Dashoguz Branch","ru":"Филиал Дашогуз","tm":"Daşoguz şahamçasy"}', '{"en":"Galkynyş St 3","ru":"ул. Галкыныш 3","tm":"Galkynyş köçesi 3"}', 'DZ', 'Daşoguz', 'billing_dsz', true),
|
||||
('LBP-01', '{"en":"Turkmenabat Branch","ru":"Филиал Туркменабад","tm":"Türkmenabat şahamçasy"}', '{"en":"Magtymguly Ave 12","ru":"пр. Махтумкули 12","tm":"Magtymguly şaýoly 12"}', 'LB', 'Türkmenabat', 'billing_lbp', true),
|
||||
('MRY-01', '{"en":"Mary Branch","ru":"Марыйский филиал","tm":"Mary şahamçasy"}', '{"en":"Mollanepes St 8","ru":"ул. Молланепес 8","tm":"Mollanepes köçesi 8"}', 'MR', 'Mary', 'billing_mry', true),
|
||||
('MRY-02', '{"en":"Bayramaly Branch (inactive)","ru":"Филиал Байрамали (неактивен)","tm":"Baýramaly şahamçasy (işjeň däl)"}', '{"en":"Bayramaly, Central 1","ru":"Байрамали, Центральная 1","tm":"Baýramaly, Merkezi 1"}', 'MR', 'Baýramaly', 'billing_mry2', false)
|
||||
) AS v(unique_code, name, address, region, province_tm, billing_username, active)
|
||||
JOIN provinces p ON p.name->>'tm' = v.province_tm;
|
||||
|
||||
INSERT INTO branches (unique_code, name, address, region, province_id, phone_numbers, active)
|
||||
SELECT
|
||||
s.region_code || '-' || s.name_slug,
|
||||
json_build_object(
|
||||
'en', (s.name->>'en') || ' branch',
|
||||
'ru', (s.name->>'ru') || ' филиал',
|
||||
'tm', (s.name->>'tm') || ' şahamçasy'
|
||||
),
|
||||
json_build_object('en', s.name->>'en', 'ru', s.name->>'ru', 'tm', s.name->>'tm'),
|
||||
s.region_code,
|
||||
s.id,
|
||||
'+993 61 92 92 48',
|
||||
true
|
||||
FROM (
|
||||
SELECT
|
||||
p.id,
|
||||
p.name,
|
||||
CASE p.region->>'tm'
|
||||
WHEN 'Aşgabat' THEN 'AG'
|
||||
WHEN 'Ahal' THEN 'AH'
|
||||
WHEN 'Balkan' THEN 'BL'
|
||||
WHEN 'Daşoguz' THEN 'DZ'
|
||||
WHEN 'Lebap' THEN 'LB'
|
||||
WHEN 'Mary' THEN 'MR'
|
||||
ELSE 'XX'
|
||||
END AS region_code,
|
||||
trim(both '-' FROM upper(regexp_replace(
|
||||
translate(p.name->>'tm', 'ÄäÇçŇňÖöŞşÜüÝý', 'AaCcNnOoSsUuYy'),
|
||||
'[^A-Za-z0-9]+', '-', 'g'
|
||||
))) AS name_slug
|
||||
FROM provinces p
|
||||
WHERE p.active
|
||||
) s
|
||||
WHERE NOT EXISTS (
|
||||
SELECT 1 FROM branches b
|
||||
WHERE b.unique_code = s.region_code || '-' || s.name_slug
|
||||
OR b.province_id = s.id
|
||||
);
|
||||
|
||||
INSERT INTO branch_user (branch_id, user_id) VALUES
|
||||
(1, 1),
|
||||
(1, 2),
|
||||
(1, 3),
|
||||
(7, 4),
|
||||
(2, 5),
|
||||
(1, 11),
|
||||
(7, 12),
|
||||
(7, 13);
|
||||
|
||||
-- ---------------------------------------------------------------------------
|
||||
-- Card types (Kart görnüşleri) & card states (çykarma sebäpleri)
|
||||
-- ---------------------------------------------------------------------------
|
||||
INSERT INTO card_types (name, price, notes, active) VALUES
|
||||
('{"en":"Altyn Asyr","ru":"Алтын Асыр","tm":"Altyn Asyr"}'::json, '32', '', true),
|
||||
('{"en":"Family","ru":"Семейная","tm":"Maşgala"}'::json, '32', '', true),
|
||||
('{"en":"Deposit","ru":"Депозитная","tm":"Goýum"}'::json, '32', '', true),
|
||||
('{"en":"Pension","ru":"Пенсионная","tm":"Pensiýa"}'::json, '32', '', true),
|
||||
('{"en":"Entrepreneur","ru":"Предпринимательская","tm":"Telekeçi"}'::json, '32', '', true),
|
||||
('{"en":"Credit","ru":"Кредитная","tm":"Karz"}'::json, '32', '', false),
|
||||
('{"en":"Overdraft","ru":"Овердрафт","tm":"Owerdraft"}'::json, '32', '', true);
|
||||
|
||||
INSERT INTO card_states (name, price, notes, active) VALUES
|
||||
('{"en":"New","ru":"Новая","tm":"Täze"}'::json, '32', '', true),
|
||||
('{"en":"Broken / damaged","ru":"Сломанная / повреждённая","tm":"Döwülen/Zaýalanan"}'::json, '32', '', true),
|
||||
('{"en":"Usage period expired","ru":"Истёк срок использования","tm":"Ulanylyş möhleti geçen"}'::json, '32', '', true),
|
||||
('{"en":"Surname change","ru":"Смена фамилии","tm":"Familiýasy üýtgeýär"}'::json, '32', '', true),
|
||||
('{"en":"Lost","ru":"Утеряна","tm":"Ýiten"}'::json, '37.75', '', true),
|
||||
('{"en":"PIN envelope (blocked)","ru":"PIN-конверт (заблокирован)","tm":"Pin bukja (bloklanan)"}'::json, '3.02', '', false),
|
||||
('{"en":"Requisites","ru":"Реквизиты","tm":"Rekwizit"}'::json, '2.30', '', false);
|
||||
|
||||
-- ---------------------------------------------------------------------------
|
||||
-- Loan types (Karz görnüşleri) & required docs
|
||||
-- ---------------------------------------------------------------------------
|
||||
INSERT INTO loan_types (name, tax, maturity, notes, active) VALUES
|
||||
('{"en":"Youth / newlyweds loan","ru":"Кредит для молодожёнов","tm":"Ýaş çatynjalara"}'::json, 1.00, '30', '{}'::json, true),
|
||||
('{"en":"Consumer loan secured by guarantor","ru":"Потребительский кредит под поручительство","tm":"Üpjünçiligine zamunlyk bolan sarp ediş karzy"}'::json, 1.00, '30', '{}'::json, true),
|
||||
('{"en":"Small loans","ru":"Кредиты малого объёма","tm":"Kiçi göwrümli karzlar"}'::json, 1.00, '30', '{}'::json, true),
|
||||
('{"en":"Consumer loan secured by collateral","ru":"Потребительский кредит под залог имущества","tm":"Üpjünçiligine girew emlägi bolan sarp ediş karzy"}'::json, 1.00, '30', '{}'::json, true),
|
||||
('{"en":"Student loan","ru":"Студенческий кредит","tm":"Talyp karzy"}'::json, 1.00, '30', '{"en":"Note","ru":"Примечание","tm":"Bellik"}'::json, true);
|
||||
|
||||
INSERT INTO loan_order_required_docs (name, value, active) VALUES
|
||||
('Passport copy', 'passport', true),
|
||||
('Income certificate', 'income', true),
|
||||
('Employment letter', 'employment', true),
|
||||
('Property documents', 'property', true),
|
||||
('Guarantor passport', 'guarantor_passport', true),
|
||||
('Old checklist (inactive)', 'legacy', false);
|
||||
|
||||
-- ---------------------------------------------------------------------------
|
||||
-- Cards belonging to users
|
||||
-- ---------------------------------------------------------------------------
|
||||
INSERT INTO cards (user_id, number, name, month, year, type) VALUES
|
||||
(5, '4169740012345678', 'SERDAR MYRADOW', '12', '28', '1'),
|
||||
(6, '4169740087654321', 'GULNAR ORAZOWA', '06', '27', '1'),
|
||||
(8, '5536910011223344', 'MAYA HALYLOWA', '03', '29', '3'),
|
||||
(7, '9860010055667788', 'DOVRAN ANNAYEW', '09', '26', '4'),
|
||||
(9, '4169740011112222', 'KERIM ATAYEW', '08', '28', '1'),
|
||||
(10, '5536910055556666', 'LEYLA GURBANOWA', '11', '29', '3');
|
||||
|
||||
-- ---------------------------------------------------------------------------
|
||||
-- Card orders
|
||||
-- ---------------------------------------------------------------------------
|
||||
INSERT INTO card_orders (
|
||||
unique_id, card_state_id, card_type_id, region, branch_id,
|
||||
customer_name, customer_surname, customer_patronic_name, born_at,
|
||||
citizenship, passport_serie, passport_id, passport_given_at, passport_given_by,
|
||||
born_place, job_location, passport_address, real_address, phone, phone_additional,
|
||||
status, passport_one, passport_two, passport_three, passport_four,
|
||||
notes, user_id, paid
|
||||
) VALUES
|
||||
(
|
||||
'CO-2026-0001', 1, 1, 'AG', 1,
|
||||
'Serdar', 'Myradow', 'Gurbanowicz', '1990-05-12',
|
||||
'TM', 'I-AG', '123456', '2015-03-20', 'Ashgabat City Police',
|
||||
'Ashgabat', 'Bank employee', 'Ashgabat, 10ýyl Abadanlyk 5', 'Ashgabat, 10ýyl Abadanlyk 5',
|
||||
'+993 61 92 92 48', '+993 61 92 92 48',
|
||||
'pending', 'pass1.jpg', 'pass2.jpg', 'pass3.jpg', 'pass4.jpg',
|
||||
'First Visa Classic order', 5, false
|
||||
),
|
||||
(
|
||||
'CO-2026-0002', 2, 2, 'AG', 1,
|
||||
'Gulnar', 'Orazowa', 'Batyrowna', '1988-11-03',
|
||||
'TM', 'I-AG', '654321', '2014-08-11', 'Ashgabat City Police',
|
||||
'Ashgabat', 'Teacher', 'Ashgabat, Andalyp 12', 'Ashgabat, Andalyp 12',
|
||||
'+993 61 92 92 48', NULL,
|
||||
'approved', 'pass1.jpg', 'pass2.jpg', 'pass3.jpg', 'pass4.jpg',
|
||||
'Lost card reissue — Gold', 6, true
|
||||
),
|
||||
(
|
||||
'CO-2026-0003', 1, 4, 'MR', 7,
|
||||
'Dovran', 'Annayew', 'Hojamyradowiç', '1995-01-25',
|
||||
'TM', 'I-MR', '112233', '2018-06-01', 'Mary Police',
|
||||
'Mary', 'Farmer', 'Mary, Garaşsyzlyk 3', 'Mary, Garaşsyzlyk 3',
|
||||
'+993 61 92 92 48', NULL,
|
||||
'rejected', 'pass1.jpg', 'pass2.jpg', 'pass3.jpg', 'pass4.jpg',
|
||||
'Incomplete documents', 7, false
|
||||
),
|
||||
(
|
||||
'CO-2026-0004', 3, 3, 'BL', 4,
|
||||
'Maya', 'Halylowa', 'Saparowna', '1992-07-19',
|
||||
'TM', 'I-BL', '445566', '2016-02-14', 'Balkanabat Police',
|
||||
'Balkanabat', 'Nurse', 'Balkanabat, Magtymguly 9', 'Balkanabat, Magtymguly 9',
|
||||
'+993 61 92 92 48', NULL,
|
||||
'pending', 'pass1.jpg', 'pass2.jpg', 'pass3.jpg', 'pass4.jpg',
|
||||
'Damaged MasterCard', 8, false
|
||||
);
|
||||
|
||||
-- ---------------------------------------------------------------------------
|
||||
-- Card PIN orders
|
||||
-- ---------------------------------------------------------------------------
|
||||
INSERT INTO card_pin_orders (
|
||||
unique_id, user_id, card_type_id, card_number, 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
|
||||
) VALUES
|
||||
(
|
||||
'CPO-2026-0001', 5, 1, '4169740012345678', 'AG', 1,
|
||||
'Serdar', 'Myradow', 'Gurbanowicz', '1990-05-12', '+993 61 92 92 48',
|
||||
'I-AG', '123456',
|
||||
'pin1.jpg', 'pin2.jpg', 'pin3.jpg', 'pin4.jpg',
|
||||
'pending', 'PIN reset request'
|
||||
),
|
||||
(
|
||||
'CPO-2026-0002', 7, 4, '9860010055667788', 'MR', 7,
|
||||
'Dovran', 'Annayew', 'Hojamyradowiç', '1995-01-25', '+993 61 92 92 48',
|
||||
'I-MR', '112233',
|
||||
'pin1.jpg', 'pin2.jpg', 'pin3.jpg', 'pin4.jpg',
|
||||
'completed', 'PIN issued'
|
||||
),
|
||||
(
|
||||
'CPO-2026-0003', NULL, 2, '4169740099990000', 'AH', 3,
|
||||
'Batyr', 'Saparow', 'Orazowicz', '1991-12-01', '+993 61 92 92 48',
|
||||
'I-AH', '334455',
|
||||
'pin1.jpg', 'pin2.jpg', 'pin3.jpg', 'pin4.jpg',
|
||||
'rejected', 'Passport mismatch'
|
||||
);
|
||||
|
||||
-- ---------------------------------------------------------------------------
|
||||
-- Card rekwizit orders
|
||||
-- ---------------------------------------------------------------------------
|
||||
INSERT INTO card_rekwizit_orders (
|
||||
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
|
||||
) VALUES
|
||||
(
|
||||
'CRO-2026-0001', 6, 1, '4169740088776655', '08', '2028',
|
||||
'AG', 1,
|
||||
'Gulnar', 'Orazowa', 'Batyrowna', '1988-11-03', '+993 61 92 92 48',
|
||||
'I-AG', '654321',
|
||||
'rek1.jpg', 'rek2.jpg', 'rek3.jpg', 'rek4.jpg',
|
||||
'pending', 'Card details request'
|
||||
),
|
||||
(
|
||||
'CRO-2026-0002', 8, 3, '9860010011223344', '11', '2027',
|
||||
'BL', 4,
|
||||
'Maya', 'Halylowa', 'Saparowna', '1992-07-19', '+993 61 92 92 48',
|
||||
'I-BL', '445566',
|
||||
'rek1.jpg', 'rek2.jpg', 'rek3.jpg', 'rek4.jpg',
|
||||
'approved', 'Details issued'
|
||||
),
|
||||
(
|
||||
'CRO-2026-0003', NULL, 2, '4169740077001122', '01', '2030',
|
||||
'AH', 3,
|
||||
'Leyla', 'Garayeva', 'Meredowna', '1993-04-08', '+993 61 92 92 48',
|
||||
'I-AH', '778899',
|
||||
'rek1.jpg', 'rek2.jpg', 'rek3.jpg', 'rek4.jpg',
|
||||
'rejected', 'Expired card'
|
||||
);
|
||||
|
||||
-- ---------------------------------------------------------------------------
|
||||
-- Loan orders
|
||||
-- ---------------------------------------------------------------------------
|
||||
INSERT INTO loan_orders (
|
||||
unique_id, source, user_id, loan_type, region, branch_id,
|
||||
customer_name, customer_surname, customer_patronic_name,
|
||||
passport_address, real_address, passport_serie, passport_id,
|
||||
passport_given_at, passport_given_by, born_place, born_at,
|
||||
email, phone, phone_additional, phone_home,
|
||||
work_region, work_province_id, work_company, work_company_accountant_number,
|
||||
work_started_at, work_salary, work_position,
|
||||
education, marriage_status,
|
||||
passport_one, passport_two, passport_three, passport_four,
|
||||
loan_amount, card_number, card_name, card_month, card_year,
|
||||
guarantor_name, guarantor_surname, guarantor_patronic_name,
|
||||
guarantor_passport_serie, guarantor_passport_id,
|
||||
guarantor_card_number, guarantor_card_name, guarantor_card_month, guarantor_card_year,
|
||||
guarantor_note,
|
||||
loan_order_required_doc_id, status, satisfiable, notes
|
||||
) VALUES
|
||||
(
|
||||
'0001', 'mobile', 9, 1, 'AG', 1,
|
||||
'Kerim', 'Atayew', 'Begliýewiç',
|
||||
'Ashgabat, Bitaraplyk 20', 'Ashgabat, Bitaraplyk 20', 'I-AG', '101010',
|
||||
'2017-01-15', 'Ashgabat City Police', 'Ashgabat', '1989-03-21',
|
||||
'kerim@bank.tm', '+993 61 92 92 48', NULL, '+993 61 92 92 48',
|
||||
'AG', 1, 'Türkmen Poçta', 'ACC-1001',
|
||||
'2019-05-01', '4500', 'Specialist',
|
||||
'higher', 'married',
|
||||
'lo1.jpg', 'lo2.jpg', 'lo3.jpg', 'lo4.jpg',
|
||||
'20000', '4169740011112222', 'KERIM ATAYEW', '08', '28',
|
||||
'Myrat', 'Atayew', 'Begliýewiç',
|
||||
'I-AG', '202020',
|
||||
'4169740033334444', 'MYRAT ATAYEW', '08', '27',
|
||||
'Brother',
|
||||
1, 'pending', 'yes', 'Consumer loan application'
|
||||
),
|
||||
(
|
||||
'0002', 'mobile', 10, 3, 'AG', 2,
|
||||
'Leyla', 'Gurbanowa', 'Saparowna',
|
||||
'Ashgabat, Andalyp 8', 'Ashgabat, Andalyp 8', 'I-AG', '303030',
|
||||
'2016-09-10', 'Ashgabat City Police', 'Ashgabat', '1994-08-02',
|
||||
'leyla@bank.tm', '+993 61 92 92 48', '+993 61 92 92 48', NULL,
|
||||
'AG', 1, 'Altyn Asyr', 'ACC-2002',
|
||||
'2020-02-15', '3800', 'Accountant',
|
||||
'higher', 'single',
|
||||
'lo1.jpg', 'lo2.jpg', 'lo3.jpg', 'lo4.jpg',
|
||||
'80000', '5536910055556666', 'LEYLA GURBANOWA', '11', '29',
|
||||
NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
|
||||
2, 'approved', 'yes', 'Auto loan approved'
|
||||
),
|
||||
(
|
||||
'0003', 'mobile', 7, 2, 'MR', 7,
|
||||
'Dovran', 'Annayew', 'Hojamyradowiç',
|
||||
'Mary, Galkynyş 15', 'Mary, Galkynyş 15', 'I-MR', '112233',
|
||||
'2012-04-22', 'Mary Police', 'Mary', '1995-01-25',
|
||||
'dovran@bank.tm', '+993 61 92 92 48', NULL, NULL,
|
||||
'MR', (SELECT id FROM provinces WHERE name->>'tm' = 'Mary'), 'Mary Textile', 'ACC-3003',
|
||||
'2015-01-10', '5200', 'Engineer',
|
||||
'higher', 'married',
|
||||
'lo1.jpg', 'lo2.jpg', 'lo3.jpg', 'lo4.jpg',
|
||||
'250000', NULL, NULL, NULL, NULL,
|
||||
'Hatyja', 'Jumaýewa', 'Berdiýewna',
|
||||
'I-MR', '505050',
|
||||
'9860010077778888', 'HATYJA JUMAYEWA', '01', '28',
|
||||
'Spouse',
|
||||
4, 'review', 'pending', 'Mortgage under review'
|
||||
),
|
||||
(
|
||||
'0004', 'mobile', NULL, 4, 'LB', 6,
|
||||
'Oguljenan', 'Çaryýewa', 'Myradowna',
|
||||
'Turkmenabat, Magtymguly 2', 'Turkmenabat, Magtymguly 2', 'I-LB', '606060',
|
||||
'2019-11-05', 'Turkmenabat Police', 'Turkmenabat', '1996-12-12',
|
||||
'ogul@mail.tm', '+993 61 92 92 48', NULL, NULL,
|
||||
'LB', (SELECT id FROM provinces WHERE name->>'tm' = 'Türkmenabat'), 'Self-employed', NULL,
|
||||
'2021-03-01', '6000', 'Entrepreneur',
|
||||
'secondary', 'single',
|
||||
'lo1.jpg', 'lo2.jpg', 'lo3.jpg', 'lo4.jpg',
|
||||
'50000', '4169740099998888', 'OGULJENAN CARYYEWA', '04', '27',
|
||||
NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
|
||||
3, 'rejected', 'no', 'Insufficient income proof'
|
||||
);
|
||||
|
||||
-- ---------------------------------------------------------------------------
|
||||
-- Loans (repayment accounts)
|
||||
-- ---------------------------------------------------------------------------
|
||||
INSERT INTO loans (user_id, passport_serie, passport_id, account_number) VALUES
|
||||
(9, 'I-AG', '101010', 'ACC-LOAN-10001'),
|
||||
(10, 'I-AG', '303030', 'ACC-LOAN-10002'),
|
||||
(7, 'I-MR', '112233', 'ACC-LOAN-10003'),
|
||||
(5, 'I-AG', '123456', 'ACC-LOAN-10004'),
|
||||
(6, 'I-AG', '654321', 'ACC-LOAN-10005');
|
||||
|
||||
-- ---------------------------------------------------------------------------
|
||||
-- Loan paid-off letters
|
||||
-- ---------------------------------------------------------------------------
|
||||
INSERT INTO loan_paid_off_letters (
|
||||
unique_id, region, branch_id, user_id,
|
||||
customer_name, customer_surname, customer_patronic_name, born_at, phone,
|
||||
passport_serie, passport_id, status, notes,
|
||||
loan_contract_number, loan_contract_date, loan_amount, loan_reason, loan_file
|
||||
) VALUES
|
||||
(
|
||||
'LPL-2026-0001', 'AG', 1, 9,
|
||||
'Kerim', 'Atayew', 'Begliýewiç', '1989-03-21', '+993 61 92 92 48',
|
||||
'I-AG', '101010', 'pending', 'Waiting for branch confirmation',
|
||||
'CTR-2024-1001', '2024-01-15', '15000', 'Consumer loan closed', 'letter1.pdf'
|
||||
),
|
||||
(
|
||||
'LPL-2026-0002', 'AG', 2, 10,
|
||||
'Leyla', 'Gurbanowa', 'Saparowna', '1994-08-02', '+993 61 92 92 48',
|
||||
'I-AG', '303030', 'approved', 'Paid off confirmed',
|
||||
'CTR-2023-2202', '2023-06-01', '8000', 'Early repayment', 'letter2.pdf'
|
||||
),
|
||||
(
|
||||
'LPL-2026-0003', 'AG', 1, NULL,
|
||||
'Batyr', 'Saparow', 'Orazowicz', '1991-12-01', '+993 61 92 92 48',
|
||||
'I-AH', '334455', 'rejected', 'Outstanding balance remains',
|
||||
'CTR-2025-3303', '2025-02-10', '20000', 'Requested too early', NULL
|
||||
);
|
||||
|
||||
-- ---------------------------------------------------------------------------
|
||||
-- Visa / Master payment orders (type = student)
|
||||
-- documents JSON keys match the admin upload slots (student + sender).
|
||||
-- ---------------------------------------------------------------------------
|
||||
INSERT INTO visa_master_payment_orders (
|
||||
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,
|
||||
paid, amount_usd
|
||||
) VALUES
|
||||
(
|
||||
'VMP-2026-0001', 'student', 'Serdar', 'Myradow', '+993 61 92 92 48', 'serdar@bank.tm',
|
||||
'AG', 1, 5, 'Aşgabat, Parahat 7',
|
||||
'{"fullName":"Myradow Serdar Orazowiç","passportSerie":"I-AG","passportNumber":"123456","depositAccount":"23202984200012345678"}'::json,
|
||||
'[{"fullName":"Orazowa Gulnar Myradowna","passportSerie":"I-AG","passportNumber":"654321"}]'::json,
|
||||
'{
|
||||
"student_visa_card_details":["visa-card-1.pdf"],
|
||||
"student_enrollment_certificate":["enrollment-1.pdf"],
|
||||
"student_ticket_copy":["ticket-1.pdf"],
|
||||
"student_internal_passport":["student-internal-1.pdf"],
|
||||
"student_foreign_passport":["student-foreign-1.pdf"],
|
||||
"student_visa_page":["student-visa-page-1.pdf"],
|
||||
"student_stamp_page":["student-stamp-1.pdf"],
|
||||
"student_enrollment_clarification":[],
|
||||
"sender_internal_passport":["sender-internal-1.pdf"],
|
||||
"sender_foreign_passport":["sender-foreign-1.pdf"],
|
||||
"sender_stamp_page":["sender-stamp-1.pdf"],
|
||||
"kinship_documents":["kinship-1.pdf"],
|
||||
"first_passport_series_info":[],
|
||||
"police_passport_series_info":[]
|
||||
}'::json,
|
||||
'pending', 'Garaşylýar',
|
||||
'Myradow Serdar Orazowiç', 'I-AG', '123456', '23202984200012345678',
|
||||
'Orazowa Gulnar Myradowna', 'I-AG', '654321', NULL,
|
||||
false, NULL
|
||||
),
|
||||
(
|
||||
'VMP-2026-0002', 'student', 'Kerim', 'Atayew', '+993 61 92 92 48', NULL,
|
||||
'AG', 2, 9, 'Aşgabat, 10 ýyl Abadançylyk',
|
||||
'{"fullName":"Atayew Kerim Begliýewiç","passportSerie":"I-AG","passportNumber":"101010","depositAccount":"23202984200010101011"}'::json,
|
||||
'[{"fullName":"Gurbanowa Leyla Saparowna","passportSerie":"I-AG","passportNumber":"303030"}]'::json,
|
||||
'{
|
||||
"student_visa_card_details":["visa-card-2.pdf"],
|
||||
"student_enrollment_certificate":[],
|
||||
"student_ticket_copy":[],
|
||||
"student_internal_passport":["student-internal-2.pdf"],
|
||||
"student_foreign_passport":[],
|
||||
"student_visa_page":[],
|
||||
"student_stamp_page":[],
|
||||
"student_enrollment_clarification":[],
|
||||
"sender_internal_passport":["sender-internal-2.pdf"],
|
||||
"sender_foreign_passport":[],
|
||||
"sender_stamp_page":["sender-stamp-2.pdf"],
|
||||
"kinship_documents":[],
|
||||
"first_passport_series_info":["old-passport-series-2.pdf"],
|
||||
"police_passport_series_info":[]
|
||||
}'::json,
|
||||
'approved', NULL,
|
||||
'Atayew Kerim Begliýewiç', 'I-AG', '101010', '23202984200010101011',
|
||||
'Gurbanowa Leyla Saparowna', 'I-AG', '303030', NULL,
|
||||
true, 150.00
|
||||
);
|
||||
|
||||
-- ---------------------------------------------------------------------------
|
||||
-- Sber payment orders (type = sber). Ids 3–8; aşakdaky töleg/loglar
|
||||
-- order_id 4, 5, 6-a salgylanýar.
|
||||
-- ---------------------------------------------------------------------------
|
||||
INSERT INTO visa_master_payment_orders (
|
||||
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,
|
||||
paid, amount_usd
|
||||
) VALUES
|
||||
(
|
||||
'VMP-2026-0003', 'sber', 'Batyr', 'Saparow', '+993 61 92 92 48', NULL,
|
||||
'AG', 1, 5, 'Aşgabat, Bitarap Türkmenistan 12',
|
||||
'{"fullName":"Saparow Batyr Annaýewiç","passportSerie":"I-AG","passportNumber":"202020","depositAccount":"23202984200020202022"}'::json,
|
||||
'[{"fullName":"Saparowa Aýna Batyrowna","passportSerie":"I-AG","passportNumber":"404040"}]'::json,
|
||||
'{
|
||||
"student_visa_card_details":["sber-card-3.pdf"],
|
||||
"student_enrollment_certificate":["enrollment-3.pdf"],
|
||||
"student_ticket_copy":[],
|
||||
"student_internal_passport":["student-internal-3.pdf"],
|
||||
"student_foreign_passport":["student-foreign-3.pdf"],
|
||||
"student_visa_page":[],
|
||||
"student_stamp_page":[],
|
||||
"student_enrollment_clarification":[],
|
||||
"sender_internal_passport":["sender-internal-3.pdf"],
|
||||
"sender_foreign_passport":[],
|
||||
"sender_stamp_page":[],
|
||||
"kinship_documents":["kinship-3.pdf"],
|
||||
"first_passport_series_info":[],
|
||||
"police_passport_series_info":[]
|
||||
}'::json,
|
||||
'pending', 'Sber tölegi garaşylýar',
|
||||
'Saparow Batyr Annaýewiç', 'I-AG', '202020', '23202984200020202022',
|
||||
'Saparowa Aýna Batyrowna', 'I-AG', '404040', NULL,
|
||||
false, 200.00
|
||||
),
|
||||
(
|
||||
'VMP-2026-0004', 'sber', 'Aýna', 'Orazowa', '+993 61 92 92 48', 'gulnar@bank.tm',
|
||||
'AG', 1, 6, 'Aşgabat, Andalyp 21',
|
||||
'{"fullName":"Orazowa Gulnar Myradowna","passportSerie":"I-AG","passportNumber":"654321","depositAccount":"23202984200065432100"}'::json,
|
||||
'[{"fullName":"Orazowa Aýna Serdarowna","passportSerie":"I-AG","passportNumber":"505050"}]'::json,
|
||||
'{
|
||||
"student_visa_card_details":["sber-card-4.pdf"],
|
||||
"student_enrollment_certificate":["enrollment-4.pdf"],
|
||||
"student_ticket_copy":[],
|
||||
"student_internal_passport":["student-internal-4.pdf"],
|
||||
"student_foreign_passport":["student-foreign-4.pdf"],
|
||||
"student_visa_page":["student-visa-page-4.pdf"],
|
||||
"student_stamp_page":[],
|
||||
"student_enrollment_clarification":[],
|
||||
"sender_internal_passport":["sender-internal-4.pdf"],
|
||||
"sender_foreign_passport":[],
|
||||
"sender_stamp_page":[],
|
||||
"kinship_documents":["kinship-4.pdf"],
|
||||
"first_passport_series_info":[],
|
||||
"police_passport_series_info":[]
|
||||
}'::json,
|
||||
'approved', 'Sber tölegi geçirildi',
|
||||
'Orazowa Gulnar Myradowna', 'I-AG', '654321', '23202984200065432100',
|
||||
'Orazowa Aýna Serdarowna', 'I-AG', '505050', NULL,
|
||||
true, 250.00
|
||||
),
|
||||
(
|
||||
'VMP-2026-0005', 'sber', 'Merdan', 'Hojaýew', '+993 61 92 92 48', 'dovran@bank.tm',
|
||||
'AG', 2, 7, 'Aşgabat, Garaşsyzlyk 55',
|
||||
'{"fullName":"Hojaýew Döwran Amanowiç","passportSerie":"I-AG","passportNumber":"606060","depositAccount":"23202984200060606066"}'::json,
|
||||
'[{"fullName":"Hojaýew Merdan Döwranowiç","passportSerie":"I-AG","passportNumber":"707070"}]'::json,
|
||||
'{
|
||||
"student_visa_card_details":["sber-card-5.pdf"],
|
||||
"student_enrollment_certificate":["enrollment-5.pdf"],
|
||||
"student_ticket_copy":[],
|
||||
"student_internal_passport":["student-internal-5.pdf"],
|
||||
"student_foreign_passport":["student-foreign-5.pdf"],
|
||||
"student_visa_page":["student-visa-page-5.pdf"],
|
||||
"student_stamp_page":[],
|
||||
"student_enrollment_clarification":[],
|
||||
"sender_internal_passport":["sender-internal-5.pdf"],
|
||||
"sender_foreign_passport":[],
|
||||
"sender_stamp_page":[],
|
||||
"kinship_documents":["kinship-5.pdf"],
|
||||
"first_passport_series_info":[],
|
||||
"police_passport_series_info":[]
|
||||
}'::json,
|
||||
'approved', 'Töleg şowsuz, gaýtadan synanyşyň',
|
||||
'Hojaýew Döwran Amanowiç', 'I-AG', '606060', '23202984200060606066',
|
||||
'Hojaýew Merdan Döwranowiç', 'I-AG', '707070', NULL,
|
||||
false, 200.00
|
||||
),
|
||||
(
|
||||
'VMP-2026-0006', 'sber', 'Leýli', 'Nurýewa', '+993 61 92 92 48', 'maya@bank.tm',
|
||||
'AG', 1, 8, 'Aşgabat, Oguzhan 3',
|
||||
'{"fullName":"Nurýewa Maýa Batyrowna","passportSerie":"I-AG","passportNumber":"808080","depositAccount":"23202984200080808088"}'::json,
|
||||
'[{"fullName":"Nurýewa Leýli Myratowna","passportSerie":"I-AG","passportNumber":"909090"}]'::json,
|
||||
'{
|
||||
"student_visa_card_details":["sber-card-6.pdf"],
|
||||
"student_enrollment_certificate":["enrollment-6.pdf"],
|
||||
"student_ticket_copy":[],
|
||||
"student_internal_passport":["student-internal-6.pdf"],
|
||||
"student_foreign_passport":["student-foreign-6.pdf"],
|
||||
"student_visa_page":["student-visa-page-6.pdf"],
|
||||
"student_stamp_page":[],
|
||||
"student_enrollment_clarification":[],
|
||||
"sender_internal_passport":["sender-internal-6.pdf"],
|
||||
"sender_foreign_passport":[],
|
||||
"sender_stamp_page":[],
|
||||
"kinship_documents":["kinship-6.pdf"],
|
||||
"first_passport_series_info":[],
|
||||
"police_passport_series_info":[]
|
||||
}'::json,
|
||||
'approved', 'GBÜS tassyklamasy garaşylýar',
|
||||
'Nurýewa Maýa Batyrowna', 'I-AG', '808080', '23202984200080808088',
|
||||
'Nurýewa Leýli Myratowna', 'I-AG', '909090', NULL,
|
||||
false, 150.00
|
||||
),
|
||||
(
|
||||
'VMP-2026-0007', 'sber', 'Rahman', 'Gurbanow', '+993 61 92 92 48', 'leyla@bank.tm',
|
||||
'AH', 3, 10, 'Ak bugdaý, Täze ýol 4',
|
||||
'{"fullName":"Gurbanowa Leyla Saparowna","passportSerie":"I-AH","passportNumber":"303030","depositAccount":"23202984200030303033"}'::json,
|
||||
'[{"fullName":"Gurbanow Rahman Kakajanowiç","passportSerie":"I-AH","passportNumber":"111222"}]'::json,
|
||||
'{
|
||||
"student_visa_card_details":["sber-card-7.pdf"],
|
||||
"student_enrollment_certificate":["enrollment-7.pdf"],
|
||||
"student_ticket_copy":[],
|
||||
"student_internal_passport":["student-internal-7.pdf"],
|
||||
"student_foreign_passport":["student-foreign-7.pdf"],
|
||||
"student_visa_page":["student-visa-page-7.pdf"],
|
||||
"student_stamp_page":[],
|
||||
"student_enrollment_clarification":[],
|
||||
"sender_internal_passport":["sender-internal-7.pdf"],
|
||||
"sender_foreign_passport":[],
|
||||
"sender_stamp_page":[],
|
||||
"kinship_documents":["kinship-7.pdf"],
|
||||
"first_passport_series_info":[],
|
||||
"police_passport_series_info":[]
|
||||
}'::json,
|
||||
'rejected', 'Okuw güwänamasy ýok',
|
||||
'Gurbanowa Leyla Saparowna', 'I-AH', '303030', '23202984200030303033',
|
||||
'Gurbanow Rahman Kakajanowiç', 'I-AH', '111222', NULL,
|
||||
false, NULL
|
||||
),
|
||||
(
|
||||
'VMP-2026-0008', 'sber', 'Myrat', 'Atayew', '+993 61 92 92 48', 'kerim@bank.tm',
|
||||
'MR', 7, 9, 'Mary, Magtymguly 18',
|
||||
'{"fullName":"Atayew Kerim Begliýewiç","passportSerie":"I-MR","passportNumber":"101010","depositAccount":"23202984200010101011"}'::json,
|
||||
'[{"fullName":"Atayew Myrat Kerimowiç","passportSerie":"I-MR","passportNumber":"121212"}]'::json,
|
||||
'{
|
||||
"student_visa_card_details":["sber-card-8.pdf"],
|
||||
"student_enrollment_certificate":["enrollment-8.pdf"],
|
||||
"student_ticket_copy":[],
|
||||
"student_internal_passport":["student-internal-8.pdf"],
|
||||
"student_foreign_passport":["student-foreign-8.pdf"],
|
||||
"student_visa_page":["student-visa-page-8.pdf"],
|
||||
"student_stamp_page":[],
|
||||
"student_enrollment_clarification":[],
|
||||
"sender_internal_passport":["sender-internal-8.pdf"],
|
||||
"sender_foreign_passport":[],
|
||||
"sender_stamp_page":[],
|
||||
"kinship_documents":["kinship-8.pdf"],
|
||||
"first_passport_series_info":[],
|
||||
"police_passport_series_info":[]
|
||||
}'::json,
|
||||
'pending', 'Sber: resminamalar barlanýar',
|
||||
'Atayew Kerim Begliýewiç', 'I-MR', '101010', '23202984200010101011',
|
||||
'Atayew Myrat Kerimowiç', 'I-MR', '121212', NULL,
|
||||
false, NULL
|
||||
);
|
||||
|
||||
-- ---------------------------------------------------------------------------
|
||||
-- Sber payout attempts (visa_master_order_payments) & step logs.
|
||||
-- Kurs: USD→TMT 3.5175, RUB→TMT 0.047504; sber_bank_fee_tmt = 100,
|
||||
-- tveb_fee_usd = 18 (= 63.32 TMT). Sber üçin gbus_fee_tmt NULL.
|
||||
-- Order ids: 4 = paid (2 aý), 5 = failed, 6 = pending (GBÜS garaşylýar).
|
||||
-- ---------------------------------------------------------------------------
|
||||
INSERT INTO visa_master_order_payments (
|
||||
order_id, user_id, payment_period, exchange_rate_usd, exchange_rate_rub, amount_tmt,
|
||||
bank_fee_tmt, gbus_fee_tmt, tveb_fee_usd, tveb_fee_tmt, total_amount_tmt,
|
||||
gateway_status, gateway_reference, gateway_response, created_by, order_number, created_at, updated_at
|
||||
) VALUES
|
||||
(4, 6, '2026-08-01', 3.5175, 0.047504, 879.38, 100, NULL, 18, 63.32, 1042.70,
|
||||
'paid', 'a1b2c3d4-0004-4001-8001-000000000001', '{"orderStatus":2,"actionCode":0,"actionCodeDescription":"Request processed successfully"}'::jsonb,
|
||||
3, '150826101512', '2026-08-15 05:15:12', '2026-08-15 05:17:40'),
|
||||
(4, 6, '2026-09-01', 3.5175, 0.047504, 879.38, 100, NULL, 18, 63.32, 1042.70,
|
||||
'paid', 'a1b2c3d4-0004-4001-8001-000000000002', '{"orderStatus":2,"actionCode":0,"actionCodeDescription":"Request processed successfully"}'::jsonb,
|
||||
3, '120926112030', '2026-09-12 06:20:30', '2026-09-12 06:22:05'),
|
||||
(5, 7, '2026-09-01', 3.5175, 0.047504, 700.00, 100, NULL, 18, 63.32, 863.32,
|
||||
'failed', 'a1b2c3d4-0005-4001-8001-000000000003', '{"orderStatus":6,"actionCode":-2007,"actionCodeDescription":"Decline. Payment time limit"}'::jsonb,
|
||||
3, '250926143011', '2026-09-25 09:30:11', '2026-09-25 09:50:11'),
|
||||
(6, 8, '2026-09-01', 3.5175, 0.047504, 527.63, 100, NULL, 18, 63.32, 690.95,
|
||||
'pending', 'a1b2c3d4-0006-4001-8001-000000000004', '{"errorCode":"0","orderId":"a1b2c3d4-0006-4001-8001-000000000004"}'::jsonb,
|
||||
3, '300926154500', '2026-09-30 10:45:00', '2026-09-30 10:45:01');
|
||||
|
||||
INSERT INTO visa_master_payment_logs (order_id, step, detail, created_by, created_at) VALUES
|
||||
(4, 'validated', '{"orderType":"sber","maxAmountUsd":250,"amountTmt":879.38,"exchangeRateUsd":3.5175}'::jsonb, 3, '2026-09-12 06:20:28'),
|
||||
(4, 'fees_calculated', '{"bankFeeTmt":100,"gbusFeeTmt":null,"tvebFeeUsd":18,"tvebFeeTmt":63.32,"exchangeRateRub":0.047504,"totalAmountTmt":1042.70}'::jsonb, 3, '2026-09-12 06:20:29'),
|
||||
(4, 'callback_received', '{"gatewayStatus":"pending"}'::jsonb, NULL, '2026-09-12 06:22:04'),
|
||||
(4, 'payment_finalized', '{"paid":true,"gatewayStatus":"paid"}'::jsonb, NULL, '2026-09-12 06:22:05'),
|
||||
(5, 'validated', '{"orderType":"sber","maxAmountUsd":250,"amountTmt":700.00,"exchangeRateUsd":3.5175}'::jsonb, 3, '2026-09-25 09:30:09'),
|
||||
(5, 'fees_calculated', '{"bankFeeTmt":100,"gbusFeeTmt":null,"tvebFeeUsd":18,"tvebFeeTmt":63.32,"exchangeRateRub":0.047504,"totalAmountTmt":863.32}'::jsonb, 3, '2026-09-25 09:30:10'),
|
||||
(5, 'status_check_response', '{"success":true,"paid":false,"orderStatus":6,"actionCode":-2007}'::jsonb, 3, '2026-09-25 09:50:10'),
|
||||
(5, 'payment_finalized', '{"paid":false,"gatewayStatus":"failed"}'::jsonb, 3, '2026-09-25 09:50:11'),
|
||||
(6, 'validated', '{"orderType":"sber","maxAmountUsd":250,"amountTmt":527.63,"exchangeRateUsd":3.5175}'::jsonb, 3, '2026-09-30 10:44:59'),
|
||||
(6, 'fees_calculated', '{"bankFeeTmt":100,"gbusFeeTmt":null,"tvebFeeUsd":18,"tvebFeeTmt":63.32,"exchangeRateRub":0.047504,"totalAmountTmt":690.95}'::jsonb, 3, '2026-09-30 10:45:00');
|
||||
|
||||
|
||||
-- ---------------------------------------------------------------------------
|
||||
-- Currency rates (Walýuta kursy)
|
||||
-- ---------------------------------------------------------------------------
|
||||
INSERT INTO currencies (currency_from, currency_to, value, created_by, updated_by) VALUES
|
||||
('EUR', 'TMT', 3.812, 2, 2),
|
||||
('USD', 'TMT', 3.5175, 2, 2),
|
||||
('EUR', 'RUB', 80.23, 2, 1),
|
||||
('USD', 'RUB', 74.0455, 2, 2),
|
||||
('RUB', 'TMT', 0.047504, 2, 2),
|
||||
('USD', 'USD', 250, 1, 1),
|
||||
('GBP', 'TMT', 4.45, 2, 2),
|
||||
('CNY', 'TMT', 0.485, 2, 3);
|
||||
|
||||
-- ---------------------------------------------------------------------------
|
||||
-- Activity logs
|
||||
-- ---------------------------------------------------------------------------
|
||||
INSERT INTO activity_logs (user_id, method, path, module, action, status_code, request_body, ip) VALUES
|
||||
(1, 'POST', '/api/admin/login', 'auth', 'login', 200, '{"email":"superadmin@bank.tm"}'::jsonb, '127.0.0.1'),
|
||||
(2, 'POST', '/api/admin/login', 'auth', 'login', 200, '{"email":"admin@bank.tm"}'::jsonb, '10.0.0.5'),
|
||||
(2, 'GET', '/api/admin/users', 'users', 'list', 200, NULL, '10.0.0.5'),
|
||||
(1, 'POST', '/api/admin/provinces', 'provinces', 'create', 200, '{"name":{"tm":"Aşgabat"}}'::jsonb, '127.0.0.1'),
|
||||
(3, 'GET', '/api/admin/card-orders', 'card-orders', 'list', 200, NULL, '10.0.0.12'),
|
||||
(3, 'PUT', '/api/admin/card-orders/2', 'card-orders', 'update', 200, '{"status":"approved"}'::jsonb, '10.0.0.12'),
|
||||
(4, 'GET', '/api/admin/loan-orders', 'loan-orders', 'list', 200, NULL, '10.0.0.20'),
|
||||
(4, 'POST', '/api/admin/loan-orders', 'loan-orders', 'create', 400, '{"loanAmount":"0"}'::jsonb, '10.0.0.20'),
|
||||
(1, 'DELETE', '/api/admin/roles/99', 'roles', 'delete', 404, NULL, '127.0.0.1'),
|
||||
(3, 'GET', '/api/admin/branches', 'branches', 'list', 200, NULL, '10.0.0.12'),
|
||||
(2, 'PUT', '/api/admin/profile', 'auth', 'update', 200, '{"firstName":"Nurmuhammet"}'::jsonb, '10.0.0.5'),
|
||||
(5, 'GET', '/api/admin/cards', 'cards', 'list', 200, NULL, '10.0.0.30');
|
||||
|
||||
-- TRUNCATE ... CASCADE payment_settings-i hem arassalaýar (users FK); ýeke setiri gaýtadan goý.
|
||||
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;
|
||||
|
||||
-- payment_texts hem şeýle (users FK); klient kodlary gaýtadan goý.
|
||||
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":"","ru":"","en":""}'::jsonb)
|
||||
ON CONFLICT (code) DO NOTHING;
|
||||
|
||||
COMMIT;
|
||||
|
||||
-- Quick counts
|
||||
SELECT 'users' AS table_name, count(*) FROM users
|
||||
UNION ALL SELECT 'roles', count(*) FROM roles
|
||||
UNION ALL SELECT 'role_permissions', count(*) FROM role_permissions
|
||||
UNION ALL SELECT 'branch_user', count(*) FROM branch_user
|
||||
UNION ALL SELECT 'permissions', count(*) FROM permissions
|
||||
UNION ALL SELECT 'provinces', count(*) FROM provinces
|
||||
UNION ALL SELECT 'branches', count(*) FROM branches
|
||||
UNION ALL SELECT 'card_types', count(*) FROM card_types
|
||||
UNION ALL SELECT 'card_states', count(*) FROM card_states
|
||||
UNION ALL SELECT 'loan_types', count(*) FROM loan_types
|
||||
UNION ALL SELECT 'loan_order_required_docs', count(*) FROM loan_order_required_docs
|
||||
UNION ALL SELECT 'cards', count(*) FROM cards
|
||||
UNION ALL SELECT 'card_orders', count(*) FROM card_orders
|
||||
UNION ALL SELECT 'card_pin_orders', count(*) FROM card_pin_orders
|
||||
UNION ALL SELECT 'card_rekwizit_orders', count(*) FROM card_rekwizit_orders
|
||||
UNION ALL SELECT 'loan_orders', count(*) FROM loan_orders
|
||||
UNION ALL SELECT 'loans', count(*) FROM loans
|
||||
UNION ALL SELECT 'loan_paid_off_letters', count(*) FROM loan_paid_off_letters
|
||||
UNION ALL SELECT 'visa_master_payment_orders', count(*) FROM visa_master_payment_orders
|
||||
UNION ALL SELECT 'visa_master_order_payments', count(*) FROM visa_master_order_payments
|
||||
UNION ALL SELECT 'visa_master_payment_logs', count(*) FROM visa_master_payment_logs
|
||||
UNION ALL SELECT 'registration_verifications', count(*) FROM registration_verifications
|
||||
UNION ALL SELECT 'activity_logs', count(*) FROM activity_logs
|
||||
UNION ALL SELECT 'backups', count(*) FROM backups
|
||||
UNION ALL SELECT 'currencies', count(*) FROM currencies
|
||||
ORDER BY 1;
|
||||
|
||||
@@ -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"]
|
||||
+20
-6
@@ -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,31 +12,44 @@ 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
|
||||
@@ -54,4 +68,4 @@ volumes:
|
||||
|
||||
networks:
|
||||
myNetwork:
|
||||
driver: bridge
|
||||
driver: bridge
|
||||
+3777
-508
File diff suppressed because it is too large.
Load diff
+3777
-508
File diff suppressed because it is too large.
Load diff
+2623
-370
File diff suppressed because it is too large.
Load diff
+6
-2
@@ -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-roles", Description: "Permission roles"},
|
||||
{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() {
|
||||
|
||||
Vendored
BIN
Binary file not shown.
@@ -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 = ®
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
@@ -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"`
|
||||
}
|
||||
@@ -0,0 +1,266 @@
|
||||
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)
|
||||
// @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)
|
||||
// @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)
|
||||
// @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)
|
||||
// @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)
|
||||
// @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)
|
||||
// @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
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -12,6 +12,11 @@ var (
|
||||
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 {
|
||||
|
||||
@@ -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
|
||||
}
|
||||
@@ -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())
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -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"`
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -0,0 +1,206 @@
|
||||
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)
|
||||
// @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"
|
||||
// @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
|
||||
// @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"
|
||||
// @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"
|
||||
// @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
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -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"`
|
||||
}
|
||||
@@ -0,0 +1,260 @@
|
||||
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)
|
||||
// @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"
|
||||
// @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"
|
||||
// @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"
|
||||
// @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"
|
||||
// @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
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -6,8 +6,8 @@ import (
|
||||
"strings"
|
||||
|
||||
"online-back/internal/cards/cardorder"
|
||||
"online-back/internal/cards/shared"
|
||||
"online-back/internal/identity/rbac"
|
||||
"online-back/internal/shared"
|
||||
"online-back/pkg/client/postgresql"
|
||||
"online-back/pkg/logging"
|
||||
"online-back/pkg/repository/genericrepo"
|
||||
@@ -50,6 +50,13 @@ 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"
|
||||
@@ -98,7 +105,7 @@ func (r *repository) List(ctx context.Context, filter cardorder.ListFilter) (car
|
||||
offsetPlaceholder := len(args) + 2
|
||||
query := fmt.Sprintf(
|
||||
`SELECT %s%s%s ORDER BY co.id LIMIT $%d OFFSET $%d`,
|
||||
cardOrderSelectColumns, cardOrderFromClause, whereClause, limitPlaceholder, offsetPlaceholder,
|
||||
cardOrderListColumns, cardOrderListFromClause, whereClause, limitPlaceholder, offsetPlaceholder,
|
||||
)
|
||||
|
||||
rows, err := r.client.Query(ctx, query, append(args, filter.Limit, offset)...)
|
||||
@@ -107,9 +114,9 @@ func (r *repository) List(ctx context.Context, filter cardorder.ListFilter) (car
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var items []cardorder.CardOrderDTO
|
||||
items := []cardorder.CardOrderListItemDTO{}
|
||||
for rows.Next() {
|
||||
item, err := scanCardOrderWithJoins(rows)
|
||||
item, err := scanCardOrderListItem(rows)
|
||||
if err != nil {
|
||||
return cardorder.ListCardOrderDTO{}, err
|
||||
}
|
||||
@@ -123,7 +130,7 @@ func (r *repository) List(ctx context.Context, filter cardorder.ListFilter) (car
|
||||
}
|
||||
|
||||
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)
|
||||
@@ -157,15 +164,11 @@ func buildListQuery(filter cardorder.ListFilter) (whereClause string, args []int
|
||||
conditions = append(conditions, fmt.Sprintf("co.region = $%d", len(args)))
|
||||
}
|
||||
|
||||
if len(conditions) == 0 {
|
||||
return "", args
|
||||
}
|
||||
|
||||
return " WHERE " + strings.Join(conditions, " AND "), args
|
||||
}
|
||||
|
||||
func (r *repository) GetByID(ctx context.Context, id int64) (cardorder.CardOrderDTO, error) {
|
||||
query := `SELECT ` + cardOrderSelectColumns + cardOrderFromClause + ` WHERE co.id = $1`
|
||||
query := `SELECT ` + cardOrderSelectColumns + cardOrderFromClause + ` WHERE co.id = $1 AND co.deleted_at IS NULL`
|
||||
return scanCardOrderWithJoins(r.client.QueryRow(ctx, query, id))
|
||||
}
|
||||
|
||||
@@ -207,7 +210,7 @@ func (r *repository) Update(ctx context.Context, id int64, dto cardorder.UpdateC
|
||||
query := fmt.Sprintf(`
|
||||
WITH updated AS (
|
||||
UPDATE card_orders SET %s, updated_at = (CURRENT_TIMESTAMP AT TIME ZONE 'UTC')
|
||||
WHERE id = $%d
|
||||
WHERE id = $%d AND deleted_at IS NULL
|
||||
RETURNING %s
|
||||
)
|
||||
SELECT %s
|
||||
@@ -234,6 +237,49 @@ 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)
|
||||
}
|
||||
|
||||
@@ -3,7 +3,7 @@ package cardorder
|
||||
import (
|
||||
"time"
|
||||
|
||||
"online-back/internal/cards/shared"
|
||||
"online-back/internal/shared"
|
||||
)
|
||||
|
||||
type CardOrderDTO struct {
|
||||
@@ -46,67 +46,67 @@ type CardOrderDTO struct {
|
||||
}
|
||||
|
||||
type CreateCardOrderDTO struct {
|
||||
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"`
|
||||
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"`
|
||||
Paid *bool `json:"paid"`
|
||||
}
|
||||
|
||||
type UpdateCardOrderDTO struct {
|
||||
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"`
|
||||
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"`
|
||||
Paid bool `json:"paid"`
|
||||
}
|
||||
|
||||
type ListFilter struct {
|
||||
@@ -121,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"`
|
||||
}
|
||||
@@ -5,9 +5,10 @@ import (
|
||||
"net/http"
|
||||
|
||||
"online-back/internal/appresult"
|
||||
"online-back/internal/cards/shared"
|
||||
"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)
|
||||
@@ -98,7 +99,7 @@ func (h *handler) getByID(c *gin.Context) {
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
if !rbac.GuardBranch(c, item.BranchId) {
|
||||
if !rbac.GuardOrder(c, item.UserId, item.BranchId) {
|
||||
return
|
||||
}
|
||||
|
||||
@@ -260,7 +261,7 @@ func parseListFilter(c *gin.Context) (ListFilter, bool) {
|
||||
}
|
||||
|
||||
func (h *handler) guardBranchByID(c *gin.Context, id int64) bool {
|
||||
if !rbac.HasBranchScope(c) {
|
||||
if rbac.SkipRecordGuard(c) {
|
||||
return true
|
||||
}
|
||||
item, err := h.repository.GetByID(c.Request.Context(), id)
|
||||
@@ -272,5 +273,5 @@ func (h *handler) guardBranchByID(c *gin.Context, id int64) bool {
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return false
|
||||
}
|
||||
return rbac.GuardBranch(c, item.BranchId)
|
||||
return rbac.GuardOrder(c, item.UserId, item.BranchId)
|
||||
}
|
||||
@@ -6,8 +6,8 @@ import (
|
||||
"strings"
|
||||
|
||||
"online-back/internal/cards/cardpinorders"
|
||||
"online-back/internal/cards/shared"
|
||||
"online-back/internal/identity/rbac"
|
||||
"online-back/internal/shared"
|
||||
"online-back/pkg/client/postgresql"
|
||||
"online-back/pkg/logging"
|
||||
"online-back/pkg/repository/genericrepo"
|
||||
@@ -78,8 +78,12 @@ func (r *repository) List(ctx context.Context, filter cardpinorders.ListFilter)
|
||||
limitPlaceholder := len(args) + 1
|
||||
offsetPlaceholder := len(args) + 2
|
||||
query := fmt.Sprintf(
|
||||
`SELECT %s%s%s ORDER BY cpo.id LIMIT $%d OFFSET $%d`,
|
||||
cardPinOrderSelectColumns, cardPinOrderFromClause, whereClause, limitPlaceholder, offsetPlaceholder,
|
||||
`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)...)
|
||||
@@ -88,10 +92,17 @@ func (r *repository) List(ctx context.Context, filter cardpinorders.ListFilter)
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var items []cardpinorders.CardPinOrderDTO
|
||||
items := []cardpinorders.CardPinOrderListItemDTO{}
|
||||
for rows.Next() {
|
||||
item, err := scanCardPinOrderWithJoins(rows)
|
||||
if err != nil {
|
||||
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)
|
||||
@@ -104,7 +115,7 @@ func (r *repository) List(ctx context.Context, filter cardpinorders.ListFilter)
|
||||
}
|
||||
|
||||
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)
|
||||
@@ -133,15 +144,11 @@ func buildListQuery(filter cardpinorders.ListFilter) (whereClause string, args [
|
||||
conditions = append(conditions, fmt.Sprintf("cpo.region = $%d", len(args)))
|
||||
}
|
||||
|
||||
if len(conditions) == 0 {
|
||||
return "", args
|
||||
}
|
||||
|
||||
return " WHERE " + strings.Join(conditions, " AND "), args
|
||||
}
|
||||
|
||||
func (r *repository) GetByID(ctx context.Context, id int64) (cardpinorders.CardPinOrderDTO, error) {
|
||||
query := `SELECT ` + cardPinOrderSelectColumns + cardPinOrderFromClause + ` WHERE cpo.id = $1`
|
||||
query := `SELECT ` + cardPinOrderSelectColumns + cardPinOrderFromClause + ` WHERE cpo.id = $1 AND cpo.deleted_at IS NULL`
|
||||
return scanCardPinOrderWithJoins(r.client.QueryRow(ctx, query, id))
|
||||
}
|
||||
|
||||
@@ -182,7 +189,7 @@ func (r *repository) Update(ctx context.Context, id int64, dto cardpinorders.Upd
|
||||
query := fmt.Sprintf(`
|
||||
WITH updated AS (
|
||||
UPDATE card_pin_orders SET %s, updated_at = (CURRENT_TIMESTAMP AT TIME ZONE 'UTC')
|
||||
WHERE id = $%d
|
||||
WHERE id = $%d AND deleted_at IS NULL
|
||||
RETURNING %s
|
||||
)
|
||||
SELECT %s
|
||||
|
||||
@@ -3,7 +3,7 @@ package cardpinorders
|
||||
import (
|
||||
"time"
|
||||
|
||||
"online-back/internal/cards/shared"
|
||||
"online-back/internal/shared"
|
||||
)
|
||||
|
||||
type CardPinOrderDTO struct {
|
||||
@@ -89,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"`
|
||||
}
|
||||
@@ -5,9 +5,10 @@ import (
|
||||
"net/http"
|
||||
|
||||
"online-back/internal/appresult"
|
||||
"online-back/internal/cards/shared"
|
||||
"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)
|
||||
@@ -97,7 +98,7 @@ func (h *handler) getByID(c *gin.Context) {
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
if !rbac.GuardBranch(c, item.BranchId) {
|
||||
if !rbac.GuardOrder(c, item.UserId, item.BranchId) {
|
||||
return
|
||||
}
|
||||
|
||||
@@ -251,7 +252,7 @@ func parseListFilter(c *gin.Context) (ListFilter, bool) {
|
||||
}
|
||||
|
||||
func (h *handler) guardBranchByID(c *gin.Context, id int64) bool {
|
||||
if !rbac.HasBranchScope(c) {
|
||||
if rbac.SkipRecordGuard(c) {
|
||||
return true
|
||||
}
|
||||
item, err := h.repository.GetByID(c.Request.Context(), id)
|
||||
@@ -263,5 +264,5 @@ func (h *handler) guardBranchByID(c *gin.Context, id int64) bool {
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return false
|
||||
}
|
||||
return rbac.GuardBranch(c, item.BranchId)
|
||||
return rbac.GuardOrder(c, item.UserId, item.BranchId)
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -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"`
|
||||
}
|
||||
@@ -0,0 +1,268 @@
|
||||
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)
|
||||
// @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"
|
||||
// @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"
|
||||
// @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"
|
||||
// @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"
|
||||
// @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)
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -3,11 +3,12 @@ package db
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"online-back/internal/cards/cards"
|
||||
"online-back/internal/cards/shared"
|
||||
"online-back/internal/identity/rbac"
|
||||
"online-back/internal/shared"
|
||||
"online-back/pkg/client/postgresql"
|
||||
"online-back/pkg/logging"
|
||||
"online-back/pkg/repository/genericrepo"
|
||||
@@ -40,10 +41,11 @@ 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) + `, ` +
|
||||
shared.UserDisplaySQL + `, COALESCE(u.username, ''), COALESCE(u.phone, ''), COALESCE(u.email, '')`
|
||||
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{}{
|
||||
@@ -95,7 +97,7 @@ func (r *repository) List(ctx context.Context, filter cards.ListFilter) (cards.L
|
||||
}
|
||||
|
||||
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)
|
||||
@@ -112,15 +114,11 @@ func buildListQuery(filter cards.ListFilter) (whereClause string, args []interfa
|
||||
conditions = append(conditions, fmt.Sprintf("c.type = $%d", len(args)))
|
||||
}
|
||||
|
||||
if len(conditions) == 0 {
|
||||
return "", args
|
||||
}
|
||||
|
||||
return " WHERE " + strings.Join(conditions, " AND "), args
|
||||
}
|
||||
|
||||
func (r *repository) GetByID(ctx context.Context, id int64) (cards.CardDTO, error) {
|
||||
query := `SELECT ` + cardSelectColumns + cardFromClause + ` WHERE c.id = $1`
|
||||
query := `SELECT ` + cardSelectColumns + cardFromClause + ` WHERE c.id = $1 AND c.deleted_at IS NULL`
|
||||
return scanCardWithUser(r.client.QueryRow(ctx, query, id))
|
||||
}
|
||||
|
||||
@@ -139,6 +137,7 @@ func (r *repository) Create(ctx context.Context, dto cards.CreateCardDTO) (cards
|
||||
)
|
||||
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,
|
||||
@@ -159,11 +158,12 @@ func (r *repository) Update(ctx context.Context, id int64, dto cards.UpdateCardD
|
||||
query := fmt.Sprintf(`
|
||||
WITH updated AS (
|
||||
UPDATE cards SET %s, updated_at = (CURRENT_TIMESTAMP AT TIME ZONE 'UTC')
|
||||
WHERE id = $%d
|
||||
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,
|
||||
)
|
||||
@@ -194,22 +194,43 @@ func scanCardRow(row genericrepo.Scanner, withUser bool) (cards.CardDTO, error)
|
||||
&item.CreatedAt, &item.UpdatedAt,
|
||||
}
|
||||
|
||||
var cardTypeNameJSON []byte
|
||||
var userName, userUsername, userPhone, userEmail string
|
||||
if withUser {
|
||||
dest = append(dest, &userName, &userUsername, &userPhone, &userEmail)
|
||||
dest = append(dest, &cardTypeNameJSON, &userName, &userUsername, &userPhone, &userEmail)
|
||||
}
|
||||
|
||||
if err := row.Scan(dest...); err != nil {
|
||||
return cards.CardDTO{}, err
|
||||
}
|
||||
if withUser && item.UserId != nil {
|
||||
item.User = &shared.UserInfo{
|
||||
Id: *item.UserId,
|
||||
Name: userName,
|
||||
Username: userUsername,
|
||||
Phone: userPhone,
|
||||
Email: userEmail,
|
||||
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
|
||||
}
|
||||
+12
-11
@@ -3,20 +3,21 @@ package cards
|
||||
import (
|
||||
"time"
|
||||
|
||||
"online-back/internal/cards/shared"
|
||||
"online-back/internal/shared"
|
||||
)
|
||||
|
||||
type CardDTO struct {
|
||||
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:"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 {
|
||||
|
||||
@@ -5,9 +5,10 @@ import (
|
||||
"net/http"
|
||||
|
||||
"online-back/internal/appresult"
|
||||
"online-back/internal/cards/shared"
|
||||
"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)
|
||||
@@ -94,6 +95,9 @@ 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
|
||||
}
|
||||
@@ -236,7 +240,7 @@ func parseListFilter(c *gin.Context) (ListFilter, bool) {
|
||||
}
|
||||
|
||||
func (h *handler) guardCardByID(c *gin.Context, id int64) bool {
|
||||
if !rbac.HasBranchScope(c) {
|
||||
if rbac.SkipRecordGuard(c) {
|
||||
return true
|
||||
}
|
||||
item, err := h.repository.GetByID(c.Request.Context(), id)
|
||||
|
||||
@@ -8,7 +8,7 @@ import (
|
||||
"strings"
|
||||
|
||||
"online-back/internal/cards/paymentcard"
|
||||
"online-back/internal/cards/shared"
|
||||
"online-back/internal/shared"
|
||||
"online-back/pkg/client/postgresql"
|
||||
"online-back/pkg/logging"
|
||||
"online-back/pkg/repository/genericrepo"
|
||||
@@ -49,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
|
||||
@@ -68,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)
|
||||
}
|
||||
@@ -107,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))
|
||||
@@ -120,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))
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
package paymentcard
|
||||
|
||||
import "online-back/internal/cards/shared"
|
||||
import "online-back/internal/shared"
|
||||
|
||||
type PaymentCardDTO struct {
|
||||
Id int64 `json:"id"`
|
||||
|
||||
@@ -6,8 +6,10 @@ import (
|
||||
"strconv"
|
||||
|
||||
"online-back/internal/appresult"
|
||||
"online-back/internal/cards/shared"
|
||||
"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)
|
||||
|
||||
@@ -8,7 +8,7 @@ import (
|
||||
"strings"
|
||||
|
||||
"online-back/internal/cards/reasonscard"
|
||||
"online-back/internal/cards/shared"
|
||||
"online-back/internal/shared"
|
||||
"online-back/pkg/client/postgresql"
|
||||
"online-back/pkg/logging"
|
||||
"online-back/pkg/repository/genericrepo"
|
||||
@@ -48,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
|
||||
@@ -62,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)
|
||||
}
|
||||
@@ -102,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))
|
||||
|
||||
@@ -3,7 +3,7 @@ package reasonscard
|
||||
import (
|
||||
"time"
|
||||
|
||||
"online-back/internal/cards/shared"
|
||||
"online-back/internal/shared"
|
||||
)
|
||||
|
||||
type ReasonCardDTO struct {
|
||||
|
||||
@@ -5,8 +5,10 @@ import (
|
||||
"net/http"
|
||||
|
||||
"online-back/internal/appresult"
|
||||
"online-back/internal/cards/shared"
|
||||
"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"
|
||||
@@ -25,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)
|
||||
|
||||
@@ -1,13 +1,18 @@
|
||||
// Package cards groups payment cards, card orders, PIN 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 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"
|
||||
@@ -32,9 +37,11 @@ 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)),
|
||||
|
||||
@@ -6,9 +6,9 @@ import (
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"online-back/internal/cards/shared"
|
||||
"online-back/internal/cards/visamaster"
|
||||
"online-back/internal/identity/rbac"
|
||||
"online-back/internal/shared"
|
||||
"online-back/pkg/client/postgresql"
|
||||
"online-back/pkg/logging"
|
||||
"online-back/pkg/repository/genericrepo"
|
||||
@@ -40,7 +40,7 @@ var orderWritableColumns = []string{
|
||||
"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",
|
||||
"paid",
|
||||
"amount_usd", "paid",
|
||||
}
|
||||
|
||||
var orderColumns = append(append([]string{"id"}, orderWritableColumns...), "created_at", "updated_at")
|
||||
@@ -81,7 +81,7 @@ func createArgs(dto visamaster.CreateVisaMasterPaymentOrderDTO) []interface{} {
|
||||
resolveStatus(dto.Status), dto.Notes,
|
||||
dto.SenderFullName, dto.SenderPassportSerie, dto.SenderPassportNumber, dto.SenderDepositAccount,
|
||||
dto.RecieverFullName, dto.RecieverPassportSerie, dto.RecieverPassportNumber, dto.RecieverDepositAccount,
|
||||
resolvePaid(dto.Paid),
|
||||
dto.AmountUsd, resolvePaid(dto.Paid),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -93,7 +93,7 @@ func updateArgs(dto visamaster.UpdateVisaMasterPaymentOrderDTO) []interface{} {
|
||||
resolveStatus(dto.Status), dto.Notes,
|
||||
dto.SenderFullName, dto.SenderPassportSerie, dto.SenderPassportNumber, dto.SenderDepositAccount,
|
||||
dto.RecieverFullName, dto.RecieverPassportSerie, dto.RecieverPassportNumber, dto.RecieverDepositAccount,
|
||||
dto.Paid,
|
||||
dto.AmountUsd, dto.Paid,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -109,8 +109,12 @@ func (r *repository) List(ctx context.Context, filter visamaster.ListFilter) (vi
|
||||
limitPlaceholder := len(args) + 1
|
||||
offsetPlaceholder := len(args) + 2
|
||||
query := fmt.Sprintf(
|
||||
`SELECT %s%s%s ORDER BY o.id DESC LIMIT $%d OFFSET $%d`,
|
||||
orderSelectColumns, orderFromClause, whereClause, limitPlaceholder, offsetPlaceholder,
|
||||
`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)...)
|
||||
@@ -119,9 +123,9 @@ func (r *repository) List(ctx context.Context, filter visamaster.ListFilter) (vi
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var items []visamaster.VisaMasterPaymentOrderDTO
|
||||
items := []visamaster.VisaMasterPaymentOrderListItemDTO{}
|
||||
for rows.Next() {
|
||||
item, err := scanOrder(rows)
|
||||
item, err := scanOrderListItem(rows)
|
||||
if err != nil {
|
||||
return visamaster.ListVisaMasterPaymentOrderDTO{}, err
|
||||
}
|
||||
@@ -135,10 +139,10 @@ func (r *repository) List(ctx context.Context, filter visamaster.ListFilter) (vi
|
||||
}
|
||||
|
||||
func buildListQuery(filter visamaster.ListFilter) (whereClause string, args []interface{}) {
|
||||
var conditions []string
|
||||
conditions := []string{"o.deleted_at IS NULL"}
|
||||
|
||||
if filter.Name != "" {
|
||||
args = append(args, likePattern(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
|
||||
@@ -146,6 +150,18 @@ func buildListQuery(filter visamaster.ListFilter) (whereClause string, args []in
|
||||
)`, 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)))
|
||||
@@ -168,22 +184,11 @@ func buildListQuery(filter visamaster.ListFilter) (whereClause string, args []in
|
||||
conditions = append(conditions, fmt.Sprintf("o.region = $%d", len(args)))
|
||||
}
|
||||
|
||||
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) (visamaster.VisaMasterPaymentOrderDTO, error) {
|
||||
query := `SELECT ` + orderSelectColumns + orderFromClause + ` WHERE o.id = $1`
|
||||
query := `SELECT ` + orderSelectColumns + orderFromClause + ` WHERE o.id = $1 AND o.deleted_at IS NULL`
|
||||
return scanOrder(r.client.QueryRow(ctx, query, id))
|
||||
}
|
||||
|
||||
@@ -224,7 +229,7 @@ func (r *repository) Update(ctx context.Context, id int64, dto visamaster.Update
|
||||
query := fmt.Sprintf(`
|
||||
WITH updated AS (
|
||||
UPDATE visa_master_payment_orders SET %s, updated_at = (CURRENT_TIMESTAMP AT TIME ZONE 'UTC')
|
||||
WHERE id = $%d
|
||||
WHERE id = $%d AND deleted_at IS NULL
|
||||
RETURNING %s
|
||||
)
|
||||
SELECT %s
|
||||
@@ -259,7 +264,7 @@ func scanOrder(row genericrepo.Scanner) (visamaster.VisaMasterPaymentOrderDTO, e
|
||||
&item.Status, &item.Notes,
|
||||
&item.SenderFullName, &item.SenderPassportSerie, &item.SenderPassportNumber, &item.SenderDepositAccount,
|
||||
&item.RecieverFullName, &item.RecieverPassportSerie, &item.RecieverPassportNumber, &item.RecieverDepositAccount,
|
||||
&item.Paid, &item.CreatedAt, &item.UpdatedAt,
|
||||
&item.AmountUsd, &item.Paid, &item.CreatedAt, &item.UpdatedAt,
|
||||
®ionNameJSON, &branchNameJSON, &item.Branch.UniqueCode, &branchRegion, &item.Branch.ProvinceId, &provinceNameJSON,
|
||||
&userName, &userUsername, &userPhone, &userEmail,
|
||||
)
|
||||
@@ -302,3 +307,39 @@ func jsonOrDefault(raw []byte, fallback string) json.RawMessage {
|
||||
}
|
||||
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, ®ionNameJSON, &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
|
||||
}
|
||||
@@ -4,7 +4,7 @@ import (
|
||||
"encoding/json"
|
||||
"time"
|
||||
|
||||
"online-back/internal/cards/shared"
|
||||
"online-back/internal/shared"
|
||||
)
|
||||
|
||||
type BranchInfo struct {
|
||||
@@ -44,6 +44,7 @@ type VisaMasterPaymentOrderDTO struct {
|
||||
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"`
|
||||
@@ -73,6 +74,7 @@ type CreateVisaMasterPaymentOrderDTO struct {
|
||||
RecieverPassportSerie *string `json:"recieverPassportSerie"`
|
||||
RecieverPassportNumber *string `json:"recieverPassportNumber"`
|
||||
RecieverDepositAccount *string `json:"recieverDepositAccount"`
|
||||
AmountUsd float64 `json:"amountUsd"`
|
||||
Paid *bool `json:"paid"`
|
||||
}
|
||||
|
||||
@@ -100,21 +102,49 @@ type UpdateVisaMasterPaymentOrderDTO struct {
|
||||
RecieverPassportSerie *string `json:"recieverPassportSerie"`
|
||||
RecieverPassportNumber *string `json:"recieverPassportNumber"`
|
||||
RecieverDepositAccount *string `json:"recieverDepositAccount"`
|
||||
AmountUsd float64 `json:"amountUsd"`
|
||||
Paid bool `json:"paid"`
|
||||
}
|
||||
|
||||
type ListFilter struct {
|
||||
Name string
|
||||
Status *string
|
||||
BranchId *int64
|
||||
BranchIds []int64
|
||||
UserId *int64
|
||||
Region string
|
||||
Page int
|
||||
Limit int
|
||||
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 []VisaMasterPaymentOrderDTO `json:"visaMasterPaymentOrders"`
|
||||
Count int64 `json:"count"`
|
||||
VisaMasterPaymentOrders []VisaMasterPaymentOrderListItemDTO `json:"visaMasterPaymentOrders"`
|
||||
}
|
||||
@@ -5,15 +5,20 @@ import (
|
||||
"net/http"
|
||||
|
||||
"online-back/internal/appresult"
|
||||
"online-back/internal/cards/shared"
|
||||
"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 {
|
||||
@@ -26,8 +31,9 @@ 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("/sber", h.listSber)
|
||||
group.GET("/:id", h.getByID)
|
||||
group.POST("", h.create)
|
||||
group.PUT("/:id", h.update)
|
||||
@@ -36,11 +42,12 @@ func (h *handler) Register(router *gin.RouterGroup) {
|
||||
|
||||
// list godoc
|
||||
// @Summary List visa/master payment orders
|
||||
// @Description Returns paginated visa/master payment orders with branch and user details
|
||||
// @Description Returns paginated visa/master payment orders; sber orders are excluded (see /visa-master-payment-orders/sber)
|
||||
// @Tags visa-master-payment-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"
|
||||
@@ -57,7 +64,38 @@ func (h *handler) list(c *gin.Context) {
|
||||
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-payment-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)
|
||||
// @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)
|
||||
@@ -97,7 +135,7 @@ func (h *handler) getByID(c *gin.Context) {
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
if !rbac.GuardBranch(c, item.BranchId) {
|
||||
if !rbac.GuardOrder(c, item.UserId, item.BranchId) {
|
||||
return
|
||||
}
|
||||
|
||||
@@ -224,6 +262,10 @@ func parseListFilter(c *gin.Context) (ListFilter, bool) {
|
||||
filter.Name = raw
|
||||
}
|
||||
|
||||
if raw := shared.QueryValue(c, "type"); raw != "" {
|
||||
filter.Type = raw
|
||||
}
|
||||
|
||||
if raw := shared.QueryValue(c, "status"); raw != "" {
|
||||
filter.Status = &raw
|
||||
}
|
||||
@@ -249,7 +291,7 @@ func parseListFilter(c *gin.Context) (ListFilter, bool) {
|
||||
}
|
||||
|
||||
func (h *handler) guardBranchByID(c *gin.Context, id int64) bool {
|
||||
if !rbac.HasBranchScope(c) {
|
||||
if rbac.SkipRecordGuard(c) {
|
||||
return true
|
||||
}
|
||||
item, err := h.repository.GetByID(c.Request.Context(), id)
|
||||
@@ -261,5 +303,5 @@ func (h *handler) guardBranchByID(c *gin.Context, id int64) bool {
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return false
|
||||
}
|
||||
return rbac.GuardBranch(c, item.BranchId)
|
||||
return rbac.GuardOrder(c, item.UserId, item.BranchId)
|
||||
}
|
||||
@@ -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"`
|
||||
|
||||
@@ -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 ¤cy.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
|
||||
}
|
||||
@@ -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"`
|
||||
}
|
||||
@@ -0,0 +1,279 @@
|
||||
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)
|
||||
// @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"
|
||||
// @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"
|
||||
// @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"
|
||||
// @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"
|
||||
// @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
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -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()
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -0,0 +1,149 @@
|
||||
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)
|
||||
// @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
|
||||
// @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
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
package dashboard
|
||||
|
||||
import "context"
|
||||
|
||||
type Repository interface {
|
||||
Overview(ctx context.Context, filter OverviewFilter) (OverviewDTO, error)
|
||||
}
|
||||
@@ -1,17 +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"
|
||||
@@ -48,11 +62,16 @@ 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.
|
||||
@@ -61,6 +80,35 @@ func New(cfg *config.Config, client *pgxpool.Pool, logger *logging.Logger) *gin.
|
||||
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)
|
||||
|
||||
// Deny by default: every admin route must declare its policy via rbac.Group.
|
||||
if err := rbac.VerifyRoutes(router.Routes(), adminAPIPrefix); err != nil {
|
||||
logger.Fatal(err)
|
||||
}
|
||||
|
||||
return router
|
||||
}
|
||||
|
||||
// paymentGatewayClient picks the real GBÜS client outside debug mode, and
|
||||
// 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)
|
||||
}
|
||||
@@ -31,14 +31,7 @@ var activityLogColumnsSQL = strings.Join(activityLogColumns, ", ")
|
||||
|
||||
const activityLogFromClause = ` FROM activity_logs al
|
||||
LEFT JOIN users u ON u.id = al.user_id
|
||||
LEFT JOIN LATERAL (
|
||||
SELECT ru.role_id
|
||||
FROM role_user ru
|
||||
WHERE ru.user_id = u.id
|
||||
ORDER BY ru.id
|
||||
LIMIT 1
|
||||
) ru ON true
|
||||
LEFT JOIN roles r ON r.id = ru.role_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, '')`
|
||||
|
||||
@@ -119,14 +112,7 @@ func (r *repository) Create(ctx context.Context, dto activitylog.CreateActivityL
|
||||
SELECT ` + activityLogSelectColumns + `
|
||||
FROM inserted al
|
||||
LEFT JOIN users u ON u.id = al.user_id
|
||||
LEFT JOIN LATERAL (
|
||||
SELECT ru.role_id
|
||||
FROM role_user ru
|
||||
WHERE ru.user_id = u.id
|
||||
ORDER BY ru.id
|
||||
LIMIT 1
|
||||
) ru ON true
|
||||
LEFT JOIN roles r ON r.id = ru.role_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,
|
||||
|
||||
@@ -8,6 +8,9 @@ import (
|
||||
|
||||
"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"
|
||||
@@ -28,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). Each log includes the actor's username and role from role_user.
|
||||
// @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
|
||||
@@ -78,7 +81,7 @@ func (h *handler) list(c *gin.Context) {
|
||||
// @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 {
|
||||
// GET /activity-logs/card-orders → list that module instead of 400.
|
||||
q := c.Request.URL.Query()
|
||||
@@ -104,24 +107,10 @@ 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 id, ok := optionalQueryID(c, "user_id", "userId"); !ok {
|
||||
@@ -146,8 +135,8 @@ func parseListFilter(c *gin.Context) (ListFilter, bool) {
|
||||
if err != nil || limit < 1 {
|
||||
return ListFilter{}, false
|
||||
}
|
||||
if limit > maxLimit {
|
||||
limit = maxLimit
|
||||
if limit > shared.MaxLimit {
|
||||
limit = shared.MaxLimit
|
||||
}
|
||||
filter.Limit = limit
|
||||
}
|
||||
@@ -169,7 +158,7 @@ func optionalQueryID(c *gin.Context, keys ...string) (*int64, bool) {
|
||||
if raw == "" {
|
||||
return nil, true
|
||||
}
|
||||
id, ok := parseID(raw)
|
||||
id, ok := shared.ParseID(raw)
|
||||
if !ok {
|
||||
return nil, false
|
||||
}
|
||||
|
||||
@@ -7,6 +7,7 @@ import (
|
||||
"sync"
|
||||
"testing"
|
||||
|
||||
"online-back/internal/shared"
|
||||
"online-back/pkg/logging"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
@@ -61,7 +62,7 @@ func TestParseListFilterIgnoresUndefinedAndCapsLimit(t *testing.T) {
|
||||
if filter.Module != "card-orders" {
|
||||
t.Fatalf("module=%q", filter.Module)
|
||||
}
|
||||
if filter.Limit != maxLimit {
|
||||
if filter.Limit != shared.MaxLimit {
|
||||
t.Fatalf("limit=%d", filter.Limit)
|
||||
}
|
||||
if filter.Page != 2 {
|
||||
@@ -90,7 +91,7 @@ func TestGetByIDListsModuleWhenPathIsNotNumeric(t *testing.T) {
|
||||
if repo.listFilter.Module != "card-orders" {
|
||||
t.Fatalf("module=%q", repo.listFilter.Module)
|
||||
}
|
||||
if repo.listFilter.Limit != maxLimit {
|
||||
if repo.listFilter.Limit != shared.MaxLimit {
|
||||
t.Fatalf("limit=%d", repo.listFilter.Limit)
|
||||
}
|
||||
}
|
||||
@@ -5,12 +5,15 @@ import (
|
||||
"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"
|
||||
@@ -31,26 +34,21 @@ 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`
|
||||
userByIDQuery = `SELECT id, password FROM users WHERE id = $1 AND deleted_at IS NULL`
|
||||
)
|
||||
|
||||
const profileFromClause = ` FROM users u
|
||||
LEFT JOIN LATERAL (
|
||||
SELECT ru.role_id
|
||||
FROM role_user ru
|
||||
WHERE ru.user_id = u.id
|
||||
ORDER BY ru.id
|
||||
LIMIT 1
|
||||
) ru ON true
|
||||
LEFT JOIN roles r ON r.id = ru.role_id`
|
||||
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(
|
||||
@@ -62,24 +60,23 @@ const profileBranchesJSON = `COALESCE((
|
||||
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
|
||||
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(
|
||||
'id', p.id,
|
||||
'code', COALESCE(p.code, ''),
|
||||
'name', p.name
|
||||
) ORDER BY p.id)
|
||||
FROM permission_role pr
|
||||
JOIN permissions p ON p.id = pr.permission_id
|
||||
WHERE pr.role_id = r.id
|
||||
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, ` + profileBranchesJSON + `, ` + profilePermissionsJSON + profileFromClause + ` WHERE u.id = $1`
|
||||
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)
|
||||
@@ -112,7 +109,7 @@ 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`
|
||||
WHERE id = $6 AND deleted_at IS NULL`
|
||||
|
||||
func (r *repository) UpdateProfile(ctx context.Context, id int, dto auth.UpdateProfileDTO) (auth.UserProfileDTO, error) {
|
||||
tag, err := r.client.Exec(ctx, updateProfileQuery,
|
||||
@@ -127,14 +124,11 @@ func (r *repository) UpdateProfile(ctx context.Context, id int, dto auth.UpdateP
|
||||
return r.GetProfile(ctx, id)
|
||||
}
|
||||
|
||||
type scannable interface {
|
||||
Scan(dest ...interface{}) error
|
||||
}
|
||||
|
||||
func scanProfile(row scannable) (auth.UserProfileDTO, error) {
|
||||
func scanProfile(row genericrepo.Scanner) (auth.UserProfileDTO, error) {
|
||||
var profile auth.UserProfileDTO
|
||||
var roleID sql.NullInt64
|
||||
var roleCode, roleName sql.NullString
|
||||
var roleCode, roleName, roleScope sql.NullString
|
||||
var roleSuper bool
|
||||
var branchesJSON []byte
|
||||
var permissionsJSON []byte
|
||||
|
||||
@@ -149,6 +143,8 @@ func scanProfile(row scannable) (auth.UserProfileDTO, error) {
|
||||
&roleID,
|
||||
&roleCode,
|
||||
&roleName,
|
||||
&roleScope,
|
||||
&roleSuper,
|
||||
&branchesJSON,
|
||||
&permissionsJSON,
|
||||
)
|
||||
@@ -158,9 +154,11 @@ func scanProfile(row scannable) (auth.UserProfileDTO, error) {
|
||||
|
||||
if roleID.Valid {
|
||||
profile.Role = &auth.ProfileRoleDTO{
|
||||
Id: roleID.Int64,
|
||||
Code: roleCode.String,
|
||||
Name: roleName.String,
|
||||
Id: roleID.Int64,
|
||||
Code: roleCode.String,
|
||||
Name: roleName.String,
|
||||
Scope: roleScope.String,
|
||||
IsSuper: roleSuper,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -177,6 +175,7 @@ func scanProfile(row scannable) (auth.UserProfileDTO, error) {
|
||||
return auth.UserProfileDTO{}, err
|
||||
}
|
||||
}
|
||||
sortByCatalog(profile.Permissions)
|
||||
return profile, nil
|
||||
}
|
||||
|
||||
@@ -184,8 +183,9 @@ func (r *repository) UserExists(ctx context.Context, username, phone string) (bo
|
||||
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)
|
||||
@@ -252,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)
|
||||
@@ -265,16 +265,6 @@ func (r *repository) CompleteRegistration(ctx context.Context, v auth.Verificati
|
||||
return 0, err
|
||||
}
|
||||
|
||||
tag, err := tx.Exec(ctx, `
|
||||
INSERT INTO role_user (role_id, user_id)
|
||||
SELECT r.id, $1 FROM roles r WHERE r.code = 'user'`, userID)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
if tag.RowsAffected() == 0 {
|
||||
return 0, errors.New(`role "user" not found`)
|
||||
}
|
||||
|
||||
if _, err := tx.Exec(ctx, `DELETE FROM registration_verifications WHERE id = $1`, v.ID); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
@@ -288,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
|
||||
@@ -310,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
|
||||
}
|
||||
@@ -334,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)]
|
||||
})
|
||||
}
|
||||
@@ -1,6 +1,10 @@
|
||||
package auth
|
||||
|
||||
import "time"
|
||||
import (
|
||||
"time"
|
||||
|
||||
"online-back/internal/shared"
|
||||
)
|
||||
|
||||
type LoginDTO struct {
|
||||
Name string `json:"name"`
|
||||
@@ -12,26 +16,23 @@ type RefreshTokenDTO struct {
|
||||
RefreshToken string `json:"refreshToken" binding:"required"`
|
||||
}
|
||||
|
||||
type LocalizedText struct {
|
||||
En string `json:"en"`
|
||||
Ru string `json:"ru"`
|
||||
Tm string `json:"tm"`
|
||||
}
|
||||
|
||||
type ProfileRoleDTO struct {
|
||||
Id int64 `json:"id"`
|
||||
Code string `json:"code"`
|
||||
Name string `json:"name"`
|
||||
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 LocalizedText `json:"name"`
|
||||
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 {
|
||||
Id int64 `json:"id"`
|
||||
Code string `json:"code"`
|
||||
Name string `json:"name"`
|
||||
}
|
||||
|
||||
@@ -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
|
||||
@@ -242,7 +243,7 @@ func (h *handler) refreshToken(c *gin.Context) {
|
||||
|
||||
// getProfile godoc
|
||||
// @Summary Get profile
|
||||
// @Description Returns the authenticated user's profile with role, branches, and permissions
|
||||
// @Description Returns the authenticated user's profile with role, branches, and permissions grouped by saha (module)
|
||||
// @Tags auth
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
|
||||
@@ -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
|
||||
}
|
||||
@@ -1,35 +0,0 @@
|
||||
package permission
|
||||
|
||||
import "time"
|
||||
|
||||
type PermissionDTO struct {
|
||||
Id int64 `json:"id"`
|
||||
Code string `json:"code"`
|
||||
Name string `json:"name"`
|
||||
GuardName string `json:"guardName"`
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
UpdatedAt time.Time `json:"updatedAt"`
|
||||
}
|
||||
|
||||
type CreatePermissionDTO struct {
|
||||
Code string `json:"code" binding:"required"`
|
||||
Name string `json:"name" binding:"required"`
|
||||
GuardName string `json:"guardName" binding:"required"`
|
||||
}
|
||||
|
||||
type UpdatePermissionDTO struct {
|
||||
Code string `json:"code" binding:"required"`
|
||||
Name string `json:"name" binding:"required"`
|
||||
GuardName string `json:"guardName" binding:"required"`
|
||||
}
|
||||
|
||||
type ListFilter struct {
|
||||
PermissionName string
|
||||
Page int
|
||||
Limit int
|
||||
}
|
||||
|
||||
type ListPermissionDTO struct {
|
||||
Count int64 `json:"count"`
|
||||
Permissions []PermissionDTO `json:"permissions"`
|
||||
}
|
||||
@@ -1,242 +1,40 @@
|
||||
package permission
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"online-back/internal/appresult"
|
||||
"online-back/internal/handlers"
|
||||
"online-back/pkg/logging"
|
||||
"online-back/internal/identity/rbac"
|
||||
"online-back/internal/identity/rbac/perm"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/jackc/pgx/v4"
|
||||
)
|
||||
|
||||
const baseURL = "/permissions"
|
||||
|
||||
type handler struct {
|
||||
logger *logging.Logger
|
||||
repository Repository
|
||||
}
|
||||
// handler serves the permission catalog. Permissions are defined in code
|
||||
// (rbac/perm) - one per module - so there is nothing to create or edit here;
|
||||
// roles pick from this list via POST/PUT /roles.
|
||||
type handler struct{}
|
||||
|
||||
func NewHandler(logger *logging.Logger, repository Repository) handlers.Handler {
|
||||
return &handler{logger: logger, repository: repository}
|
||||
func NewHandler() handlers.Handler {
|
||||
return &handler{}
|
||||
}
|
||||
|
||||
func (h *handler) Register(router *gin.RouterGroup) {
|
||||
group := router.Group(baseURL, appresult.JwtTokenCheck())
|
||||
group := rbac.Group(router, baseURL, rbac.RequireStaff(perm.Roles))
|
||||
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 permissions
|
||||
// @Description Returns paginated permissions with optional filters
|
||||
// @Description Returns the permission catalog: one code per module, in display order. Holding a code grants read and write in that module; the role's scope decides which records.
|
||||
// @Tags permission
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param permission_name query string false "Filter by name"
|
||||
// @Param page query int false "Page number" default(1)
|
||||
// @Param limit query int false "Items per page" default(10)
|
||||
// @Success 200 {object} appresult.AppSuccess
|
||||
// @Failure 400 {object} appresult.AppError
|
||||
// @Failure 500 {object} appresult.AppError
|
||||
// @Router /permissions [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 permissions failed: %v", err)
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, appresult.SuccessWithData(result))
|
||||
}
|
||||
|
||||
// getByID godoc
|
||||
// @Summary Get permission by ID
|
||||
// @Description Returns a single permission
|
||||
// @Tags permission
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param id path int true "Permission ID"
|
||||
// @Success 200 {object} appresult.AppSuccess
|
||||
// @Failure 400 {object} appresult.AppError
|
||||
// @Failure 404 {object} appresult.AppError
|
||||
// @Failure 500 {object} appresult.AppError
|
||||
// @Router /permissions/{id} [get]
|
||||
func (h *handler) getByID(c *gin.Context) {
|
||||
id, ok := 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 permission failed: %v", err)
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, appresult.SuccessWithData(item))
|
||||
}
|
||||
|
||||
// create godoc
|
||||
// @Summary Create permission
|
||||
// @Description Creates a new permission
|
||||
// @Tags permission
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param body body CreatePermissionDTO true "Permission payload"
|
||||
// @Success 201 {object} appresult.AppSuccess
|
||||
// @Failure 400 {object} appresult.AppError
|
||||
// @Failure 500 {object} appresult.AppError
|
||||
// @Router /permissions [post]
|
||||
func (h *handler) create(c *gin.Context) {
|
||||
var dto CreatePermissionDTO
|
||||
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 permission failed: %v", err)
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusCreated, appresult.SuccessWithData(item))
|
||||
}
|
||||
|
||||
// update godoc
|
||||
// @Summary Update permission
|
||||
// @Description Updates an existing permission
|
||||
// @Tags permission
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param id path int true "Permission ID"
|
||||
// @Param body body UpdatePermissionDTO true "Permission payload"
|
||||
// @Success 200 {object} appresult.AppSuccess
|
||||
// @Failure 400 {object} appresult.AppError
|
||||
// @Failure 404 {object} appresult.AppError
|
||||
// @Failure 500 {object} appresult.AppError
|
||||
// @Router /permissions/{id} [put]
|
||||
func (h *handler) update(c *gin.Context) {
|
||||
id, ok := parseID(c.Param("id"))
|
||||
if !ok {
|
||||
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
|
||||
return
|
||||
}
|
||||
|
||||
var dto UpdatePermissionDTO
|
||||
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 permission failed: %v", err)
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, appresult.SuccessWithData(item))
|
||||
}
|
||||
|
||||
// delete godoc
|
||||
// @Summary Delete permission
|
||||
// @Description Deletes a permission
|
||||
// @Tags permission
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param id path int true "Permission ID"
|
||||
// @Success 200 {object} appresult.AppSuccess
|
||||
// @Failure 400 {object} appresult.AppError
|
||||
// @Failure 404 {object} appresult.AppError
|
||||
// @Failure 500 {object} appresult.AppError
|
||||
// @Router /permissions/{id} [delete]
|
||||
func (h *handler) delete(c *gin.Context) {
|
||||
id, ok := 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 permission failed: %v", err)
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, appresult.SuccessWithData("permission 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,
|
||||
}
|
||||
|
||||
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("permission_name")); raw != "" {
|
||||
filter.PermissionName = raw
|
||||
}
|
||||
|
||||
return filter, true
|
||||
c.JSON(http.StatusOK, appresult.SuccessWithData(perm.All))
|
||||
}
|
||||
@@ -1,11 +0,0 @@
|
||||
package permission
|
||||
|
||||
import "context"
|
||||
|
||||
type Repository interface {
|
||||
List(ctx context.Context, filter ListFilter) (ListPermissionDTO, error)
|
||||
GetByID(ctx context.Context, id int64) (PermissionDTO, error)
|
||||
Create(ctx context.Context, dto CreatePermissionDTO) (PermissionDTO, error)
|
||||
Update(ctx context.Context, id int64, dto UpdatePermissionDTO) (PermissionDTO, error)
|
||||
Delete(ctx context.Context, id int64) error
|
||||
}
|
||||
@@ -1,69 +0,0 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
|
||||
"online-back/internal/identity/permissionrole"
|
||||
"online-back/pkg/client/postgresql"
|
||||
"online-back/pkg/logging"
|
||||
|
||||
"github.com/jackc/pgx/v4"
|
||||
)
|
||||
|
||||
type repository struct {
|
||||
client postgresql.Client
|
||||
logger *logging.Logger
|
||||
}
|
||||
|
||||
func NewRepository(client postgresql.Client, logger *logging.Logger) permissionrole.Repository {
|
||||
return &repository{client: client, logger: logger}
|
||||
}
|
||||
|
||||
func (r *repository) Create(ctx context.Context, dto permissionrole.CreatePermissionRoleDTO) (permissionrole.PermissionRoleDTO, error) {
|
||||
query := `
|
||||
WITH upserted AS (
|
||||
INSERT INTO permission_role (permission_id, role_id)
|
||||
VALUES ($1, $2)
|
||||
ON CONFLICT (permission_id, role_id) DO UPDATE SET
|
||||
updated_at = (CURRENT_TIMESTAMP AT TIME ZONE 'UTC')
|
||||
RETURNING id, permission_id, role_id, created_at, updated_at
|
||||
)
|
||||
SELECT upserted.id, upserted.permission_id, p.name, upserted.role_id, r.name, upserted.created_at, upserted.updated_at
|
||||
FROM upserted
|
||||
JOIN permissions p ON p.id = upserted.permission_id
|
||||
JOIN roles r ON r.id = upserted.role_id`
|
||||
|
||||
row := r.client.QueryRow(ctx, query, dto.PermissionId, dto.RoleId)
|
||||
return scanPermissionRole(row)
|
||||
}
|
||||
|
||||
func (r *repository) Delete(ctx context.Context, id int64) error {
|
||||
tag, err := r.client.Exec(ctx, `DELETE FROM permission_role WHERE id = $1`, id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if tag.RowsAffected() == 0 {
|
||||
return pgx.ErrNoRows
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
type scannable interface {
|
||||
Scan(dest ...interface{}) error
|
||||
}
|
||||
|
||||
func scanPermissionRole(row scannable) (permissionrole.PermissionRoleDTO, error) {
|
||||
var item permissionrole.PermissionRoleDTO
|
||||
|
||||
err := row.Scan(
|
||||
&item.Id, &item.PermissionId, &item.PermissionName, &item.RoleId, &item.RoleName, &item.CreatedAt, &item.UpdatedAt,
|
||||
)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return permissionrole.PermissionRoleDTO{}, err
|
||||
}
|
||||
if err != nil {
|
||||
return permissionrole.PermissionRoleDTO{}, err
|
||||
}
|
||||
return item, nil
|
||||
}
|
||||
@@ -1,18 +0,0 @@
|
||||
package permissionrole
|
||||
|
||||
import "time"
|
||||
|
||||
type PermissionRoleDTO struct {
|
||||
Id int64 `json:"id"`
|
||||
RoleId int64 `json:"roleId"`
|
||||
RoleName string `json:"roleName"`
|
||||
PermissionId int64 `json:"permissionId"`
|
||||
PermissionName string `json:"permissionName"`
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
UpdatedAt time.Time `json:"updatedAt"`
|
||||
}
|
||||
|
||||
type CreatePermissionRoleDTO struct {
|
||||
PermissionId int64 `json:"permissionId" binding:"required"`
|
||||
RoleId int64 `json:"roleId" binding:"required"`
|
||||
}
|
||||
@@ -1,99 +0,0 @@
|
||||
package permissionrole
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
"strconv"
|
||||
|
||||
"online-back/internal/appresult"
|
||||
"online-back/internal/handlers"
|
||||
"online-back/pkg/logging"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/jackc/pgx/v4"
|
||||
)
|
||||
|
||||
const baseURL = "/permission-roles"
|
||||
|
||||
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 := router.Group(baseURL, appresult.JwtTokenCheck())
|
||||
group.POST("", h.create)
|
||||
group.DELETE("/:id", h.delete)
|
||||
}
|
||||
|
||||
// create godoc
|
||||
// @Summary Assign permission to role
|
||||
// @Description Creates a permission-role assignment, or updates the existing pair if already assigned
|
||||
// @Tags permission-roles
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param body body CreatePermissionRoleDTO true "Permission-role payload"
|
||||
// @Success 201 {object} appresult.AppSuccess
|
||||
// @Failure 400 {object} appresult.AppError
|
||||
// @Failure 500 {object} appresult.AppError
|
||||
// @Router /permission-roles [post]
|
||||
func (h *handler) create(c *gin.Context) {
|
||||
var dto CreatePermissionRoleDTO
|
||||
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 permission role failed: %v", err)
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusCreated, appresult.SuccessWithData(item))
|
||||
}
|
||||
|
||||
// delete godoc
|
||||
// @Summary Remove permission from role
|
||||
// @Description Deletes a permission-role assignment
|
||||
// @Tags permission-roles
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param id path int true "Permission-role ID"
|
||||
// @Success 200 {object} appresult.AppSuccess
|
||||
// @Failure 400 {object} appresult.AppError
|
||||
// @Failure 404 {object} appresult.AppError
|
||||
// @Failure 500 {object} appresult.AppError
|
||||
// @Router /permission-roles/{id} [delete]
|
||||
func (h *handler) delete(c *gin.Context) {
|
||||
id, ok := 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 permission role failed: %v", err)
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, appresult.SuccessWithData("permission role 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
|
||||
}
|
||||
@@ -1,8 +0,0 @@
|
||||
package permissionrole
|
||||
|
||||
import "context"
|
||||
|
||||
type Repository interface {
|
||||
Create(ctx context.Context, dto CreatePermissionRoleDTO) (PermissionRoleDTO, error)
|
||||
Delete(ctx context.Context, id int64) error
|
||||
}
|
||||
@@ -10,167 +10,292 @@ import (
|
||||
|
||||
"online-back/internal/appresult"
|
||||
"online-back/internal/config"
|
||||
"online-back/internal/identity/rbac/perm"
|
||||
"online-back/pkg/logging"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/golang-jwt/jwt"
|
||||
"github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
const (
|
||||
roleUser = "user"
|
||||
roleOperator = "operator"
|
||||
adminPrefix = "/api/admin"
|
||||
contextRole = "role"
|
||||
contextPrincipal = "rbacPrincipal"
|
||||
contextService = "rbacService"
|
||||
)
|
||||
|
||||
func RequirePermission(service *Service, code string) gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
rawID, exists := c.Get("id")
|
||||
if !exists {
|
||||
c.AbortWithStatusJSON(http.StatusForbidden, appresult.ErrForbidden)
|
||||
return
|
||||
}
|
||||
// Public: no token (login, register, payment callback).
|
||||
func Public() Policy {
|
||||
return Policy{name: "public", read: rule{kind: rulePublic}, write: rule{kind: rulePublic}}
|
||||
}
|
||||
|
||||
userID, err := strconv.ParseInt(rawID.(string), 10, 64)
|
||||
if err != nil {
|
||||
c.AbortWithStatusJSON(http.StatusForbidden, appresult.ErrForbidden)
|
||||
return
|
||||
}
|
||||
// Authenticated: any logged-in user, clients included (profile, file).
|
||||
func Authenticated() Policy {
|
||||
return Policy{name: "authenticated", read: rule{kind: ruleAuthenticated}, write: rule{kind: ruleAuthenticated}}
|
||||
}
|
||||
|
||||
granted, err := service.HasPermission(c.Request.Context(), userID, code)
|
||||
if err != nil || !granted {
|
||||
c.AbortWithStatusJSON(http.StatusForbidden, appresult.ErrForbidden)
|
||||
return
|
||||
}
|
||||
// Staff: any logged-in user whose role scope is not own.
|
||||
func Staff() Policy {
|
||||
return Policy{name: "staff", read: rule{kind: ruleStaff}, write: rule{kind: ruleStaff}}
|
||||
}
|
||||
|
||||
c.Next()
|
||||
// Require: code for every method. Own-scope callers are limited to their
|
||||
// own records, branch-scope callers to their branches.
|
||||
func Require(code perm.Code) Policy {
|
||||
r := rule{kind: rulePermission, perm: string(code)}
|
||||
return Policy{name: "require:" + string(code), read: r, write: r}
|
||||
}
|
||||
|
||||
// RequireStaff: Require, but never for own-scope callers.
|
||||
func RequireStaff(code perm.Code) Policy {
|
||||
r := rule{kind: rulePermission, perm: string(code), staffOnly: true}
|
||||
return Policy{name: "require-staff:" + string(code), read: r, write: r}
|
||||
}
|
||||
|
||||
// Catalog: reference data every logged-in user reads (loan types, branches,
|
||||
// currencies, ...); writes need code and a staff scope.
|
||||
func Catalog(code perm.Code) Policy {
|
||||
return Policy{
|
||||
name: "catalog:" + string(code),
|
||||
read: rule{kind: ruleAuthenticated},
|
||||
write: rule{kind: rulePermission, perm: string(code), staffOnly: true},
|
||||
}
|
||||
}
|
||||
|
||||
func Guard(service *Service) gin.HandlerFunc {
|
||||
// StaffRead: any staff member reads, writes need code.
|
||||
func StaffRead(code perm.Code) Policy {
|
||||
return Policy{
|
||||
name: "staff-read:" + string(code),
|
||||
read: rule{kind: ruleStaff},
|
||||
write: rule{kind: rulePermission, perm: string(code), staffOnly: true},
|
||||
}
|
||||
}
|
||||
|
||||
// Guard runs on every /api/admin request before the route's group
|
||||
// middleware: it resolves the route's policy (deny if none), and for
|
||||
// non-public routes loads the caller's principal into the context.
|
||||
func Guard(service Authorizer) gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
if c.Request.Method == http.MethodOptions || isPublicAdminPath(c.Request.URL.Path) {
|
||||
if c.Request.Method == http.MethodOptions || c.FullPath() == "" {
|
||||
c.Next()
|
||||
return
|
||||
}
|
||||
|
||||
policy, ok := routes.lookup(c.FullPath())
|
||||
if !ok {
|
||||
abortForbidden(c, "route has no rbac policy", nil)
|
||||
return
|
||||
}
|
||||
if policy.public() {
|
||||
c.Next()
|
||||
return
|
||||
}
|
||||
|
||||
userID, ok := requestUserID(c)
|
||||
if !ok {
|
||||
// The group's JwtTokenCheck answers with the proper 401/403.
|
||||
c.Next()
|
||||
return
|
||||
}
|
||||
|
||||
code, err := service.RoleCode(c.Request.Context(), userID)
|
||||
principal, err := service.Load(c.Request.Context(), userID)
|
||||
if err != nil {
|
||||
logging.GetLogger().Errorf("rbac: load principal %d failed: %v", userID, err)
|
||||
c.AbortWithStatusJSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
if principal == nil {
|
||||
abortForbidden(c, "user or role not found", logrus.Fields{"userId": userID})
|
||||
return
|
||||
}
|
||||
|
||||
c.Set("id", strconv.FormatInt(userID, 10))
|
||||
c.Set(contextRole, code)
|
||||
c.Set(contextPrincipal, principal)
|
||||
c.Set(contextService, service)
|
||||
c.Next()
|
||||
}
|
||||
}
|
||||
|
||||
switch code {
|
||||
case roleOperator:
|
||||
enforceOperator(c, service, userID)
|
||||
func (p Policy) handler() gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
r := p.ruleFor(c.Request.Method)
|
||||
principal := PrincipalFrom(c)
|
||||
if principal == nil {
|
||||
abortForbidden(c, "no principal", nil)
|
||||
return
|
||||
case roleUser, "":
|
||||
if !userRoleAllows(c.Request.Method, c.Request.URL.Path) {
|
||||
c.AbortWithStatusJSON(http.StatusForbidden, appresult.ErrForbidden)
|
||||
}
|
||||
|
||||
switch r.kind {
|
||||
case ruleAuthenticated:
|
||||
case ruleStaff:
|
||||
if principal.Scope == ScopeOwn {
|
||||
abortForbidden(c, "staff only", logrus.Fields{"userId": principal.UserID})
|
||||
return
|
||||
}
|
||||
case rulePermission:
|
||||
if !principal.Can(perm.Code(r.perm)) {
|
||||
abortForbidden(c, "missing permission", logrus.Fields{"userId": principal.UserID, "permission": r.perm})
|
||||
return
|
||||
}
|
||||
if r.staffOnly && principal.Scope == ScopeOwn {
|
||||
abortForbidden(c, "staff only", logrus.Fields{"userId": principal.UserID, "permission": r.perm})
|
||||
return
|
||||
}
|
||||
if !enforceScope(c, principal) {
|
||||
return
|
||||
}
|
||||
scopeOwnedLists(c, userID)
|
||||
c.Next()
|
||||
return
|
||||
default:
|
||||
c.Next()
|
||||
abortForbidden(c, "unknown rule", nil)
|
||||
return
|
||||
}
|
||||
c.Next()
|
||||
}
|
||||
}
|
||||
|
||||
func enforceOperator(c *gin.Context, service *Service, userID int64) {
|
||||
ids, err := service.BranchIDs(c.Request.Context(), userID)
|
||||
// enforceScope applies the role's data scope to a permission-gated request.
|
||||
// own: list queries and write bodies are pinned to the caller's user id.
|
||||
// branch: the caller must have branches, and write bodies may only name
|
||||
// those branches (and, on update, users visible in them).
|
||||
func enforceScope(c *gin.Context, p *Principal) bool {
|
||||
switch p.Scope {
|
||||
case ScopeAll:
|
||||
return true
|
||||
case ScopeOwn:
|
||||
pinOwnQuery(c, p.UserID)
|
||||
return pinOwnBody(c, p.UserID)
|
||||
case ScopeBranch:
|
||||
if len(p.BranchIDs) == 0 {
|
||||
abortForbidden(c, "branch scope without assigned branches", logrus.Fields{"userId": p.UserID})
|
||||
return false
|
||||
}
|
||||
return branchWriteAllowed(c, p.BranchIDs)
|
||||
}
|
||||
abortForbidden(c, "unknown scope", logrus.Fields{"userId": p.UserID, "scope": p.Scope})
|
||||
return false
|
||||
}
|
||||
|
||||
func pinOwnQuery(c *gin.Context, userID int64) {
|
||||
query := c.Request.URL.Query()
|
||||
id := strconv.FormatInt(userID, 10)
|
||||
query.Set("user_id", id)
|
||||
query.Set("created_by", id)
|
||||
c.Request.URL.RawQuery = query.Encode()
|
||||
}
|
||||
|
||||
func pinOwnBody(c *gin.Context, userID int64) bool {
|
||||
if !isWrite(c.Request.Method) || c.Request.Method == http.MethodDelete {
|
||||
return true
|
||||
}
|
||||
body, ok := readBody(c)
|
||||
if !ok {
|
||||
return false
|
||||
}
|
||||
if len(bytes.TrimSpace(body)) == 0 {
|
||||
return true
|
||||
}
|
||||
|
||||
var payload map[string]interface{}
|
||||
if err := json.Unmarshal(body, &payload); err != nil {
|
||||
return true
|
||||
}
|
||||
payload["userId"] = userID
|
||||
payload["user_id"] = userID
|
||||
payload["createdBy"] = userID
|
||||
payload["created_by"] = userID
|
||||
rewritten, err := json.Marshal(payload)
|
||||
if err != nil {
|
||||
return true
|
||||
}
|
||||
c.Request.Body = io.NopCloser(bytes.NewBuffer(rewritten))
|
||||
c.Request.ContentLength = int64(len(rewritten))
|
||||
return true
|
||||
}
|
||||
|
||||
func branchWriteAllowed(c *gin.Context, branchIDs []int64) bool {
|
||||
switch c.Request.Method {
|
||||
case http.MethodPost, http.MethodPut, http.MethodPatch:
|
||||
default:
|
||||
return true
|
||||
}
|
||||
body, ok := readBody(c)
|
||||
if !ok {
|
||||
return false
|
||||
}
|
||||
if len(bytes.TrimSpace(body)) == 0 {
|
||||
return true
|
||||
}
|
||||
|
||||
var payload struct {
|
||||
BranchId *int64 `json:"branchId"`
|
||||
UserId *int64 `json:"userId"`
|
||||
}
|
||||
if err := json.Unmarshal(body, &payload); err != nil {
|
||||
return true
|
||||
}
|
||||
|
||||
if payload.BranchId != nil && *payload.BranchId > 0 && !containsInt64(branchIDs, *payload.BranchId) {
|
||||
abortForbidden(c, "payload branchId not in caller's branches", logrus.Fields{
|
||||
"requestedBranchId": *payload.BranchId,
|
||||
"allowedBranchIds": branchIDs,
|
||||
})
|
||||
return false
|
||||
}
|
||||
|
||||
// A new order's customer has no record in the branch yet; the branchId
|
||||
// check above already scopes the create, so only reassignment (PUT/PATCH)
|
||||
// has to name a user visible in the caller's branches.
|
||||
if c.Request.Method == http.MethodPost || payload.UserId == nil || *payload.UserId <= 0 {
|
||||
return true
|
||||
}
|
||||
service := serviceFrom(c)
|
||||
if service == nil {
|
||||
abortForbidden(c, "no rbac service", nil)
|
||||
return false
|
||||
}
|
||||
visible, err := service.UserVisibleInBranches(c.Request.Context(), *payload.UserId, branchIDs)
|
||||
if err != nil {
|
||||
c.AbortWithStatusJSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
return false
|
||||
}
|
||||
c.Set(contextBranchIDs, ids)
|
||||
|
||||
if !operatorRoleAllows(c.Request.Method, c.Request.URL.Path) {
|
||||
c.AbortWithStatusJSON(http.StatusForbidden, appresult.ErrForbidden)
|
||||
return
|
||||
if !visible {
|
||||
abortForbidden(c, "payload userId not visible in caller's branches", logrus.Fields{
|
||||
"requestedUserId": *payload.UserId,
|
||||
"allowedBranchIds": branchIDs,
|
||||
})
|
||||
return false
|
||||
}
|
||||
|
||||
if !operatorProfileOrFile(c.Request.URL.Path) && len(ids) == 0 {
|
||||
c.AbortWithStatusJSON(http.StatusForbidden, appresult.ErrForbidden)
|
||||
return
|
||||
}
|
||||
|
||||
if !operatorWriteAllowed(c, service, ids) {
|
||||
return
|
||||
}
|
||||
|
||||
c.Next()
|
||||
return true
|
||||
}
|
||||
|
||||
func isPublicAdminPath(path string) bool {
|
||||
switch strings.TrimSuffix(path, "/") {
|
||||
case adminPrefix + "/login",
|
||||
adminPrefix + "/token",
|
||||
adminPrefix + "/register",
|
||||
adminPrefix + "/register/verify",
|
||||
adminPrefix + "/forgot-password",
|
||||
adminPrefix + "/forgot-password/verify":
|
||||
func readBody(c *gin.Context) ([]byte, bool) {
|
||||
body, err := io.ReadAll(c.Request.Body)
|
||||
if err != nil {
|
||||
c.AbortWithStatusJSON(http.StatusBadRequest, appresult.ErrMissingParam)
|
||||
return nil, false
|
||||
}
|
||||
c.Request.Body = io.NopCloser(bytes.NewBuffer(body))
|
||||
return body, true
|
||||
}
|
||||
|
||||
func isWrite(method string) bool {
|
||||
switch method {
|
||||
case http.MethodPost, http.MethodPut, http.MethodPatch, http.MethodDelete:
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
func userRoleAllows(method, path string) bool {
|
||||
if method != http.MethodGet {
|
||||
return false
|
||||
}
|
||||
|
||||
rest := strings.TrimSuffix(strings.TrimPrefix(path, adminPrefix), "/")
|
||||
if rest == "" {
|
||||
return false
|
||||
}
|
||||
if !strings.HasPrefix(rest, "/") {
|
||||
rest = "/" + rest
|
||||
}
|
||||
|
||||
for _, prefix := range userRolePrefixes {
|
||||
if rest == prefix || strings.HasPrefix(rest, prefix+"/") {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func scopeOwnedLists(c *gin.Context, userID int64) {
|
||||
rest := strings.TrimSuffix(strings.TrimPrefix(c.Request.URL.Path, adminPrefix), "/")
|
||||
if rest == "" {
|
||||
return
|
||||
// abortForbidden logs which rbac check denied the request before writing the
|
||||
// 403, since appresult.ErrForbidden alone doesn't say.
|
||||
func abortForbidden(c *gin.Context, reason string, fields logrus.Fields) {
|
||||
entry := logging.GetLogger().WithFields(logrus.Fields{
|
||||
"method": c.Request.Method,
|
||||
"path": c.Request.URL.Path,
|
||||
})
|
||||
for k, v := range fields {
|
||||
entry = entry.WithField(k, v)
|
||||
}
|
||||
if !strings.HasPrefix(rest, "/") {
|
||||
rest = "/" + rest
|
||||
}
|
||||
|
||||
owned := false
|
||||
for _, prefix := range userOwnedPrefixes {
|
||||
if rest == prefix || strings.HasPrefix(rest, prefix+"/") {
|
||||
owned = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !owned {
|
||||
return
|
||||
}
|
||||
|
||||
query := c.Request.URL.Query()
|
||||
query.Set("user_id", strconv.FormatInt(userID, 10))
|
||||
c.Request.URL.RawQuery = query.Encode()
|
||||
entry.Warn("rbac forbidden: " + reason)
|
||||
c.AbortWithStatusJSON(http.StatusForbidden, appresult.ErrForbidden)
|
||||
}
|
||||
|
||||
func requestUserID(c *gin.Context) (int64, bool) {
|
||||
@@ -231,141 +356,3 @@ func bearerToken(header string) string {
|
||||
}
|
||||
return strings.TrimSpace(header)
|
||||
}
|
||||
|
||||
var userRolePrefixes = []string{
|
||||
"/profile",
|
||||
"/cards",
|
||||
"/card-orders",
|
||||
"/card-pin-orders",
|
||||
"/payment-cards",
|
||||
"/reasons-cards",
|
||||
"/visa-master-payment-orders",
|
||||
"/loan-orders",
|
||||
"/loan-types",
|
||||
"/loans-documents",
|
||||
"/loans-repayment",
|
||||
"/loan-paid-off-letters",
|
||||
}
|
||||
|
||||
var userOwnedPrefixes = []string{
|
||||
"/cards",
|
||||
"/card-orders",
|
||||
"/card-pin-orders",
|
||||
"/visa-master-payment-orders",
|
||||
"/loan-orders",
|
||||
}
|
||||
|
||||
func operatorRoleAllows(method, path string) bool {
|
||||
rest := adminREST(path)
|
||||
if rest == "" {
|
||||
return false
|
||||
}
|
||||
if method == http.MethodGet {
|
||||
for _, prefix := range operatorGetPrefixes {
|
||||
if rest == prefix || strings.HasPrefix(rest, prefix+"/") {
|
||||
return true
|
||||
}
|
||||
}
|
||||
}
|
||||
for _, prefix := range operatorWritePrefixes {
|
||||
if rest == prefix || strings.HasPrefix(rest, prefix+"/") {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func operatorProfileOrFile(path string) bool {
|
||||
rest := adminREST(path)
|
||||
return rest == "/profile" || rest == "/file" || strings.HasPrefix(rest, "/file/")
|
||||
}
|
||||
|
||||
func operatorWriteAllowed(c *gin.Context, service *Service, branchIDs []int64) bool {
|
||||
switch c.Request.Method {
|
||||
case http.MethodPost, http.MethodPut, http.MethodPatch:
|
||||
default:
|
||||
return true
|
||||
}
|
||||
if operatorProfileOrFile(c.Request.URL.Path) || len(branchIDs) == 0 {
|
||||
return true
|
||||
}
|
||||
|
||||
body, err := io.ReadAll(c.Request.Body)
|
||||
if err != nil {
|
||||
c.AbortWithStatusJSON(http.StatusBadRequest, appresult.ErrMissingParam)
|
||||
return false
|
||||
}
|
||||
c.Request.Body = io.NopCloser(bytes.NewBuffer(body))
|
||||
if len(bytes.TrimSpace(body)) == 0 {
|
||||
return true
|
||||
}
|
||||
|
||||
var payload struct {
|
||||
BranchId *int64 `json:"branchId"`
|
||||
UserId *int64 `json:"userId"`
|
||||
}
|
||||
if err := json.Unmarshal(body, &payload); err != nil {
|
||||
return true
|
||||
}
|
||||
|
||||
if payload.BranchId != nil && *payload.BranchId > 0 && !containsInt64(branchIDs, *payload.BranchId) {
|
||||
c.AbortWithStatusJSON(http.StatusForbidden, appresult.ErrForbidden)
|
||||
return false
|
||||
}
|
||||
if payload.UserId != nil && *payload.UserId > 0 {
|
||||
visible, err := service.UserVisibleInBranches(c.Request.Context(), *payload.UserId, branchIDs)
|
||||
if err != nil {
|
||||
c.AbortWithStatusJSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return false
|
||||
}
|
||||
if !visible {
|
||||
c.AbortWithStatusJSON(http.StatusForbidden, appresult.ErrForbidden)
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func adminREST(path string) string {
|
||||
rest := strings.TrimSuffix(strings.TrimPrefix(path, adminPrefix), "/")
|
||||
if rest == "" {
|
||||
return ""
|
||||
}
|
||||
if !strings.HasPrefix(rest, "/") {
|
||||
rest = "/" + rest
|
||||
}
|
||||
return rest
|
||||
}
|
||||
|
||||
var operatorWritePrefixes = []string{
|
||||
"/profile",
|
||||
"/file",
|
||||
"/users",
|
||||
"/branch-users",
|
||||
"/cards",
|
||||
"/card-orders",
|
||||
"/card-pin-orders",
|
||||
"/visa-master-payment-orders",
|
||||
"/loan-orders",
|
||||
"/loans-repayment",
|
||||
"/loan-paid-off-letters",
|
||||
}
|
||||
|
||||
var operatorGetPrefixes = []string{
|
||||
"/profile",
|
||||
"/file",
|
||||
"/users",
|
||||
"/cards",
|
||||
"/card-orders",
|
||||
"/card-pin-orders",
|
||||
"/payment-cards",
|
||||
"/reasons-cards",
|
||||
"/visa-master-payment-orders",
|
||||
"/loan-orders",
|
||||
"/loan-types",
|
||||
"/loans-documents",
|
||||
"/loans-repayment",
|
||||
"/loan-paid-off-letters",
|
||||
"/provinces",
|
||||
"/branches",
|
||||
}
|
||||
Loaded 100 of 182 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user