ch some
Some checks failed
CI/CD / Vet, test, build (push) Has been cancelled
CI/CD / Docker image (push) Has been cancelled
CI/CD / Deploy binary to server (push) Has been cancelled

This commit is contained in:
2026-09-04 19:33:26 +05:00
parent 28509eb4ca
commit d1a6fcaadc
102 changed files with 2089 additions and 1957 deletions

View File

@@ -12,7 +12,7 @@ migrate:
migrate-rollback: migrate-rollback:
migrate -database 'postgres://bank_admin:bank%40%2323%23%40_password@localhost:5424/bank_db?sslmode=disable' -path db/migrations down migrate -database 'postgres://bank_admin:bank%40%2323%23%40_password@localhost:5424/bank_db?sslmode=disable' -path db/migrations down
seed: 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 # ---- for linux
# migrate: # migrate:

View File

@@ -56,14 +56,21 @@ Additional Swagger endpoints (categories, settings) are documented but not yet i
├── config.yaml # Runtime configuration ├── config.yaml # Runtime configuration
├── docker-compose.yaml # Local development stack ├── docker-compose.yaml # Local development stack
├── db/migrations/ # SQL migrations ├── db/migrations/ # SQL migrations
├── db/seed.sql # Consolidated, idempotent seed data
├── docs/ # Generated Swagger docs ├── docs/ # Generated Swagger docs
├── internal/ ├── internal/
│ ├── admin/auth/ # Admin auth handlers & repository
│ ├── appresult/ # Response helpers & JWT middleware │ ├── appresult/ # Response helpers & JWT middleware
│ ├── config/ # Config loader │ ├── 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/ └── pkg/
├── client/postgresql/ # PostgreSQL connection pool ├── client/postgresql/ # PostgreSQL connection pool
├── repository/genericrepo/ # Shared List/GetByID/Delete repository helper
├── logging/ # Structured logging ├── logging/ # Structured logging
└── utils/ # JWT & file utilities └── utils/ # JWT & file utilities
``` ```
@@ -165,6 +172,14 @@ make migrate-rollback
Migration files live in `db/migrations/`. 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
```
## Development ## Development
### Run tests ### Run tests

View File

@@ -45,6 +45,7 @@ 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_branch_id;
DROP INDEX IF EXISTS idx_card_rekwizit_orders_user_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_branch_id;
DROP INDEX IF EXISTS idx_card_pin_orders_user_id; DROP INDEX IF EXISTS idx_card_pin_orders_user_id;
@@ -59,6 +60,8 @@ DROP INDEX IF EXISTS idx_branches_province_id;
DROP INDEX IF EXISTS idx_branch_user_branch_id; DROP INDEX IF EXISTS idx_branch_user_branch_id;
DROP INDEX IF EXISTS idx_branch_user_user_id; DROP INDEX IF EXISTS idx_branch_user_user_id;
DROP INDEX IF EXISTS idx_permissions_code; DROP INDEX IF EXISTS idx_permissions_code;
DROP INDEX IF EXISTS idx_permissions_module;
DROP INDEX IF EXISTS idx_permissions_guard_name;
DROP INDEX IF EXISTS idx_roles_code; DROP INDEX IF EXISTS idx_roles_code;
DROP INDEX IF EXISTS idx_permission_role_role_id; DROP INDEX IF EXISTS idx_permission_role_role_id;
DROP INDEX IF EXISTS idx_permission_user_user_id; DROP INDEX IF EXISTS idx_permission_user_user_id;

View File

@@ -55,6 +55,7 @@ CREATE TABLE IF NOT EXISTS permissions (
code character varying(255) NOT NULL DEFAULT '', code character varying(255) NOT NULL DEFAULT '',
name character varying(255) NOT NULL, name character varying(255) NOT NULL,
guard_name character varying(255) NOT NULL, guard_name character varying(255) NOT NULL,
module character varying(255) NOT NULL DEFAULT '',
created_at TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') 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 updated_at TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL
); );
@@ -460,7 +461,7 @@ CREATE TABLE IF NOT EXISTS card_rekwizit_orders (
FOREIGN KEY (user_id) REFERENCES users(id) FOREIGN KEY (user_id) REFERENCES users(id)
); );
CREATE TABLE card_balances ( CREATE TABLE IF NOT EXISTS card_balances (
id bigserial PRIMARY KEY, id bigserial PRIMARY KEY,
passport_number TEXT NOT NULL, passport_number TEXT NOT NULL,
card_number TEXT NOT NULL, card_number TEXT NOT NULL,
@@ -474,14 +475,17 @@ CREATE TABLE card_balances (
status TEXT NOT NULL DEFAULT 'pending', status TEXT NOT NULL DEFAULT 'pending',
checked_at TIMESTAMPTZ, checked_at TIMESTAMPTZ,
branch_id BIGINT,
created_by BIGINT, created_by BIGINT,
created_at TIMESTAMPTZ NOT NULL DEFAULT now(), created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
updated_at TIMESTAMPTZ NOT NULL DEFAULT now(), updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
deleted_at TIMESTAMPTZ, deleted_at TIMESTAMPTZ,
CONSTRAINT chk_month CHECK (expiry_month BETWEEN 1 AND 12), CONSTRAINT chk_month CHECK (expiry_month BETWEEN 1 AND 12),
CONSTRAINT chk_card CHECK (card_number ~ '^[0-9]{16,19}$'), -- CONSTRAINT chk_card CHECK (card_number ~ '^[0-9]{16,19}$'),
CONSTRAINT chk_status CHECK (status IN ('pending','success','failed','expired')) 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 ( CREATE TABLE IF NOT EXISTS backups (
@@ -524,6 +528,8 @@ CREATE INDEX IF NOT EXISTS idx_permission_role_role_id ON permission_role(role_i
CREATE INDEX IF NOT EXISTS idx_permission_user_user_id ON permission_user(user_id); CREATE INDEX IF NOT EXISTS idx_permission_user_user_id ON permission_user(user_id);
CREATE INDEX IF NOT EXISTS idx_roles_code ON roles(code); CREATE INDEX IF NOT EXISTS idx_roles_code ON roles(code);
CREATE INDEX IF NOT EXISTS idx_permissions_code ON permissions(code); CREATE INDEX IF NOT EXISTS idx_permissions_code ON permissions(code);
CREATE INDEX IF NOT EXISTS idx_permissions_module ON permissions(module);
CREATE INDEX IF NOT EXISTS idx_permissions_guard_name ON permissions(guard_name);
CREATE INDEX IF NOT EXISTS idx_branch_user_user_id ON branch_user(user_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_branch_user_branch_id ON branch_user(branch_id);
@@ -540,6 +546,8 @@ CREATE INDEX IF NOT EXISTS idx_card_pin_orders_branch_id ON card_pin_orders(bran
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_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_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_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_orders_branch_id ON loan_orders(branch_id);

View File

@@ -1 +0,0 @@
UPDATE roles SET guard_name = 'admin' WHERE code = 'operator';

View File

@@ -1,7 +0,0 @@
-- Guard enforces API access by roles.guard_name:
-- web = customer (own data)
-- operator = branch staff
-- admin = admin / manager / superadmin
UPDATE roles SET guard_name = 'web' WHERE code = 'user';
UPDATE roles SET guard_name = 'operator' WHERE code = 'operator';
UPDATE roles SET guard_name = 'admin' WHERE code IN ('admin', 'superadmin', 'manager');

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -1,10 +1,14 @@
-- Dev / staging mock data. Re-runnable: wipes app tables then reloads. -- 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 -- 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): -- Login (password = test1234):
-- superadmin@bank.tm / +993 61 92 92 48 -- superadmin@bank.tm / +993 61 92 92 48
-- admin@bank.tm -- admin@bank.tm
-- manager@bank.tm -- manager@bank.tm
-- operator@bank.tm -- operator@bank.tm (cards saha)
-- loanop@bank.tm (loans saha)
-- bothop@bank.tm (cards + loans)
-- currency@bank.tm (admin guard — walýuta)
-- serdar@bank.tm … leyla@bank.tm (role=user) -- serdar@bank.tm … leyla@bank.tm (role=user)
BEGIN; BEGIN;
@@ -20,6 +24,7 @@ TRUNCATE TABLE
card_rekwizit_orders, card_rekwizit_orders,
card_pin_orders, card_pin_orders,
card_orders, card_orders,
card_balances,
cards, cards,
loan_order_required_docs, loan_order_required_docs,
loan_types, loan_types,
@@ -29,6 +34,7 @@ TRUNCATE TABLE
branches, branches,
provinces, provinces,
permission_role, permission_role,
permission_user,
role_user, role_user,
permissions, permissions,
roles, roles,
@@ -37,8 +43,9 @@ TRUNCATE TABLE
RESTART IDENTITY CASCADE; RESTART IDENTITY CASCADE;
-- --------------------------------------------------------------------------- -- ---------------------------------------------------------------------------
-- Users (10): superadmin, admin, manager, operator, -- Users (13): superadmin, admin, manager, operator,
-- 1 branch-assigned user (serdar), 5 users (gulnar…leyla). -- 1 branch-assigned user (serdar), 5 users (gulnar…leyla),
-- 1 currency maintainer, 1 loan operator, 1 cards+loans operator.
-- Password = test1234 for all. Phone unique (idx_users_phone). -- Password = test1234 for all. Phone unique (idx_users_phone).
-- --------------------------------------------------------------------------- -- ---------------------------------------------------------------------------
INSERT INTO users (email, password, name, first_name, last_name, username, phone, role, active) VALUES INSERT INTO users (email, password, name, first_name, last_name, username, phone, role, active) VALUES
@@ -101,38 +108,55 @@ INSERT INTO users (email, password, name, first_name, last_name, username, phone
'$2a$12$.9KVj6x7wxUMdPcBJ6UpweYbzW4Mka0d2mQj7O20YHXpBKlb3ypdC', '$2a$12$.9KVj6x7wxUMdPcBJ6UpweYbzW4Mka0d2mQj7O20YHXpBKlb3ypdC',
'Leyla Gurbanowa', 'Leyla', 'Gurbanowa', 'leyla', 'Leyla Gurbanowa', 'Leyla', 'Gurbanowa', 'leyla',
'+993 61 92 92 40', 'user', true '+993 61 92 92 40', 'user', true
),
(
'currency@bank.tm',
'$2a$12$.9KVj6x7wxUMdPcBJ6UpweYbzW4Mka0d2mQj7O20YHXpBKlb3ypdC',
'Walýuta operator', 'Berdi', 'Hojayew', 'currency',
'+993 61 92 92 38', 'currency_maintainer', true
),
(
'loanop@bank.tm',
'$2a$12$.9KVj6x7wxUMdPcBJ6UpweYbzW4Mka0d2mQj7O20YHXpBKlb3ypdC',
'Loan Operator', 'Jeren', 'Atayeva', 'loanop',
'+993 61 92 92 37', 'operator', true
),
(
'bothop@bank.tm',
'$2a$12$.9KVj6x7wxUMdPcBJ6UpweYbzW4Mka0d2mQj7O20YHXpBKlb3ypdC',
'Full Operator', 'Batyr', 'Myradow', 'bothop',
'+993 61 92 92 36', 'operator', true
); );
-- --------------------------------------------------------------------------- -- ---------------------------------------------------------------------------
-- Roles & permissions -- Roles & permissions
-- --------------------------------------------------------------------------- -- ---------------------------------------------------------------------------
INSERT INTO roles (code, name, guard_name) VALUES INSERT INTO roles (code, name, guard_name) VALUES
('superadmin', 'Super Administrator', 'admin'), ('user', 'User', 'web'),
('admin', 'Administrator', 'admin'),
('manager', 'Branch Manager', 'admin'),
('operator', 'Operator', 'operator'), ('operator', 'Operator', 'operator'),
('user', 'User', 'web'); ('admin', 'Admin', 'admin'),
('superadmin', 'Superadmin', 'admin'),
('manager', 'Branch Manager', 'admin'),
('currency_maintainer', 'Walyuta kursy operator', 'admin');
INSERT INTO permissions (code, name, guard_name) VALUES INSERT INTO permissions (code, name, guard_name, module) VALUES
('users.view', 'View users', 'admin'), -- admin-only sahalar
('users.manage', 'Manage users', 'admin'), ('users.view', 'View users', 'admin', 'users'),
('roles.view', 'View roles', 'admin'), ('users.manage', 'Manage users', 'admin', 'users'),
('roles.manage', 'Manage roles', 'admin'), ('roles.view', 'View roles', 'admin', 'roles'),
('branches.view', 'View branches', 'admin'), ('roles.manage', 'Manage roles', 'admin', 'roles'),
('branches.manage', 'Manage branches', 'admin'), ('branches.view', 'View branches', 'admin', 'branches'),
('provinces.view', 'View provinces', 'admin'), ('branches.manage', 'Manage branches', 'admin', 'branches'),
('provinces.manage', 'Manage provinces', 'admin'), ('provinces.view', 'View provinces', 'admin', 'provinces'),
('cards.view', 'View cards', 'admin'), ('provinces.manage', 'Manage provinces', 'admin', 'provinces'),
('cards.manage', 'Manage cards', 'admin'), ('activity-logs.view', 'View activity logs', 'admin', 'activity-logs'),
('card-orders.view', 'View card orders', 'admin'), ('backups.view', 'View backups', 'admin', 'backups'),
('card-orders.manage', 'Manage card orders', 'admin'), ('backups.manage', 'Manage backups', 'admin', 'backups'),
('loans.view', 'View loans', 'admin'), ('currencies.view', 'View currencies', 'admin', 'currencies'),
('loans.manage', 'Manage loans', 'admin'), ('currencies.manage', 'Manage currencies', 'admin', 'currencies'),
('activity-logs.view', 'View activity logs', 'admin'), -- operator: two sahalar only
('backups.view', 'View backups', 'admin'), ('cards', 'Cards', 'operator', 'cards'),
('backups.manage', 'Manage backups', 'admin'), ('loans', 'Loans', 'operator', 'loans');
('currencies.view', 'View currencies', 'admin'),
('currencies.manage', 'Manage currencies', 'admin');
INSERT INTO role_user (role_id, user_id) INSERT INTO role_user (role_id, user_id)
SELECT r.id, u.id SELECT r.id, u.id
@@ -148,154 +172,139 @@ INSERT INTO permission_role (permission_id, role_id)
SELECT p.id, r.id SELECT p.id, r.id
FROM permissions p FROM permissions p
JOIN roles r ON r.code = 'manager' JOIN roles r ON r.code = 'manager'
WHERE p.code IN ( WHERE p.code IN ('cards', 'loans');
'branches.view', 'provinces.view', 'cards.view',
'card-orders.view', 'card-orders.manage', 'loans.view', 'loans.manage'
);
-- Operator role default: cards saha only.
INSERT INTO permission_role (permission_id, role_id) INSERT INTO permission_role (permission_id, role_id)
SELECT p.id, r.id SELECT p.id, r.id
FROM permissions p FROM permissions p
JOIN roles r ON r.code = 'operator' JOIN roles r ON r.code = 'operator'
WHERE p.code IN ( WHERE p.code = 'cards';
'card-orders.view', 'loans.view', 'cards.view', 'branches.view'
); -- loanop (user 12): loans only — deny role cards, allow loans.
-- bothop (user 13): keep role cards, add loans.
INSERT INTO permission_user (permission_id, user_id, effect)
SELECT p.id, 12, 'deny' FROM permissions p WHERE p.code = 'cards'
UNION ALL
SELECT p.id, 12, 'allow' FROM permissions p WHERE p.code = 'loans'
UNION ALL
SELECT p.id, 13, 'allow' FROM permissions p WHERE p.code = 'loans';
-- --------------------------------------------------------------------------- -- ---------------------------------------------------------------------------
-- Provinces (Turkmenistan) — name = etrap, region = welaýat -- Provinces — name = etrap, region = welaýat (admin location list)
-- --------------------------------------------------------------------------- -- ---------------------------------------------------------------------------
INSERT INTO provinces (name, region, active) VALUES INSERT INTO provinces (name, region, active) VALUES
-- Paýtagt ('{"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":"Ashgabat","ru":"Ашхабад","tm":"Aşgabat"}'::json, ('{"en":"Babadayhan","ru":"Бабадайхан","tm":"Babadaýhan"}'::json, '{"en":"Ahal","ru":"Ахал","tm":"Ahal"}'::json, true),
'{"en":"Capital","ru":"Столица","tm":"Paýtagt"}'::json, ('{"en":"Baherden","ru":"Бахерден","tm":"Bäherden"}'::json, '{"en":"Ahal","ru":"Ахал","tm":"Ahal"}'::json, true),
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),
-- Ahal welaýaty ('{"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":"Anew","ru":"Анев","tm":"Änew"}'::json, ('{"en":"Balkanabat","ru":"Балканабад","tm":"Balkanabat"}'::json, '{"en":"Balkan","ru":"Балкан","tm":"Balkan"}'::json, true),
'{"en":"Ahal Region","ru":"Ахалский велаят","tm":"Ahal welaýaty"}'::json, ('{"en":"Bereket","ru":"Берекет","tm":"Bereket"}'::json, '{"en":"Balkan","ru":"Балкан","tm":"Balkan"}'::json, true),
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":"Gokdepe","ru":"Гокдепе","tm":"Gökdepe"}'::json, ('{"en":"Gyzylarbat","ru":"Кызыларбат","tm":"Gyzylarbat"}'::json, '{"en":"Balkan","ru":"Балкан","tm":"Balkan"}'::json, true),
'{"en":"Ahal Region","ru":"Ахалский велаят","tm":"Ahal welaýaty"}'::json, ('{"en":"Hazar","ru":"Хазар","tm":"Hazar"}'::json, '{"en":"Balkan","ru":"Балкан","tm":"Balkan"}'::json, true),
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":"Tejen","ru":"Теджен","tm":"Tejen"}'::json, ('{"en":"Boldumsaz","ru":"Болдумсаз","tm":"Boldumsaz"}'::json, '{"en":"Dashoguz","ru":"Дашогуз","tm":"Daşoguz"}'::json, true),
'{"en":"Ahal Region","ru":"Ахалский велаят","tm":"Ahal welaýaty"}'::json, ('{"en":"Dashoguz","ru":"Дашогуз","tm":"Daşoguz"}'::json, '{"en":"Dashoguz","ru":"Дашогуз","tm":"Daşoguz"}'::json, true),
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),
-- Balkan welaýaty ('{"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":"Balkanabat","ru":"Балканабад","tm":"Balkanabat"}'::json, ('{"en":"Ruhubelent","ru":"Рухубелент","tm":"Ruhubelent"}'::json, '{"en":"Dashoguz","ru":"Дашогуз","tm":"Daşoguz"}'::json, true),
'{"en":"Balkan Region","ru":"Балканский велаят","tm":"Balkan welaýaty"}'::json, ('{"en":"S. Turkmenbashy","ru":"С. Туркменбашы","tm":"S. Türkmenbaşy ad."}'::json, '{"en":"Dashoguz","ru":"Дашогуз","tm":"Daşoguz"}'::json, true),
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":"Turkmenbashy","ru":"Туркменбаши","tm":"Türkmenbaşy"}'::json, ('{"en":"Darganata","ru":"Дарганата","tm":"Darganata"}'::json, '{"en":"Lebap","ru":"Лебап","tm":"Lebap"}'::json, true),
'{"en":"Balkan Region","ru":"Балканский велаят","tm":"Balkan welaýaty"}'::json, ('{"en":"Dowletli","ru":"Довлетли","tm":"Döwletli"}'::json, '{"en":"Lebap","ru":"Лебап","tm":"Lebap"}'::json, true),
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":"Serdar","ru":"Сердар","tm":"Serdar"}'::json, ('{"en":"Hojambaz","ru":"Ходжамбаз","tm":"Hojambaz"}'::json, '{"en":"Lebap","ru":"Лебап","tm":"Lebap"}'::json, true),
'{"en":"Balkan Region","ru":"Балканский велаят","tm":"Balkan welaýaty"}'::json, ('{"en":"Kerki","ru":"Керки","tm":"Kerki"}'::json, '{"en":"Lebap","ru":"Лебап","tm":"Lebap"}'::json, true),
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),
-- Daşoguz welaýaty ('{"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":"Dashoguz","ru":"Дашогуз","tm":"Daşoguz"}'::json, ('{"en":"Turkmenabat","ru":"Туркменабад","tm":"Türkmenabat"}'::json, '{"en":"Lebap","ru":"Лебап","tm":"Lebap"}'::json, true),
'{"en":"Dashoguz Region","ru":"Дашогузский велаят","tm":"Daşoguz welaýaty"}'::json, ('{"en":"Bayramaly","ru":"Байрамали","tm":"Baýramaly"}'::json, '{"en":"Mary","ru":"Мары","tm":"Mary"}'::json, true),
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":"Koneurgench","ru":"Кёнеургенч","tm":"Köneürgenç"}'::json, ('{"en":"Oguzhan","ru":"Огузхан","tm":"Oguzhan"}'::json, '{"en":"Mary","ru":"Мары","tm":"Mary"}'::json, true),
'{"en":"Dashoguz Region","ru":"Дашогузский велаят","tm":"Daşoguz welaýaty"}'::json, ('{"en":"Sakarchage","ru":"Сакарчаге","tm":"Sakarçäge"}'::json, '{"en":"Mary","ru":"Мары","tm":"Mary"}'::json, true),
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),
-- Lebap welaýaty ('{"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":"Turkmenabat","ru":"Туркменабад","tm":"Türkmenabat"}'::json, ('{"en":"Yoloten","ru":"Ёлётен","tm":"Ýolöten"}'::json, '{"en":"Mary","ru":"Мары","tm":"Mary"}'::json, true);
'{"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 -- Branches — 8 named mock şahamça first (ids 1–8 for order FKs),
-- then one şahamça per remaining etrap.
-- --------------------------------------------------------------------------- -- ---------------------------------------------------------------------------
INSERT INTO branches ( INSERT INTO branches (
unique_code, name, address, region, province_id, phone_numbers, unique_code, name, address, region, province_id, phone_numbers,
billing_username, billing_password, active billing_username, billing_password, active
) VALUES )
( SELECT v.unique_code, v.name::json, v.address::json, v.region, p.id, '+993 61 92 92 48', v.billing_username, 'billing_pass', v.active
'AGB-01', FROM (VALUES
'{"en":"Ashgabat Central Branch","ru":"Центральный филиал Ашхабад","tm":"Aşgabat Merkezi şahamça"}'::json, ('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),
'{"en":"Archabil Ave 1","ru":"пр. Арчабиль 1","tm":"Arçabil şaýoly 1"}'::json, ('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),
'AG', 1, '+993 61 92 92 48', 'billing_agb', 'billing_pass', 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),
'AGB-02', ('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),
'{"en":"Ashgabat Kopetdag Branch","ru":"Филиал Копетдаг","tm":"Köpetdag şahamçasy"}'::json, ('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),
'{"en":"Turkmenbashy Ave 45","ru":"пр. Туркменбаши 45","tm":"Türkmenbaşy şaýoly 45"}'::json, ('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)
'AG', 1, '+993 61 92 92 48', 'billing_agb2', 'billing_pass', true ) AS v(unique_code, name, address, region, province_tm, billing_username, active)
), JOIN provinces p ON p.name->>'tm' = v.province_tm;
(
'AHL-01', INSERT INTO branches (unique_code, name, address, region, province_id, phone_numbers, active)
'{"en":"Ahal Branch","ru":"Ахалский филиал","tm":"Ahal şahamçasy"}'::json, SELECT
'{"en":"Anew, Main St 10","ru":"Анев, ул. Главная 10","tm":"Änew, Baş köçe 10"}'::json, s.region_code || '-' || s.name_slug,
'AH', 2, '+993 61 92 92 48', 'billing_ahl', 'billing_pass', true json_build_object(
), 'en', (s.name->>'en') || ' branch',
( 'ru', (s.name->>'ru') || ' филиал',
'BLK-01', 'tm', (s.name->>'tm') || ' şahamçasy'
'{"en":"Balkanabat Branch","ru":"Филиал Балканабад","tm":"Balkanabat şahamçasy"}'::json, ),
'{"en":"Garaşsyzlyk St 7","ru":"ул. Гарашсызлык 7","tm":"Garaşsyzlyk köçesi 7"}'::json, json_build_object('en', s.name->>'en', 'ru', s.name->>'ru', 'tm', s.name->>'tm'),
'BL', 5, '+993 61 92 92 48', 'billing_blk', 'billing_pass', true s.region_code,
), s.id,
( '+993 61 92 92 48',
'DSZ-01', true
'{"en":"Dashoguz Branch","ru":"Филиал Дашогуз","tm":"Daşoguz şahamçasy"}'::json, FROM (
'{"en":"Galkynyş St 3","ru":"ул. Галкыныш 3","tm":"Galkynyş köçesi 3"}'::json, SELECT
'DZ', 8, '+993 61 92 92 48', 'billing_dsz', 'billing_pass', true p.id,
), p.name,
( CASE p.region->>'tm'
'LBP-01', WHEN 'Aşgabat' THEN 'AG'
'{"en":"Turkmenabat Branch","ru":"Филиал Туркменабад","tm":"Türkmenabat şahamçasy"}'::json, WHEN 'Ahal' THEN 'AH'
'{"en":"Magtymguly Ave 12","ru":"пр. Махтумкули 12","tm":"Magtymguly şaýoly 12"}'::json, WHEN 'Balkan' THEN 'BL'
'LB', 10, '+993 61 92 92 48', 'billing_lbp', 'billing_pass', true WHEN 'Daşoguz' THEN 'DZ'
), WHEN 'Lebap' THEN 'LB'
( WHEN 'Mary' THEN 'MR'
'MRY-01', ELSE 'XX'
'{"en":"Mary Branch","ru":"Марыйский филиал","tm":"Mary şahamçasy"}'::json, END AS region_code,
'{"en":"Mollanepes St 8","ru":"ул. Молланепес 8","tm":"Mollanepes köçesi 8"}'::json, trim(both '-' FROM upper(regexp_replace(
'MR', 12, '+993 61 92 92 48', 'billing_mry', 'billing_pass', true translate(p.name->>'tm', 'ÄäÇçŇňÖöŞşÜüÝý', 'AaCcNnOoSsUuYy'),
), '[^A-Za-z0-9]+', '-', 'g'
( ))) AS name_slug
'MRY-02', FROM provinces p
'{"en":"Bayramaly Branch (inactive)","ru":"Филиал Байрамали (неактивен)","tm":"Baýramaly şahamçasy (işjeň däl)"}'::json, WHERE p.active
'{"en":"Bayramaly, Central 1","ru":"Байрамали, Центральная 1","tm":"Baýramaly, Merkezi 1"}'::json, ) s
'MR', 13, '+993 61 92 92 48', 'billing_mry2', 'billing_pass', false 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 INSERT INTO branch_user (branch_id, user_id) VALUES
@@ -303,89 +312,41 @@ INSERT INTO branch_user (branch_id, user_id) VALUES
(1, 2), (1, 2),
(1, 3), (1, 3),
(7, 4), (7, 4),
(2, 5); (2, 5),
(1, 11),
(7, 12),
(7, 13);
-- --------------------------------------------------------------------------- -- ---------------------------------------------------------------------------
-- Card types (payment-cards) & card states (reasons-cards) -- Card types (Kart görnüşleri) & card states (çykarma sebäpleri)
-- --------------------------------------------------------------------------- -- ---------------------------------------------------------------------------
INSERT INTO card_types (name, price, notes, active) VALUES INSERT INTO card_types (name, price, notes, active) VALUES
( ('{"en":"Altyn Asyr","ru":"Алтын Асыр","tm":"Altyn Asyr"}'::json, '32', '', true),
'{"en":"Visa Classic","ru":"Visa Classic","tm":"Visa Classic"}'::json, ('{"en":"Family","ru":"Семейная","tm":"Maşgala"}'::json, '32', '', true),
'50', 'Standard debit card', 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":"Visa Gold","ru":"Visa Gold","tm":"Visa Gold"}'::json, ('{"en":"Credit","ru":"Кредитная","tm":"Karz"}'::json, '32', '', false),
'150', 'Premium debit card', true ('{"en":"Overdraft","ru":"Овердрафт","tm":"Owerdraft"}'::json, '32', '', 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 INSERT INTO card_states (name, price, notes, active) VALUES
( ('{"en":"New","ru":"Новая","tm":"Täze"}'::json, '32', '', true),
'{"en":"New card","ru":"Новая карта","tm":"Täze kart"}'::json, ('{"en":"Broken / damaged","ru":"Сломанная / повреждённая","tm":"Döwülen/Zaýalanan"}'::json, '32', '', true),
'0', 'First-time issue', 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":"Lost / stolen","ru":"Утеря / кража","tm":"Ýiten / ogurlanan"}'::json, ('{"en":"PIN envelope (blocked)","ru":"PIN-конверт (заблокирован)","tm":"Pin bukja (bloklanan)"}'::json, '3.02', '', false),
'20', 'Reissue after loss', true ('{"en":"Requisites","ru":"Реквизиты","tm":"Rekwizit"}'::json, '2.30', '', false);
),
(
'{"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 -- Loan types (Karz görnüşleri) & required docs
-- --------------------------------------------------------------------------- -- ---------------------------------------------------------------------------
INSERT INTO loan_types (name, tax, maturity, notes, active) VALUES 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","ru":"Потребительский кредит","tm":"Sarp ediş karzy"}'::json, ('{"en":"Consumer loan secured by guarantor","ru":"Потребительский кредит под поручительство","tm":"Üpjünçiligine zamunlyk bolan sarp ediş karzy"}'::json, 1.00, '30', '{}'::json, true),
12.50, '12', ('{"en":"Small loans","ru":"Кредиты малого объёма","tm":"Kiçi göwrümli karzlar"}'::json, 1.00, '30', '{}'::json, true),
'{"en":"Up to 12 months","ru":"До 12 месяцев","tm":"12 aýa çenli"}'::json, ('{"en":"Consumer loan secured by collateral","ru":"Потребительский кредит под залог имущества","tm":"Üpjünçiligine girew emlägi bolan sarp ediş karzy"}'::json, 1.00, '30', '{}'::json, true),
true ('{"en":"Student loan","ru":"Студенческий кредит","tm":"Talyp karzy"}'::json, 1.00, '30', '{"en":"Note","ru":"Примечание","tm":"Bellik"}'::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 INSERT INTO loan_order_required_docs (name, value, active) VALUES
('Passport copy', 'passport', true), ('Passport copy', 'passport', true),
@@ -579,7 +540,7 @@ INSERT INTO loan_orders (
'Mary, Galkynyş 15', 'Mary, Galkynyş 15', 'I-MR', '112233', 'Mary, Galkynyş 15', 'Mary, Galkynyş 15', 'I-MR', '112233',
'2012-04-22', 'Mary Police', 'Mary', '1995-01-25', '2012-04-22', 'Mary Police', 'Mary', '1995-01-25',
'dovran@bank.tm', '+993 61 92 92 48', NULL, NULL, 'dovran@bank.tm', '+993 61 92 92 48', NULL, NULL,
'MR', 12, 'Mary Textile', 'ACC-3003', 'MR', (SELECT id FROM provinces WHERE name->>'tm' = 'Mary'), 'Mary Textile', 'ACC-3003',
'2015-01-10', '5200', 'Engineer', '2015-01-10', '5200', 'Engineer',
'higher', 'married', 'higher', 'married',
'lo1.jpg', 'lo2.jpg', 'lo3.jpg', 'lo4.jpg', 'lo1.jpg', 'lo2.jpg', 'lo3.jpg', 'lo4.jpg',
@@ -596,7 +557,7 @@ INSERT INTO loan_orders (
'Turkmenabat, Magtymguly 2', 'Turkmenabat, Magtymguly 2', 'I-LB', '606060', 'Turkmenabat, Magtymguly 2', 'Turkmenabat, Magtymguly 2', 'I-LB', '606060',
'2019-11-05', 'Turkmenabat Police', 'Turkmenabat', '1996-12-12', '2019-11-05', 'Turkmenabat Police', 'Turkmenabat', '1996-12-12',
'ogul@mail.tm', '+993 61 92 92 48', NULL, NULL, 'ogul@mail.tm', '+993 61 92 92 48', NULL, NULL,
'LB', 10, 'Self-employed', NULL, 'LB', (SELECT id FROM provinces WHERE name->>'tm' = 'Türkmenabat'), 'Self-employed', NULL,
'2021-03-01', '6000', 'Entrepreneur', '2021-03-01', '6000', 'Entrepreneur',
'secondary', 'single', 'secondary', 'single',
'lo1.jpg', 'lo2.jpg', 'lo3.jpg', 'lo4.jpg', 'lo1.jpg', 'lo2.jpg', 'lo3.jpg', 'lo4.jpg',

View File

@@ -5113,6 +5113,18 @@ const docTemplate = `{
"name": "permission_name", "name": "permission_name",
"in": "query" "in": "query"
}, },
{
"type": "string",
"description": "Filter by guard (web, operator, admin)",
"name": "guard_name",
"in": "query"
},
{
"type": "string",
"description": "Filter by saha (cards, loans, …)",
"name": "module",
"in": "query"
},
{ {
"type": "integer", "type": "integer",
"default": 1, "default": 1,
@@ -5199,6 +5211,45 @@ const docTemplate = `{
} }
} }
}, },
"/permissions/tree": {
"get": {
"security": [
{
"BearerAuth": []
}
],
"description": "Returns permissions grouped as guard → module (saha) → permissions",
"produces": [
"application/json"
],
"tags": [
"permission"
],
"summary": "Permission tree",
"parameters": [
{
"type": "string",
"description": "Filter by guard (web, operator, admin)",
"name": "guard_name",
"in": "query"
}
],
"responses": {
"200": {
"description": "OK",
"schema": {
"$ref": "#/definitions/appresult.AppSuccess"
}
},
"500": {
"description": "Internal Server Error",
"schema": {
"$ref": "#/definitions/appresult.AppError"
}
}
}
}
},
"/permissions/{id}": { "/permissions/{id}": {
"get": { "get": {
"security": [ "security": [
@@ -5370,7 +5421,7 @@ const docTemplate = `{
"BearerAuth": [] "BearerAuth": []
} }
], ],
"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)",
"produces": [ "produces": [
"application/json" "application/json"
], ],
@@ -6781,7 +6832,7 @@ const docTemplate = `{
"BearerAuth": [] "BearerAuth": []
} }
], ],
"description": "Returns a single user with assigned branches and roleId", "description": "Returns a single user with assigned branches, roleId, and effective permissions",
"produces": [ "produces": [
"application/json" "application/json"
], ],
@@ -7534,6 +7585,9 @@ const docTemplate = `{
"balanceCurrency": { "balanceCurrency": {
"type": "string" "type": "string"
}, },
"branchId": {
"type": "integer"
},
"cardNumber": { "cardNumber": {
"type": "string" "type": "string"
}, },
@@ -7573,6 +7627,9 @@ const docTemplate = `{
"balanceCurrency": { "balanceCurrency": {
"type": "string" "type": "string"
}, },
"branchId": {
"type": "integer"
},
"cardNumber": { "cardNumber": {
"type": "string" "type": "string"
}, },
@@ -9056,20 +9113,6 @@ const docTemplate = `{
} }
} }
}, },
"online-back_internal_cards_shared.LocalizedText": {
"type": "object",
"properties": {
"en": {
"type": "string"
},
"ru": {
"type": "string"
},
"tm": {
"type": "string"
}
}
},
"paymentcard.CreatePaymentCardDTO": { "paymentcard.CreatePaymentCardDTO": {
"type": "object", "type": "object",
"required": [ "required": [
@@ -9087,7 +9130,7 @@ const docTemplate = `{
"type": "string" "type": "string"
}, },
"title": { "title": {
"$ref": "#/definitions/online-back_internal_cards_shared.LocalizedText" "$ref": "#/definitions/shared.LocalizedText"
} }
} }
}, },
@@ -9116,7 +9159,7 @@ const docTemplate = `{
"type": "string" "type": "string"
}, },
"title": { "title": {
"$ref": "#/definitions/online-back_internal_cards_shared.LocalizedText" "$ref": "#/definitions/shared.LocalizedText"
} }
} }
}, },
@@ -9125,6 +9168,7 @@ const docTemplate = `{
"required": [ "required": [
"code", "code",
"guardName", "guardName",
"module",
"name" "name"
], ],
"properties": { "properties": {
@@ -9132,6 +9176,14 @@ const docTemplate = `{
"type": "string" "type": "string"
}, },
"guardName": { "guardName": {
"type": "string",
"enum": [
"web",
"operator",
"admin"
]
},
"module": {
"type": "string" "type": "string"
}, },
"name": { "name": {
@@ -9144,6 +9196,7 @@ const docTemplate = `{
"required": [ "required": [
"code", "code",
"guardName", "guardName",
"module",
"name" "name"
], ],
"properties": { "properties": {
@@ -9151,6 +9204,14 @@ const docTemplate = `{
"type": "string" "type": "string"
}, },
"guardName": { "guardName": {
"type": "string",
"enum": [
"web",
"operator",
"admin"
]
},
"module": {
"type": "string" "type": "string"
}, },
"name": { "name": {
@@ -9263,7 +9324,7 @@ const docTemplate = `{
"type": "string" "type": "string"
}, },
"title": { "title": {
"$ref": "#/definitions/online-back_internal_cards_shared.LocalizedText" "$ref": "#/definitions/shared.LocalizedText"
} }
} }
}, },
@@ -9284,7 +9345,7 @@ const docTemplate = `{
"type": "string" "type": "string"
}, },
"title": { "title": {
"$ref": "#/definitions/online-back_internal_cards_shared.LocalizedText" "$ref": "#/definitions/shared.LocalizedText"
} }
} }
}, },
@@ -9300,7 +9361,12 @@ const docTemplate = `{
"type": "string" "type": "string"
}, },
"guardName": { "guardName": {
"type": "string" "type": "string",
"enum": [
"web",
"operator",
"admin"
]
}, },
"name": { "name": {
"type": "string" "type": "string"
@@ -9319,7 +9385,12 @@ const docTemplate = `{
"type": "string" "type": "string"
}, },
"guardName": { "guardName": {
"type": "string" "type": "string",
"enum": [
"web",
"operator",
"admin"
]
}, },
"name": { "name": {
"type": "string" "type": "string"
@@ -9341,6 +9412,20 @@ const docTemplate = `{
} }
} }
}, },
"shared.LocalizedText": {
"type": "object",
"properties": {
"en": {
"type": "string"
},
"ru": {
"type": "string"
},
"tm": {
"type": "string"
}
}
},
"user.CreateUserDTO": { "user.CreateUserDTO": {
"type": "object", "type": "object",
"required": [ "required": [

View File

@@ -5107,6 +5107,18 @@
"name": "permission_name", "name": "permission_name",
"in": "query" "in": "query"
}, },
{
"type": "string",
"description": "Filter by guard (web, operator, admin)",
"name": "guard_name",
"in": "query"
},
{
"type": "string",
"description": "Filter by saha (cards, loans, …)",
"name": "module",
"in": "query"
},
{ {
"type": "integer", "type": "integer",
"default": 1, "default": 1,
@@ -5193,6 +5205,45 @@
} }
} }
}, },
"/permissions/tree": {
"get": {
"security": [
{
"BearerAuth": []
}
],
"description": "Returns permissions grouped as guard → module (saha) → permissions",
"produces": [
"application/json"
],
"tags": [
"permission"
],
"summary": "Permission tree",
"parameters": [
{
"type": "string",
"description": "Filter by guard (web, operator, admin)",
"name": "guard_name",
"in": "query"
}
],
"responses": {
"200": {
"description": "OK",
"schema": {
"$ref": "#/definitions/appresult.AppSuccess"
}
},
"500": {
"description": "Internal Server Error",
"schema": {
"$ref": "#/definitions/appresult.AppError"
}
}
}
}
},
"/permissions/{id}": { "/permissions/{id}": {
"get": { "get": {
"security": [ "security": [
@@ -5364,7 +5415,7 @@
"BearerAuth": [] "BearerAuth": []
} }
], ],
"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)",
"produces": [ "produces": [
"application/json" "application/json"
], ],
@@ -6775,7 +6826,7 @@
"BearerAuth": [] "BearerAuth": []
} }
], ],
"description": "Returns a single user with assigned branches and roleId", "description": "Returns a single user with assigned branches, roleId, and effective permissions",
"produces": [ "produces": [
"application/json" "application/json"
], ],
@@ -7528,6 +7579,9 @@
"balanceCurrency": { "balanceCurrency": {
"type": "string" "type": "string"
}, },
"branchId": {
"type": "integer"
},
"cardNumber": { "cardNumber": {
"type": "string" "type": "string"
}, },
@@ -7567,6 +7621,9 @@
"balanceCurrency": { "balanceCurrency": {
"type": "string" "type": "string"
}, },
"branchId": {
"type": "integer"
},
"cardNumber": { "cardNumber": {
"type": "string" "type": "string"
}, },
@@ -9050,20 +9107,6 @@
} }
} }
}, },
"online-back_internal_cards_shared.LocalizedText": {
"type": "object",
"properties": {
"en": {
"type": "string"
},
"ru": {
"type": "string"
},
"tm": {
"type": "string"
}
}
},
"paymentcard.CreatePaymentCardDTO": { "paymentcard.CreatePaymentCardDTO": {
"type": "object", "type": "object",
"required": [ "required": [
@@ -9081,7 +9124,7 @@
"type": "string" "type": "string"
}, },
"title": { "title": {
"$ref": "#/definitions/online-back_internal_cards_shared.LocalizedText" "$ref": "#/definitions/shared.LocalizedText"
} }
} }
}, },
@@ -9110,7 +9153,7 @@
"type": "string" "type": "string"
}, },
"title": { "title": {
"$ref": "#/definitions/online-back_internal_cards_shared.LocalizedText" "$ref": "#/definitions/shared.LocalizedText"
} }
} }
}, },
@@ -9119,6 +9162,7 @@
"required": [ "required": [
"code", "code",
"guardName", "guardName",
"module",
"name" "name"
], ],
"properties": { "properties": {
@@ -9126,6 +9170,14 @@
"type": "string" "type": "string"
}, },
"guardName": { "guardName": {
"type": "string",
"enum": [
"web",
"operator",
"admin"
]
},
"module": {
"type": "string" "type": "string"
}, },
"name": { "name": {
@@ -9138,6 +9190,7 @@
"required": [ "required": [
"code", "code",
"guardName", "guardName",
"module",
"name" "name"
], ],
"properties": { "properties": {
@@ -9145,6 +9198,14 @@
"type": "string" "type": "string"
}, },
"guardName": { "guardName": {
"type": "string",
"enum": [
"web",
"operator",
"admin"
]
},
"module": {
"type": "string" "type": "string"
}, },
"name": { "name": {
@@ -9257,7 +9318,7 @@
"type": "string" "type": "string"
}, },
"title": { "title": {
"$ref": "#/definitions/online-back_internal_cards_shared.LocalizedText" "$ref": "#/definitions/shared.LocalizedText"
} }
} }
}, },
@@ -9278,7 +9339,7 @@
"type": "string" "type": "string"
}, },
"title": { "title": {
"$ref": "#/definitions/online-back_internal_cards_shared.LocalizedText" "$ref": "#/definitions/shared.LocalizedText"
} }
} }
}, },
@@ -9294,7 +9355,12 @@
"type": "string" "type": "string"
}, },
"guardName": { "guardName": {
"type": "string" "type": "string",
"enum": [
"web",
"operator",
"admin"
]
}, },
"name": { "name": {
"type": "string" "type": "string"
@@ -9313,7 +9379,12 @@
"type": "string" "type": "string"
}, },
"guardName": { "guardName": {
"type": "string" "type": "string",
"enum": [
"web",
"operator",
"admin"
]
}, },
"name": { "name": {
"type": "string" "type": "string"
@@ -9335,6 +9406,20 @@
} }
} }
}, },
"shared.LocalizedText": {
"type": "object",
"properties": {
"en": {
"type": "string"
},
"ru": {
"type": "string"
},
"tm": {
"type": "string"
}
}
},
"user.CreateUserDTO": { "user.CreateUserDTO": {
"type": "object", "type": "object",
"required": [ "required": [

View File

@@ -196,6 +196,8 @@ definitions:
type: number type: number
balanceCurrency: balanceCurrency:
type: string type: string
branchId:
type: integer
cardNumber: cardNumber:
type: string type: string
checkedAt: checkedAt:
@@ -223,6 +225,8 @@ definitions:
type: number type: number
balanceCurrency: balanceCurrency:
type: string type: string
branchId:
type: integer
cardNumber: cardNumber:
type: string type: string
checkedAt: checkedAt:
@@ -1263,15 +1267,6 @@ definitions:
- tax - tax
- title - title
type: object type: object
online-back_internal_cards_shared.LocalizedText:
properties:
en:
type: string
ru:
type: string
tm:
type: string
type: object
paymentcard.CreatePaymentCardDTO: paymentcard.CreatePaymentCardDTO:
properties: properties:
active: active:
@@ -1281,7 +1276,7 @@ definitions:
price: price:
type: string type: string
title: title:
$ref: '#/definitions/online-back_internal_cards_shared.LocalizedText' $ref: '#/definitions/shared.LocalizedText'
required: required:
- price - price
- title - title
@@ -1300,7 +1295,7 @@ definitions:
price: price:
type: string type: string
title: title:
$ref: '#/definitions/online-back_internal_cards_shared.LocalizedText' $ref: '#/definitions/shared.LocalizedText'
required: required:
- price - price
- title - title
@@ -1310,12 +1305,19 @@ definitions:
code: code:
type: string type: string
guardName: guardName:
enum:
- web
- operator
- admin
type: string
module:
type: string type: string
name: name:
type: string type: string
required: required:
- code - code
- guardName - guardName
- module
- name - name
type: object type: object
permission.UpdatePermissionDTO: permission.UpdatePermissionDTO:
@@ -1323,12 +1325,19 @@ definitions:
code: code:
type: string type: string
guardName: guardName:
enum:
- web
- operator
- admin
type: string
module:
type: string type: string
name: name:
type: string type: string
required: required:
- code - code
- guardName - guardName
- module
- name - name
type: object type: object
permissionrole.CreatePermissionRoleDTO: permissionrole.CreatePermissionRoleDTO:
@@ -1399,7 +1408,7 @@ definitions:
price: price:
type: string type: string
title: title:
$ref: '#/definitions/online-back_internal_cards_shared.LocalizedText' $ref: '#/definitions/shared.LocalizedText'
required: required:
- price - price
- title - title
@@ -1413,7 +1422,7 @@ definitions:
price: price:
type: string type: string
title: title:
$ref: '#/definitions/online-back_internal_cards_shared.LocalizedText' $ref: '#/definitions/shared.LocalizedText'
required: required:
- price - price
- title - title
@@ -1423,6 +1432,10 @@ definitions:
code: code:
type: string type: string
guardName: guardName:
enum:
- web
- operator
- admin
type: string type: string
name: name:
type: string type: string
@@ -1436,6 +1449,10 @@ definitions:
code: code:
type: string type: string
guardName: guardName:
enum:
- web
- operator
- admin
type: string type: string
name: name:
type: string type: string
@@ -1454,6 +1471,15 @@ definitions:
- roleId - roleId
- userId - userId
type: object type: object
shared.LocalizedText:
properties:
en:
type: string
ru:
type: string
tm:
type: string
type: object
user.CreateUserDTO: user.CreateUserDTO:
properties: properties:
active: active:
@@ -4920,6 +4946,14 @@ paths:
in: query in: query
name: permission_name name: permission_name
type: string type: string
- description: Filter by guard (web, operator, admin)
in: query
name: guard_name
type: string
- description: Filter by saha (cards, loans, …)
in: query
name: module
type: string
- default: 1 - default: 1
description: Page number description: Page number
in: query in: query
@@ -5086,10 +5120,34 @@ paths:
summary: Update permission summary: Update permission
tags: tags:
- permission - permission
/permissions/tree:
get:
description: Returns permissions grouped as guard → module (saha) → permissions
parameters:
- description: Filter by guard (web, operator, admin)
in: query
name: guard_name
type: string
produces:
- application/json
responses:
"200":
description: OK
schema:
$ref: '#/definitions/appresult.AppSuccess'
"500":
description: Internal Server Error
schema:
$ref: '#/definitions/appresult.AppError'
security:
- BearerAuth: []
summary: Permission tree
tags:
- permission
/profile: /profile:
get: get:
description: Returns the authenticated user's profile with role, branches, and description: Returns the authenticated user's profile with role, branches, and
permissions permissions grouped by saha (module)
produces: produces:
- application/json - application/json
responses: responses:
@@ -5943,7 +6001,8 @@ paths:
tags: tags:
- user - user
get: get:
description: Returns a single user with assigned branches and roleId description: Returns a single user with assigned branches, roleId, and effective
permissions
parameters: parameters:
- description: User ID - description: User ID
in: path in: path

View File

@@ -6,6 +6,7 @@ import (
"strings" "strings"
"online-back/internal/backup" "online-back/internal/backup"
"online-back/internal/shared"
"online-back/pkg/client/postgresql" "online-back/pkg/client/postgresql"
"online-back/pkg/logging" "online-back/pkg/logging"
"online-back/pkg/repository/genericrepo" "online-back/pkg/repository/genericrepo"
@@ -32,21 +33,11 @@ var backupColumns = []string{
var backupColumnsSQL = strings.Join(backupColumns, ", ") var backupColumnsSQL = strings.Join(backupColumns, ", ")
const userDisplaySQL = `COALESCE(NULLIF(TRIM(CONCAT_WS(' ', u.first_name, u.last_name)), ''), NULLIF(u.name, ''), u.username, '')`
const backupFromClause = ` FROM backups b const backupFromClause = ` FROM backups b
LEFT JOIN users u ON u.id = b.created_by` LEFT JOIN users u ON u.id = b.created_by`
var backupSelectColumns = prefixed("b", backupColumns) + `, var backupSelectColumns = shared.PrefixedColumns("b", backupColumns) + `,
` + userDisplaySQL + `, COALESCE(u.username, ''), COALESCE(u.phone, ''), COALESCE(u.email, '')` ` + shared.UserDisplaySQL + `, COALESCE(u.username, ''), COALESCE(u.phone, ''), COALESCE(u.email, '')`
func prefixed(alias string, cols []string) string {
parts := make([]string, len(cols))
for i, col := range cols {
parts[i] = alias + "." + col
}
return strings.Join(parts, ", ")
}
func (r *repository) List(ctx context.Context, filter backup.ListFilter) (backup.ListBackupDTO, error) { func (r *repository) List(ctx context.Context, filter backup.ListFilter) (backup.ListBackupDTO, error) {
whereClause, args := buildListQuery(filter) whereClause, args := buildListQuery(filter)
@@ -89,7 +80,7 @@ func buildListQuery(filter backup.ListFilter) (whereClause string, args []interf
var conditions []string var conditions []string
if filter.Search != "" { if filter.Search != "" {
args = append(args, likePattern(filter.Search)) args = append(args, shared.LikePattern(filter.Search))
conditions = append(conditions, fmt.Sprintf(`b.file_name ILIKE $%d ESCAPE '\'`, len(args))) conditions = append(conditions, fmt.Sprintf(`b.file_name ILIKE $%d ESCAPE '\'`, len(args)))
} }
@@ -104,10 +95,6 @@ func buildListQuery(filter backup.ListFilter) (whereClause string, args []interf
return " WHERE " + strings.Join(conditions, " AND "), args return " WHERE " + strings.Join(conditions, " AND "), args
} }
func likePattern(term string) string {
return "%" + escapeLike(term) + "%"
}
func escapeLike(term string) string { func escapeLike(term string) string {
term = strings.ReplaceAll(term, `\`, `\\`) term = strings.ReplaceAll(term, `\`, `\\`)
term = strings.ReplaceAll(term, `%`, `\%`) term = strings.ReplaceAll(term, `%`, `\%`)

View File

@@ -7,6 +7,7 @@ import (
"online-back/internal/appresult" "online-back/internal/appresult"
"online-back/internal/handlers" "online-back/internal/handlers"
"online-back/internal/shared"
"online-back/pkg/logging" "online-back/pkg/logging"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
@@ -77,7 +78,7 @@ func (h *handler) list(c *gin.Context) {
// @Failure 500 {object} appresult.AppError // @Failure 500 {object} appresult.AppError
// @Router /backups/{id} [get] // @Router /backups/{id} [get]
func (h *handler) getByID(c *gin.Context) { func (h *handler) getByID(c *gin.Context) {
id, ok := parseID(c.Param("id")) id, ok := shared.ParseID(c.Param("id"))
if !ok { if !ok {
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam) c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
return return
@@ -130,7 +131,7 @@ func (h *handler) create(c *gin.Context) {
// @Failure 500 {object} appresult.AppError // @Failure 500 {object} appresult.AppError
// @Router /backups/{id}/download [get] // @Router /backups/{id}/download [get]
func (h *handler) download(c *gin.Context) { func (h *handler) download(c *gin.Context) {
id, ok := parseID(c.Param("id")) id, ok := shared.ParseID(c.Param("id"))
if !ok { if !ok {
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam) c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
return return
@@ -171,7 +172,7 @@ func (h *handler) download(c *gin.Context) {
// @Failure 500 {object} appresult.AppError // @Failure 500 {object} appresult.AppError
// @Router /backups/{id} [delete] // @Router /backups/{id} [delete]
func (h *handler) delete(c *gin.Context) { func (h *handler) delete(c *gin.Context) {
id, ok := parseID(c.Param("id")) id, ok := shared.ParseID(c.Param("id"))
if !ok { if !ok {
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam) c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
return return

View File

@@ -5,22 +5,10 @@ import (
"strings" "strings"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
)
const ( "online-back/internal/shared"
defaultPage = 1
defaultLimit = 10
maxLimit = 100
) )
func parseID(raw string) (int64, bool) {
id, err := strconv.ParseInt(raw, 10, 64)
if err != nil || id <= 0 {
return 0, false
}
return id, true
}
func queryValue(c *gin.Context, keys ...string) string { func queryValue(c *gin.Context, keys ...string) string {
for _, key := range keys { for _, key := range keys {
if raw := strings.TrimSpace(c.Query(key)); raw != "" && raw != "undefined" && raw != "null" { if raw := strings.TrimSpace(c.Query(key)); raw != "" && raw != "undefined" && raw != "null" {
@@ -31,8 +19,8 @@ func queryValue(c *gin.Context, keys ...string) string {
} }
func parsePageLimit(c *gin.Context) (page, limit int, ok bool) { func parsePageLimit(c *gin.Context) (page, limit int, ok bool) {
page = defaultPage page = shared.DefaultPage
limit = defaultLimit limit = shared.DefaultLimit
if raw := queryValue(c, "page"); raw != "" { if raw := queryValue(c, "page"); raw != "" {
p, err := strconv.Atoi(raw) p, err := strconv.Atoi(raw)
@@ -47,8 +35,8 @@ func parsePageLimit(c *gin.Context) (page, limit int, ok bool) {
if err != nil || l < 1 { if err != nil || l < 1 {
return 0, 0, false return 0, 0, false
} }
if l > maxLimit { if l > shared.MaxLimit {
l = maxLimit l = shared.MaxLimit
} }
limit = l limit = l
} }

View File

@@ -2,11 +2,13 @@ package db
import ( import (
"context" "context"
"database/sql"
"fmt" "fmt"
"strings" "strings"
"online-back/internal/cards/cardbalance" "online-back/internal/cards/cardbalance"
"online-back/internal/cards/shared" "online-back/internal/identity/rbac"
"online-back/internal/shared"
"online-back/pkg/client/postgresql" "online-back/pkg/client/postgresql"
"online-back/pkg/logging" "online-back/pkg/logging"
"online-back/pkg/repository/genericrepo" "online-back/pkg/repository/genericrepo"
@@ -30,23 +32,24 @@ func NewRepository(client postgresql.Client, logger *logging.Logger) cardbalance
var cardBalanceColumns = []string{ var cardBalanceColumns = []string{
"id", "passport_number", "card_last4", "expiry_month", "expiry_year", "expiry_at", "id", "passport_number", "card_last4", "expiry_month", "expiry_year", "expiry_at",
"balance_amount", "balance_currency", "status", "checked_at", "balance_amount", "balance_currency", "status", "checked_at",
"created_by", "created_at", "updated_at", "branch_id", "created_by", "created_at", "updated_at",
} }
var cardBalanceColumnsSQL = strings.Join(cardBalanceColumns, ", ") var cardBalanceColumnsSQL = strings.Join(cardBalanceColumns, ", ")
var cardBalanceWritableColumns = []string{ var cardBalanceWritableColumns = []string{
"passport_number", "card_number", "expiry_month", "expiry_year", "passport_number", "card_number", "expiry_month", "expiry_year",
"balance_amount", "balance_currency", "status", "checked_at", "created_by", "balance_amount", "balance_currency", "status", "checked_at", "branch_id", "created_by",
} }
var cardBalanceWritableColumnsSQL = strings.Join(cardBalanceWritableColumns, ", ") var cardBalanceWritableColumnsSQL = strings.Join(cardBalanceWritableColumns, ", ")
const cardBalanceFromClause = ` FROM card_balances cb const cardBalanceFromClause = ` FROM card_balances cb
LEFT JOIN users u ON u.id = cb.created_by` 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) + `, var cardBalanceSelectColumns = shared.PrefixedColumns("cb", cardBalanceColumns) + `,
COALESCE(u.username, ''), COALESCE(u.phone, ''), COALESCE(u.email, ''), ` + shared.UserDisplaySQL COALESCE(u.username, ''), COALESCE(u.phone, ''), COALESCE(u.email, ''), ` + shared.UserDisplaySQL + `, b.name`
func resolveStatus(status *string) string { func resolveStatus(status *string) string {
if status == nil || strings.TrimSpace(*status) == "" { if status == nil || strings.TrimSpace(*status) == "" {
@@ -66,7 +69,7 @@ func createArgs(dto cardbalance.CreateCardBalanceDTO) []interface{} {
return []interface{}{ return []interface{}{
dto.PassportNumber, dto.CardNumber, dto.ExpiryMonth, dto.ExpiryYear, dto.PassportNumber, dto.CardNumber, dto.ExpiryMonth, dto.ExpiryYear,
dto.BalanceAmount, resolveCurrency(dto.BalanceCurrency), resolveStatus(dto.Status), dto.BalanceAmount, resolveCurrency(dto.BalanceCurrency), resolveStatus(dto.Status),
shared.OptionalTime(dto.CheckedAt), shared.OptionalInt64(dto.CreatedBy), shared.OptionalTime(dto.CheckedAt), shared.OptionalInt64(dto.BranchId), shared.OptionalInt64(dto.CreatedBy),
} }
} }
@@ -74,7 +77,7 @@ func updateArgs(dto cardbalance.UpdateCardBalanceDTO) []interface{} {
return []interface{}{ return []interface{}{
dto.PassportNumber, dto.CardNumber, dto.ExpiryMonth, dto.ExpiryYear, dto.PassportNumber, dto.CardNumber, dto.ExpiryMonth, dto.ExpiryYear,
dto.BalanceAmount, resolveCurrency(dto.BalanceCurrency), resolveStatus(dto.Status), dto.BalanceAmount, resolveCurrency(dto.BalanceCurrency), resolveStatus(dto.Status),
shared.OptionalTime(dto.CheckedAt), shared.OptionalInt64(dto.CreatedBy), shared.OptionalTime(dto.CheckedAt), shared.OptionalInt64(dto.BranchId), shared.OptionalInt64(dto.CreatedBy),
} }
} }
@@ -133,6 +136,13 @@ func buildListQuery(filter cardbalance.ListFilter) (whereClause string, args []i
conditions = append(conditions, fmt.Sprintf("cb.created_by = $%d", len(args))) 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 return " WHERE " + strings.Join(conditions, " AND "), args
} }
@@ -156,7 +166,8 @@ func (r *repository) Create(ctx context.Context, dto cardbalance.CreateCardBalan
) )
SELECT %s SELECT %s
FROM inserted cb FROM inserted cb
LEFT JOIN users u ON u.id = cb.created_by`, LEFT JOIN users u ON u.id = cb.created_by
LEFT JOIN branches b ON b.id = cb.branch_id`,
cardBalanceWritableColumnsSQL, strings.Join(placeholders, ", "), cardBalanceWritableColumnsSQL, strings.Join(placeholders, ", "),
cardBalanceColumnsSQL, cardBalanceSelectColumns, cardBalanceColumnsSQL, cardBalanceSelectColumns,
) )
@@ -181,7 +192,8 @@ func (r *repository) Update(ctx context.Context, id int64, dto cardbalance.Updat
) )
SELECT %s SELECT %s
FROM updated cb FROM updated cb
LEFT JOIN users u ON u.id = cb.created_by`, 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, strings.Join(assignments, ", "), len(args), cardBalanceColumnsSQL, cardBalanceSelectColumns,
) )
@@ -201,19 +213,30 @@ func (r *repository) Delete(ctx context.Context, id int64) error {
func scanCardBalanceWithJoins(row genericrepo.Scanner) (cardbalance.CardBalanceDTO, error) { func scanCardBalanceWithJoins(row genericrepo.Scanner) (cardbalance.CardBalanceDTO, error) {
var item cardbalance.CardBalanceDTO var item cardbalance.CardBalanceDTO
var branchID sql.NullInt64
var branchNameJSON []byte
var userUsername, userPhone, userEmail, userName string var userUsername, userPhone, userEmail, userName string
dest := []interface{}{ dest := []interface{}{
&item.Id, &item.PassportNumber, &item.CardLast4, &item.ExpiryMonth, &item.ExpiryYear, &item.ExpiryAt, &item.Id, &item.PassportNumber, &item.CardLast4, &item.ExpiryMonth, &item.ExpiryYear, &item.ExpiryAt,
&item.BalanceAmount, &item.BalanceCurrency, &item.Status, &item.CheckedAt, &item.BalanceAmount, &item.BalanceCurrency, &item.Status, &item.CheckedAt,
&item.CreatedById, &item.CreatedAt, &item.UpdatedAt, &branchID, &item.CreatedById, &item.CreatedAt, &item.UpdatedAt,
&userUsername, &userPhone, &userEmail, &userName, &userUsername, &userPhone, &userEmail, &userName, &branchNameJSON,
} }
if err := row.Scan(dest...); err != nil { if err := row.Scan(dest...); err != nil {
return cardbalance.CardBalanceDTO{}, err 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 { if item.CreatedById != nil {
item.CreatedBy = &shared.UserInfo{ item.CreatedBy = &shared.UserInfo{
Id: *item.CreatedById, Id: *item.CreatedById,

View File

@@ -3,24 +3,26 @@ package cardbalance
import ( import (
"time" "time"
"online-back/internal/cards/shared" "online-back/internal/shared"
) )
type CardBalanceDTO struct { type CardBalanceDTO struct {
Id int64 `json:"id"` Id int64 `json:"id"`
PassportNumber string `json:"passportNumber"` PassportNumber string `json:"passportNumber"`
CardLast4 string `json:"cardLast4"` CardLast4 string `json:"cardLast4"`
ExpiryMonth int16 `json:"expiryMonth"` ExpiryMonth int16 `json:"expiryMonth"`
ExpiryYear int16 `json:"expiryYear"` ExpiryYear int16 `json:"expiryYear"`
ExpiryAt time.Time `json:"expiryAt"` ExpiryAt time.Time `json:"expiryAt"`
BalanceAmount *float64 `json:"balanceAmount"` BalanceAmount *float64 `json:"balanceAmount"`
BalanceCurrency string `json:"balanceCurrency"` BalanceCurrency string `json:"balanceCurrency"`
Status string `json:"status"` Status string `json:"status"`
CheckedAt *time.Time `json:"checkedAt"` CheckedAt *time.Time `json:"checkedAt"`
CreatedById *int64 `json:"-"` BranchId int64 `json:"-"`
CreatedBy *shared.UserInfo `json:"createdBy,omitempty"` Branch *shared.NamedInfo `json:"branch,omitempty"`
CreatedAt time.Time `json:"createdAt"` CreatedById *int64 `json:"-"`
UpdatedAt time.Time `json:"updatedAt"` CreatedBy *shared.UserInfo `json:"createdBy,omitempty"`
CreatedAt time.Time `json:"createdAt"`
UpdatedAt time.Time `json:"updatedAt"`
} }
type CreateCardBalanceDTO struct { type CreateCardBalanceDTO struct {
@@ -32,6 +34,7 @@ type CreateCardBalanceDTO struct {
BalanceCurrency *string `json:"balanceCurrency"` BalanceCurrency *string `json:"balanceCurrency"`
Status *string `json:"status"` Status *string `json:"status"`
CheckedAt *shared.FlexibleTime `json:"checkedAt" swaggertype:"string" format:"date-time"` CheckedAt *shared.FlexibleTime `json:"checkedAt" swaggertype:"string" format:"date-time"`
BranchId *shared.FlexibleInt64 `json:"branchId" swaggertype:"integer"`
CreatedBy *shared.FlexibleInt64 `json:"createdBy" swaggertype:"integer"` CreatedBy *shared.FlexibleInt64 `json:"createdBy" swaggertype:"integer"`
} }
@@ -44,6 +47,7 @@ type UpdateCardBalanceDTO struct {
BalanceCurrency *string `json:"balanceCurrency"` BalanceCurrency *string `json:"balanceCurrency"`
Status *string `json:"status"` Status *string `json:"status"`
CheckedAt *shared.FlexibleTime `json:"checkedAt" swaggertype:"string" format:"date-time"` CheckedAt *shared.FlexibleTime `json:"checkedAt" swaggertype:"string" format:"date-time"`
BranchId *shared.FlexibleInt64 `json:"branchId" swaggertype:"integer"`
CreatedBy *shared.FlexibleInt64 `json:"createdBy" swaggertype:"integer"` CreatedBy *shared.FlexibleInt64 `json:"createdBy" swaggertype:"integer"`
} }
@@ -51,6 +55,8 @@ type ListFilter struct {
Status *string Status *string
PassportNumber string PassportNumber string
CreatedBy *int64 CreatedBy *int64
BranchId *int64
BranchIds []int64
Page int Page int
Limit int Limit int
} }

View File

@@ -5,8 +5,9 @@ import (
"net/http" "net/http"
"online-back/internal/appresult" "online-back/internal/appresult"
"online-back/internal/cards/shared"
"online-back/internal/handlers" "online-back/internal/handlers"
"online-back/internal/identity/rbac"
"online-back/internal/shared"
"online-back/pkg/logging" "online-back/pkg/logging"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
@@ -94,6 +95,9 @@ func (h *handler) getByID(c *gin.Context) {
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer) c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return return
} }
if !rbac.GuardOrder(c, item.CreatedById, item.BranchId) {
return
}
c.JSON(http.StatusOK, appresult.SuccessWithData(item)) c.JSON(http.StatusOK, appresult.SuccessWithData(item))
} }
@@ -148,6 +152,10 @@ func (h *handler) update(c *gin.Context) {
return return
} }
if !h.guardCardBalanceByID(c, id) {
return
}
var dto UpdateCardBalanceDTO var dto UpdateCardBalanceDTO
if err := c.ShouldBindJSON(&dto); err != nil { if err := c.ShouldBindJSON(&dto); err != nil {
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam) c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
@@ -187,6 +195,10 @@ func (h *handler) delete(c *gin.Context) {
return return
} }
if !h.guardCardBalanceByID(c, id) {
return
}
if err := h.repository.Delete(c.Request.Context(), id); errors.Is(err, pgx.ErrNoRows) { if err := h.repository.Delete(c.Request.Context(), id); errors.Is(err, pgx.ErrNoRows) {
c.JSON(http.StatusNotFound, appresult.ErrNotFound) c.JSON(http.StatusNotFound, appresult.ErrNotFound)
return return
@@ -199,6 +211,22 @@ func (h *handler) delete(c *gin.Context) {
c.JSON(http.StatusOK, appresult.SuccessWithData("card balance removed")) 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) { func parseListFilter(c *gin.Context) (ListFilter, bool) {
page, limit, ok := shared.ParsePageLimit(c) page, limit, ok := shared.ParsePageLimit(c)
if !ok { if !ok {
@@ -220,5 +248,12 @@ func parseListFilter(c *gin.Context) (ListFilter, bool) {
filter.CreatedBy = id 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 return filter, true
} }

View File

@@ -6,8 +6,8 @@ import (
"strings" "strings"
"online-back/internal/cards/cardorder" "online-back/internal/cards/cardorder"
"online-back/internal/cards/shared"
"online-back/internal/identity/rbac" "online-back/internal/identity/rbac"
"online-back/internal/shared"
"online-back/pkg/client/postgresql" "online-back/pkg/client/postgresql"
"online-back/pkg/logging" "online-back/pkg/logging"
"online-back/pkg/repository/genericrepo" "online-back/pkg/repository/genericrepo"

View File

@@ -3,7 +3,7 @@ package cardorder
import ( import (
"time" "time"
"online-back/internal/cards/shared" "online-back/internal/shared"
) )
type CardOrderDTO struct { type CardOrderDTO struct {
@@ -46,67 +46,67 @@ type CardOrderDTO struct {
} }
type CreateCardOrderDTO struct { type CreateCardOrderDTO struct {
UniqueId *string `json:"uniqueId"` UniqueId *string `json:"uniqueId"`
CardStateId shared.FlexibleInt64 `json:"cardStateId" binding:"required" swaggertype:"integer"` CardStateId shared.FlexibleInt64 `json:"cardStateId" binding:"required" swaggertype:"integer"`
CardTypeId shared.FlexibleInt64 `json:"cardTypeId" binding:"required" swaggertype:"integer"` CardTypeId shared.FlexibleInt64 `json:"cardTypeId" binding:"required" swaggertype:"integer"`
Region string `json:"region" binding:"required"` Region string `json:"region" binding:"required"`
BranchId shared.FlexibleInt64 `json:"branchId" binding:"required" swaggertype:"integer"` BranchId shared.FlexibleInt64 `json:"branchId" binding:"required" swaggertype:"integer"`
CustomerName string `json:"customerName" binding:"required"` CustomerName string `json:"customerName" binding:"required"`
CustomerSurname string `json:"customerSurname" binding:"required"` CustomerSurname string `json:"customerSurname" binding:"required"`
CustomerPatronicName *string `json:"customerPatronicName"` CustomerPatronicName *string `json:"customerPatronicName"`
BornAt *shared.FlexibleTime `json:"bornAt" swaggertype:"string" format:"date"` BornAt *shared.FlexibleTime `json:"bornAt" swaggertype:"string" format:"date"`
OldSurname *string `json:"oldSurname"` OldSurname *string `json:"oldSurname"`
Citizenship string `json:"citizenship" binding:"required"` Citizenship string `json:"citizenship" binding:"required"`
PassportSerie string `json:"passportSerie" binding:"required"` PassportSerie string `json:"passportSerie" binding:"required"`
PassportId string `json:"passportId" binding:"required"` PassportId string `json:"passportId" binding:"required"`
PassportGivenAt shared.FlexibleTime `json:"passportGivenAt" swaggertype:"string" format:"date"` PassportGivenAt shared.FlexibleTime `json:"passportGivenAt" swaggertype:"string" format:"date"`
PassportGivenBy string `json:"passportGivenBy" binding:"required"` PassportGivenBy string `json:"passportGivenBy" binding:"required"`
BornPlace string `json:"bornPlace" binding:"required"` BornPlace string `json:"bornPlace" binding:"required"`
JobLocation *string `json:"jobLocation"` JobLocation *string `json:"jobLocation"`
PassportAddress *string `json:"passportAddress"` PassportAddress *string `json:"passportAddress"`
RealAddress *string `json:"realAddress"` RealAddress *string `json:"realAddress"`
Phone *string `json:"phone"` Phone *string `json:"phone"`
PhoneAdditional *string `json:"phoneAdditional"` PhoneAdditional *string `json:"phoneAdditional"`
Status *string `json:"status"` Status *string `json:"status"`
PassportOne string `json:"passportOne" binding:"required"` PassportOne string `json:"passportOne" binding:"required"`
PassportTwo string `json:"passportTwo" binding:"required"` PassportTwo string `json:"passportTwo" binding:"required"`
PassportThree string `json:"passportThree" binding:"required"` PassportThree string `json:"passportThree" binding:"required"`
PassportFour string `json:"passportFour" binding:"required"` PassportFour string `json:"passportFour" binding:"required"`
Notes *string `json:"notes"` Notes *string `json:"notes"`
UserId *shared.FlexibleInt64 `json:"userId" swaggertype:"integer"` UserId *shared.FlexibleInt64 `json:"userId" swaggertype:"integer"`
Paid *bool `json:"paid"` Paid *bool `json:"paid"`
} }
type UpdateCardOrderDTO struct { type UpdateCardOrderDTO struct {
UniqueId *string `json:"uniqueId"` UniqueId *string `json:"uniqueId"`
CardStateId shared.FlexibleInt64 `json:"cardStateId" binding:"required" swaggertype:"integer"` CardStateId shared.FlexibleInt64 `json:"cardStateId" binding:"required" swaggertype:"integer"`
CardTypeId shared.FlexibleInt64 `json:"cardTypeId" binding:"required" swaggertype:"integer"` CardTypeId shared.FlexibleInt64 `json:"cardTypeId" binding:"required" swaggertype:"integer"`
Region string `json:"region" binding:"required"` Region string `json:"region" binding:"required"`
BranchId shared.FlexibleInt64 `json:"branchId" binding:"required" swaggertype:"integer"` BranchId shared.FlexibleInt64 `json:"branchId" binding:"required" swaggertype:"integer"`
CustomerName string `json:"customerName" binding:"required"` CustomerName string `json:"customerName" binding:"required"`
CustomerSurname string `json:"customerSurname" binding:"required"` CustomerSurname string `json:"customerSurname" binding:"required"`
CustomerPatronicName *string `json:"customerPatronicName"` CustomerPatronicName *string `json:"customerPatronicName"`
BornAt *shared.FlexibleTime `json:"bornAt" swaggertype:"string" format:"date"` BornAt *shared.FlexibleTime `json:"bornAt" swaggertype:"string" format:"date"`
OldSurname *string `json:"oldSurname"` OldSurname *string `json:"oldSurname"`
Citizenship string `json:"citizenship" binding:"required"` Citizenship string `json:"citizenship" binding:"required"`
PassportSerie string `json:"passportSerie" binding:"required"` PassportSerie string `json:"passportSerie" binding:"required"`
PassportId string `json:"passportId" binding:"required"` PassportId string `json:"passportId" binding:"required"`
PassportGivenAt shared.FlexibleTime `json:"passportGivenAt" swaggertype:"string" format:"date"` PassportGivenAt shared.FlexibleTime `json:"passportGivenAt" swaggertype:"string" format:"date"`
PassportGivenBy string `json:"passportGivenBy" binding:"required"` PassportGivenBy string `json:"passportGivenBy" binding:"required"`
BornPlace string `json:"bornPlace" binding:"required"` BornPlace string `json:"bornPlace" binding:"required"`
JobLocation *string `json:"jobLocation"` JobLocation *string `json:"jobLocation"`
PassportAddress *string `json:"passportAddress"` PassportAddress *string `json:"passportAddress"`
RealAddress *string `json:"realAddress"` RealAddress *string `json:"realAddress"`
Phone *string `json:"phone"` Phone *string `json:"phone"`
PhoneAdditional *string `json:"phoneAdditional"` PhoneAdditional *string `json:"phoneAdditional"`
Status *string `json:"status"` Status *string `json:"status"`
PassportOne string `json:"passportOne" binding:"required"` PassportOne string `json:"passportOne" binding:"required"`
PassportTwo string `json:"passportTwo" binding:"required"` PassportTwo string `json:"passportTwo" binding:"required"`
PassportThree string `json:"passportThree" binding:"required"` PassportThree string `json:"passportThree" binding:"required"`
PassportFour string `json:"passportFour" binding:"required"` PassportFour string `json:"passportFour" binding:"required"`
Notes *string `json:"notes"` Notes *string `json:"notes"`
UserId *shared.FlexibleInt64 `json:"userId" swaggertype:"integer"` UserId *shared.FlexibleInt64 `json:"userId" swaggertype:"integer"`
Paid bool `json:"paid"` Paid bool `json:"paid"`
} }
type ListFilter struct { type ListFilter struct {

View File

@@ -5,9 +5,9 @@ import (
"net/http" "net/http"
"online-back/internal/appresult" "online-back/internal/appresult"
"online-back/internal/cards/shared"
"online-back/internal/handlers" "online-back/internal/handlers"
"online-back/internal/identity/rbac" "online-back/internal/identity/rbac"
"online-back/internal/shared"
"online-back/pkg/logging" "online-back/pkg/logging"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"

View File

@@ -6,8 +6,8 @@ import (
"strings" "strings"
"online-back/internal/cards/cardpinorders" "online-back/internal/cards/cardpinorders"
"online-back/internal/cards/shared"
"online-back/internal/identity/rbac" "online-back/internal/identity/rbac"
"online-back/internal/shared"
"online-back/pkg/client/postgresql" "online-back/pkg/client/postgresql"
"online-back/pkg/logging" "online-back/pkg/logging"
"online-back/pkg/repository/genericrepo" "online-back/pkg/repository/genericrepo"

View File

@@ -3,7 +3,7 @@ package cardpinorders
import ( import (
"time" "time"
"online-back/internal/cards/shared" "online-back/internal/shared"
) )
type CardPinOrderDTO struct { type CardPinOrderDTO struct {

View File

@@ -5,9 +5,9 @@ import (
"net/http" "net/http"
"online-back/internal/appresult" "online-back/internal/appresult"
"online-back/internal/cards/shared"
"online-back/internal/handlers" "online-back/internal/handlers"
"online-back/internal/identity/rbac" "online-back/internal/identity/rbac"
"online-back/internal/shared"
"online-back/pkg/logging" "online-back/pkg/logging"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"

View File

@@ -6,8 +6,8 @@ import (
"strings" "strings"
"online-back/internal/cards/cardrekwizit" "online-back/internal/cards/cardrekwizit"
"online-back/internal/cards/shared"
"online-back/internal/identity/rbac" "online-back/internal/identity/rbac"
"online-back/internal/shared"
"online-back/pkg/client/postgresql" "online-back/pkg/client/postgresql"
"online-back/pkg/logging" "online-back/pkg/logging"
"online-back/pkg/repository/genericrepo" "online-back/pkg/repository/genericrepo"

View File

@@ -3,7 +3,7 @@ package cardrekwizit
import ( import (
"time" "time"
"online-back/internal/cards/shared" "online-back/internal/shared"
) )
type CardRekwizitOrderDTO struct { type CardRekwizitOrderDTO struct {
@@ -96,6 +96,6 @@ type ListFilter struct {
} }
type ListCardRekwizitOrderDTO struct { type ListCardRekwizitOrderDTO struct {
Count int64 `json:"count"` Count int64 `json:"count"`
CardRekwizitOrders []CardRekwizitOrderDTO `json:"cardRekwizitOrders"` CardRekwizitOrders []CardRekwizitOrderDTO `json:"cardRekwizitOrders"`
} }

View File

@@ -5,9 +5,9 @@ import (
"net/http" "net/http"
"online-back/internal/appresult" "online-back/internal/appresult"
"online-back/internal/cards/shared"
"online-back/internal/handlers" "online-back/internal/handlers"
"online-back/internal/identity/rbac" "online-back/internal/identity/rbac"
"online-back/internal/shared"
"online-back/pkg/logging" "online-back/pkg/logging"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"

View File

@@ -7,8 +7,8 @@ import (
"strings" "strings"
"online-back/internal/cards/cards" "online-back/internal/cards/cards"
"online-back/internal/cards/shared"
"online-back/internal/identity/rbac" "online-back/internal/identity/rbac"
"online-back/internal/shared"
"online-back/pkg/client/postgresql" "online-back/pkg/client/postgresql"
"online-back/pkg/logging" "online-back/pkg/logging"
"online-back/pkg/repository/genericrepo" "online-back/pkg/repository/genericrepo"

View File

@@ -3,7 +3,7 @@ package cards
import ( import (
"time" "time"
"online-back/internal/cards/shared" "online-back/internal/shared"
) )
type CardDTO struct { type CardDTO struct {

View File

@@ -5,9 +5,9 @@ import (
"net/http" "net/http"
"online-back/internal/appresult" "online-back/internal/appresult"
"online-back/internal/cards/shared"
"online-back/internal/handlers" "online-back/internal/handlers"
"online-back/internal/identity/rbac" "online-back/internal/identity/rbac"
"online-back/internal/shared"
"online-back/pkg/logging" "online-back/pkg/logging"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"

View File

@@ -8,7 +8,7 @@ import (
"strings" "strings"
"online-back/internal/cards/paymentcard" "online-back/internal/cards/paymentcard"
"online-back/internal/cards/shared" "online-back/internal/shared"
"online-back/pkg/client/postgresql" "online-back/pkg/client/postgresql"
"online-back/pkg/logging" "online-back/pkg/logging"
"online-back/pkg/repository/genericrepo" "online-back/pkg/repository/genericrepo"
@@ -49,7 +49,7 @@ func buildListQuery(filter paymentcard.ListFilter) (whereClause string, args []i
var conditions []string var conditions []string
if filter.CardName != "" { if filter.CardName != "" {
args = append(args, likePattern(filter.CardName)) args = append(args, shared.LikePattern(filter.CardName))
n := len(args) n := len(args)
conditions = append(conditions, fmt.Sprintf(`( 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 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 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) { func (r *repository) GetByID(ctx context.Context, id int64) (paymentcard.PaymentCardDTO, error) {
return r.generic.GetByID(ctx, id) return r.generic.GetByID(ctx, id)
} }

View File

@@ -1,6 +1,6 @@
package paymentcard package paymentcard
import "online-back/internal/cards/shared" import "online-back/internal/shared"
type PaymentCardDTO struct { type PaymentCardDTO struct {
Id int64 `json:"id"` Id int64 `json:"id"`

View File

@@ -6,8 +6,8 @@ import (
"strconv" "strconv"
"online-back/internal/appresult" "online-back/internal/appresult"
"online-back/internal/cards/shared"
"online-back/internal/handlers" "online-back/internal/handlers"
"online-back/internal/shared"
"online-back/pkg/logging" "online-back/pkg/logging"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"

View File

@@ -8,7 +8,7 @@ import (
"strings" "strings"
"online-back/internal/cards/reasonscard" "online-back/internal/cards/reasonscard"
"online-back/internal/cards/shared" "online-back/internal/shared"
"online-back/pkg/client/postgresql" "online-back/pkg/client/postgresql"
"online-back/pkg/logging" "online-back/pkg/logging"
"online-back/pkg/repository/genericrepo" "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{}) { func buildListQuery(filter reasonscard.ListFilter) (whereClause string, args []interface{}) {
var conditions []string var conditions []string
if filter.ReasonName != "" { if filter.ReasonName != "" {
args = append(args, likePattern(filter.ReasonName)) args = append(args, shared.LikePattern(filter.ReasonName))
n := len(args) n := len(args)
conditions = append(conditions, fmt.Sprintf(`( 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 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 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) { func (r *repository) GetByID(ctx context.Context, id int64) (reasonscard.ReasonCardDTO, error) {
return r.generic.GetByID(ctx, id) return r.generic.GetByID(ctx, id)
} }

View File

@@ -3,7 +3,7 @@ package reasonscard
import ( import (
"time" "time"
"online-back/internal/cards/shared" "online-back/internal/shared"
) )
type ReasonCardDTO struct { type ReasonCardDTO struct {

View File

@@ -5,8 +5,8 @@ import (
"net/http" "net/http"
"online-back/internal/appresult" "online-back/internal/appresult"
"online-back/internal/cards/shared"
"online-back/internal/handlers" "online-back/internal/handlers"
"online-back/internal/shared"
"online-back/pkg/logging" "online-back/pkg/logging"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"

View File

@@ -6,9 +6,9 @@ import (
"fmt" "fmt"
"strings" "strings"
"online-back/internal/cards/shared"
"online-back/internal/cards/visamaster" "online-back/internal/cards/visamaster"
"online-back/internal/identity/rbac" "online-back/internal/identity/rbac"
"online-back/internal/shared"
"online-back/pkg/client/postgresql" "online-back/pkg/client/postgresql"
"online-back/pkg/logging" "online-back/pkg/logging"
"online-back/pkg/repository/genericrepo" "online-back/pkg/repository/genericrepo"
@@ -138,7 +138,7 @@ func buildListQuery(filter visamaster.ListFilter) (whereClause string, args []in
var conditions []string var conditions []string
if filter.Name != "" { if filter.Name != "" {
args = append(args, likePattern(filter.Name)) args = append(args, shared.LikePattern(filter.Name))
n := len(args) n := len(args)
conditions = append(conditions, fmt.Sprintf(`( conditions = append(conditions, fmt.Sprintf(`(
o.passport_name ILIKE $%[1]d OR o.passport_surname ILIKE $%[1]d o.passport_name ILIKE $%[1]d OR o.passport_surname ILIKE $%[1]d
@@ -175,13 +175,6 @@ func buildListQuery(filter visamaster.ListFilter) (whereClause string, args []in
return " WHERE " + strings.Join(conditions, " AND "), 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) { 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`
return scanOrder(r.client.QueryRow(ctx, query, id)) return scanOrder(r.client.QueryRow(ctx, query, id))

View File

@@ -4,7 +4,7 @@ import (
"encoding/json" "encoding/json"
"time" "time"
"online-back/internal/cards/shared" "online-back/internal/shared"
) )
type BranchInfo struct { type BranchInfo struct {

View File

@@ -5,9 +5,9 @@ import (
"net/http" "net/http"
"online-back/internal/appresult" "online-back/internal/appresult"
"online-back/internal/cards/shared"
"online-back/internal/handlers" "online-back/internal/handlers"
"online-back/internal/identity/rbac" "online-back/internal/identity/rbac"
"online-back/internal/shared"
"online-back/pkg/logging" "online-back/pkg/logging"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"

View File

@@ -7,6 +7,7 @@ import (
"strings" "strings"
"online-back/internal/currency" "online-back/internal/currency"
"online-back/internal/shared"
"online-back/pkg/client/postgresql" "online-back/pkg/client/postgresql"
"online-back/pkg/logging" "online-back/pkg/logging"
"online-back/pkg/repository/genericrepo" "online-back/pkg/repository/genericrepo"
@@ -41,18 +42,10 @@ const currencyFromClause = ` FROM currencies c
LEFT JOIN users cu ON cu.id = c.created_by LEFT JOIN users cu ON cu.id = c.created_by
LEFT JOIN users uu ON uu.id = c.updated_by` LEFT JOIN users uu ON uu.id = c.updated_by`
var currencySelectColumns = prefixed("c", currencyColumns) + `, 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, "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, '')` ` + fmt.Sprintf(userDisplaySQL, "uu", "uu", "uu", "uu") + `, COALESCE(uu.username, ''), COALESCE(uu.phone, ''), COALESCE(uu.email, '')`
func prefixed(alias string, cols []string) string {
parts := make([]string, len(cols))
for i, col := range cols {
parts[i] = alias + "." + col
}
return strings.Join(parts, ", ")
}
func (r *repository) List(ctx context.Context, filter currency.ListFilter) (currency.ListCurrencyDTO, error) { func (r *repository) List(ctx context.Context, filter currency.ListFilter) (currency.ListCurrencyDTO, error) {
whereClause, args := buildListQuery(filter) whereClause, args := buildListQuery(filter)
@@ -94,7 +87,7 @@ func buildListQuery(filter currency.ListFilter) (whereClause string, args []inte
var conditions []string var conditions []string
if filter.Search != "" { if filter.Search != "" {
args = append(args, likePattern(filter.Search)) args = append(args, shared.LikePattern(filter.Search))
n := len(args) n := len(args)
conditions = append(conditions, fmt.Sprintf(`( conditions = append(conditions, fmt.Sprintf(`(
c.currency_from ILIKE $%[1]d ESCAPE '\' OR c.currency_to ILIKE $%[1]d ESCAPE '\' c.currency_from ILIKE $%[1]d ESCAPE '\' OR c.currency_to ILIKE $%[1]d ESCAPE '\'
@@ -117,13 +110,6 @@ func buildListQuery(filter currency.ListFilter) (whereClause string, args []inte
return " WHERE " + strings.Join(conditions, " AND "), 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) (currency.CurrencyDTO, error) { func (r *repository) GetByID(ctx context.Context, id int64) (currency.CurrencyDTO, error) {
query := `SELECT ` + currencySelectColumns + currencyFromClause + ` WHERE c.id = $1` query := `SELECT ` + currencySelectColumns + currencyFromClause + ` WHERE c.id = $1`
return scanCurrencyWithUsers(r.client.QueryRow(ctx, query, id)) return scanCurrencyWithUsers(r.client.QueryRow(ctx, query, id))

View File

@@ -8,6 +8,7 @@ import (
"online-back/internal/appresult" "online-back/internal/appresult"
"online-back/internal/handlers" "online-back/internal/handlers"
"online-back/internal/shared"
"online-back/pkg/logging" "online-back/pkg/logging"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
@@ -79,7 +80,7 @@ func (h *handler) list(c *gin.Context) {
// @Failure 500 {object} appresult.AppError // @Failure 500 {object} appresult.AppError
// @Router /currencies/{id} [get] // @Router /currencies/{id} [get]
func (h *handler) getByID(c *gin.Context) { func (h *handler) getByID(c *gin.Context) {
id, ok := parseID(c.Param("id")) id, ok := shared.ParseID(c.Param("id"))
if !ok { if !ok {
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam) c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
return return
@@ -145,7 +146,7 @@ func (h *handler) create(c *gin.Context) {
// @Failure 500 {object} appresult.AppError // @Failure 500 {object} appresult.AppError
// @Router /currencies/{id} [put] // @Router /currencies/{id} [put]
func (h *handler) update(c *gin.Context) { func (h *handler) update(c *gin.Context) {
id, ok := parseID(c.Param("id")) id, ok := shared.ParseID(c.Param("id"))
if !ok { if !ok {
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam) c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
return return
@@ -186,7 +187,7 @@ func (h *handler) update(c *gin.Context) {
// @Failure 500 {object} appresult.AppError // @Failure 500 {object} appresult.AppError
// @Router /currencies/{id} [delete] // @Router /currencies/{id} [delete]
func (h *handler) delete(c *gin.Context) { func (h *handler) delete(c *gin.Context) {
id, ok := parseID(c.Param("id")) id, ok := shared.ParseID(c.Param("id"))
if !ok { if !ok {
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam) c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
return return
@@ -204,22 +205,8 @@ func (h *handler) delete(c *gin.Context) {
c.JSON(http.StatusOK, appresult.SuccessWithData("currency removed")) c.JSON(http.StatusOK, appresult.SuccessWithData("currency 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) { func parseListFilter(c *gin.Context) (ListFilter, bool) {
filter := ListFilter{Page: defaultPage, Limit: defaultLimit} filter := ListFilter{Page: shared.DefaultPage, Limit: shared.DefaultLimit}
if raw := queryValue(c, "page"); raw != "" { if raw := queryValue(c, "page"); raw != "" {
page, err := strconv.Atoi(raw) page, err := strconv.Atoi(raw)
@@ -234,8 +221,8 @@ func parseListFilter(c *gin.Context) (ListFilter, bool) {
if err != nil || limit < 1 { if err != nil || limit < 1 {
return ListFilter{}, false return ListFilter{}, false
} }
if limit > maxLimit { if limit > shared.MaxLimit {
limit = maxLimit limit = shared.MaxLimit
} }
filter.Limit = limit filter.Limit = limit
} }

View File

@@ -8,6 +8,7 @@ import (
"online-back/internal/appresult" "online-back/internal/appresult"
"online-back/internal/handlers" "online-back/internal/handlers"
"online-back/internal/shared"
"online-back/pkg/logging" "online-back/pkg/logging"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
@@ -78,7 +79,7 @@ func (h *handler) list(c *gin.Context) {
// @Failure 500 {object} appresult.AppError // @Failure 500 {object} appresult.AppError
// @Router /activity-logs/{id} [get] // @Router /activity-logs/{id} [get]
func (h *handler) getByID(c *gin.Context) { func (h *handler) getByID(c *gin.Context) {
id, ok := parseID(c.Param("id")) id, ok := shared.ParseID(c.Param("id"))
if !ok { if !ok {
// GET /activity-logs/card-orders → list that module instead of 400. // GET /activity-logs/card-orders → list that module instead of 400.
q := c.Request.URL.Query() q := c.Request.URL.Query()
@@ -104,24 +105,10 @@ func (h *handler) getByID(c *gin.Context) {
c.JSON(http.StatusOK, appresult.SuccessWithData(item)) 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) { func parseListFilter(c *gin.Context) (ListFilter, bool) {
filter := ListFilter{ filter := ListFilter{
Page: defaultPage, Page: shared.DefaultPage,
Limit: defaultLimit, Limit: shared.DefaultLimit,
} }
if id, ok := optionalQueryID(c, "user_id", "userId"); !ok { if id, ok := optionalQueryID(c, "user_id", "userId"); !ok {
@@ -146,8 +133,8 @@ func parseListFilter(c *gin.Context) (ListFilter, bool) {
if err != nil || limit < 1 { if err != nil || limit < 1 {
return ListFilter{}, false return ListFilter{}, false
} }
if limit > maxLimit { if limit > shared.MaxLimit {
limit = maxLimit limit = shared.MaxLimit
} }
filter.Limit = limit filter.Limit = limit
} }
@@ -169,7 +156,7 @@ func optionalQueryID(c *gin.Context, keys ...string) (*int64, bool) {
if raw == "" { if raw == "" {
return nil, true return nil, true
} }
id, ok := parseID(raw) id, ok := shared.ParseID(raw)
if !ok { if !ok {
return nil, false return nil, false
} }

View File

@@ -7,6 +7,7 @@ import (
"sync" "sync"
"testing" "testing"
"online-back/internal/shared"
"online-back/pkg/logging" "online-back/pkg/logging"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
@@ -61,7 +62,7 @@ func TestParseListFilterIgnoresUndefinedAndCapsLimit(t *testing.T) {
if filter.Module != "card-orders" { if filter.Module != "card-orders" {
t.Fatalf("module=%q", filter.Module) t.Fatalf("module=%q", filter.Module)
} }
if filter.Limit != maxLimit { if filter.Limit != shared.MaxLimit {
t.Fatalf("limit=%d", filter.Limit) t.Fatalf("limit=%d", filter.Limit)
} }
if filter.Page != 2 { if filter.Page != 2 {
@@ -90,7 +91,7 @@ func TestGetByIDListsModuleWhenPathIsNotNumeric(t *testing.T) {
if repo.listFilter.Module != "card-orders" { if repo.listFilter.Module != "card-orders" {
t.Fatalf("module=%q", repo.listFilter.Module) 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) t.Fatalf("limit=%d", repo.listFilter.Limit)
} }
} }

View File

@@ -11,6 +11,7 @@ import (
"online-back/internal/identity/auth" "online-back/internal/identity/auth"
"online-back/pkg/client/postgresql" "online-back/pkg/client/postgresql"
"online-back/pkg/logging" "online-back/pkg/logging"
"online-back/pkg/repository/genericrepo"
"github.com/jackc/pgconn" "github.com/jackc/pgconn"
"github.com/jackc/pgx/v4" "github.com/jackc/pgx/v4"
@@ -71,15 +72,29 @@ const profilePermissionsJSON = `COALESCE((
SELECT json_agg(jsonb_build_object( SELECT json_agg(jsonb_build_object(
'id', p.id, 'id', p.id,
'code', COALESCE(p.code, ''), 'code', COALESCE(p.code, ''),
'name', p.name 'name', p.name,
) ORDER BY p.id) 'guardName', p.guard_name,
FROM permission_role pr 'module', COALESCE(p.module, '')
JOIN permissions p ON p.id = pr.permission_id ) ORDER BY p.module, p.id)
WHERE pr.role_id = r.id FROM permissions p
WHERE NOT EXISTS (
SELECT 1 FROM permission_user pu
WHERE pu.user_id = u.id AND pu.permission_id = p.id AND pu.effect = 'deny'
)
AND (
EXISTS (
SELECT 1 FROM permission_user pu
WHERE pu.user_id = u.id AND pu.permission_id = p.id AND pu.effect = 'allow'
)
OR EXISTS (
SELECT 1 FROM permission_role pr
WHERE pr.role_id = r.id AND pr.permission_id = p.id
)
)
), '[]'::json)` ), '[]'::json)`
const profileQuery = `SELECT u.id, u.name, u.first_name, u.last_name, u.phone, u.avatar, u.created_at, 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.guard_name, ` + profileBranchesJSON + `, ` + profilePermissionsJSON + profileFromClause + ` WHERE u.id = $1`
func (r *repository) Login(ctx context.Context, dto auth.LoginDTO) (auth.UserCredentials, error) { func (r *repository) Login(ctx context.Context, dto auth.LoginDTO) (auth.UserCredentials, error) {
phone := strings.TrimSpace(dto.Phone) phone := strings.TrimSpace(dto.Phone)
@@ -127,14 +142,10 @@ func (r *repository) UpdateProfile(ctx context.Context, id int, dto auth.UpdateP
return r.GetProfile(ctx, id) return r.GetProfile(ctx, id)
} }
type scannable interface { func scanProfile(row genericrepo.Scanner) (auth.UserProfileDTO, error) {
Scan(dest ...interface{}) error
}
func scanProfile(row scannable) (auth.UserProfileDTO, error) {
var profile auth.UserProfileDTO var profile auth.UserProfileDTO
var roleID sql.NullInt64 var roleID sql.NullInt64
var roleCode, roleName sql.NullString var roleCode, roleName, roleGuard sql.NullString
var branchesJSON []byte var branchesJSON []byte
var permissionsJSON []byte var permissionsJSON []byte
@@ -149,6 +160,7 @@ func scanProfile(row scannable) (auth.UserProfileDTO, error) {
&roleID, &roleID,
&roleCode, &roleCode,
&roleName, &roleName,
&roleGuard,
&branchesJSON, &branchesJSON,
&permissionsJSON, &permissionsJSON,
) )
@@ -158,9 +170,10 @@ func scanProfile(row scannable) (auth.UserProfileDTO, error) {
if roleID.Valid { if roleID.Valid {
profile.Role = &auth.ProfileRoleDTO{ profile.Role = &auth.ProfileRoleDTO{
Id: roleID.Int64, Id: roleID.Int64,
Code: roleCode.String, Code: roleCode.String,
Name: roleName.String, Name: roleName.String,
GuardName: roleGuard.String,
} }
} }
@@ -177,6 +190,7 @@ func scanProfile(row scannable) (auth.UserProfileDTO, error) {
return auth.UserProfileDTO{}, err return auth.UserProfileDTO{}, err
} }
} }
profile.Modules = auth.GroupProfileModules(profile.Permissions)
return profile, nil return profile, nil
} }

View File

@@ -19,9 +19,10 @@ type LocalizedText struct {
} }
type ProfileRoleDTO struct { type ProfileRoleDTO struct {
Id int64 `json:"id"` Id int64 `json:"id"`
Code string `json:"code"` Code string `json:"code"`
Name string `json:"name"` Name string `json:"name"`
GuardName string `json:"guardName"`
} }
type ProfileBranchDTO struct { type ProfileBranchDTO struct {
@@ -31,9 +32,16 @@ type ProfileBranchDTO struct {
} }
type ProfilePermissionDTO struct { type ProfilePermissionDTO struct {
Id int64 `json:"id"` Id int64 `json:"id"`
Code string `json:"code"` Code string `json:"code"`
Name string `json:"name"` Name string `json:"name"`
GuardName string `json:"guardName"`
Module string `json:"module"`
}
type ProfileModuleDTO struct {
Module string `json:"module"`
Permissions []ProfilePermissionDTO `json:"permissions"`
} }
type UserProfileDTO struct { type UserProfileDTO struct {
@@ -45,6 +53,7 @@ type UserProfileDTO struct {
Avatar string `json:"avatar"` Avatar string `json:"avatar"`
Role *ProfileRoleDTO `json:"role"` Role *ProfileRoleDTO `json:"role"`
Branches []ProfileBranchDTO `json:"branches"` Branches []ProfileBranchDTO `json:"branches"`
Modules []ProfileModuleDTO `json:"modules"`
Permissions []ProfilePermissionDTO `json:"permissions"` Permissions []ProfilePermissionDTO `json:"permissions"`
CreatedAt time.Time `json:"createdAt"` CreatedAt time.Time `json:"createdAt"`
} }

View File

@@ -242,7 +242,7 @@ func (h *handler) refreshToken(c *gin.Context) {
// getProfile godoc // getProfile godoc
// @Summary Get profile // @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 // @Tags auth
// @Produce json // @Produce json
// @Security BearerAuth // @Security BearerAuth

View File

@@ -0,0 +1,37 @@
package auth
import (
"sort"
"online-back/internal/identity/permission"
)
func GroupProfileModules(perms []ProfilePermissionDTO) []ProfileModuleDTO {
buckets := make(map[string][]ProfilePermissionDTO)
seen := make(map[string]struct{})
for _, p := range perms {
module := p.Module
buckets[module] = append(buckets[module], p)
seen[module] = struct{}{}
}
modules := make([]ProfileModuleDTO, 0, len(seen))
for _, name := range permission.ModuleOrder() {
ps, ok := buckets[name]
if !ok {
continue
}
modules = append(modules, ProfileModuleDTO{Module: name, Permissions: ps})
delete(seen, name)
}
var extra []string
for name := range seen {
extra = append(extra, name)
}
sort.Strings(extra)
for _, name := range extra {
modules = append(modules, ProfileModuleDTO{Module: name, Permissions: buckets[name]})
}
return modules
}

View File

@@ -7,6 +7,7 @@ import (
"strings" "strings"
"online-back/internal/identity/permission" "online-back/internal/identity/permission"
"online-back/internal/shared"
"online-back/pkg/client/postgresql" "online-back/pkg/client/postgresql"
"online-back/pkg/logging" "online-back/pkg/logging"
"online-back/pkg/repository/genericrepo" "online-back/pkg/repository/genericrepo"
@@ -28,9 +29,9 @@ func NewRepository(client postgresql.Client, logger *logging.Logger) permission.
} }
} }
const permissionColumns = `p.id, p.code, p.name, p.guard_name, p.created_at, p.updated_at` const permissionColumns = `p.id, p.code, p.name, p.guard_name, p.module, p.created_at, p.updated_at`
const permissionReturningColumns = `id, code, name, guard_name, created_at, updated_at` const permissionReturningColumns = `id, code, name, guard_name, module, created_at, updated_at`
func (r *repository) List(ctx context.Context, filter permission.ListFilter) (permission.ListPermissionDTO, error) { func (r *repository) List(ctx context.Context, filter permission.ListFilter) (permission.ListPermissionDTO, error) {
whereClause, args := buildListQuery(filter) whereClause, args := buildListQuery(filter)
@@ -46,10 +47,18 @@ func (r *repository) List(ctx context.Context, filter permission.ListFilter) (pe
func buildListQuery(filter permission.ListFilter) (whereClause string, args []interface{}) { func buildListQuery(filter permission.ListFilter) (whereClause string, args []interface{}) {
var conditions []string var conditions []string
if filter.PermissionName != "" { if filter.PermissionName != "" {
args = append(args, likePattern(filter.PermissionName)) args = append(args, shared.LikePattern(filter.PermissionName))
n := len(args) n := len(args)
conditions = append(conditions, fmt.Sprintf(`p.name ILIKE $%d`, n)) conditions = append(conditions, fmt.Sprintf(`p.name ILIKE $%d`, n))
} }
if filter.GuardName != "" {
args = append(args, filter.GuardName)
conditions = append(conditions, fmt.Sprintf(`p.guard_name = $%d`, len(args)))
}
if filter.Module != "" {
args = append(args, filter.Module)
conditions = append(conditions, fmt.Sprintf(`p.module = $%d`, len(args)))
}
if len(conditions) == 0 { if len(conditions) == 0 {
return "", args return "", args
@@ -58,35 +67,57 @@ func buildListQuery(filter permission.ListFilter) (whereClause string, args []in
return " WHERE " + strings.Join(conditions, " AND "), 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) { func (r *repository) GetByID(ctx context.Context, id int64) (permission.PermissionDTO, error) {
return r.generic.GetByID(ctx, id) return r.generic.GetByID(ctx, id)
} }
func (r *repository) Tree(ctx context.Context, guardName string) (permission.PermissionTreeDTO, error) {
query := `SELECT ` + permissionColumns + ` FROM permissions p`
var args []interface{}
if guardName != "" {
query += ` WHERE p.guard_name = $1`
args = append(args, guardName)
}
query += ` ORDER BY p.guard_name, p.module, p.id`
rows, err := r.client.Query(ctx, query, args...)
if err != nil {
return permission.PermissionTreeDTO{}, err
}
defer rows.Close()
var items []permission.PermissionDTO
for rows.Next() {
item, err := scanPermission(rows)
if err != nil {
return permission.PermissionTreeDTO{}, err
}
items = append(items, item)
}
if err := rows.Err(); err != nil {
return permission.PermissionTreeDTO{}, err
}
return permission.BuildTree(items), nil
}
func (r *repository) Create(ctx context.Context, dto permission.CreatePermissionDTO) (permission.PermissionDTO, error) { func (r *repository) Create(ctx context.Context, dto permission.CreatePermissionDTO) (permission.PermissionDTO, error) {
query := fmt.Sprintf(` query := fmt.Sprintf(`
INSERT INTO permissions (code, name, guard_name) INSERT INTO permissions (code, name, guard_name, module)
VALUES ($1, $2, $3) VALUES ($1, $2, $3, $4)
RETURNING %s`, permissionReturningColumns) RETURNING %s`, permissionReturningColumns)
return scanPermission(r.client.QueryRow(ctx, query, dto.Code, dto.Name, dto.GuardName)) return scanPermission(r.client.QueryRow(ctx, query, dto.Code, dto.Name, dto.GuardName, dto.Module))
} }
func (r *repository) Update(ctx context.Context, id int64, dto permission.UpdatePermissionDTO) (permission.PermissionDTO, error) { func (r *repository) Update(ctx context.Context, id int64, dto permission.UpdatePermissionDTO) (permission.PermissionDTO, error) {
query := fmt.Sprintf(` query := fmt.Sprintf(`
UPDATE permissions SET UPDATE permissions SET
code = $1, name = $2, guard_name = $3, code = $1, name = $2, guard_name = $3, module = $4,
updated_at = (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') updated_at = (CURRENT_TIMESTAMP AT TIME ZONE 'UTC')
WHERE id = $4 WHERE id = $5
RETURNING %s`, permissionReturningColumns) RETURNING %s`, permissionReturningColumns)
item, err := scanPermission(r.client.QueryRow(ctx, query, dto.Code, dto.Name, dto.GuardName, id)) item, err := scanPermission(r.client.QueryRow(ctx, query, dto.Code, dto.Name, dto.GuardName, dto.Module, id))
if errors.Is(err, pgx.ErrNoRows) { if errors.Is(err, pgx.ErrNoRows) {
return permission.PermissionDTO{}, err return permission.PermissionDTO{}, err
} }
@@ -100,7 +131,7 @@ func (r *repository) Delete(ctx context.Context, id int64) error {
func scanPermission(row genericrepo.Scanner) (permission.PermissionDTO, error) { func scanPermission(row genericrepo.Scanner) (permission.PermissionDTO, error) {
var item permission.PermissionDTO var item permission.PermissionDTO
if err := row.Scan( if err := row.Scan(
&item.Id, &item.Code, &item.Name, &item.GuardName, &item.CreatedAt, &item.UpdatedAt, &item.Id, &item.Code, &item.Name, &item.GuardName, &item.Module, &item.CreatedAt, &item.UpdatedAt,
); err != nil { ); err != nil {
return permission.PermissionDTO{}, err return permission.PermissionDTO{}, err
} }

View File

@@ -7,24 +7,29 @@ type PermissionDTO struct {
Code string `json:"code"` Code string `json:"code"`
Name string `json:"name"` Name string `json:"name"`
GuardName string `json:"guardName"` GuardName string `json:"guardName"`
Module string `json:"module"`
CreatedAt time.Time `json:"createdAt"` CreatedAt time.Time `json:"createdAt"`
UpdatedAt time.Time `json:"updatedAt"` UpdatedAt time.Time `json:"updatedAt"`
} }
type CreatePermissionDTO struct { type CreatePermissionDTO struct {
Code string `json:"code" binding:"required"` Code string `json:"code" binding:"required"`
Name string `json:"name" binding:"required"` Name string `json:"name" binding:"required"`
GuardName string `json:"guardName" binding:"required"` GuardName string `json:"guardName" binding:"required,oneof=web operator admin"`
Module string `json:"module" binding:"required"`
} }
type UpdatePermissionDTO struct { type UpdatePermissionDTO struct {
Code string `json:"code" binding:"required"` Code string `json:"code" binding:"required"`
Name string `json:"name" binding:"required"` Name string `json:"name" binding:"required"`
GuardName string `json:"guardName" binding:"required"` GuardName string `json:"guardName" binding:"required,oneof=web operator admin"`
Module string `json:"module" binding:"required"`
} }
type ListFilter struct { type ListFilter struct {
PermissionName string PermissionName string
GuardName string
Module string
Page int Page int
Limit int Limit int
} }
@@ -33,3 +38,17 @@ type ListPermissionDTO struct {
Count int64 `json:"count"` Count int64 `json:"count"`
Permissions []PermissionDTO `json:"permissions"` Permissions []PermissionDTO `json:"permissions"`
} }
type PermissionTreeDTO struct {
Guards []GuardModulesDTO `json:"guards"`
}
type GuardModulesDTO struct {
GuardName string `json:"guardName"`
Modules []ModulePermissionsDTO `json:"modules"`
}
type ModulePermissionsDTO struct {
Module string `json:"module"`
Permissions []PermissionDTO `json:"permissions"`
}

View File

@@ -8,6 +8,7 @@ import (
"online-back/internal/appresult" "online-back/internal/appresult"
"online-back/internal/handlers" "online-back/internal/handlers"
"online-back/internal/shared"
"online-back/pkg/logging" "online-back/pkg/logging"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
@@ -28,6 +29,7 @@ func NewHandler(logger *logging.Logger, repository Repository) handlers.Handler
func (h *handler) Register(router *gin.RouterGroup) { func (h *handler) Register(router *gin.RouterGroup) {
group := router.Group(baseURL, appresult.JwtTokenCheck()) group := router.Group(baseURL, appresult.JwtTokenCheck())
group.GET("", h.list) group.GET("", h.list)
group.GET("/tree", h.tree)
group.GET("/:id", h.getByID) group.GET("/:id", h.getByID)
group.POST("", h.create) group.POST("", h.create)
group.PUT("/:id", h.update) group.PUT("/:id", h.update)
@@ -41,6 +43,8 @@ func (h *handler) Register(router *gin.RouterGroup) {
// @Produce json // @Produce json
// @Security BearerAuth // @Security BearerAuth
// @Param permission_name query string false "Filter by name" // @Param permission_name query string false "Filter by name"
// @Param guard_name query string false "Filter by guard (web, operator, admin)"
// @Param module query string false "Filter by saha (cards, loans, …)"
// @Param page query int false "Page number" default(1) // @Param page query int false "Page number" default(1)
// @Param limit query int false "Items per page" default(10) // @Param limit query int false "Items per page" default(10)
// @Success 200 {object} appresult.AppSuccess // @Success 200 {object} appresult.AppSuccess
@@ -64,6 +68,32 @@ func (h *handler) list(c *gin.Context) {
c.JSON(http.StatusOK, appresult.SuccessWithData(result)) c.JSON(http.StatusOK, appresult.SuccessWithData(result))
} }
// tree godoc
// @Summary Permission tree
// @Description Returns permissions grouped as guard → module (saha) → permissions
// @Tags permission
// @Produce json
// @Security BearerAuth
// @Param guard_name query string false "Filter by guard (web, operator, admin)"
// @Success 200 {object} appresult.AppSuccess
// @Failure 500 {object} appresult.AppError
// @Router /permissions/tree [get]
func (h *handler) tree(c *gin.Context) {
guardName := strings.TrimSpace(c.Query("guard_name"))
if guardName == "" {
guardName = strings.TrimSpace(c.Query("guardName"))
}
result, err := h.repository.Tree(c.Request.Context(), guardName)
if err != nil {
h.logger.Errorf("permission tree failed: %v", err)
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return
}
c.JSON(http.StatusOK, appresult.SuccessWithData(result))
}
// getByID godoc // getByID godoc
// @Summary Get permission by ID // @Summary Get permission by ID
// @Description Returns a single permission // @Description Returns a single permission
@@ -77,7 +107,7 @@ func (h *handler) list(c *gin.Context) {
// @Failure 500 {object} appresult.AppError // @Failure 500 {object} appresult.AppError
// @Router /permissions/{id} [get] // @Router /permissions/{id} [get]
func (h *handler) getByID(c *gin.Context) { func (h *handler) getByID(c *gin.Context) {
id, ok := parseID(c.Param("id")) id, ok := shared.ParseID(c.Param("id"))
if !ok { if !ok {
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam) c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
return return
@@ -115,6 +145,10 @@ func (h *handler) create(c *gin.Context) {
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam) c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
return return
} }
if !IsKnownModule(dto.Module) {
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
return
}
item, err := h.repository.Create(c.Request.Context(), dto) item, err := h.repository.Create(c.Request.Context(), dto)
if err != nil { if err != nil {
@@ -141,7 +175,7 @@ func (h *handler) create(c *gin.Context) {
// @Failure 500 {object} appresult.AppError // @Failure 500 {object} appresult.AppError
// @Router /permissions/{id} [put] // @Router /permissions/{id} [put]
func (h *handler) update(c *gin.Context) { func (h *handler) update(c *gin.Context) {
id, ok := parseID(c.Param("id")) id, ok := shared.ParseID(c.Param("id"))
if !ok { if !ok {
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam) c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
return return
@@ -152,6 +186,10 @@ func (h *handler) update(c *gin.Context) {
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam) c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
return return
} }
if !IsKnownModule(dto.Module) {
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
return
}
item, err := h.repository.Update(c.Request.Context(), id, dto) item, err := h.repository.Update(c.Request.Context(), id, dto)
if errors.Is(err, pgx.ErrNoRows) { if errors.Is(err, pgx.ErrNoRows) {
@@ -180,7 +218,7 @@ func (h *handler) update(c *gin.Context) {
// @Failure 500 {object} appresult.AppError // @Failure 500 {object} appresult.AppError
// @Router /permissions/{id} [delete] // @Router /permissions/{id} [delete]
func (h *handler) delete(c *gin.Context) { func (h *handler) delete(c *gin.Context) {
id, ok := parseID(c.Param("id")) id, ok := shared.ParseID(c.Param("id"))
if !ok { if !ok {
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam) c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
return return
@@ -198,24 +236,10 @@ func (h *handler) delete(c *gin.Context) {
c.JSON(http.StatusOK, appresult.SuccessWithData("permission removed")) 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) { func parseListFilter(c *gin.Context) (ListFilter, bool) {
filter := ListFilter{ filter := ListFilter{
Page: defaultPage, Page: shared.DefaultPage,
Limit: defaultLimit, Limit: shared.DefaultLimit,
} }
if raw := c.Query("page"); raw != "" { if raw := c.Query("page"); raw != "" {
@@ -228,7 +252,7 @@ func parseListFilter(c *gin.Context) (ListFilter, bool) {
if raw := c.Query("limit"); raw != "" { if raw := c.Query("limit"); raw != "" {
limit, err := strconv.Atoi(raw) limit, err := strconv.Atoi(raw)
if err != nil || limit < 1 || limit > maxLimit { if err != nil || limit < 1 || limit > shared.MaxLimit {
return ListFilter{}, false return ListFilter{}, false
} }
filter.Limit = limit filter.Limit = limit
@@ -237,6 +261,24 @@ func parseListFilter(c *gin.Context) (ListFilter, bool) {
if raw := strings.TrimSpace(c.Query("permission_name")); raw != "" { if raw := strings.TrimSpace(c.Query("permission_name")); raw != "" {
filter.PermissionName = raw filter.PermissionName = raw
} }
if raw := firstQuery(c, "guard_name", "guardName"); raw != "" {
filter.GuardName = raw
}
if raw := firstQuery(c, "module"); raw != "" {
filter.Module = raw
}
return filter, true return filter, true
} }
func firstQuery(c *gin.Context, keys ...string) string {
for _, key := range keys {
if key == "" {
continue
}
if raw := strings.TrimSpace(c.Query(key)); raw != "" {
return raw
}
}
return ""
}

View File

@@ -0,0 +1,54 @@
package permission
const (
ModuleDashboard = "dashboard"
ModuleCards = "cards"
ModuleLoans = "loans"
ModuleUsers = "users"
ModuleRoles = "roles"
ModuleBranches = "branches"
ModuleProvinces = "provinces"
ModuleActivityLogs = "activity-logs"
ModuleBackups = "backups"
ModuleCurrencies = "currencies"
)
var moduleOrder = []string{
ModuleDashboard,
ModuleCards,
ModuleLoans,
ModuleUsers,
ModuleRoles,
ModuleBranches,
ModuleProvinces,
ModuleActivityLogs,
ModuleBackups,
ModuleCurrencies,
}
var guardOrder = []string{"operator", "admin", "web"}
var knownModules = map[string]struct{}{
ModuleDashboard: {},
ModuleCards: {},
ModuleLoans: {},
ModuleUsers: {},
ModuleRoles: {},
ModuleBranches: {},
ModuleProvinces: {},
ModuleActivityLogs: {},
ModuleBackups: {},
ModuleCurrencies: {},
}
func IsKnownModule(module string) bool {
_, ok := knownModules[module]
return ok
}
// ModuleOrder is the display order of sahalar in trees and profile.
func ModuleOrder() []string {
out := make([]string, len(moduleOrder))
copy(out, moduleOrder)
return out
}

View File

@@ -4,6 +4,7 @@ import "context"
type Repository interface { type Repository interface {
List(ctx context.Context, filter ListFilter) (ListPermissionDTO, error) List(ctx context.Context, filter ListFilter) (ListPermissionDTO, error)
Tree(ctx context.Context, guardName string) (PermissionTreeDTO, error)
GetByID(ctx context.Context, id int64) (PermissionDTO, error) GetByID(ctx context.Context, id int64) (PermissionDTO, error)
Create(ctx context.Context, dto CreatePermissionDTO) (PermissionDTO, error) Create(ctx context.Context, dto CreatePermissionDTO) (PermissionDTO, error)
Update(ctx context.Context, id int64, dto UpdatePermissionDTO) (PermissionDTO, error) Update(ctx context.Context, id int64, dto UpdatePermissionDTO) (PermissionDTO, error)

View File

@@ -0,0 +1,67 @@
package permission
import "sort"
type treeKey struct {
guard string
module string
}
// BuildTree groups a flat permission list into guard → module → permissions
// so the admin UI can render sahalar (cards, loans, …) as a tree.
func BuildTree(items []PermissionDTO) PermissionTreeDTO {
buckets := make(map[treeKey][]PermissionDTO)
guardsSeen := make(map[string]struct{})
modulesByGuard := make(map[string]map[string]struct{})
for _, item := range items {
key := treeKey{guard: item.GuardName, module: item.Module}
buckets[key] = append(buckets[key], item)
guardsSeen[item.GuardName] = struct{}{}
if modulesByGuard[item.GuardName] == nil {
modulesByGuard[item.GuardName] = make(map[string]struct{})
}
modulesByGuard[item.GuardName][item.Module] = struct{}{}
}
guards := make([]GuardModulesDTO, 0, len(guardsSeen))
for _, guard := range orderedKeys(guardOrder, guardsSeen) {
modulesSeen := modulesByGuard[guard]
modules := make([]ModulePermissionsDTO, 0, len(modulesSeen))
for _, module := range orderedKeys(moduleOrder, modulesSeen) {
perms := buckets[treeKey{guard: guard, module: module}]
if perms == nil {
perms = []PermissionDTO{}
}
modules = append(modules, ModulePermissionsDTO{
Module: module,
Permissions: perms,
})
}
guards = append(guards, GuardModulesDTO{
GuardName: guard,
Modules: modules,
})
}
return PermissionTreeDTO{Guards: guards}
}
func orderedKeys(order []string, seen map[string]struct{}) []string {
keys := make([]string, 0, len(seen))
used := make(map[string]struct{}, len(seen))
for _, name := range order {
if _, ok := seen[name]; ok {
keys = append(keys, name)
used[name] = struct{}{}
}
}
var extra []string
for name := range seen {
if _, ok := used[name]; !ok {
extra = append(extra, name)
}
}
sort.Strings(extra)
return append(keys, extra...)
}

View File

@@ -7,6 +7,7 @@ import (
"online-back/internal/identity/permissionrole" "online-back/internal/identity/permissionrole"
"online-back/pkg/client/postgresql" "online-back/pkg/client/postgresql"
"online-back/pkg/logging" "online-back/pkg/logging"
"online-back/pkg/repository/genericrepo"
"github.com/jackc/pgx/v4" "github.com/jackc/pgx/v4"
) )
@@ -39,21 +40,10 @@ func (r *repository) Create(ctx context.Context, dto permissionrole.CreatePermis
} }
func (r *repository) Delete(ctx context.Context, id int64) error { func (r *repository) Delete(ctx context.Context, id int64) error {
tag, err := r.client.Exec(ctx, `DELETE FROM permission_role WHERE id = $1`, id) return genericrepo.Delete(ctx, r.client, "permission_role", id)
if err != nil {
return err
}
if tag.RowsAffected() == 0 {
return pgx.ErrNoRows
}
return nil
} }
type scannable interface { func scanPermissionRole(row genericrepo.Scanner) (permissionrole.PermissionRoleDTO, error) {
Scan(dest ...interface{}) error
}
func scanPermissionRole(row scannable) (permissionrole.PermissionRoleDTO, error) {
var item permissionrole.PermissionRoleDTO var item permissionrole.PermissionRoleDTO
err := row.Scan( err := row.Scan(

View File

@@ -1,16 +1,12 @@
package permissionrole package permissionrole
import ( import (
"errors"
"net/http"
"strconv"
"online-back/internal/appresult" "online-back/internal/appresult"
"online-back/internal/handlers" "online-back/internal/handlers"
"online-back/internal/shared"
"online-back/pkg/logging" "online-back/pkg/logging"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
"github.com/jackc/pgx/v4"
) )
const baseURL = "/permission-roles" const baseURL = "/permission-roles"
@@ -43,20 +39,7 @@ func (h *handler) Register(router *gin.RouterGroup) {
// @Failure 500 {object} appresult.AppError // @Failure 500 {object} appresult.AppError
// @Router /permission-roles [post] // @Router /permission-roles [post]
func (h *handler) create(c *gin.Context) { func (h *handler) create(c *gin.Context) {
var dto CreatePermissionRoleDTO shared.CreateAssoc[CreatePermissionRoleDTO, PermissionRoleDTO](c, h.logger, h.repository, "permission role")
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 // delete godoc
@@ -72,28 +55,5 @@ func (h *handler) create(c *gin.Context) {
// @Failure 500 {object} appresult.AppError // @Failure 500 {object} appresult.AppError
// @Router /permission-roles/{id} [delete] // @Router /permission-roles/{id} [delete]
func (h *handler) delete(c *gin.Context) { func (h *handler) delete(c *gin.Context) {
id, ok := parseID(c.Param("id")) shared.DeleteAssoc[CreatePermissionRoleDTO, PermissionRoleDTO](c, h.logger, h.repository, "permission role")
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
} }

View File

@@ -7,6 +7,7 @@ import (
"online-back/internal/identity/permissionuser" "online-back/internal/identity/permissionuser"
"online-back/pkg/client/postgresql" "online-back/pkg/client/postgresql"
"online-back/pkg/logging" "online-back/pkg/logging"
"online-back/pkg/repository/genericrepo"
"github.com/jackc/pgx/v4" "github.com/jackc/pgx/v4"
) )
@@ -40,21 +41,10 @@ func (r *repository) Create(ctx context.Context, dto permissionuser.CreatePermis
} }
func (r *repository) Delete(ctx context.Context, id int64) error { func (r *repository) Delete(ctx context.Context, id int64) error {
tag, err := r.client.Exec(ctx, `DELETE FROM permission_user WHERE id = $1`, id) return genericrepo.Delete(ctx, r.client, "permission_user", id)
if err != nil {
return err
}
if tag.RowsAffected() == 0 {
return pgx.ErrNoRows
}
return nil
} }
type scannable interface { func scanPermissionUser(row genericrepo.Scanner) (permissionuser.PermissionUserDTO, error) {
Scan(dest ...interface{}) error
}
func scanPermissionUser(row scannable) (permissionuser.PermissionUserDTO, error) {
var item permissionuser.PermissionUserDTO var item permissionuser.PermissionUserDTO
err := row.Scan( err := row.Scan(

View File

@@ -1,16 +1,12 @@
package permissionuser package permissionuser
import ( import (
"errors"
"net/http"
"strconv"
"online-back/internal/appresult" "online-back/internal/appresult"
"online-back/internal/handlers" "online-back/internal/handlers"
"online-back/internal/shared"
"online-back/pkg/logging" "online-back/pkg/logging"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
"github.com/jackc/pgx/v4"
) )
const baseURL = "/permission-users" const baseURL = "/permission-users"
@@ -43,20 +39,7 @@ func (h *handler) Register(router *gin.RouterGroup) {
// @Failure 500 {object} appresult.AppError // @Failure 500 {object} appresult.AppError
// @Router /permission-users [post] // @Router /permission-users [post]
func (h *handler) create(c *gin.Context) { func (h *handler) create(c *gin.Context) {
var dto CreatePermissionUserDTO shared.CreateAssoc[CreatePermissionUserDTO, PermissionUserDTO](c, h.logger, h.repository, "permission user")
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 user failed: %v", err)
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return
}
c.JSON(http.StatusCreated, appresult.SuccessWithData(item))
} }
// delete godoc // delete godoc
@@ -72,28 +55,5 @@ func (h *handler) create(c *gin.Context) {
// @Failure 500 {object} appresult.AppError // @Failure 500 {object} appresult.AppError
// @Router /permission-users/{id} [delete] // @Router /permission-users/{id} [delete]
func (h *handler) delete(c *gin.Context) { func (h *handler) delete(c *gin.Context) {
id, ok := parseID(c.Param("id")) shared.DeleteAssoc[CreatePermissionUserDTO, PermissionUserDTO](c, h.logger, h.repository, "permission user")
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 user failed: %v", err)
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return
}
c.JSON(http.StatusOK, appresult.SuccessWithData("permission user 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
} }

View File

@@ -10,9 +10,11 @@ import (
"online-back/internal/appresult" "online-back/internal/appresult"
"online-back/internal/config" "online-back/internal/config"
"online-back/pkg/logging"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
"github.com/golang-jwt/jwt" "github.com/golang-jwt/jwt"
"github.com/sirupsen/logrus"
) )
const ( const (
@@ -109,15 +111,27 @@ func enforceOperator(c *gin.Context, service Authorizer, userID int64) {
c.Set(contextBranchIDs, ids) c.Set(contextBranchIDs, ids)
if !operatorRoleAllows(c.Request.Method, c.Request.URL.Path) { if !operatorRoleAllows(c.Request.Method, c.Request.URL.Path) {
c.AbortWithStatusJSON(http.StatusForbidden, appresult.ErrForbidden) abortForbidden(c, "route not in operator allow-list", logrus.Fields{"userId": userID})
return return
} }
if !operatorProfileOrFile(c.Request.URL.Path) && len(ids) == 0 { if !operatorProfileOrFile(c.Request.URL.Path) && !operatorClientsList(c.Request.URL.Path) && len(ids) == 0 {
c.AbortWithStatusJSON(http.StatusForbidden, appresult.ErrForbidden) abortForbidden(c, "operator has no assigned branches", logrus.Fields{"userId": userID})
return return
} }
if perm := operatorPathPermission(c.Request.Method, c.Request.URL.Path); perm != "" {
granted, err := service.HasPermission(c.Request.Context(), userID, perm)
if err != nil {
c.AbortWithStatusJSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return
}
if !granted {
abortForbidden(c, "missing permission for operator path", logrus.Fields{"userId": userID, "permission": perm})
return
}
}
if !operatorWriteAllowed(c, service, ids) { if !operatorWriteAllowed(c, service, ids) {
return return
} }
@@ -125,6 +139,31 @@ func enforceOperator(c *gin.Context, service Authorizer, userID int64) {
c.Next() c.Next()
} }
// abortForbidden logs why a request was denied (method, path, and any extra
// fields the caller passes) before writing the 403, since appresult.ErrForbidden
// alone gives the client and the logs no way to tell which rbac check failed.
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)
}
entry.Warn("rbac forbidden: " + reason)
c.AbortWithStatusJSON(http.StatusForbidden, appresult.ErrForbidden)
}
// EffectiveGuard resolves the guard a role with the given code/guard_name
// would run requests under - the same resolution Guard() applies to the
// caller on every request. Exposed so callers that grant a role (e.g. the
// user handler) can ask "would this reach guardAdmin?" against the role's
// real guard_name instead of matching against a hardcoded list of role
// names, which drifts the moment a new role is added.
func EffectiveGuard(code, guardName string) string {
return effectiveGuard(code, guardName)
}
func effectiveGuard(code, guardName string) string { func effectiveGuard(code, guardName string) string {
code = strings.ToLower(strings.TrimSpace(code)) code = strings.ToLower(strings.TrimSpace(code))
guard := strings.ToLower(strings.TrimSpace(guardName)) guard := strings.ToLower(strings.TrimSpace(guardName))
@@ -132,7 +171,7 @@ func effectiveGuard(code, guardName string) string {
switch code { switch code {
case "admin", "superadmin", "manager": case "admin", "superadmin", "manager":
return guardAdmin return guardAdmin
case roleOperator: case roleOperator, "operatot":
return guardOperator return guardOperator
} }
@@ -220,6 +259,8 @@ func enforceOwnWrites(c *gin.Context, userID int64) bool {
} }
payload["userId"] = userID payload["userId"] = userID
payload["user_id"] = userID payload["user_id"] = userID
payload["createdBy"] = userID
payload["created_by"] = userID
rewritten, err := json.Marshal(payload) rewritten, err := json.Marshal(payload)
if err != nil { if err != nil {
return true return true
@@ -251,6 +292,7 @@ func scopeOwnedLists(c *gin.Context, userID int64) {
query := c.Request.URL.Query() query := c.Request.URL.Query()
query.Set("user_id", strconv.FormatInt(userID, 10)) query.Set("user_id", strconv.FormatInt(userID, 10))
query.Set("created_by", strconv.FormatInt(userID, 10))
c.Request.URL.RawQuery = query.Encode() c.Request.URL.RawQuery = query.Encode()
} }
@@ -319,6 +361,9 @@ var userCatalogPrefixes = []string{
"/loan-types", "/loan-types",
"/loans-documents", "/loans-documents",
"/currencies", "/currencies",
"/branches",
"/provinces",
"/users/clients",
} }
var userSelfPrefixes = []string{ var userSelfPrefixes = []string{
@@ -328,6 +373,7 @@ var userSelfPrefixes = []string{
var userOwnedPrefixes = []string{ var userOwnedPrefixes = []string{
"/cards", "/cards",
"/card-balances",
"/card-orders", "/card-orders",
"/card-pin-orders", "/card-pin-orders",
"/card-rekwizit-orders", "/card-rekwizit-orders",
@@ -362,6 +408,11 @@ func operatorProfileOrFile(path string) bool {
return rest == "/profile" || rest == "/file" || strings.HasPrefix(rest, "/file/") return rest == "/profile" || rest == "/file" || strings.HasPrefix(rest, "/file/")
} }
func operatorClientsList(path string) bool {
rest := adminREST(path)
return rest == "/users/clients" || strings.HasPrefix(rest, "/users/clients/")
}
func operatorWriteAllowed(c *gin.Context, service Authorizer, branchIDs []int64) bool { func operatorWriteAllowed(c *gin.Context, service Authorizer, branchIDs []int64) bool {
switch c.Request.Method { switch c.Request.Method {
case http.MethodPost, http.MethodPut, http.MethodPatch: case http.MethodPost, http.MethodPut, http.MethodPatch:
@@ -391,9 +442,21 @@ func operatorWriteAllowed(c *gin.Context, service Authorizer, branchIDs []int64)
} }
if payload.BranchId != nil && *payload.BranchId > 0 && !containsInt64(branchIDs, *payload.BranchId) { if payload.BranchId != nil && *payload.BranchId > 0 && !containsInt64(branchIDs, *payload.BranchId) {
c.AbortWithStatusJSON(http.StatusForbidden, appresult.ErrForbidden) abortForbidden(c, "payload branchId not in operator's assigned branches", logrus.Fields{
"requestedBranchId": *payload.BranchId,
"allowedBranchIds": branchIDs,
})
return false return false
} }
// A new order's customer has no prior record in the branch to be
// "visible" through yet — the branchId check above already scopes the
// create to the operator's own branch, so only enforce user visibility
// when reassigning an existing record (PUT/PATCH).
if c.Request.Method == http.MethodPost {
return true
}
if payload.UserId != nil && *payload.UserId > 0 { if payload.UserId != nil && *payload.UserId > 0 {
visible, err := service.UserVisibleInBranches(c.Request.Context(), *payload.UserId, branchIDs) visible, err := service.UserVisibleInBranches(c.Request.Context(), *payload.UserId, branchIDs)
if err != nil { if err != nil {
@@ -401,7 +464,10 @@ func operatorWriteAllowed(c *gin.Context, service Authorizer, branchIDs []int64)
return false return false
} }
if !visible { if !visible {
c.AbortWithStatusJSON(http.StatusForbidden, appresult.ErrForbidden) abortForbidden(c, "payload userId not visible in operator's branches", logrus.Fields{
"requestedUserId": *payload.UserId,
"allowedBranchIds": branchIDs,
})
return false return false
} }
} }
@@ -419,19 +485,65 @@ func adminREST(path string) string {
return rest return rest
} }
// operatorPathPermission returns "cards" or "loans" for saha endpoints.
// Empty string: shared catalog (profile, file, dashboard, branches, provinces,
// users/clients, currencies read) — any operator may call it.
func operatorPathPermission(method, path string) string {
rest := adminREST(path)
switch {
case matchesPrefix(rest, []string{
"/cards",
"/card-balances",
"/card-orders",
"/card-pin-orders",
"/card-rekwizit-orders",
"/visa-master-payment-orders",
"/payment-cards",
"/reasons-cards",
}):
return "cards"
case matchesPrefix(rest, []string{
"/loan-orders",
"/loans-repayment",
"/loan-paid-off-letters",
"/loan-types",
"/loans-documents",
}):
return "loans"
case matchesPrefix(rest, []string{"/users/clients"}):
return ""
case matchesPrefix(rest, []string{"/users", "/branch-users"}):
if method == http.MethodGet {
return "users.view"
}
return "users.manage"
}
return ""
}
var operatorWritePrefixes = []string{ var operatorWritePrefixes = []string{
"/profile", "/profile",
"/file", "/file",
"/users", "/users",
"/branch-users", "/branch-users",
"/cards", "/cards",
"/card-balances",
"/card-orders", "/card-orders",
"/card-pin-orders", "/card-pin-orders",
"/card-rekwizit-orders", "/card-rekwizit-orders",
"/visa-master-payment-orders", "/visa-master-payment-orders",
"/payment-cards",
"/reasons-cards",
"/loan-orders", "/loan-orders",
"/loans-repayment", "/loans-repayment",
"/loan-paid-off-letters", "/loan-paid-off-letters",
"/loan-types",
"/loans-documents",
} }
var operatorGetPrefixes = []string{ var operatorGetPrefixes = []string{
@@ -440,6 +552,7 @@ var operatorGetPrefixes = []string{
"/dashboard", "/dashboard",
"/users", "/users",
"/cards", "/cards",
"/card-balances",
"/card-orders", "/card-orders",
"/card-pin-orders", "/card-pin-orders",
"/card-rekwizit-orders", "/card-rekwizit-orders",

View File

@@ -35,14 +35,22 @@ func TestUserRoleAllows(t *testing.T) {
{http.MethodPost, "/api/admin/card-orders", true}, {http.MethodPost, "/api/admin/card-orders", true},
{http.MethodPut, "/api/admin/loan-orders/2", true}, {http.MethodPut, "/api/admin/loan-orders/2", true},
{http.MethodDelete, "/api/admin/loan-orders/2", true}, {http.MethodDelete, "/api/admin/loan-orders/2", true},
{http.MethodGet, "/api/admin/card-balances", false}, {http.MethodGet, "/api/admin/card-balances", true},
{http.MethodPost, "/api/admin/card-balances", true},
{http.MethodPut, "/api/admin/card-balances/9", true},
{http.MethodDelete, "/api/admin/card-balances/9", true},
{http.MethodGet, "/api/admin/profile", true}, {http.MethodGet, "/api/admin/profile", true},
{http.MethodPut, "/api/admin/profile", true}, {http.MethodPut, "/api/admin/profile", true},
{http.MethodPost, "/api/admin/file", true}, {http.MethodPost, "/api/admin/file", true},
{http.MethodDelete, "/api/admin/profile", false}, {http.MethodDelete, "/api/admin/profile", false},
{http.MethodGet, "/api/admin/users", false}, {http.MethodGet, "/api/admin/users", false},
{http.MethodGet, "/api/admin/activity-logs", false}, {http.MethodGet, "/api/admin/activity-logs", false},
{http.MethodGet, "/api/admin/provinces", false}, {http.MethodGet, "/api/admin/provinces", true},
{http.MethodPost, "/api/admin/provinces", false},
{http.MethodGet, "/api/admin/branches", true},
{http.MethodPost, "/api/admin/branches", false},
{http.MethodGet, "/api/admin/users/clients", true},
{http.MethodPost, "/api/admin/users", false},
{http.MethodGet, "/api/admin/loan-types", true}, {http.MethodGet, "/api/admin/loan-types", true},
{http.MethodPost, "/api/admin/loan-types", false}, {http.MethodPost, "/api/admin/loan-types", false},
{http.MethodPost, "/api/admin/loan-orders", true}, {http.MethodPost, "/api/admin/loan-orders", true},
@@ -75,11 +83,13 @@ func TestOperatorRoleAllows(t *testing.T) {
{http.MethodDelete, "/api/admin/card-orders/2", true}, {http.MethodDelete, "/api/admin/card-orders/2", true},
{http.MethodGet, "/api/admin/dashboard", true}, {http.MethodGet, "/api/admin/dashboard", true},
{http.MethodGet, "/api/admin/users", true}, {http.MethodGet, "/api/admin/users", true},
{http.MethodGet, "/api/admin/users/clients", true},
{http.MethodPost, "/api/admin/users", true}, {http.MethodPost, "/api/admin/users", true},
{http.MethodGet, "/api/admin/activity-logs", false}, {http.MethodGet, "/api/admin/activity-logs", false},
{http.MethodGet, "/api/admin/provinces", true}, {http.MethodGet, "/api/admin/provinces", true},
{http.MethodPost, "/api/admin/provinces", false}, {http.MethodPost, "/api/admin/provinces", false},
{http.MethodGet, "/api/admin/card-balances", false}, {http.MethodGet, "/api/admin/card-balances", true},
{http.MethodPost, "/api/admin/card-balances", true},
} }
for _, tt := range tests { for _, tt := range tests {
if got := operatorRoleAllows(tt.method, tt.path); got != tt.want { if got := operatorRoleAllows(tt.method, tt.path); got != tt.want {
@@ -88,12 +98,124 @@ func TestOperatorRoleAllows(t *testing.T) {
} }
} }
func TestUserPrefixDoesNotBleedIntoOtherModules(t *testing.T) { func TestOperatorClientsListNeedsNoPermission(t *testing.T) {
if userRoleAllows(http.MethodGet, "/api/admin/card-balances") { if got := operatorPathPermission(http.MethodGet, "/api/admin/users/clients"); got != "" {
t.Fatal("/cards must not grant /card-balances") t.Fatalf("clients GET perm=%q, want none", got)
} }
if operatorRoleAllows(http.MethodGet, "/api/admin/card-balances") { if got := operatorPathPermission(http.MethodGet, "/api/admin/users"); got != "users.view" {
t.Fatal("operator /cards must not grant /card-balances") t.Fatalf("users GET perm=%q, want users.view", got)
}
auth := &stubAuth{role: roleOperator, branches: []int64{1}, perms: map[string]bool{}}
if status := serveGuard(auth, http.MethodGet, "/api/admin/users/clients", "7", nil); status != http.StatusOK {
t.Fatalf("clients status=%d", status)
}
if status := serveGuard(auth, http.MethodGet, "/api/admin/users", "7", nil); status != http.StatusForbidden {
t.Fatalf("users list status=%d", status)
}
noBranch := &stubAuth{role: roleOperator, perms: map[string]bool{}}
if status := serveGuard(noBranch, http.MethodGet, "/api/admin/users/clients", "7", nil); status != http.StatusOK {
t.Fatalf("no-branch clients status=%d", status)
}
}
func TestOperatorCardsAndLoansSahalar(t *testing.T) {
cardsOnly := &stubAuth{role: roleOperator, branches: []int64{1}, perms: map[string]bool{"cards": true}}
loansOnly := &stubAuth{role: roleOperator, branches: []int64{1}, perms: map[string]bool{"loans": true}}
both := &stubAuth{role: roleOperator, branches: []int64{1}, perms: map[string]bool{"cards": true, "loans": true}}
if status := serveGuard(cardsOnly, http.MethodGet, "/api/admin/card-orders", "7", nil); status != http.StatusOK {
t.Fatalf("cards GET orders=%d", status)
}
if status := serveGuard(cardsOnly, http.MethodPost, "/api/admin/card-pin-orders", "7", nil); status != http.StatusOK {
t.Fatalf("cards POST pin=%d", status)
}
if status := serveGuard(cardsOnly, http.MethodGet, "/api/admin/visa-master-payment-orders", "7", nil); status != http.StatusOK {
t.Fatalf("cards GET visa=%d", status)
}
if status := serveGuard(cardsOnly, http.MethodGet, "/api/admin/loan-orders", "7", nil); status != http.StatusForbidden {
t.Fatalf("cards GET loans=%d", status)
}
if status := serveGuard(loansOnly, http.MethodGet, "/api/admin/loan-orders", "7", nil); status != http.StatusOK {
t.Fatalf("loans GET orders=%d", status)
}
if status := serveGuard(loansOnly, http.MethodPut, "/api/admin/loan-paid-off-letters/1", "7", nil); status != http.StatusOK {
t.Fatalf("loans PUT letter=%d", status)
}
if status := serveGuard(loansOnly, http.MethodGet, "/api/admin/card-orders", "7", nil); status != http.StatusForbidden {
t.Fatalf("loans GET cards=%d", status)
}
if status := serveGuard(both, http.MethodGet, "/api/admin/card-orders", "7", nil); status != http.StatusOK {
t.Fatalf("both GET cards=%d", status)
}
if status := serveGuard(both, http.MethodGet, "/api/admin/loan-orders", "7", nil); status != http.StatusOK {
t.Fatalf("both GET loans=%d", status)
}
if status := serveGuard(cardsOnly, http.MethodGet, "/api/admin/card-balances", "7", nil); status != http.StatusOK {
t.Fatalf("cards GET balances=%d", status)
}
if status := serveGuard(loansOnly, http.MethodGet, "/api/admin/card-balances", "7", nil); status != http.StatusForbidden {
t.Fatalf("loans GET balances=%d", status)
}
if got := operatorPathPermission(http.MethodGet, "/api/admin/card-balances"); got != "cards" {
t.Fatalf("card-balances path=%q", got)
}
if got := operatorPathPermission(http.MethodPost, "/api/admin/card-orders"); got != "cards" {
t.Fatalf("card-orders path=%q", got)
}
}
func TestAllCardAndLoanRoutesMapped(t *testing.T) {
cardPaths := []string{
"/api/admin/cards",
"/api/admin/card-balances",
"/api/admin/card-orders",
"/api/admin/card-pin-orders",
"/api/admin/card-rekwizit-orders",
"/api/admin/visa-master-payment-orders",
"/api/admin/payment-cards",
"/api/admin/reasons-cards",
}
loanPaths := []string{
"/api/admin/loan-orders",
"/api/admin/loans-repayment",
"/api/admin/loan-paid-off-letters",
"/api/admin/loan-types",
"/api/admin/loans-documents",
}
for _, path := range cardPaths {
if got := operatorPathPermission(http.MethodGet, path); got != "cards" {
t.Errorf("GET %s perm=%q, want cards", path, got)
}
if got := operatorPathPermission(http.MethodPost, path); got != "cards" {
t.Errorf("POST %s perm=%q, want cards", path, got)
}
if !operatorRoleAllows(http.MethodGet, path) || !operatorRoleAllows(http.MethodPost, path) {
t.Errorf("%s not on operator allowlist", path)
}
}
for _, path := range loanPaths {
if got := operatorPathPermission(http.MethodGet, path); got != "loans" {
t.Errorf("GET %s perm=%q, want loans", path, got)
}
if got := operatorPathPermission(http.MethodPost, path); got != "loans" {
t.Errorf("POST %s perm=%q, want loans", path, got)
}
if !operatorRoleAllows(http.MethodGet, path) || !operatorRoleAllows(http.MethodPost, path) {
t.Errorf("%s not on operator allowlist", path)
}
}
}
func TestUserPrefixDoesNotBleedIntoOtherModules(t *testing.T) {
if matchesPrefix("/card-balances", []string{"/cards"}) {
t.Fatal("/cards prefix must not match /card-balances")
}
if !matchesPrefix("/card-balances", userOwnedPrefixes) {
t.Fatal("/card-balances must be granted via its own entry in userOwnedPrefixes")
} }
} }
@@ -139,6 +261,7 @@ func TestScopeOwnedListsInjectsUserID(t *testing.T) {
"/api/admin/loan-orders", "/api/admin/loan-orders",
"/api/admin/loans-repayment", "/api/admin/loans-repayment",
"/api/admin/loan-paid-off-letters", "/api/admin/loan-paid-off-letters",
"/api/admin/card-balances",
} }
for _, path := range paths { for _, path := range paths {
w := httptest.NewRecorder() w := httptest.NewRecorder()
@@ -151,6 +274,21 @@ func TestScopeOwnedListsInjectsUserID(t *testing.T) {
} }
} }
func TestScopeOwnedListsInjectsCreatedByForCardBalances(t *testing.T) {
gin.SetMode(gin.TestMode)
w := httptest.NewRecorder()
c, _ := gin.CreateTestContext(w)
c.Request = httptest.NewRequest(http.MethodGet, "/api/admin/card-balances?status=pending", nil)
scopeOwnedLists(c, 42)
if got := c.Request.URL.Query().Get("created_by"); got != "42" {
t.Fatalf("card-balances created_by=%q, want 42", got)
}
if got := c.Request.URL.Query().Get("status"); got != "pending" {
t.Fatalf("existing query params must be preserved, status=%q", got)
}
}
func TestScopeOwnedListsSkipsReferenceData(t *testing.T) { func TestScopeOwnedListsSkipsReferenceData(t *testing.T) {
gin.SetMode(gin.TestMode) gin.SetMode(gin.TestMode)
w := httptest.NewRecorder() w := httptest.NewRecorder()
@@ -182,10 +320,17 @@ func TestGuardMatrix(t *testing.T) {
{"user PUT card-orders", roleUser, nil, http.MethodPut, "/api/admin/card-orders/3", http.StatusOK}, {"user PUT card-orders", roleUser, nil, http.MethodPut, "/api/admin/card-orders/3", http.StatusOK},
{"user DELETE loan-orders", roleUser, nil, http.MethodDelete, "/api/admin/loan-orders/3", http.StatusOK}, {"user DELETE loan-orders", roleUser, nil, http.MethodDelete, "/api/admin/loan-orders/3", http.StatusOK},
{"user PATCH cards", roleUser, nil, http.MethodPatch, "/api/admin/cards/3", http.StatusOK}, {"user PATCH cards", roleUser, nil, http.MethodPatch, "/api/admin/cards/3", http.StatusOK},
{"user GET card-balances", roleUser, nil, http.MethodGet, "/api/admin/card-balances", http.StatusOK},
{"user POST card-balances", roleUser, nil, http.MethodPost, "/api/admin/card-balances", http.StatusOK},
{"user DELETE card-balances", roleUser, nil, http.MethodDelete, "/api/admin/card-balances/3", http.StatusOK},
{"user POST loans-repayment", roleUser, nil, http.MethodPost, "/api/admin/loans-repayment", http.StatusOK}, {"user POST loans-repayment", roleUser, nil, http.MethodPost, "/api/admin/loans-repayment", http.StatusOK},
{"user PUT profile", roleUser, nil, http.MethodPut, "/api/admin/profile", http.StatusOK}, {"user PUT profile", roleUser, nil, http.MethodPut, "/api/admin/profile", http.StatusOK},
{"user POST file", roleUser, nil, http.MethodPost, "/api/admin/file", http.StatusOK}, {"user POST file", roleUser, nil, http.MethodPost, "/api/admin/file", http.StatusOK},
{"user GET users", roleUser, nil, http.MethodGet, "/api/admin/users", http.StatusForbidden}, {"user GET users", roleUser, nil, http.MethodGet, "/api/admin/users", http.StatusForbidden},
{"user GET users/clients", roleUser, nil, http.MethodGet, "/api/admin/users/clients", http.StatusOK},
{"user GET branches", roleUser, nil, http.MethodGet, "/api/admin/branches", http.StatusOK},
{"user GET provinces", roleUser, nil, http.MethodGet, "/api/admin/provinces", http.StatusOK},
{"user POST branches", roleUser, nil, http.MethodPost, "/api/admin/branches", http.StatusForbidden},
{"no-role GET currencies", "", nil, http.MethodGet, "/api/admin/currencies", http.StatusOK}, {"no-role GET currencies", "", nil, http.MethodGet, "/api/admin/currencies", http.StatusOK},
{"no-role GET backups", "", nil, http.MethodGet, "/api/admin/backups", http.StatusForbidden}, {"no-role GET backups", "", nil, http.MethodGet, "/api/admin/backups", http.StatusForbidden},
@@ -196,6 +341,7 @@ func TestGuardMatrix(t *testing.T) {
{"operator POST card-orders", roleOperator, []int64{1}, http.MethodPost, "/api/admin/card-orders", http.StatusOK}, {"operator POST card-orders", roleOperator, []int64{1}, http.MethodPost, "/api/admin/card-orders", http.StatusOK},
{"operator no branch GET currencies", roleOperator, nil, http.MethodGet, "/api/admin/currencies", http.StatusForbidden}, {"operator no branch GET currencies", roleOperator, nil, http.MethodGet, "/api/admin/currencies", http.StatusForbidden},
{"operator no branch GET profile", roleOperator, nil, http.MethodGet, "/api/admin/profile", http.StatusOK}, {"operator no branch GET profile", roleOperator, nil, http.MethodGet, "/api/admin/profile", http.StatusOK},
{"operator no branch GET users/clients", roleOperator, nil, http.MethodGet, "/api/admin/users/clients", http.StatusOK},
{"admin GET backups", "admin", nil, http.MethodGet, "/api/admin/backups", http.StatusOK}, {"admin GET backups", "admin", nil, http.MethodGet, "/api/admin/backups", http.StatusOK},
{"admin POST currencies", "admin", nil, http.MethodPost, "/api/admin/currencies", http.StatusOK}, {"admin POST currencies", "admin", nil, http.MethodPost, "/api/admin/currencies", http.StatusOK},
@@ -289,9 +435,17 @@ func TestOperatorWriteAllowedUserVisibility(t *testing.T) {
t.Fatalf("visible user status=%d", status) t.Fatalf("visible user status=%d", status)
} }
// Creating a brand-new order for a customer who has no prior record in
// the branch must still succeed — the branchId check alone scopes a
// create to the operator's own branch.
hidden := &stubAuth{role: roleOperator, branches: []int64{1}, visible: false} hidden := &stubAuth{role: roleOperator, branches: []int64{1}, visible: false}
if status := serveGuard(hidden, http.MethodPost, "/api/admin/card-orders", "7", []byte(`{"userId":15}`)); status != http.StatusForbidden { if status := serveGuard(hidden, http.MethodPost, "/api/admin/card-orders", "7", []byte(`{"userId":15}`)); status != http.StatusOK {
t.Fatalf("hidden user status=%d", status) t.Fatalf("new customer create status=%d", status)
}
// Reassigning an existing order's customer still enforces visibility.
if status := serveGuard(hidden, http.MethodPut, "/api/admin/card-orders/1", "7", []byte(`{"userId":15}`)); status != http.StatusForbidden {
t.Fatalf("update hidden user status=%d", status)
} }
} }
@@ -349,6 +503,40 @@ func TestAllowsBranchAndGuardUser(t *testing.T) {
} }
} }
func TestGuardNewBranchAssignment(t *testing.T) {
gin.SetMode(gin.TestMode)
w := httptest.NewRecorder()
c, _ := gin.CreateTestContext(w)
c.Request = httptest.NewRequest(http.MethodPost, "/", nil)
// No branch scope (admin caller): always allowed.
if !GuardNewBranchAssignment(c, 42) {
t.Fatal("admin caller should be able to assign any user")
}
// Operator scoped to branch 1.
c.Set(contextBranchIDs, []int64{1})
// Target has no existing branch: first-time assignment is allowed.
c.Set(contextService, &stubAuth{branches: nil})
if !GuardNewBranchAssignment(c, 42) {
t.Fatal("unbranched target should be assignable")
}
// Target already belongs to the operator's own branch: no-op re-assignment is allowed.
c.Set(contextService, &stubAuth{branches: []int64{1}})
if !GuardNewBranchAssignment(c, 42) {
t.Fatal("target already in caller's branch should be assignable")
}
// Target belongs to a different branch: reject cross-branch poaching.
c.Set(contextService, &stubAuth{branches: []int64{2}})
if GuardNewBranchAssignment(c, 42) {
t.Fatal("target from a foreign branch must not be assignable")
}
}
func TestBindBranchIDs(t *testing.T) { func TestBindBranchIDs(t *testing.T) {
gin.SetMode(gin.TestMode) gin.SetMode(gin.TestMode)
w := httptest.NewRecorder() w := httptest.NewRecorder()
@@ -402,12 +590,13 @@ func TestUserInBranchSQLIncludesNewOrderTables(t *testing.T) {
for _, table := range []string{ for _, table := range []string{
"branch_user", "card_orders", "loan_orders", "card_pin_orders", "branch_user", "card_orders", "loan_orders", "card_pin_orders",
"card_rekwizit_orders", "visa_master_payment_orders", "loan_paid_off_letters", "card_rekwizit_orders", "visa_master_payment_orders", "loan_paid_off_letters",
"card_balances",
} { } {
if !strings.Contains(sql, table) { if !strings.Contains(sql, table) {
t.Errorf("missing %s", table) t.Errorf("missing %s", table)
} }
} }
if strings.Count(sql, "$3") != 7 { if strings.Count(sql, "$3") != 8 {
t.Fatalf("$3 count=%d", strings.Count(sql, "$3")) t.Fatalf("$3 count=%d", strings.Count(sql, "$3"))
} }
} }
@@ -460,6 +649,9 @@ func (s *stubAuth) BranchIDs(context.Context, int64) ([]int64, error) {
} }
func (s *stubAuth) HasPermission(_ context.Context, _ int64, code string) (bool, error) { func (s *stubAuth) HasPermission(_ context.Context, _ int64, code string) (bool, error) {
if s.perms == nil {
return true, nil
}
return s.perms[code], nil return s.perms[code], nil
} }
@@ -486,6 +678,7 @@ func TestEffectiveGuard(t *testing.T) {
{"", "", guardWeb}, {"", "", guardWeb},
{roleOperator, guardAdmin, guardOperator}, {roleOperator, guardAdmin, guardOperator},
{roleOperator, guardWeb, guardOperator}, {roleOperator, guardWeb, guardOperator},
{"operatot", guardWeb, guardOperator},
{"superadmin", guardWeb, guardAdmin}, {"superadmin", guardWeb, guardAdmin},
{"admin", guardWeb, guardAdmin}, {"admin", guardWeb, guardAdmin},
{"manager", guardOperator, guardAdmin}, {"manager", guardOperator, guardAdmin},
@@ -548,6 +741,34 @@ func TestEnforceOwnWritesRewritesUserID(t *testing.T) {
} }
} }
func TestEnforceOwnWritesRewritesCreatedByForCardBalances(t *testing.T) {
gin.SetMode(gin.TestMode)
r := gin.New()
r.Use(func(c *gin.Context) {
c.Set("id", "7")
c.Next()
})
r.Use(Guard(&stubAuth{role: roleUser}))
r.POST("/api/admin/card-balances", func(c *gin.Context) {
body, _ := io.ReadAll(c.Request.Body)
c.String(http.StatusOK, string(body))
})
w := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodPost, "/api/admin/card-balances", bytes.NewReader([]byte(`{"createdBy":99,"cardNumber":"4111111111111111"}`)))
req.Header.Set("Content-Type", "application/json")
r.ServeHTTP(w, req)
if w.Code != http.StatusOK {
t.Fatalf("status=%d", w.Code)
}
if !strings.Contains(w.Body.String(), `"createdBy":7`) {
t.Fatalf("createdBy not rewritten: %s", w.Body.String())
}
if !strings.Contains(w.Body.String(), `"created_by":7`) {
t.Fatalf("created_by not rewritten: %s", w.Body.String())
}
}
func TestGuardOwnedOwnScope(t *testing.T) { func TestGuardOwnedOwnScope(t *testing.T) {
gin.SetMode(gin.TestMode) gin.SetMode(gin.TestMode)
w := httptest.NewRecorder() w := httptest.NewRecorder()

View File

@@ -9,6 +9,14 @@ import (
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
) )
// The three valid guard names. Use these constants when validating
// the guardName field in role/permission DTOs.
const (
GuardWeb = guardWeb
GuardOperator = guardOperator
GuardAdmin = guardAdmin
)
const ( const (
contextBranchIDs = "branchIds" contextBranchIDs = "branchIds"
contextService = "rbacService" contextService = "rbacService"
@@ -43,6 +51,10 @@ func IsOwnScope(c *gin.Context) bool {
return GuardFrom(c) == guardWeb return GuardFrom(c) == guardWeb
} }
func IsAdminGuard(c *gin.Context) bool {
return GuardFrom(c) == guardAdmin
}
func SkipRecordGuard(c *gin.Context) bool { func SkipRecordGuard(c *gin.Context) bool {
return !HasBranchScope(c) && !IsOwnScope(c) return !HasBranchScope(c) && !IsOwnScope(c)
} }
@@ -94,6 +106,40 @@ func GuardBranch(c *gin.Context, branchID int64) bool {
return false return false
} }
// GuardNewBranchAssignment guards POST /branch-users: a branch-scoped caller
// may only assign a user who is unbranched or already in one of their own
// branches. Without this, an operator holding users.manage could pull
// another branch's operator into their own branch — the destination-branch
// check alone doesn't catch that, since it never looks at the target's
// current branch.
func GuardNewBranchAssignment(c *gin.Context, targetUserID int64) bool {
if !HasBranchScope(c) {
return true
}
raw, ok := c.Get(contextService)
if !ok {
c.JSON(http.StatusForbidden, appresult.ErrForbidden)
return false
}
service, _ := raw.(Authorizer)
if service == nil {
c.JSON(http.StatusForbidden, appresult.ErrForbidden)
return false
}
currentBranches, err := service.BranchIDs(c.Request.Context(), targetUserID)
if err != nil {
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return false
}
for _, branchID := range currentBranches {
if !AllowsBranch(c, branchID) {
c.JSON(http.StatusForbidden, appresult.ErrForbidden)
return false
}
}
return true
}
func GuardUser(c *gin.Context, userID int64) bool { func GuardUser(c *gin.Context, userID int64) bool {
if IsOwnScope(c) { if IsOwnScope(c) {
id := userID id := userID
@@ -139,7 +185,8 @@ func UserInBranchSQL(userExpr string, placeholder int) string {
OR EXISTS (SELECT 1 FROM card_rekwizit_orders cro WHERE cro.user_id = %s AND cro.branch_id = ANY($%d)) OR EXISTS (SELECT 1 FROM card_rekwizit_orders cro WHERE cro.user_id = %s AND cro.branch_id = ANY($%d))
OR EXISTS (SELECT 1 FROM visa_master_payment_orders vmo WHERE vmo.user_id = %s AND vmo.branch_id = ANY($%d)) OR EXISTS (SELECT 1 FROM visa_master_payment_orders vmo WHERE vmo.user_id = %s AND vmo.branch_id = ANY($%d))
OR EXISTS (SELECT 1 FROM loan_paid_off_letters lpl WHERE lpl.user_id = %s AND lpl.branch_id = ANY($%d)) OR EXISTS (SELECT 1 FROM loan_paid_off_letters lpl WHERE lpl.user_id = %s AND lpl.branch_id = ANY($%d))
)`, userExpr, placeholder, userExpr, placeholder, userExpr, placeholder, userExpr, placeholder, userExpr, placeholder, userExpr, placeholder, userExpr, placeholder) OR EXISTS (SELECT 1 FROM card_balances cb WHERE cb.created_by = %s AND cb.branch_id = ANY($%d))
)`, userExpr, placeholder, userExpr, placeholder, userExpr, placeholder, userExpr, placeholder, userExpr, placeholder, userExpr, placeholder, userExpr, placeholder, userExpr, placeholder)
} }
func containsInt64(ids []int64, want int64) bool { func containsInt64(ids []int64, want int64) bool {

View File

@@ -7,6 +7,7 @@ import (
"strings" "strings"
"online-back/internal/identity/role" "online-back/internal/identity/role"
"online-back/internal/shared"
"online-back/pkg/client/postgresql" "online-back/pkg/client/postgresql"
"online-back/pkg/logging" "online-back/pkg/logging"
"online-back/pkg/repository/genericrepo" "online-back/pkg/repository/genericrepo"
@@ -46,7 +47,7 @@ func (r *repository) List(ctx context.Context, filter role.ListFilter) (role.Lis
func buildListQuery(filter role.ListFilter) (whereClause string, args []interface{}) { func buildListQuery(filter role.ListFilter) (whereClause string, args []interface{}) {
var conditions []string var conditions []string
if filter.RoleName != "" { if filter.RoleName != "" {
args = append(args, likePattern(filter.RoleName)) args = append(args, shared.LikePattern(filter.RoleName))
n := len(args) n := len(args)
conditions = append(conditions, fmt.Sprintf(`r.name ILIKE $%d`, n)) conditions = append(conditions, fmt.Sprintf(`r.name ILIKE $%d`, n))
} }
@@ -58,13 +59,6 @@ func buildListQuery(filter role.ListFilter) (whereClause string, args []interfac
return " WHERE " + strings.Join(conditions, " AND "), 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) (role.RoleDTO, error) { func (r *repository) GetByID(ctx context.Context, id int64) (role.RoleDTO, error) {
return r.generic.GetByID(ctx, id) return r.generic.GetByID(ctx, id)
} }

View File

@@ -12,15 +12,15 @@ type RoleDTO struct {
} }
type CreateRoleDTO struct { type CreateRoleDTO struct {
Code string `json:"code" binding:"required"` Code string `json:"code" binding:"required"`
Name string `json:"name" binding:"required"` Name string `json:"name" binding:"required"`
GuardName string `json:"guardName" binding:"required"` GuardName string `json:"guardName" binding:"required,oneof=web operator admin"`
} }
type UpdateRoleDTO struct { type UpdateRoleDTO struct {
Code string `json:"code" binding:"required"` Code string `json:"code" binding:"required"`
Name string `json:"name" binding:"required"` Name string `json:"name" binding:"required"`
GuardName string `json:"guardName" binding:"required"` GuardName string `json:"guardName" binding:"required,oneof=web operator admin"`
} }
type ListFilter struct { type ListFilter struct {

View File

@@ -8,6 +8,7 @@ import (
"online-back/internal/appresult" "online-back/internal/appresult"
"online-back/internal/handlers" "online-back/internal/handlers"
"online-back/internal/shared"
"online-back/pkg/logging" "online-back/pkg/logging"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
@@ -77,7 +78,7 @@ func (h *handler) list(c *gin.Context) {
// @Failure 500 {object} appresult.AppError // @Failure 500 {object} appresult.AppError
// @Router /roles/{id} [get] // @Router /roles/{id} [get]
func (h *handler) getByID(c *gin.Context) { func (h *handler) getByID(c *gin.Context) {
id, ok := parseID(c.Param("id")) id, ok := shared.ParseID(c.Param("id"))
if !ok { if !ok {
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam) c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
return return
@@ -141,7 +142,7 @@ func (h *handler) create(c *gin.Context) {
// @Failure 500 {object} appresult.AppError // @Failure 500 {object} appresult.AppError
// @Router /roles/{id} [put] // @Router /roles/{id} [put]
func (h *handler) update(c *gin.Context) { func (h *handler) update(c *gin.Context) {
id, ok := parseID(c.Param("id")) id, ok := shared.ParseID(c.Param("id"))
if !ok { if !ok {
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam) c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
return return
@@ -180,7 +181,7 @@ func (h *handler) update(c *gin.Context) {
// @Failure 500 {object} appresult.AppError // @Failure 500 {object} appresult.AppError
// @Router /roles/{id} [delete] // @Router /roles/{id} [delete]
func (h *handler) delete(c *gin.Context) { func (h *handler) delete(c *gin.Context) {
id, ok := parseID(c.Param("id")) id, ok := shared.ParseID(c.Param("id"))
if !ok { if !ok {
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam) c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
return return
@@ -198,24 +199,10 @@ func (h *handler) delete(c *gin.Context) {
c.JSON(http.StatusOK, appresult.SuccessWithData("role removed")) c.JSON(http.StatusOK, appresult.SuccessWithData("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
}
const (
defaultPage = 1
defaultLimit = 10
maxLimit = 100
)
func parseListFilter(c *gin.Context) (ListFilter, bool) { func parseListFilter(c *gin.Context) (ListFilter, bool) {
filter := ListFilter{ filter := ListFilter{
Page: defaultPage, Page: shared.DefaultPage,
Limit: defaultLimit, Limit: shared.DefaultLimit,
} }
if raw := c.Query("page"); raw != "" { if raw := c.Query("page"); raw != "" {
@@ -228,7 +215,7 @@ func parseListFilter(c *gin.Context) (ListFilter, bool) {
if raw := c.Query("limit"); raw != "" { if raw := c.Query("limit"); raw != "" {
limit, err := strconv.Atoi(raw) limit, err := strconv.Atoi(raw)
if err != nil || limit < 1 || limit > maxLimit { if err != nil || limit < 1 || limit > shared.MaxLimit {
return ListFilter{}, false return ListFilter{}, false
} }
filter.Limit = limit filter.Limit = limit

View File

@@ -7,6 +7,7 @@ import (
"online-back/internal/identity/roleusers" "online-back/internal/identity/roleusers"
"online-back/pkg/client/postgresql" "online-back/pkg/client/postgresql"
"online-back/pkg/logging" "online-back/pkg/logging"
"online-back/pkg/repository/genericrepo"
"github.com/jackc/pgx/v4" "github.com/jackc/pgx/v4"
) )
@@ -50,21 +51,10 @@ func (r *repository) Create(ctx context.Context, dto roleusers.CreateRoleUserDTO
} }
func (r *repository) Delete(ctx context.Context, id int64) error { func (r *repository) Delete(ctx context.Context, id int64) error {
tag, err := r.client.Exec(ctx, `DELETE FROM role_user WHERE id = $1`, id) return genericrepo.Delete(ctx, r.client, "role_user", id)
if err != nil {
return err
}
if tag.RowsAffected() == 0 {
return pgx.ErrNoRows
}
return nil
} }
type scannable interface { func scanRoleUser(row genericrepo.Scanner) (roleusers.RoleUserDTO, error) {
Scan(dest ...interface{}) error
}
func scanRoleUser(row scannable) (roleusers.RoleUserDTO, error) {
var item roleusers.RoleUserDTO var item roleusers.RoleUserDTO
err := row.Scan( err := row.Scan(

View File

@@ -1,16 +1,12 @@
package roleusers package roleusers
import ( import (
"errors"
"net/http"
"strconv"
"online-back/internal/appresult" "online-back/internal/appresult"
"online-back/internal/handlers" "online-back/internal/handlers"
"online-back/internal/shared"
"online-back/pkg/logging" "online-back/pkg/logging"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
"github.com/jackc/pgx/v4"
) )
const baseURL = "/role-users" const baseURL = "/role-users"
@@ -43,20 +39,7 @@ func (h *handler) Register(router *gin.RouterGroup) {
// @Failure 500 {object} appresult.AppError // @Failure 500 {object} appresult.AppError
// @Router /role-users [post] // @Router /role-users [post]
func (h *handler) create(c *gin.Context) { func (h *handler) create(c *gin.Context) {
var dto CreateRoleUserDTO shared.CreateAssoc[CreateRoleUserDTO, RoleUserDTO](c, h.logger, h.repository, "role user")
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 role user failed: %v", err)
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return
}
c.JSON(http.StatusCreated, appresult.SuccessWithData(item))
} }
// delete godoc // delete godoc
@@ -72,28 +55,5 @@ func (h *handler) create(c *gin.Context) {
// @Failure 500 {object} appresult.AppError // @Failure 500 {object} appresult.AppError
// @Router /role-users/{id} [delete] // @Router /role-users/{id} [delete]
func (h *handler) delete(c *gin.Context) { func (h *handler) delete(c *gin.Context) {
id, ok := parseID(c.Param("id")) shared.DeleteAssoc[CreateRoleUserDTO, RoleUserDTO](c, h.logger, h.repository, "role user")
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 role user failed: %v", err)
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return
}
c.JSON(http.StatusOK, appresult.SuccessWithData("role user 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
} }

View File

@@ -10,8 +10,10 @@ import (
"online-back/internal/identity/rbac" "online-back/internal/identity/rbac"
"online-back/internal/identity/user" "online-back/internal/identity/user"
"online-back/internal/shared"
"online-back/pkg/client/postgresql" "online-back/pkg/client/postgresql"
"online-back/pkg/logging" "online-back/pkg/logging"
"online-back/pkg/repository/genericrepo"
"github.com/jackc/pgx/v4" "github.com/jackc/pgx/v4"
"golang.org/x/crypto/bcrypt" "golang.org/x/crypto/bcrypt"
@@ -55,6 +57,31 @@ const userBranchesJSON = `COALESCE((
) b ) b
), '[]'::json)` ), '[]'::json)`
const userPermissionsJSON = `COALESCE((
SELECT json_agg(jsonb_build_object(
'id', p.id,
'code', COALESCE(p.code, ''),
'name', p.name,
'guardName', p.guard_name,
'module', COALESCE(p.module, '')
) ORDER BY p.module, p.id)
FROM permissions p
WHERE NOT EXISTS (
SELECT 1 FROM permission_user pu
WHERE pu.user_id = u.id AND pu.permission_id = p.id AND pu.effect = 'deny'
)
AND (
EXISTS (
SELECT 1 FROM permission_user pu
WHERE pu.user_id = u.id AND pu.permission_id = p.id AND pu.effect = 'allow'
)
OR EXISTS (
SELECT 1 FROM permission_role pr
WHERE pr.role_id = r.id AND pr.permission_id = p.id
)
)
), '[]'::json)`
func (r *repository) List(ctx context.Context, filter user.ListFilter) (user.ListUserDTO, error) { func (r *repository) List(ctx context.Context, filter user.ListFilter) (user.ListUserDTO, error) {
fromClause, whereClause, args := buildFilteredListQuery(filter, listVisibleRoles...) fromClause, whereClause, args := buildFilteredListQuery(filter, listVisibleRoles...)
return r.paginateUsers(ctx, filter, fromClause, whereClause, args) return r.paginateUsers(ctx, filter, fromClause, whereClause, args)
@@ -181,7 +208,7 @@ func appendNameSearch(conditions []string, args []interface{}, term string) ([]s
if term == "" { if term == "" {
return conditions, args return conditions, args
} }
args = append(args, likePattern(term)) args = append(args, shared.LikePattern(term))
n := len(args) n := len(args)
conditions = append(conditions, fmt.Sprintf( conditions = append(conditions, fmt.Sprintf(
`(u.username ILIKE $%d OR u.first_name ILIKE $%d OR u.last_name ILIKE $%d OR CONCAT_WS(' ', u.first_name, u.last_name) ILIKE $%d)`, `(u.username ILIKE $%d OR u.first_name ILIKE $%d OR u.last_name ILIKE $%d OR CONCAT_WS(' ', u.first_name, u.last_name) ILIKE $%d)`,
@@ -190,13 +217,6 @@ func appendNameSearch(conditions []string, args []interface{}, term string) ([]s
return conditions, args return conditions, args
} }
func likePattern(term string) string {
term = strings.ReplaceAll(term, `\`, `\\`)
term = strings.ReplaceAll(term, `%`, `\%`)
term = strings.ReplaceAll(term, `_`, `\_`)
return "%" + term + "%"
}
func (r *repository) GetByRole(ctx context.Context, role string, filter user.ListFilter) (user.ListUserDTO, error) { func (r *repository) GetByRole(ctx context.Context, role string, filter user.ListFilter) (user.ListUserDTO, error) {
fromClause, whereClause, args := buildFilteredListQuery(filter, role) fromClause, whereClause, args := buildFilteredListQuery(filter, role)
if len(filter.BranchIds) == 0 { if len(filter.BranchIds) == 0 {
@@ -211,8 +231,8 @@ func (r *repository) GetByRole(ctx context.Context, role string, filter user.Lis
} }
func (r *repository) GetByID(ctx context.Context, id int64) (user.UserDTO, error) { func (r *repository) GetByID(ctx context.Context, id int64) (user.UserDTO, error) {
query := fmt.Sprintf(`SELECT %s, %s%s WHERE u.id = $1`, userColumns, userBranchesJSON, userFromClause) query := fmt.Sprintf(`SELECT %s, %s, %s%s WHERE u.id = $1`, userColumns, userBranchesJSON, userPermissionsJSON, userFromClause)
item, err := scanStaffUser(r.client.QueryRow(ctx, query, id)) item, err := scanUserDetail(r.client.QueryRow(ctx, query, id))
if errors.Is(err, pgx.ErrNoRows) { if errors.Is(err, pgx.ErrNoRows) {
return user.UserDTO{}, err return user.UserDTO{}, err
} }
@@ -306,14 +326,16 @@ func (r *repository) Update(ctx context.Context, id int64, dto user.UpdateUserDT
} }
func (r *repository) Delete(ctx context.Context, id int64) error { func (r *repository) Delete(ctx context.Context, id int64) error {
tag, err := r.client.Exec(ctx, `DELETE FROM users WHERE id = $1`, id) return genericrepo.Delete(ctx, r.client, "users", id)
if err != nil { }
return err
func (r *repository) RoleGuardName(ctx context.Context, code string) (string, error) {
var guardName string
err := r.client.QueryRow(ctx, `SELECT guard_name FROM roles WHERE code = $1`, code).Scan(&guardName)
if errors.Is(err, pgx.ErrNoRows) {
return "", nil
} }
if tag.RowsAffected() == 0 { return guardName, err
return pgx.ErrNoRows
}
return nil
} }
func assignRoleByCode(ctx context.Context, tx pgx.Tx, userID int64, roleCode string) error { func assignRoleByCode(ctx context.Context, tx pgx.Tx, userID int64, roleCode string) error {
@@ -344,11 +366,7 @@ func roleIDByCode(ctx context.Context, tx pgx.Tx, roleCode string) *int64 {
return &id return &id
} }
type scannable interface { func scanUser(row genericrepo.Scanner) (user.UserDTO, error) {
Scan(dest ...interface{}) error
}
func scanUser(row scannable) (user.UserDTO, error) {
var item user.UserDTO var item user.UserDTO
if err := row.Scan( if err := row.Scan(
&item.Id, &item.Email, &item.Name, &item.FirstName, &item.LastName, &item.Username, &item.Phone, &item.Avatar, &item.Id, &item.Email, &item.Name, &item.FirstName, &item.LastName, &item.Username, &item.Phone, &item.Avatar,
@@ -359,7 +377,7 @@ func scanUser(row scannable) (user.UserDTO, error) {
return item, nil return item, nil
} }
func scanUserWithRoleID(row scannable) (user.UserDTO, error) { func scanUserWithRoleID(row genericrepo.Scanner) (user.UserDTO, error) {
var item user.UserDTO var item user.UserDTO
var roleID sql.NullInt64 var roleID sql.NullInt64
var roleCode sql.NullString var roleCode sql.NullString
@@ -373,7 +391,7 @@ func scanUserWithRoleID(row scannable) (user.UserDTO, error) {
return item, nil return item, nil
} }
func scanStaffUser(row scannable) (user.UserDTO, error) { func scanStaffUser(row genericrepo.Scanner) (user.UserDTO, error) {
var item user.UserDTO var item user.UserDTO
var roleID sql.NullInt64 var roleID sql.NullInt64
var roleCode sql.NullString var roleCode sql.NullString
@@ -385,16 +403,50 @@ func scanStaffUser(row scannable) (user.UserDTO, error) {
return user.UserDTO{}, err return user.UserDTO{}, err
} }
applyJoinedRole(&item, roleID, roleCode) applyJoinedRole(&item, roleID, roleCode)
if len(branchesJSON) == 0 || string(branchesJSON) == "null" { if err := unmarshalJSON(branchesJSON, &item.Branches); err != nil {
item.Branches = []user.StaffBranchDTO{}
return item, nil
}
if err := json.Unmarshal(branchesJSON, &item.Branches); err != nil {
return user.UserDTO{}, err return user.UserDTO{}, err
} }
if item.Branches == nil {
item.Branches = []user.StaffBranchDTO{}
}
return item, nil return item, nil
} }
func scanUserDetail(row genericrepo.Scanner) (user.UserDTO, error) {
var item user.UserDTO
var roleID sql.NullInt64
var roleCode sql.NullString
var branchesJSON []byte
var permissionsJSON []byte
if err := row.Scan(
&item.Id, &item.Email, &item.Name, &item.FirstName, &item.LastName, &item.Username, &item.Phone, &item.Avatar,
&item.Active, &item.CreatedAt, &item.UpdatedAt, &roleID, &roleCode, &branchesJSON, &permissionsJSON,
); err != nil {
return user.UserDTO{}, err
}
applyJoinedRole(&item, roleID, roleCode)
if err := unmarshalJSON(branchesJSON, &item.Branches); err != nil {
return user.UserDTO{}, err
}
if err := unmarshalJSON(permissionsJSON, &item.Permissions); err != nil {
return user.UserDTO{}, err
}
if item.Branches == nil {
item.Branches = []user.StaffBranchDTO{}
}
if item.Permissions == nil {
item.Permissions = []user.UserPermissionDTO{}
}
return item, nil
}
func unmarshalJSON(raw []byte, dest interface{}) error {
if len(raw) == 0 || string(raw) == "null" {
return nil
}
return json.Unmarshal(raw, dest)
}
func applyJoinedRole(item *user.UserDTO, roleID sql.NullInt64, roleCode sql.NullString) { func applyJoinedRole(item *user.UserDTO, roleID sql.NullInt64, roleCode sql.NullString) {
if roleCode.Valid { if roleCode.Valid {
item.Role = roleCode.String item.Role = roleCode.String

View File

@@ -14,21 +14,30 @@ type StaffBranchDTO struct {
Name LocalizedText `json:"name"` Name LocalizedText `json:"name"`
} }
type UserPermissionDTO struct {
Id int64 `json:"id"`
Code string `json:"code"`
Name string `json:"name"`
GuardName string `json:"guardName"`
Module string `json:"module"`
}
type UserDTO struct { type UserDTO struct {
Id int64 `json:"id"` Id int64 `json:"id"`
Email string `json:"email"` Email string `json:"email"`
Name string `json:"name"` Name string `json:"name"`
FirstName string `json:"firstName"` FirstName string `json:"firstName"`
LastName string `json:"lastName"` LastName string `json:"lastName"`
Username string `json:"username"` Username string `json:"username"`
Phone string `json:"phone"` Phone string `json:"phone"`
Avatar string `json:"avatar"` Avatar string `json:"avatar"`
Role string `json:"role"` Role string `json:"role"`
RoleId *int64 `json:"roleId,omitempty"` RoleId *int64 `json:"roleId,omitempty"`
Active bool `json:"active"` Active bool `json:"active"`
CreatedAt time.Time `json:"createdAt"` CreatedAt time.Time `json:"createdAt"`
UpdatedAt time.Time `json:"updatedAt"` UpdatedAt time.Time `json:"updatedAt"`
Branches []StaffBranchDTO `json:"branches,omitempty"` Branches []StaffBranchDTO `json:"branches,omitempty"`
Permissions []UserPermissionDTO `json:"permissions,omitempty"`
} }
type CreateUserDTO struct { type CreateUserDTO struct {

View File

@@ -14,6 +14,7 @@ import (
"online-back/internal/appresult" "online-back/internal/appresult"
"online-back/internal/config" "online-back/internal/config"
"online-back/internal/identity/rbac" "online-back/internal/identity/rbac"
"online-back/internal/shared"
"online-back/pkg/logging" "online-back/pkg/logging"
minioUpload "online-back/pkg/minio" minioUpload "online-back/pkg/minio"
@@ -79,6 +80,7 @@ func (h *handler) list(c *gin.Context) {
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam) c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
return return
} }
rbac.BindBranchIDs(c, &filter.BranchIds)
result, err := h.repository.List(c.Request.Context(), filter) result, err := h.repository.List(c.Request.Context(), filter)
if err != nil { if err != nil {
@@ -141,6 +143,7 @@ func (h *handler) listStaff(c *gin.Context) {
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam) c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
return return
} }
rbac.BindBranchIDs(c, &filter.BranchIds)
result, err := h.repository.ListStaff(c.Request.Context(), filter) result, err := h.repository.ListStaff(c.Request.Context(), filter)
if err != nil { if err != nil {
@@ -154,7 +157,7 @@ func (h *handler) listStaff(c *gin.Context) {
// getByID godoc // getByID godoc
// @Summary Get user by ID // @Summary Get user by ID
// @Description Returns a single user with assigned branches and roleId // @Description Returns a single user with assigned branches, roleId, and effective permissions
// @Tags user // @Tags user
// @Produce json // @Produce json
// @Security BearerAuth // @Security BearerAuth
@@ -165,7 +168,7 @@ func (h *handler) listStaff(c *gin.Context) {
// @Failure 500 {object} appresult.AppError // @Failure 500 {object} appresult.AppError
// @Router /users/{id} [get] // @Router /users/{id} [get]
func (h *handler) getByID(c *gin.Context) { func (h *handler) getByID(c *gin.Context) {
id, ok := parseID(c.Param("id")) id, ok := shared.ParseID(c.Param("id"))
if !ok { if !ok {
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam) c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
return return
@@ -207,6 +210,15 @@ func (h *handler) create(c *gin.Context) {
return return
} }
if allowed, err := h.roleAssignmentAllowed(c, dto.Role); err != nil {
h.logger.Errorf("resolve role guard failed: %v", err)
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return
} else if !allowed {
c.JSON(http.StatusForbidden, appresult.ErrForbidden)
return
}
item, err := h.repository.Create(c.Request.Context(), dto) item, err := h.repository.Create(c.Request.Context(), dto)
if err != nil { if err != nil {
h.logger.Errorf("create user failed: %v", err) h.logger.Errorf("create user failed: %v", err)
@@ -232,7 +244,7 @@ func (h *handler) create(c *gin.Context) {
// @Failure 500 {object} appresult.AppError // @Failure 500 {object} appresult.AppError
// @Router /users/{id} [put] // @Router /users/{id} [put]
func (h *handler) update(c *gin.Context) { func (h *handler) update(c *gin.Context) {
id, ok := parseID(c.Param("id")) id, ok := shared.ParseID(c.Param("id"))
if !ok { if !ok {
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam) c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
return return
@@ -248,6 +260,15 @@ func (h *handler) update(c *gin.Context) {
return return
} }
if allowed, err := h.roleAssignmentAllowed(c, dto.Role); err != nil {
h.logger.Errorf("resolve role guard failed: %v", err)
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return
} else if !allowed {
c.JSON(http.StatusForbidden, appresult.ErrForbidden)
return
}
item, err := h.repository.Update(c.Request.Context(), id, dto) item, err := h.repository.Update(c.Request.Context(), id, dto)
if errors.Is(err, pgx.ErrNoRows) { if errors.Is(err, pgx.ErrNoRows) {
c.JSON(http.StatusNotFound, appresult.ErrNotFound) c.JSON(http.StatusNotFound, appresult.ErrNotFound)
@@ -275,7 +296,7 @@ func (h *handler) update(c *gin.Context) {
// @Failure 500 {object} appresult.AppError // @Failure 500 {object} appresult.AppError
// @Router /users/{id} [delete] // @Router /users/{id} [delete]
func (h *handler) delete(c *gin.Context) { func (h *handler) delete(c *gin.Context) {
id, ok := parseID(c.Param("id")) id, ok := shared.ParseID(c.Param("id"))
if !ok { if !ok {
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam) c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
return return
@@ -297,24 +318,31 @@ func (h *handler) delete(c *gin.Context) {
c.JSON(http.StatusOK, appresult.SuccessWithData("user removed")) c.JSON(http.StatusOK, appresult.SuccessWithData("user removed"))
} }
func parseID(raw string) (int64, bool) { // roleAssignmentAllowed asks "would granting this role let the target run
id, err := strconv.ParseInt(raw, 10, 64) // requests as guardAdmin?" using the role's real guard_name, the same input
if err != nil || id <= 0 { // rbac.Guard() resolves on every request - not a hardcoded list of role
return 0, false // names, which would drift the moment a new role is added. Without this, an
// operator holding users.manage could set role:"admin" on themselves via
// this same endpoint and escape branch scoping entirely.
func (h *handler) roleAssignmentAllowed(c *gin.Context, role string) (bool, error) {
if rbac.IsAdminGuard(c) {
return true, nil
} }
return id, true code := strings.ToLower(strings.TrimSpace(role))
if code == "" {
code = "user"
}
guardName, err := h.repository.RoleGuardName(c.Request.Context(), code)
if err != nil {
return false, err
}
return rbac.EffectiveGuard(code, guardName) != rbac.GuardAdmin, nil
} }
const (
defaultPage = 1
defaultLimit = 10
maxLimit = 100
)
func parseListFilter(c *gin.Context) (ListFilter, bool) { func parseListFilter(c *gin.Context) (ListFilter, bool) {
filter := ListFilter{ filter := ListFilter{
Page: defaultPage, Page: shared.DefaultPage,
Limit: defaultLimit, Limit: shared.DefaultLimit,
} }
if raw := c.Query("page"); raw != "" { if raw := c.Query("page"); raw != "" {
@@ -327,7 +355,7 @@ func parseListFilter(c *gin.Context) (ListFilter, bool) {
if raw := c.Query("limit"); raw != "" { if raw := c.Query("limit"); raw != "" {
limit, err := strconv.Atoi(raw) limit, err := strconv.Atoi(raw)
if err != nil || limit < 1 || limit > maxLimit { if err != nil || limit < 1 || limit > shared.MaxLimit {
return ListFilter{}, false return ListFilter{}, false
} }
filter.Limit = limit filter.Limit = limit
@@ -339,8 +367,6 @@ func parseListFilter(c *gin.Context) (ListFilter, bool) {
filter.Search = raw filter.Search = raw
} }
rbac.BindBranchIDs(c, &filter.BranchIds)
return filter, true return filter, true
} }

View File

@@ -0,0 +1,97 @@
package user
import (
"context"
"net/http"
"net/http/httptest"
"testing"
"github.com/gin-gonic/gin"
)
// stubRoleRepo only implements RoleGuardName meaningfully - the other
// methods exist solely to satisfy the Repository interface, since
// roleAssignmentAllowed never calls them.
type stubRoleRepo struct {
guards map[string]string
}
func (s *stubRoleRepo) List(context.Context, ListFilter) (ListUserDTO, error) {
return ListUserDTO{}, nil
}
func (s *stubRoleRepo) ListStaff(context.Context, ListFilter) (ListUserDTO, error) {
return ListUserDTO{}, nil
}
func (s *stubRoleRepo) GetByID(context.Context, int64) (UserDTO, error) { return UserDTO{}, nil }
func (s *stubRoleRepo) GetByRole(context.Context, string, ListFilter) (ListUserDTO, error) {
return ListUserDTO{}, nil
}
func (s *stubRoleRepo) Create(context.Context, CreateUserDTO) (UserDTO, error) { return UserDTO{}, nil }
func (s *stubRoleRepo) Update(context.Context, int64, UpdateUserDTO) (UserDTO, error) {
return UserDTO{}, nil
}
func (s *stubRoleRepo) Delete(context.Context, int64) error { return nil }
func (s *stubRoleRepo) RoleGuardName(_ context.Context, code string) (string, error) {
return s.guards[code], nil
}
var _ Repository = (*stubRoleRepo)(nil)
func TestRoleAssignmentAllowed(t *testing.T) {
gin.SetMode(gin.TestMode)
// Mirrors db/seed.sql's roles table, plus a role added after this code
// was written - to prove the check follows guard_name, not a hardcoded
// list of role names.
repo := &stubRoleRepo{guards: map[string]string{
"user": "web",
"operator": "operator",
"admin": "admin",
"superadmin": "admin",
"manager": "admin",
"currency_maintainer": "admin",
"custom_branch_ops": "operator",
}}
h := &handler{repository: repo}
newContext := func(guard string) *gin.Context {
w := httptest.NewRecorder()
c, _ := gin.CreateTestContext(w)
c.Request = httptest.NewRequest(http.MethodPut, "/", nil)
if guard != "" {
c.Set("guard", guard)
}
return c
}
admin := newContext("admin")
for _, role := range []string{"", "user", "operator", "admin", "superadmin", "manager", "currency_maintainer", "unknown-role"} {
allowed, err := h.roleAssignmentAllowed(admin, role)
if err != nil {
t.Fatalf("role %q: unexpected error %v", role, err)
}
if !allowed {
t.Fatalf("admin guard should be able to assign role %q", role)
}
}
operator := newContext("operator")
for _, role := range []string{"", "user", "operator", "USER", " Operator ", "custom_branch_ops"} {
allowed, err := h.roleAssignmentAllowed(operator, role)
if err != nil {
t.Fatalf("role %q: unexpected error %v", role, err)
}
if !allowed {
t.Fatalf("operator guard should be able to assign role %q", role)
}
}
for _, role := range []string{"admin", "superadmin", "manager", "currency_maintainer", "unknown-role"} {
allowed, err := h.roleAssignmentAllowed(operator, role)
if err != nil {
t.Fatalf("role %q: unexpected error %v", role, err)
}
if allowed {
t.Fatalf("operator guard must not be able to assign role %q", role)
}
}
}

View File

@@ -10,4 +10,7 @@ type Repository interface {
Create(ctx context.Context, dto CreateUserDTO) (UserDTO, error) Create(ctx context.Context, dto CreateUserDTO) (UserDTO, error)
Update(ctx context.Context, id int64, dto UpdateUserDTO) (UserDTO, error) Update(ctx context.Context, id int64, dto UpdateUserDTO) (UserDTO, error)
Delete(ctx context.Context, id int64) error Delete(ctx context.Context, id int64) error
// RoleGuardName returns the guard_name of the role with the given code,
// or "" if no such role exists.
RoleGuardName(ctx context.Context, code string) (string, error)
} }

View File

@@ -8,6 +8,7 @@ import (
"online-back/internal/identity/userbranch" "online-back/internal/identity/userbranch"
"online-back/pkg/client/postgresql" "online-back/pkg/client/postgresql"
"online-back/pkg/logging" "online-back/pkg/logging"
"online-back/pkg/repository/genericrepo"
"github.com/jackc/pgx/v4" "github.com/jackc/pgx/v4"
) )
@@ -61,21 +62,10 @@ func (r *repository) GetByID(ctx context.Context, id int64) (userbranch.UserBran
} }
func (r *repository) Delete(ctx context.Context, id int64) error { func (r *repository) Delete(ctx context.Context, id int64) error {
tag, err := r.client.Exec(ctx, `DELETE FROM branch_user WHERE id = $1`, id) return genericrepo.Delete(ctx, r.client, "branch_user", id)
if err != nil {
return err
}
if tag.RowsAffected() == 0 {
return pgx.ErrNoRows
}
return nil
} }
type scannable interface { func scanUserBranch(row genericrepo.Scanner) (userbranch.UserBranchDTO, error) {
Scan(dest ...interface{}) error
}
func scanUserBranch(row scannable) (userbranch.UserBranchDTO, error) {
var item userbranch.UserBranchDTO var item userbranch.UserBranchDTO
var branchNameJSON []byte var branchNameJSON []byte

View File

@@ -3,11 +3,11 @@ package userbranch
import ( import (
"errors" "errors"
"net/http" "net/http"
"strconv"
"online-back/internal/appresult" "online-back/internal/appresult"
"online-back/internal/handlers" "online-back/internal/handlers"
"online-back/internal/identity/rbac" "online-back/internal/identity/rbac"
"online-back/internal/shared"
"online-back/pkg/logging" "online-back/pkg/logging"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
@@ -50,6 +50,10 @@ func (h *handler) create(c *gin.Context) {
return return
} }
if !rbac.GuardNewBranchAssignment(c, dto.UserId) {
return
}
item, err := h.repository.Create(c.Request.Context(), dto) item, err := h.repository.Create(c.Request.Context(), dto)
if err != nil { if err != nil {
h.logger.Errorf("create branch user failed: %v", err) h.logger.Errorf("create branch user failed: %v", err)
@@ -73,7 +77,7 @@ func (h *handler) create(c *gin.Context) {
// @Failure 500 {object} appresult.AppError // @Failure 500 {object} appresult.AppError
// @Router /branch-users/{id} [delete] // @Router /branch-users/{id} [delete]
func (h *handler) delete(c *gin.Context) { func (h *handler) delete(c *gin.Context) {
id, ok := parseID(c.Param("id")) id, ok := shared.ParseID(c.Param("id"))
if !ok { if !ok {
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam) c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
return return
@@ -105,11 +109,3 @@ func (h *handler) delete(c *gin.Context) {
c.JSON(http.StatusOK, appresult.SuccessWithData("branch user removed")) c.JSON(http.StatusOK, appresult.SuccessWithData("branch user 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
}

View File

@@ -7,7 +7,7 @@ import (
"online-back/internal/identity/rbac" "online-back/internal/identity/rbac"
"online-back/internal/lending/loanorders" "online-back/internal/lending/loanorders"
"online-back/internal/lending/shared" "online-back/internal/shared"
"online-back/pkg/client/postgresql" "online-back/pkg/client/postgresql"
"online-back/pkg/logging" "online-back/pkg/logging"
"online-back/pkg/repository/genericrepo" "online-back/pkg/repository/genericrepo"
@@ -76,11 +76,11 @@ func resolveSource(source string) string {
func createArgs(dto loanorders.CreateLoanOrderDTO) []interface{} { func createArgs(dto loanorders.CreateLoanOrderDTO) []interface{} {
return []interface{}{ return []interface{}{
dto.UniqueId, resolveSource(dto.Source), loanorders.FlexInt64Ptr(dto.UserId), dto.LoanType.Int64(), dto.Region, dto.BranchId.Int64(), dto.UniqueId, resolveSource(dto.Source), shared.OptionalInt64(dto.UserId), dto.LoanType.Int64(), dto.Region, dto.BranchId.Int64(),
dto.CustomerName, dto.CustomerSurname, dto.CustomerPatronicName, dto.CustomerName, dto.CustomerSurname, dto.CustomerPatronicName,
dto.PassportAddress, dto.RealAddress, dto.PassportSerie, dto.PassportId, dto.PassportGivenAt.Time(), dto.PassportGivenBy, dto.PassportAddress, dto.RealAddress, dto.PassportSerie, dto.PassportId, dto.PassportGivenAt.Time(), dto.PassportGivenBy,
dto.BornPlace, dto.BornAt.Time(), dto.Email, dto.Phone, dto.PhoneAdditional, dto.PhoneHome, dto.BornPlace, dto.BornAt.Time(), dto.Email, dto.Phone, dto.PhoneAdditional, dto.PhoneHome,
dto.WorkRegion, loanorders.FlexInt64Ptr(dto.WorkProvinceId), dto.WorkCompany, dto.WorkCompanyAccountantNumber, loanorders.FlexTimePtr(dto.WorkStartedAt), dto.WorkRegion, shared.OptionalInt64(dto.WorkProvinceId), dto.WorkCompany, dto.WorkCompanyAccountantNumber, shared.OptionalTime(dto.WorkStartedAt),
dto.WorkSalary, dto.WorkPosition, dto.Education, dto.MarriageStatus, dto.WorkSalary, dto.WorkPosition, dto.Education, dto.MarriageStatus,
dto.PassportOne, dto.PassportTwo, dto.PassportThree, dto.PassportFour, dto.PassportOne, dto.PassportTwo, dto.PassportThree, dto.PassportFour,
dto.LoanAmount, dto.CardNumber, dto.CardName, dto.CardMonth, dto.CardYear, dto.LoanAmount, dto.CardNumber, dto.CardName, dto.CardMonth, dto.CardYear,
@@ -89,17 +89,17 @@ func createArgs(dto loanorders.CreateLoanOrderDTO) []interface{} {
dto.Guarantor2Name, dto.Guarantor2Surname, dto.Guarantor2PatronicName, dto.Guarantor2PassportSerie, dto.Guarantor2PassportId, dto.Guarantor2Name, dto.Guarantor2Surname, dto.Guarantor2PatronicName, dto.Guarantor2PassportSerie, dto.Guarantor2PassportId,
dto.Guarantor2CardNumber, dto.Guarantor2CardName, dto.Guarantor2CardMonth, dto.Guarantor2CardYear, dto.Guarantor2Note, dto.Guarantor2CardNumber, dto.Guarantor2CardName, dto.Guarantor2CardMonth, dto.Guarantor2CardYear, dto.Guarantor2Note,
dto.LoanCardNumber, dto.LoanCardName, dto.LoanCardMonth, dto.LoanCardYear, dto.LoanCardNumber, dto.LoanCardName, dto.LoanCardMonth, dto.LoanCardYear,
loanorders.FlexInt64Ptr(dto.LoanOrderRequiredDocId), dto.Status, dto.Satisfiable, dto.Notes, shared.OptionalInt64(dto.LoanOrderRequiredDocId), dto.Status, dto.Satisfiable, dto.Notes,
} }
} }
func updateArgs(dto loanorders.UpdateLoanOrderDTO) []interface{} { func updateArgs(dto loanorders.UpdateLoanOrderDTO) []interface{} {
return []interface{}{ return []interface{}{
dto.UniqueId, resolveSource(dto.Source), loanorders.FlexInt64Ptr(dto.UserId), dto.LoanType.Int64(), dto.Region, dto.BranchId.Int64(), dto.UniqueId, resolveSource(dto.Source), shared.OptionalInt64(dto.UserId), dto.LoanType.Int64(), dto.Region, dto.BranchId.Int64(),
dto.CustomerName, dto.CustomerSurname, dto.CustomerPatronicName, dto.CustomerName, dto.CustomerSurname, dto.CustomerPatronicName,
dto.PassportAddress, dto.RealAddress, dto.PassportSerie, dto.PassportId, dto.PassportGivenAt.Time(), dto.PassportGivenBy, dto.PassportAddress, dto.RealAddress, dto.PassportSerie, dto.PassportId, dto.PassportGivenAt.Time(), dto.PassportGivenBy,
dto.BornPlace, dto.BornAt.Time(), dto.Email, dto.Phone, dto.PhoneAdditional, dto.PhoneHome, dto.BornPlace, dto.BornAt.Time(), dto.Email, dto.Phone, dto.PhoneAdditional, dto.PhoneHome,
dto.WorkRegion, loanorders.FlexInt64Ptr(dto.WorkProvinceId), dto.WorkCompany, dto.WorkCompanyAccountantNumber, loanorders.FlexTimePtr(dto.WorkStartedAt), dto.WorkRegion, shared.OptionalInt64(dto.WorkProvinceId), dto.WorkCompany, dto.WorkCompanyAccountantNumber, shared.OptionalTime(dto.WorkStartedAt),
dto.WorkSalary, dto.WorkPosition, dto.Education, dto.MarriageStatus, dto.WorkSalary, dto.WorkPosition, dto.Education, dto.MarriageStatus,
dto.PassportOne, dto.PassportTwo, dto.PassportThree, dto.PassportFour, dto.PassportOne, dto.PassportTwo, dto.PassportThree, dto.PassportFour,
dto.LoanAmount, dto.CardNumber, dto.CardName, dto.CardMonth, dto.CardYear, dto.LoanAmount, dto.CardNumber, dto.CardName, dto.CardMonth, dto.CardYear,
@@ -108,7 +108,7 @@ func updateArgs(dto loanorders.UpdateLoanOrderDTO) []interface{} {
dto.Guarantor2Name, dto.Guarantor2Surname, dto.Guarantor2PatronicName, dto.Guarantor2PassportSerie, dto.Guarantor2PassportId, dto.Guarantor2Name, dto.Guarantor2Surname, dto.Guarantor2PatronicName, dto.Guarantor2PassportSerie, dto.Guarantor2PassportId,
dto.Guarantor2CardNumber, dto.Guarantor2CardName, dto.Guarantor2CardMonth, dto.Guarantor2CardYear, dto.Guarantor2Note, dto.Guarantor2CardNumber, dto.Guarantor2CardName, dto.Guarantor2CardMonth, dto.Guarantor2CardYear, dto.Guarantor2Note,
dto.LoanCardNumber, dto.LoanCardName, dto.LoanCardMonth, dto.LoanCardYear, dto.LoanCardNumber, dto.LoanCardName, dto.LoanCardMonth, dto.LoanCardYear,
loanorders.FlexInt64Ptr(dto.LoanOrderRequiredDocId), dto.Status, dto.Satisfiable, dto.Notes, shared.OptionalInt64(dto.LoanOrderRequiredDocId), dto.Status, dto.Satisfiable, dto.Notes,
} }
} }

View File

@@ -3,7 +3,7 @@ package loanorders
import ( import (
"time" "time"
"online-back/internal/lending/shared" "online-back/internal/shared"
) )
type LoanOrderDTO struct { type LoanOrderDTO struct {
@@ -85,143 +85,143 @@ type LoanOrderDTO struct {
} }
type CreateLoanOrderDTO struct { type CreateLoanOrderDTO struct {
Source string `json:"source"` Source string `json:"source"`
UserId *FlexibleInt64 `json:"userId" swaggertype:"integer"` UserId *shared.FlexibleInt64 `json:"userId" swaggertype:"integer"`
UniqueId *string `json:"uniqueId"` UniqueId *string `json:"uniqueId"`
LoanType FlexibleInt64 `json:"loanType" binding:"required" swaggertype:"integer"` LoanType shared.FlexibleInt64 `json:"loanType" binding:"required" swaggertype:"integer"`
Region string `json:"region" binding:"required"` Region string `json:"region" binding:"required"`
BranchId FlexibleInt64 `json:"branchId" binding:"required" swaggertype:"integer"` BranchId shared.FlexibleInt64 `json:"branchId" binding:"required" swaggertype:"integer"`
CustomerName string `json:"customerName" binding:"required"` CustomerName string `json:"customerName" binding:"required"`
CustomerSurname string `json:"customerSurname" binding:"required"` CustomerSurname string `json:"customerSurname" binding:"required"`
CustomerPatronicName *string `json:"customerPatronicName"` CustomerPatronicName *string `json:"customerPatronicName"`
PassportAddress string `json:"passportAddress" binding:"required"` PassportAddress string `json:"passportAddress" binding:"required"`
RealAddress string `json:"realAddress" binding:"required"` RealAddress string `json:"realAddress" binding:"required"`
PassportSerie string `json:"passportSerie" binding:"required"` PassportSerie string `json:"passportSerie" binding:"required"`
PassportId string `json:"passportId" binding:"required"` PassportId string `json:"passportId" binding:"required"`
PassportGivenAt FlexibleTime `json:"passportGivenAt" binding:"required" swaggertype:"string" format:"date"` PassportGivenAt shared.FlexibleTime `json:"passportGivenAt" binding:"required" swaggertype:"string" format:"date"`
PassportGivenBy string `json:"passportGivenBy" binding:"required"` PassportGivenBy string `json:"passportGivenBy" binding:"required"`
BornPlace string `json:"bornPlace" binding:"required"` BornPlace string `json:"bornPlace" binding:"required"`
BornAt FlexibleTime `json:"bornAt" binding:"required" swaggertype:"string" format:"date"` BornAt shared.FlexibleTime `json:"bornAt" binding:"required" swaggertype:"string" format:"date"`
Email *string `json:"email"` Email *string `json:"email"`
Phone string `json:"phone" binding:"required"` Phone string `json:"phone" binding:"required"`
PhoneAdditional *string `json:"phoneAdditional"` PhoneAdditional *string `json:"phoneAdditional"`
PhoneHome *string `json:"phoneHome"` PhoneHome *string `json:"phoneHome"`
WorkRegion *string `json:"workRegion"` WorkRegion *string `json:"workRegion"`
WorkProvinceId *FlexibleInt64 `json:"workProvinceId" swaggertype:"integer"` WorkProvinceId *shared.FlexibleInt64 `json:"workProvinceId" swaggertype:"integer"`
WorkCompany *string `json:"workCompany"` WorkCompany *string `json:"workCompany"`
WorkCompanyAccountantNumber *string `json:"workCompanyAccountantNumber"` WorkCompanyAccountantNumber *string `json:"workCompanyAccountantNumber"`
WorkStartedAt *FlexibleTime `json:"workStartedAt" swaggertype:"string" format:"date"` WorkStartedAt *shared.FlexibleTime `json:"workStartedAt" swaggertype:"string" format:"date"`
WorkSalary *string `json:"workSalary"` WorkSalary *string `json:"workSalary"`
WorkPosition *string `json:"workPosition"` WorkPosition *string `json:"workPosition"`
Education string `json:"education" binding:"required"` Education string `json:"education" binding:"required"`
MarriageStatus string `json:"marriageStatus" binding:"required"` MarriageStatus string `json:"marriageStatus" binding:"required"`
PassportOne string `json:"passportOne" binding:"required"` PassportOne string `json:"passportOne" binding:"required"`
PassportTwo string `json:"passportTwo" binding:"required"` PassportTwo string `json:"passportTwo" binding:"required"`
PassportThree string `json:"passportThree" binding:"required"` PassportThree string `json:"passportThree" binding:"required"`
PassportFour string `json:"passportFour" binding:"required"` PassportFour string `json:"passportFour" binding:"required"`
LoanAmount *string `json:"loanAmount"` LoanAmount *string `json:"loanAmount"`
CardNumber *string `json:"cardNumber"` CardNumber *string `json:"cardNumber"`
CardName *string `json:"cardName"` CardName *string `json:"cardName"`
CardMonth *string `json:"cardMonth"` CardMonth *string `json:"cardMonth"`
CardYear *string `json:"cardYear"` CardYear *string `json:"cardYear"`
GuarantorName *string `json:"guarantorName"` GuarantorName *string `json:"guarantorName"`
GuarantorSurname *string `json:"guarantorSurname"` GuarantorSurname *string `json:"guarantorSurname"`
GuarantorPatronicName *string `json:"guarantorPatronicName"` GuarantorPatronicName *string `json:"guarantorPatronicName"`
GuarantorPassportSerie *string `json:"guarantorPassportSerie"` GuarantorPassportSerie *string `json:"guarantorPassportSerie"`
GuarantorPassportId *string `json:"guarantorPassportId"` GuarantorPassportId *string `json:"guarantorPassportId"`
GuarantorCardNumber *string `json:"guarantorCardNumber"` GuarantorCardNumber *string `json:"guarantorCardNumber"`
GuarantorCardName *string `json:"guarantorCardName"` GuarantorCardName *string `json:"guarantorCardName"`
GuarantorCardMonth *string `json:"guarantorCardMonth"` GuarantorCardMonth *string `json:"guarantorCardMonth"`
GuarantorCardYear *string `json:"guarantorCardYear"` GuarantorCardYear *string `json:"guarantorCardYear"`
GuarantorNote *string `json:"guarantorNote"` GuarantorNote *string `json:"guarantorNote"`
Guarantor2Name *string `json:"guarantor2Name"` Guarantor2Name *string `json:"guarantor2Name"`
Guarantor2Surname *string `json:"guarantor2Surname"` Guarantor2Surname *string `json:"guarantor2Surname"`
Guarantor2PatronicName *string `json:"guarantor2PatronicName"` Guarantor2PatronicName *string `json:"guarantor2PatronicName"`
Guarantor2PassportSerie *string `json:"guarantor2PassportSerie"` Guarantor2PassportSerie *string `json:"guarantor2PassportSerie"`
Guarantor2PassportId *string `json:"guarantor2PassportId"` Guarantor2PassportId *string `json:"guarantor2PassportId"`
Guarantor2CardNumber *string `json:"guarantor2CardNumber"` Guarantor2CardNumber *string `json:"guarantor2CardNumber"`
Guarantor2CardName *string `json:"guarantor2CardName"` Guarantor2CardName *string `json:"guarantor2CardName"`
Guarantor2CardMonth *string `json:"guarantor2CardMonth"` Guarantor2CardMonth *string `json:"guarantor2CardMonth"`
Guarantor2CardYear *string `json:"guarantor2CardYear"` Guarantor2CardYear *string `json:"guarantor2CardYear"`
Guarantor2Note *string `json:"guarantor2Note"` Guarantor2Note *string `json:"guarantor2Note"`
LoanCardNumber *string `json:"loanCardNumber"` LoanCardNumber *string `json:"loanCardNumber"`
LoanCardName *string `json:"loanCardName"` LoanCardName *string `json:"loanCardName"`
LoanCardMonth *string `json:"loanCardMonth"` LoanCardMonth *string `json:"loanCardMonth"`
LoanCardYear *string `json:"loanCardYear"` LoanCardYear *string `json:"loanCardYear"`
LoanOrderRequiredDocId *FlexibleInt64 `json:"loanOrderRequiredDocId" swaggertype:"integer"` LoanOrderRequiredDocId *shared.FlexibleInt64 `json:"loanOrderRequiredDocId" swaggertype:"integer"`
Status *string `json:"status"` Status *string `json:"status"`
Satisfiable *string `json:"satisfiable"` Satisfiable *string `json:"satisfiable"`
Notes *string `json:"notes"` Notes *string `json:"notes"`
} }
type UpdateLoanOrderDTO struct { type UpdateLoanOrderDTO struct {
UniqueId *string `json:"uniqueId"` UniqueId *string `json:"uniqueId"`
Source string `json:"source"` Source string `json:"source"`
UserId *FlexibleInt64 `json:"userId" swaggertype:"integer"` UserId *shared.FlexibleInt64 `json:"userId" swaggertype:"integer"`
LoanType FlexibleInt64 `json:"loanType" binding:"required" swaggertype:"integer"` LoanType shared.FlexibleInt64 `json:"loanType" binding:"required" swaggertype:"integer"`
Region string `json:"region" binding:"required"` Region string `json:"region" binding:"required"`
BranchId FlexibleInt64 `json:"branchId" binding:"required" swaggertype:"integer"` BranchId shared.FlexibleInt64 `json:"branchId" binding:"required" swaggertype:"integer"`
CustomerName string `json:"customerName" binding:"required"` CustomerName string `json:"customerName" binding:"required"`
CustomerSurname string `json:"customerSurname" binding:"required"` CustomerSurname string `json:"customerSurname" binding:"required"`
CustomerPatronicName *string `json:"customerPatronicName"` CustomerPatronicName *string `json:"customerPatronicName"`
PassportAddress string `json:"passportAddress" binding:"required"` PassportAddress string `json:"passportAddress" binding:"required"`
RealAddress string `json:"realAddress" binding:"required"` RealAddress string `json:"realAddress" binding:"required"`
PassportSerie string `json:"passportSerie" binding:"required"` PassportSerie string `json:"passportSerie" binding:"required"`
PassportId string `json:"passportId" binding:"required"` PassportId string `json:"passportId" binding:"required"`
PassportGivenAt FlexibleTime `json:"passportGivenAt" binding:"required" swaggertype:"string" format:"date"` PassportGivenAt shared.FlexibleTime `json:"passportGivenAt" binding:"required" swaggertype:"string" format:"date"`
PassportGivenBy string `json:"passportGivenBy" binding:"required"` PassportGivenBy string `json:"passportGivenBy" binding:"required"`
BornPlace string `json:"bornPlace" binding:"required"` BornPlace string `json:"bornPlace" binding:"required"`
BornAt FlexibleTime `json:"bornAt" binding:"required" swaggertype:"string" format:"date"` BornAt shared.FlexibleTime `json:"bornAt" binding:"required" swaggertype:"string" format:"date"`
Email *string `json:"email"` Email *string `json:"email"`
Phone string `json:"phone" binding:"required"` Phone string `json:"phone" binding:"required"`
PhoneAdditional *string `json:"phoneAdditional"` PhoneAdditional *string `json:"phoneAdditional"`
PhoneHome *string `json:"phoneHome"` PhoneHome *string `json:"phoneHome"`
WorkRegion *string `json:"workRegion"` WorkRegion *string `json:"workRegion"`
WorkProvinceId *FlexibleInt64 `json:"workProvinceId" swaggertype:"integer"` WorkProvinceId *shared.FlexibleInt64 `json:"workProvinceId" swaggertype:"integer"`
WorkCompany *string `json:"workCompany"` WorkCompany *string `json:"workCompany"`
WorkCompanyAccountantNumber *string `json:"workCompanyAccountantNumber"` WorkCompanyAccountantNumber *string `json:"workCompanyAccountantNumber"`
WorkStartedAt *FlexibleTime `json:"workStartedAt" swaggertype:"string" format:"date"` WorkStartedAt *shared.FlexibleTime `json:"workStartedAt" swaggertype:"string" format:"date"`
WorkSalary *string `json:"workSalary"` WorkSalary *string `json:"workSalary"`
WorkPosition *string `json:"workPosition"` WorkPosition *string `json:"workPosition"`
Education string `json:"education" binding:"required"` Education string `json:"education" binding:"required"`
MarriageStatus string `json:"marriageStatus" binding:"required"` MarriageStatus string `json:"marriageStatus" binding:"required"`
PassportOne string `json:"passportOne" binding:"required"` PassportOne string `json:"passportOne" binding:"required"`
PassportTwo string `json:"passportTwo" binding:"required"` PassportTwo string `json:"passportTwo" binding:"required"`
PassportThree string `json:"passportThree" binding:"required"` PassportThree string `json:"passportThree" binding:"required"`
PassportFour string `json:"passportFour" binding:"required"` PassportFour string `json:"passportFour" binding:"required"`
LoanAmount *string `json:"loanAmount"` LoanAmount *string `json:"loanAmount"`
CardNumber *string `json:"cardNumber"` CardNumber *string `json:"cardNumber"`
CardName *string `json:"cardName"` CardName *string `json:"cardName"`
CardMonth *string `json:"cardMonth"` CardMonth *string `json:"cardMonth"`
CardYear *string `json:"cardYear"` CardYear *string `json:"cardYear"`
GuarantorName *string `json:"guarantorName"` GuarantorName *string `json:"guarantorName"`
GuarantorSurname *string `json:"guarantorSurname"` GuarantorSurname *string `json:"guarantorSurname"`
GuarantorPatronicName *string `json:"guarantorPatronicName"` GuarantorPatronicName *string `json:"guarantorPatronicName"`
GuarantorPassportSerie *string `json:"guarantorPassportSerie"` GuarantorPassportSerie *string `json:"guarantorPassportSerie"`
GuarantorPassportId *string `json:"guarantorPassportId"` GuarantorPassportId *string `json:"guarantorPassportId"`
GuarantorCardNumber *string `json:"guarantorCardNumber"` GuarantorCardNumber *string `json:"guarantorCardNumber"`
GuarantorCardName *string `json:"guarantorCardName"` GuarantorCardName *string `json:"guarantorCardName"`
GuarantorCardMonth *string `json:"guarantorCardMonth"` GuarantorCardMonth *string `json:"guarantorCardMonth"`
GuarantorCardYear *string `json:"guarantorCardYear"` GuarantorCardYear *string `json:"guarantorCardYear"`
GuarantorNote *string `json:"guarantorNote"` GuarantorNote *string `json:"guarantorNote"`
Guarantor2Name *string `json:"guarantor2Name"` Guarantor2Name *string `json:"guarantor2Name"`
Guarantor2Surname *string `json:"guarantor2Surname"` Guarantor2Surname *string `json:"guarantor2Surname"`
Guarantor2PatronicName *string `json:"guarantor2PatronicName"` Guarantor2PatronicName *string `json:"guarantor2PatronicName"`
Guarantor2PassportSerie *string `json:"guarantor2PassportSerie"` Guarantor2PassportSerie *string `json:"guarantor2PassportSerie"`
Guarantor2PassportId *string `json:"guarantor2PassportId"` Guarantor2PassportId *string `json:"guarantor2PassportId"`
Guarantor2CardNumber *string `json:"guarantor2CardNumber"` Guarantor2CardNumber *string `json:"guarantor2CardNumber"`
Guarantor2CardName *string `json:"guarantor2CardName"` Guarantor2CardName *string `json:"guarantor2CardName"`
Guarantor2CardMonth *string `json:"guarantor2CardMonth"` Guarantor2CardMonth *string `json:"guarantor2CardMonth"`
Guarantor2CardYear *string `json:"guarantor2CardYear"` Guarantor2CardYear *string `json:"guarantor2CardYear"`
Guarantor2Note *string `json:"guarantor2Note"` Guarantor2Note *string `json:"guarantor2Note"`
LoanCardNumber *string `json:"loanCardNumber"` LoanCardNumber *string `json:"loanCardNumber"`
LoanCardName *string `json:"loanCardName"` LoanCardName *string `json:"loanCardName"`
LoanCardMonth *string `json:"loanCardMonth"` LoanCardMonth *string `json:"loanCardMonth"`
LoanCardYear *string `json:"loanCardYear"` LoanCardYear *string `json:"loanCardYear"`
LoanOrderRequiredDocId *FlexibleInt64 `json:"loanOrderRequiredDocId" swaggertype:"integer"` LoanOrderRequiredDocId *shared.FlexibleInt64 `json:"loanOrderRequiredDocId" swaggertype:"integer"`
Status *string `json:"status"` Status *string `json:"status"`
Satisfiable *string `json:"satisfiable"` Satisfiable *string `json:"satisfiable"`
Notes *string `json:"notes"` Notes *string `json:"notes"`
} }
type ListFilter struct { type ListFilter struct {

View File

@@ -1,127 +0,0 @@
package loanorders
import (
"encoding/json"
"strconv"
"strings"
"time"
)
type FlexibleTime time.Time
func (t FlexibleTime) Time() time.Time { return time.Time(t) }
func (t FlexibleTime) IsZero() bool { return time.Time(t).IsZero() }
func (t FlexibleTime) MarshalJSON() ([]byte, error) {
return time.Time(t).MarshalJSON()
}
func (t *FlexibleTime) UnmarshalJSON(b []byte) error {
*t = FlexibleTime{}
raw := strings.TrimSpace(string(b))
if raw == "" || raw == "null" {
return nil
}
var n json.Number
if err := json.Unmarshal(b, &n); err == nil {
s := n.String()
if parsed, ok := parseFlexibleTime(s); ok {
*t = parsed
return nil
}
if unix, err := n.Int64(); err == nil && unix > 0 {
*t = FlexibleTime(time.Unix(unix, 0).UTC())
}
return nil
}
var s string
if err := json.Unmarshal(b, &s); err != nil {
return nil
}
if parsed, ok := parseFlexibleTime(s); ok {
*t = parsed
}
return nil
}
func parseFlexibleTime(s string) (FlexibleTime, bool) {
s = strings.TrimSpace(s)
if s == "" {
return FlexibleTime{}, false
}
switch strings.ToLower(s) {
case "string", "undefined", "null", "none", "invalid", "nan", "-":
return FlexibleTime{}, false
}
for _, layout := range []string{
time.RFC3339Nano,
time.RFC3339,
"2006-01-02T15:04:05Z07:00",
"2006-01-02T15:04:05.000Z",
"2006-01-02T15:04:05",
"2006-01-02 15:04:05",
"2006-01-02",
"02.01.2006",
"02/01/2006",
"02-01-2006",
"2006/01/02",
"20060102",
} {
if parsed, err := time.Parse(layout, s); err == nil {
return FlexibleTime(parsed), true
}
}
return FlexibleTime{}, false
}
type FlexibleInt64 int64
func (n FlexibleInt64) Int64() int64 { return int64(n) }
func (n *FlexibleInt64) UnmarshalJSON(b []byte) error {
if string(b) == "null" {
*n = 0
return nil
}
var v int64
if err := json.Unmarshal(b, &v); err == nil {
*n = FlexibleInt64(v)
return nil
}
var s string
if err := json.Unmarshal(b, &s); err != nil {
return err
}
s = strings.TrimSpace(s)
if s == "" {
*n = 0
return nil
}
v, err := strconv.ParseInt(s, 10, 64)
if err != nil {
return err
}
*n = FlexibleInt64(v)
return nil
}
func FlexInt64Ptr(v *FlexibleInt64) *int64 {
if v == nil {
return nil
}
i := v.Int64()
return &i
}
func FlexTimePtr(v *FlexibleTime) *time.Time {
if v == nil || v.IsZero() {
return nil
}
t := v.Time()
return &t
}

View File

@@ -9,6 +9,7 @@ import (
"online-back/internal/appresult" "online-back/internal/appresult"
"online-back/internal/handlers" "online-back/internal/handlers"
"online-back/internal/identity/rbac" "online-back/internal/identity/rbac"
"online-back/internal/shared"
"online-back/pkg/logging" "online-back/pkg/logging"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
@@ -112,7 +113,7 @@ func (h *handler) respondList(c *gin.Context, filter ListFilter) {
// @Failure 500 {object} appresult.AppError // @Failure 500 {object} appresult.AppError
// @Router /loan-orders/{id} [get] // @Router /loan-orders/{id} [get]
func (h *handler) getByID(c *gin.Context) { func (h *handler) getByID(c *gin.Context) {
id, ok := parseID(c.Param("id")) id, ok := shared.ParseID(c.Param("id"))
if !ok { if !ok {
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam) c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
return return
@@ -183,7 +184,7 @@ func (h *handler) create(c *gin.Context) {
// @Failure 500 {object} appresult.AppError // @Failure 500 {object} appresult.AppError
// @Router /loan-orders/{id} [put] // @Router /loan-orders/{id} [put]
func (h *handler) update(c *gin.Context) { func (h *handler) update(c *gin.Context) {
id, ok := parseID(c.Param("id")) id, ok := shared.ParseID(c.Param("id"))
if !ok { if !ok {
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam) c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
return return
@@ -226,7 +227,7 @@ func (h *handler) update(c *gin.Context) {
// @Failure 500 {object} appresult.AppError // @Failure 500 {object} appresult.AppError
// @Router /loan-orders/{id} [delete] // @Router /loan-orders/{id} [delete]
func (h *handler) delete(c *gin.Context) { func (h *handler) delete(c *gin.Context) {
id, ok := parseID(c.Param("id")) id, ok := shared.ParseID(c.Param("id"))
if !ok { if !ok {
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam) c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
return return
@@ -248,28 +249,14 @@ func (h *handler) delete(c *gin.Context) {
c.JSON(http.StatusOK, appresult.SuccessWithData("loan order removed")) c.JSON(http.StatusOK, appresult.SuccessWithData("loan order removed"))
} }
func parseID(raw string) (int64, bool) {
id, err := strconv.ParseInt(raw, 10, 64)
if err != nil || id <= 0 {
return 0, false
}
return id, true
}
const (
defaultPage = 1
defaultLimit = 10
maxLimit = 100
)
func parseListFilter(c *gin.Context) (ListFilter, bool) { func parseListFilter(c *gin.Context) (ListFilter, bool) {
filter := ListFilter{ filter := ListFilter{
Page: defaultPage, Page: shared.DefaultPage,
Limit: defaultLimit, Limit: shared.DefaultLimit,
} }
if raw := queryValue(c, "branch_id", "branchId"); raw != "" { if raw := queryValue(c, "branch_id", "branchId"); raw != "" {
id, ok := parseID(raw) id, ok := shared.ParseID(raw)
if !ok { if !ok {
return ListFilter{}, false return ListFilter{}, false
} }
@@ -277,7 +264,7 @@ func parseListFilter(c *gin.Context) (ListFilter, bool) {
} }
if raw := queryValue(c, "user_id", "userId"); raw != "" { if raw := queryValue(c, "user_id", "userId"); raw != "" {
id, ok := parseID(raw) id, ok := shared.ParseID(raw)
if !ok { if !ok {
return ListFilter{}, false return ListFilter{}, false
} }
@@ -297,8 +284,8 @@ func parseListFilter(c *gin.Context) (ListFilter, bool) {
if err != nil || limit < 1 { if err != nil || limit < 1 {
return ListFilter{}, false return ListFilter{}, false
} }
if limit > maxLimit { if limit > shared.MaxLimit {
limit = maxLimit limit = shared.MaxLimit
} }
filter.Limit = limit filter.Limit = limit
} }

View File

@@ -7,7 +7,7 @@ import (
"online-back/internal/identity/rbac" "online-back/internal/identity/rbac"
"online-back/internal/lending/loanpaidletter" "online-back/internal/lending/loanpaidletter"
"online-back/internal/lending/shared" "online-back/internal/shared"
"online-back/pkg/client/postgresql" "online-back/pkg/client/postgresql"
"online-back/pkg/logging" "online-back/pkg/logging"
"online-back/pkg/repository/genericrepo" "online-back/pkg/repository/genericrepo"
@@ -111,12 +111,12 @@ func buildListQuery(filter loanpaidletter.ListFilter) (whereClause string, args
var conditions []string var conditions []string
if filter.PassportId != "" { if filter.PassportId != "" {
args = append(args, likePattern(filter.PassportId)) args = append(args, shared.LikePattern(filter.PassportId))
conditions = append(conditions, fmt.Sprintf("l.passport_id ILIKE $%d", len(args))) conditions = append(conditions, fmt.Sprintf("l.passport_id ILIKE $%d", len(args)))
} }
if filter.Name != "" { if filter.Name != "" {
args = append(args, likePattern(filter.Name)) args = append(args, shared.LikePattern(filter.Name))
n := len(args) n := len(args)
conditions = append(conditions, fmt.Sprintf(`( conditions = append(conditions, fmt.Sprintf(`(
l.customer_name ILIKE $%[1]d OR l.customer_surname ILIKE $%[1]d OR COALESCE(l.customer_patronic_name, '') ILIKE $%[1]d l.customer_name ILIKE $%[1]d OR l.customer_surname ILIKE $%[1]d OR COALESCE(l.customer_patronic_name, '') ILIKE $%[1]d
@@ -152,13 +152,6 @@ func buildListQuery(filter loanpaidletter.ListFilter) (whereClause string, args
return " WHERE " + strings.Join(conditions, " AND "), 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) ListBranchesByProvince(ctx context.Context, provinceID int64, activeOnly bool) (loanpaidletter.ListBranchesByProvinceDTO, error) { func (r *repository) ListBranchesByProvince(ctx context.Context, provinceID int64, activeOnly bool) (loanpaidletter.ListBranchesByProvinceDTO, error) {
args := []interface{}{provinceID} args := []interface{}{provinceID}
where := ` WHERE province_id = $1` where := ` WHERE province_id = $1`

View File

@@ -3,7 +3,7 @@ package loanpaidletter
import ( import (
"time" "time"
"online-back/internal/lending/shared" "online-back/internal/shared"
) )
type LoanPaidLetterDTO struct { type LoanPaidLetterDTO struct {

View File

@@ -9,6 +9,7 @@ import (
"online-back/internal/appresult" "online-back/internal/appresult"
"online-back/internal/handlers" "online-back/internal/handlers"
"online-back/internal/identity/rbac" "online-back/internal/identity/rbac"
"online-back/internal/shared"
"online-back/pkg/logging" "online-back/pkg/logging"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
@@ -83,7 +84,7 @@ func (h *handler) list(c *gin.Context) {
// @Failure 500 {object} appresult.AppError // @Failure 500 {object} appresult.AppError
// @Router /loan-paid-off-letters/branches [get] // @Router /loan-paid-off-letters/branches [get]
func (h *handler) listBranchesByProvince(c *gin.Context) { func (h *handler) listBranchesByProvince(c *gin.Context) {
provinceID, ok := parseID(c.Query("province_id")) provinceID, ok := shared.ParseID(c.Query("province_id"))
if !ok { if !ok {
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam) c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
return return
@@ -122,7 +123,7 @@ func (h *handler) listBranchesByProvince(c *gin.Context) {
// @Failure 500 {object} appresult.AppError // @Failure 500 {object} appresult.AppError
// @Router /loan-paid-off-letters/{id} [get] // @Router /loan-paid-off-letters/{id} [get]
func (h *handler) getByID(c *gin.Context) { func (h *handler) getByID(c *gin.Context) {
id, ok := parseID(c.Param("id")) id, ok := shared.ParseID(c.Param("id"))
if !ok { if !ok {
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam) c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
return return
@@ -189,7 +190,7 @@ func (h *handler) create(c *gin.Context) {
// @Failure 500 {object} appresult.AppError // @Failure 500 {object} appresult.AppError
// @Router /loan-paid-off-letters/{id} [put] // @Router /loan-paid-off-letters/{id} [put]
func (h *handler) update(c *gin.Context) { func (h *handler) update(c *gin.Context) {
id, ok := parseID(c.Param("id")) id, ok := shared.ParseID(c.Param("id"))
if !ok { if !ok {
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam) c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
return return
@@ -232,7 +233,7 @@ func (h *handler) update(c *gin.Context) {
// @Failure 500 {object} appresult.AppError // @Failure 500 {object} appresult.AppError
// @Router /loan-paid-off-letters/{id} [delete] // @Router /loan-paid-off-letters/{id} [delete]
func (h *handler) delete(c *gin.Context) { func (h *handler) delete(c *gin.Context) {
id, ok := parseID(c.Param("id")) id, ok := shared.ParseID(c.Param("id"))
if !ok { if !ok {
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam) c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
return return
@@ -254,24 +255,10 @@ func (h *handler) delete(c *gin.Context) {
c.JSON(http.StatusOK, appresult.SuccessWithData("loan paid off letter removed")) c.JSON(http.StatusOK, appresult.SuccessWithData("loan paid off letter 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) { func parseListFilter(c *gin.Context) (ListFilter, bool) {
filter := ListFilter{ filter := ListFilter{
Page: defaultPage, Page: shared.DefaultPage,
Limit: defaultLimit, Limit: shared.DefaultLimit,
} }
if raw := c.Query("page"); raw != "" { if raw := c.Query("page"); raw != "" {
@@ -284,7 +271,7 @@ func parseListFilter(c *gin.Context) (ListFilter, bool) {
if raw := c.Query("limit"); raw != "" { if raw := c.Query("limit"); raw != "" {
limit, err := strconv.Atoi(raw) limit, err := strconv.Atoi(raw)
if err != nil || limit < 1 || limit > maxLimit { if err != nil || limit < 1 || limit > shared.MaxLimit {
return ListFilter{}, false return ListFilter{}, false
} }
filter.Limit = limit filter.Limit = limit
@@ -307,7 +294,7 @@ func parseListFilter(c *gin.Context) (ListFilter, bool) {
} }
if raw := c.Query("branch_id"); raw != "" { if raw := c.Query("branch_id"); raw != "" {
id, ok := parseID(raw) id, ok := shared.ParseID(raw)
if !ok { if !ok {
return ListFilter{}, false return ListFilter{}, false
} }
@@ -319,7 +306,7 @@ func parseListFilter(c *gin.Context) (ListFilter, bool) {
raw = strings.TrimSpace(c.Query("userId")) raw = strings.TrimSpace(c.Query("userId"))
} }
if raw != "" { if raw != "" {
id, ok := parseID(raw) id, ok := shared.ParseID(raw)
if !ok { if !ok {
return ListFilter{}, false return ListFilter{}, false
} }

View File

@@ -7,6 +7,7 @@ import (
"strings" "strings"
"online-back/internal/lending/loansdocument" "online-back/internal/lending/loansdocument"
"online-back/internal/shared"
"online-back/pkg/client/postgresql" "online-back/pkg/client/postgresql"
"online-back/pkg/logging" "online-back/pkg/logging"
"online-back/pkg/repository/genericrepo" "online-back/pkg/repository/genericrepo"
@@ -47,7 +48,7 @@ func buildListQuery(filter loansdocument.ListFilter) (whereClause string, args [
var conditions []string var conditions []string
if filter.DocumentName != "" { if filter.DocumentName != "" {
args = append(args, likePattern(filter.DocumentName)) args = append(args, shared.LikePattern(filter.DocumentName))
n := len(args) n := len(args)
conditions = append(conditions, fmt.Sprintf(`d.name ILIKE $%d`, n)) conditions = append(conditions, fmt.Sprintf(`d.name ILIKE $%d`, n))
} }
@@ -64,13 +65,6 @@ func buildListQuery(filter loansdocument.ListFilter) (whereClause string, args [
return " WHERE " + strings.Join(conditions, " AND "), 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) (loansdocument.LoanDocumentDTO, error) { func (r *repository) GetByID(ctx context.Context, id int64) (loansdocument.LoanDocumentDTO, error) {
return r.generic.GetByID(ctx, id) return r.generic.GetByID(ctx, id)
} }

View File

@@ -8,6 +8,7 @@ import (
"online-back/internal/appresult" "online-back/internal/appresult"
"online-back/internal/handlers" "online-back/internal/handlers"
"online-back/internal/shared"
"online-back/pkg/logging" "online-back/pkg/logging"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
@@ -79,7 +80,7 @@ func (h *handler) list(c *gin.Context) {
// @Failure 500 {object} appresult.AppError // @Failure 500 {object} appresult.AppError
// @Router /loans-documents/{id} [get] // @Router /loans-documents/{id} [get]
func (h *handler) getByID(c *gin.Context) { func (h *handler) getByID(c *gin.Context) {
id, ok := parseID(c.Param("id")) id, ok := shared.ParseID(c.Param("id"))
if !ok { if !ok {
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam) c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
return return
@@ -143,7 +144,7 @@ func (h *handler) create(c *gin.Context) {
// @Failure 500 {object} appresult.AppError // @Failure 500 {object} appresult.AppError
// @Router /loans-documents/{id} [put] // @Router /loans-documents/{id} [put]
func (h *handler) update(c *gin.Context) { func (h *handler) update(c *gin.Context) {
id, ok := parseID(c.Param("id")) id, ok := shared.ParseID(c.Param("id"))
if !ok { if !ok {
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam) c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
return return
@@ -184,7 +185,7 @@ func (h *handler) update(c *gin.Context) {
// @Failure 500 {object} appresult.AppError // @Failure 500 {object} appresult.AppError
// @Router /loans-documents/{id}/active [put] // @Router /loans-documents/{id}/active [put]
func (h *handler) updateActive(c *gin.Context) { func (h *handler) updateActive(c *gin.Context) {
id, ok := parseID(c.Param("id")) id, ok := shared.ParseID(c.Param("id"))
if !ok { if !ok {
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam) c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
return return
@@ -223,7 +224,7 @@ func (h *handler) updateActive(c *gin.Context) {
// @Failure 500 {object} appresult.AppError // @Failure 500 {object} appresult.AppError
// @Router /loans-documents/{id} [delete] // @Router /loans-documents/{id} [delete]
func (h *handler) delete(c *gin.Context) { func (h *handler) delete(c *gin.Context) {
id, ok := parseID(c.Param("id")) id, ok := shared.ParseID(c.Param("id"))
if !ok { if !ok {
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam) c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
return return
@@ -241,24 +242,10 @@ func (h *handler) delete(c *gin.Context) {
c.JSON(http.StatusOK, appresult.SuccessWithData("loan document removed")) c.JSON(http.StatusOK, appresult.SuccessWithData("loan document 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) { func parseListFilter(c *gin.Context) (ListFilter, bool) {
filter := ListFilter{ filter := ListFilter{
Page: defaultPage, Page: shared.DefaultPage,
Limit: defaultLimit, Limit: shared.DefaultLimit,
} }
if raw := c.Query("page"); raw != "" { if raw := c.Query("page"); raw != "" {
@@ -271,7 +258,7 @@ func parseListFilter(c *gin.Context) (ListFilter, bool) {
if raw := c.Query("limit"); raw != "" { if raw := c.Query("limit"); raw != "" {
limit, err := strconv.Atoi(raw) limit, err := strconv.Atoi(raw)
if err != nil || limit < 1 || limit > maxLimit { if err != nil || limit < 1 || limit > shared.MaxLimit {
return ListFilter{}, false return ListFilter{}, false
} }
filter.Limit = limit filter.Limit = limit

View File

@@ -8,7 +8,7 @@ import (
"online-back/internal/identity/rbac" "online-back/internal/identity/rbac"
"online-back/internal/lending/loansrepayment" "online-back/internal/lending/loansrepayment"
"online-back/internal/lending/shared" "online-back/internal/shared"
"online-back/pkg/client/postgresql" "online-back/pkg/client/postgresql"
"online-back/pkg/logging" "online-back/pkg/logging"
"online-back/pkg/repository/genericrepo" "online-back/pkg/repository/genericrepo"
@@ -77,7 +77,7 @@ func (r *repository) List(ctx context.Context, filter loansrepayment.ListFilter)
func buildListQuery(filter loansrepayment.ListFilter) (whereClause string, args []interface{}) { func buildListQuery(filter loansrepayment.ListFilter) (whereClause string, args []interface{}) {
var conditions []string var conditions []string
if filter.PassportId != "" { if filter.PassportId != "" {
args = append(args, likePattern(filter.PassportId)) args = append(args, shared.LikePattern(filter.PassportId))
conditions = append(conditions, fmt.Sprintf("l.passport_id ILIKE $%d", len(args))) conditions = append(conditions, fmt.Sprintf("l.passport_id ILIKE $%d", len(args)))
} }
@@ -98,13 +98,6 @@ func buildListQuery(filter loansrepayment.ListFilter) (whereClause string, args
return " WHERE " + strings.Join(conditions, " AND "), 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) (loansrepayment.LoanRepaymentDTO, error) { func (r *repository) GetByID(ctx context.Context, id int64) (loansrepayment.LoanRepaymentDTO, error) {
query := `SELECT ` + loanColumns + loanFromClause + ` WHERE l.id = $1` query := `SELECT ` + loanColumns + loanFromClause + ` WHERE l.id = $1`
return scanLoanRepayment(r.client.QueryRow(ctx, query, id)) return scanLoanRepayment(r.client.QueryRow(ctx, query, id))

View File

@@ -3,7 +3,7 @@ package loansrepayment
import ( import (
"time" "time"
"online-back/internal/lending/shared" "online-back/internal/shared"
) )
type LoanRepaymentDTO struct { type LoanRepaymentDTO struct {

View File

@@ -9,6 +9,7 @@ import (
"online-back/internal/appresult" "online-back/internal/appresult"
"online-back/internal/handlers" "online-back/internal/handlers"
"online-back/internal/identity/rbac" "online-back/internal/identity/rbac"
"online-back/internal/shared"
"online-back/pkg/logging" "online-back/pkg/logging"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
@@ -78,7 +79,7 @@ func (h *handler) list(c *gin.Context) {
// @Failure 500 {object} appresult.AppError // @Failure 500 {object} appresult.AppError
// @Router /loans-repayment/{id} [get] // @Router /loans-repayment/{id} [get]
func (h *handler) getByID(c *gin.Context) { func (h *handler) getByID(c *gin.Context) {
id, ok := parseID(c.Param("id")) id, ok := shared.ParseID(c.Param("id"))
if !ok { if !ok {
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam) c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
return return
@@ -145,7 +146,7 @@ func (h *handler) create(c *gin.Context) {
// @Failure 500 {object} appresult.AppError // @Failure 500 {object} appresult.AppError
// @Router /loans-repayment/{id} [put] // @Router /loans-repayment/{id} [put]
func (h *handler) update(c *gin.Context) { func (h *handler) update(c *gin.Context) {
id, ok := parseID(c.Param("id")) id, ok := shared.ParseID(c.Param("id"))
if !ok { if !ok {
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam) c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
return return
@@ -188,7 +189,7 @@ func (h *handler) update(c *gin.Context) {
// @Failure 500 {object} appresult.AppError // @Failure 500 {object} appresult.AppError
// @Router /loans-repayment/{id} [delete] // @Router /loans-repayment/{id} [delete]
func (h *handler) delete(c *gin.Context) { func (h *handler) delete(c *gin.Context) {
id, ok := parseID(c.Param("id")) id, ok := shared.ParseID(c.Param("id"))
if !ok { if !ok {
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam) c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
return return
@@ -210,24 +211,10 @@ func (h *handler) delete(c *gin.Context) {
c.JSON(http.StatusOK, appresult.SuccessWithData("loan repayment removed")) c.JSON(http.StatusOK, appresult.SuccessWithData("loan repayment 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) { func parseListFilter(c *gin.Context) (ListFilter, bool) {
filter := ListFilter{ filter := ListFilter{
Page: defaultPage, Page: shared.DefaultPage,
Limit: defaultLimit, Limit: shared.DefaultLimit,
} }
if raw := c.Query("page"); raw != "" { if raw := c.Query("page"); raw != "" {
@@ -240,7 +227,7 @@ func parseListFilter(c *gin.Context) (ListFilter, bool) {
if raw := c.Query("limit"); raw != "" { if raw := c.Query("limit"); raw != "" {
limit, err := strconv.Atoi(raw) limit, err := strconv.Atoi(raw)
if err != nil || limit < 1 || limit > maxLimit { if err != nil || limit < 1 || limit > shared.MaxLimit {
return ListFilter{}, false return ListFilter{}, false
} }
filter.Limit = limit filter.Limit = limit
@@ -255,7 +242,7 @@ func parseListFilter(c *gin.Context) (ListFilter, bool) {
raw = strings.TrimSpace(c.Query("userId")) raw = strings.TrimSpace(c.Query("userId"))
} }
if raw != "" { if raw != "" {
id, ok := parseID(raw) id, ok := shared.ParseID(raw)
if !ok { if !ok {
return ListFilter{}, false return ListFilter{}, false
} }

View File

@@ -8,6 +8,7 @@ import (
"strings" "strings"
"online-back/internal/lending/loantype" "online-back/internal/lending/loantype"
"online-back/internal/shared"
"online-back/pkg/client/postgresql" "online-back/pkg/client/postgresql"
"online-back/pkg/logging" "online-back/pkg/logging"
"online-back/pkg/repository/genericrepo" "online-back/pkg/repository/genericrepo"
@@ -47,7 +48,7 @@ func (r *repository) List(ctx context.Context, filter loantype.ListFilter) (loan
func buildListQuery(filter loantype.ListFilter) (whereClause string, args []interface{}) { func buildListQuery(filter loantype.ListFilter) (whereClause string, args []interface{}) {
var conditions []string var conditions []string
if filter.LoanTypeName != "" { if filter.LoanTypeName != "" {
args = append(args, likePattern(filter.LoanTypeName)) args = append(args, shared.LikePattern(filter.LoanTypeName))
n := len(args) n := len(args)
conditions = append(conditions, fmt.Sprintf(`( conditions = append(conditions, fmt.Sprintf(`(
lt.name->>'en' ILIKE $%[1]d OR lt.name->>'ru' ILIKE $%[1]d OR lt.name->>'tm' ILIKE $%[1]d lt.name->>'en' ILIKE $%[1]d OR lt.name->>'ru' ILIKE $%[1]d OR lt.name->>'tm' ILIKE $%[1]d
@@ -61,13 +62,6 @@ func buildListQuery(filter loantype.ListFilter) (whereClause string, args []inte
return " WHERE " + strings.Join(conditions, " AND "), 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) (loantype.LoanTypeDTO, error) { func (r *repository) GetByID(ctx context.Context, id int64) (loantype.LoanTypeDTO, error) {
return r.generic.GetByID(ctx, id) return r.generic.GetByID(ctx, id)
} }

View File

@@ -8,6 +8,7 @@ import (
"online-back/internal/appresult" "online-back/internal/appresult"
"online-back/internal/handlers" "online-back/internal/handlers"
"online-back/internal/shared"
"online-back/pkg/logging" "online-back/pkg/logging"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
@@ -77,7 +78,7 @@ func (h *handler) list(c *gin.Context) {
// @Failure 500 {object} appresult.AppError // @Failure 500 {object} appresult.AppError
// @Router /loan-types/{id} [get] // @Router /loan-types/{id} [get]
func (h *handler) getByID(c *gin.Context) { func (h *handler) getByID(c *gin.Context) {
id, ok := parseID(c.Param("id")) id, ok := shared.ParseID(c.Param("id"))
if !ok { if !ok {
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam) c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
return return
@@ -141,7 +142,7 @@ func (h *handler) create(c *gin.Context) {
// @Failure 500 {object} appresult.AppError // @Failure 500 {object} appresult.AppError
// @Router /loan-types/{id} [put] // @Router /loan-types/{id} [put]
func (h *handler) update(c *gin.Context) { func (h *handler) update(c *gin.Context) {
id, ok := parseID(c.Param("id")) id, ok := shared.ParseID(c.Param("id"))
if !ok { if !ok {
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam) c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
return return
@@ -180,7 +181,7 @@ func (h *handler) update(c *gin.Context) {
// @Failure 500 {object} appresult.AppError // @Failure 500 {object} appresult.AppError
// @Router /loan-types/{id} [delete] // @Router /loan-types/{id} [delete]
func (h *handler) delete(c *gin.Context) { func (h *handler) delete(c *gin.Context) {
id, ok := parseID(c.Param("id")) id, ok := shared.ParseID(c.Param("id"))
if !ok { if !ok {
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam) c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
return return
@@ -198,24 +199,10 @@ func (h *handler) delete(c *gin.Context) {
c.JSON(http.StatusOK, appresult.SuccessWithData("loan type removed")) c.JSON(http.StatusOK, appresult.SuccessWithData("loan type 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) { func parseListFilter(c *gin.Context) (ListFilter, bool) {
filter := ListFilter{ filter := ListFilter{
Page: defaultPage, Page: shared.DefaultPage,
Limit: defaultLimit, Limit: shared.DefaultLimit,
} }
if raw := c.Query("page"); raw != "" { if raw := c.Query("page"); raw != "" {
@@ -228,7 +215,7 @@ func parseListFilter(c *gin.Context) (ListFilter, bool) {
if raw := c.Query("limit"); raw != "" { if raw := c.Query("limit"); raw != "" {
limit, err := strconv.Atoi(raw) limit, err := strconv.Atoi(raw)
if err != nil || limit < 1 || limit > maxLimit { if err != nil || limit < 1 || limit > shared.MaxLimit {
return ListFilter{}, false return ListFilter{}, false
} }
filter.Limit = limit filter.Limit = limit

View File

@@ -1,59 +0,0 @@
package shared
import (
"encoding/json"
"strings"
)
type LocalizedText struct {
En string `json:"en"`
Ru string `json:"ru"`
Tm string `json:"tm"`
}
type UserInfo struct {
Id int64 `json:"id"`
Name string `json:"name"`
Username string `json:"username"`
Phone string `json:"phone"`
Email string `json:"email"`
}
type NamedInfo struct {
Id int64 `json:"id"`
Name LocalizedText `json:"name"`
}
// TextInfo is for catalog rows whose name is a plain string (not localized JSON).
type TextInfo struct {
Id int64 `json:"id"`
Name string `json:"name"`
}
type BranchInfo struct {
Id int64 `json:"id"`
Name LocalizedText `json:"name"`
UniqueCode string `json:"uniqueCode,omitempty"`
}
const UserDisplaySQL = `COALESCE(NULLIF(TRIM(CONCAT_WS(' ', u.first_name, u.last_name)), ''), NULLIF(u.name, ''), u.username, '')`
const UserInfoSQL = UserDisplaySQL + `, COALESCE(u.username, ''), COALESCE(u.phone, ''), COALESCE(u.email, '')`
func PrefixedColumns(alias string, cols []string) string {
parts := make([]string, len(cols))
for i, col := range cols {
parts[i] = alias + "." + col
}
return strings.Join(parts, ", ")
}
func UnmarshalLocalized(raw []byte, dest *LocalizedText) error {
if len(raw) == 0 {
return nil
}
if err := json.Unmarshal(raw, dest); err != nil {
*dest = LocalizedText{}
}
return nil
}

View File

@@ -9,6 +9,7 @@ import (
"online-back/internal/identity/rbac" "online-back/internal/identity/rbac"
"online-back/internal/org/branches" "online-back/internal/org/branches"
"online-back/internal/shared"
"online-back/pkg/client/postgresql" "online-back/pkg/client/postgresql"
"online-back/pkg/logging" "online-back/pkg/logging"
"online-back/pkg/repository/genericrepo" "online-back/pkg/repository/genericrepo"
@@ -105,7 +106,7 @@ func buildListQuery(filter branches.ListFilter) (whereClause string, args []inte
} }
if filter.ProvinceName != "" { if filter.ProvinceName != "" {
args = append(args, likePattern(filter.ProvinceName)) args = append(args, shared.LikePattern(filter.ProvinceName))
n := len(args) n := len(args)
conditions = append(conditions, fmt.Sprintf(`( conditions = append(conditions, fmt.Sprintf(`(
p.name->>'en' ILIKE $%[1]d OR p.name->>'ru' ILIKE $%[1]d OR p.name->>'tm' ILIKE $%[1]d p.name->>'en' ILIKE $%[1]d OR p.name->>'ru' ILIKE $%[1]d OR p.name->>'tm' ILIKE $%[1]d
@@ -113,7 +114,7 @@ func buildListQuery(filter branches.ListFilter) (whereClause string, args []inte
} }
if filter.BranchName != "" { if filter.BranchName != "" {
args = append(args, likePattern(filter.BranchName)) args = append(args, shared.LikePattern(filter.BranchName))
n := len(args) n := len(args)
conditions = append(conditions, fmt.Sprintf(`( conditions = append(conditions, fmt.Sprintf(`(
b.name->>'en' ILIKE $%[1]d OR b.name->>'ru' ILIKE $%[1]d OR b.name->>'tm' ILIKE $%[1]d b.name->>'en' ILIKE $%[1]d OR b.name->>'ru' ILIKE $%[1]d OR b.name->>'tm' ILIKE $%[1]d
@@ -121,7 +122,7 @@ func buildListQuery(filter branches.ListFilter) (whereClause string, args []inte
} }
if filter.UniqueCode != "" { if filter.UniqueCode != "" {
args = append(args, likePattern(filter.UniqueCode)) args = append(args, shared.LikePattern(filter.UniqueCode))
n := len(args) n := len(args)
conditions = append(conditions, fmt.Sprintf("b.unique_code ILIKE $%d", n)) conditions = append(conditions, fmt.Sprintf("b.unique_code ILIKE $%d", n))
} }
@@ -137,13 +138,6 @@ func buildListQuery(filter branches.ListFilter) (whereClause string, args []inte
return " WHERE " + strings.Join(conditions, " AND "), 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) (branches.BranchDTO, error) { func (r *repository) GetByID(ctx context.Context, id int64) (branches.BranchDTO, error) {
query := fmt.Sprintf(`SELECT %s%s WHERE b.id = $1`, branchSelectColumns, branchFromClause) query := fmt.Sprintf(`SELECT %s%s WHERE b.id = $1`, branchSelectColumns, branchFromClause)
row := r.client.QueryRow(ctx, query, id) row := r.client.QueryRow(ctx, query, id)

View File

@@ -10,6 +10,7 @@ import (
"online-back/internal/handlers" "online-back/internal/handlers"
"online-back/internal/identity/rbac" "online-back/internal/identity/rbac"
"online-back/internal/org/province" "online-back/internal/org/province"
"online-back/internal/shared"
"online-back/pkg/logging" "online-back/pkg/logging"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
@@ -68,6 +69,11 @@ func (h *handler) list(c *gin.Context) {
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer) c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return return
} }
if !rbac.IsAdminGuard(c) {
for i := range result.Branches {
clearBranchSecrets(&result.Branches[i])
}
}
c.JSON(http.StatusOK, appresult.SuccessWithData(result)) c.JSON(http.StatusOK, appresult.SuccessWithData(result))
} }
@@ -148,7 +154,7 @@ func (h *handler) listEtraps(c *gin.Context) {
// @Failure 500 {object} appresult.AppError // @Failure 500 {object} appresult.AppError
// @Router /branches/{id} [get] // @Router /branches/{id} [get]
func (h *handler) getByID(c *gin.Context) { func (h *handler) getByID(c *gin.Context) {
id, ok := parseID(c.Param("id")) id, ok := shared.ParseID(c.Param("id"))
if !ok { if !ok {
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam) c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
return return
@@ -167,6 +173,9 @@ func (h *handler) getByID(c *gin.Context) {
if !rbac.GuardBranch(c, item.Id) { if !rbac.GuardBranch(c, item.Id) {
return return
} }
if !rbac.IsAdminGuard(c) {
clearBranchSecrets(&item)
}
c.JSON(http.StatusOK, appresult.SuccessWithData(item)) c.JSON(http.StatusOK, appresult.SuccessWithData(item))
} }
@@ -219,7 +228,7 @@ func (h *handler) create(c *gin.Context) {
// @Failure 500 {object} appresult.AppError // @Failure 500 {object} appresult.AppError
// @Router /branches/{id} [put] // @Router /branches/{id} [put]
func (h *handler) update(c *gin.Context) { func (h *handler) update(c *gin.Context) {
id, ok := parseID(c.Param("id")) id, ok := shared.ParseID(c.Param("id"))
if !ok { if !ok {
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam) c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
return return
@@ -262,7 +271,7 @@ func (h *handler) update(c *gin.Context) {
// @Failure 500 {object} appresult.AppError // @Failure 500 {object} appresult.AppError
// @Router /branches/{id} [delete] // @Router /branches/{id} [delete]
func (h *handler) delete(c *gin.Context) { func (h *handler) delete(c *gin.Context) {
id, ok := parseID(c.Param("id")) id, ok := shared.ParseID(c.Param("id"))
if !ok { if !ok {
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam) c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
return return
@@ -285,14 +294,6 @@ func isClientError(err error) bool {
return msg == "province not found" || msg == "unique code already exists" return msg == "province not found" || msg == "unique code already exists"
} }
func parseID(raw string) (int64, bool) {
id, err := strconv.ParseInt(raw, 10, 64)
if err != nil || id <= 0 {
return 0, false
}
return id, true
}
func parseActiveOnly(c *gin.Context, defaultValue bool) (bool, bool) { func parseActiveOnly(c *gin.Context, defaultValue bool) (bool, bool) {
raw := c.Query("active") raw := c.Query("active")
if raw == "" { if raw == "" {
@@ -305,20 +306,14 @@ func parseActiveOnly(c *gin.Context, defaultValue bool) (bool, bool) {
return active, true return active, true
} }
const (
defaultPage = 1
defaultLimit = 10
maxLimit = 100
)
func parseListFilter(c *gin.Context) (ListFilter, bool) { func parseListFilter(c *gin.Context) (ListFilter, bool) {
filter := ListFilter{ filter := ListFilter{
Page: defaultPage, Page: shared.DefaultPage,
Limit: defaultLimit, Limit: shared.DefaultLimit,
} }
if raw := c.Query("province_id"); raw != "" { if raw := c.Query("province_id"); raw != "" {
id, ok := parseID(raw) id, ok := shared.ParseID(raw)
if !ok { if !ok {
return ListFilter{}, false return ListFilter{}, false
} }
@@ -335,7 +330,7 @@ func parseListFilter(c *gin.Context) (ListFilter, bool) {
if raw := c.Query("limit"); raw != "" { if raw := c.Query("limit"); raw != "" {
limit, err := strconv.Atoi(raw) limit, err := strconv.Atoi(raw)
if err != nil || limit < 1 || limit > maxLimit { if err != nil || limit < 1 || limit > shared.MaxLimit {
return ListFilter{}, false return ListFilter{}, false
} }
filter.Limit = limit filter.Limit = limit
@@ -356,3 +351,17 @@ func parseListFilter(c *gin.Context) (ListFilter, bool) {
rbac.BindBranchIDs(c, &filter.BranchIds) rbac.BindBranchIDs(c, &filter.BranchIds)
return filter, true return filter, true
} }
func clearBranchSecrets(item *BranchDTO) {
if item == nil {
return
}
item.BillingUsername = ""
item.BillingPassword = ""
item.BillingSberUsername = ""
item.BillingSberPassword = ""
item.BillingVisaMasterUsername = ""
item.BillingVisaMasterPassword = ""
item.BillingSwiftUsername = ""
item.BillingSwiftPassword = ""
}

View File

@@ -8,6 +8,7 @@ import (
"strings" "strings"
"online-back/internal/org/province" "online-back/internal/org/province"
"online-back/internal/shared"
"online-back/pkg/client/postgresql" "online-back/pkg/client/postgresql"
"online-back/pkg/logging" "online-back/pkg/logging"
"online-back/pkg/repository/genericrepo" "online-back/pkg/repository/genericrepo"
@@ -116,7 +117,7 @@ func buildListQuery(filter province.ListFilter) (whereClause string, args []inte
var conditions []string var conditions []string
if filter.Name != "" { if filter.Name != "" {
args = append(args, likePattern(filter.Name)) args = append(args, shared.LikePattern(filter.Name))
n := len(args) n := len(args)
conditions = append(conditions, fmt.Sprintf(`( conditions = append(conditions, fmt.Sprintf(`(
name->>'en' ILIKE $%[1]d OR name->>'ru' ILIKE $%[1]d OR name->>'tm' ILIKE $%[1]d name->>'en' ILIKE $%[1]d OR name->>'ru' ILIKE $%[1]d OR name->>'tm' ILIKE $%[1]d
@@ -124,7 +125,7 @@ func buildListQuery(filter province.ListFilter) (whereClause string, args []inte
} }
if filter.Region != "" { if filter.Region != "" {
args = append(args, likePattern(filter.Region)) args = append(args, shared.LikePattern(filter.Region))
n := len(args) n := len(args)
conditions = append(conditions, fmt.Sprintf(`( conditions = append(conditions, fmt.Sprintf(`(
region->>'en' ILIKE $%[1]d OR region->>'ru' ILIKE $%[1]d OR region->>'tm' ILIKE $%[1]d region->>'en' ILIKE $%[1]d OR region->>'ru' ILIKE $%[1]d OR region->>'tm' ILIKE $%[1]d
@@ -143,13 +144,6 @@ func buildListQuery(filter province.ListFilter) (whereClause string, args []inte
return " WHERE " + strings.Join(conditions, " AND "), 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) (province.ProvinceDTO, error) { func (r *repository) GetByID(ctx context.Context, id int64) (province.ProvinceDTO, error) {
return r.generic.GetByID(ctx, id) return r.generic.GetByID(ctx, id)
} }

View File

@@ -8,6 +8,7 @@ import (
"online-back/internal/appresult" "online-back/internal/appresult"
"online-back/internal/handlers" "online-back/internal/handlers"
"online-back/internal/shared"
"online-back/pkg/logging" "online-back/pkg/logging"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
@@ -82,7 +83,7 @@ func (h *handler) list(c *gin.Context) {
// @Failure 500 {object} appresult.AppError // @Failure 500 {object} appresult.AppError
// @Router /provinces/{id} [get] // @Router /provinces/{id} [get]
func (h *handler) getByID(c *gin.Context) { func (h *handler) getByID(c *gin.Context) {
id, ok := parseID(c.Param("id")) id, ok := shared.ParseID(c.Param("id"))
if !ok { if !ok {
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam) c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
return return
@@ -146,7 +147,7 @@ func (h *handler) create(c *gin.Context) {
// @Failure 500 {object} appresult.AppError // @Failure 500 {object} appresult.AppError
// @Router /provinces/{id} [put] // @Router /provinces/{id} [put]
func (h *handler) update(c *gin.Context) { func (h *handler) update(c *gin.Context) {
id, ok := parseID(c.Param("id")) id, ok := shared.ParseID(c.Param("id"))
if !ok { if !ok {
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam) c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
return return
@@ -185,7 +186,7 @@ func (h *handler) update(c *gin.Context) {
// @Failure 500 {object} appresult.AppError // @Failure 500 {object} appresult.AppError
// @Router /provinces/{id} [delete] // @Router /provinces/{id} [delete]
func (h *handler) delete(c *gin.Context) { func (h *handler) delete(c *gin.Context) {
id, ok := parseID(c.Param("id")) id, ok := shared.ParseID(c.Param("id"))
if !ok { if !ok {
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam) c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
return return
@@ -203,24 +204,10 @@ func (h *handler) delete(c *gin.Context) {
c.JSON(http.StatusOK, appresult.SuccessWithData("province removed")) c.JSON(http.StatusOK, appresult.SuccessWithData("province 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) { func parseListFilter(c *gin.Context) (ListFilter, bool) {
filter := ListFilter{ filter := ListFilter{
Page: defaultPage, Page: shared.DefaultPage,
Limit: defaultLimit, Limit: shared.DefaultLimit,
} }
if raw := c.Query("page"); raw != "" { if raw := c.Query("page"); raw != "" {
@@ -233,7 +220,7 @@ func parseListFilter(c *gin.Context) (ListFilter, bool) {
if raw := c.Query("limit"); raw != "" { if raw := c.Query("limit"); raw != "" {
limit, err := strconv.Atoi(raw) limit, err := strconv.Atoi(raw)
if err != nil || limit < 1 || limit > maxLimit { if err != nil || limit < 1 || limit > shared.MaxLimit {
return ListFilter{}, false return ListFilter{}, false
} }
filter.Limit = limit filter.Limit = limit

63
internal/shared/assoc.go Normal file
View File

@@ -0,0 +1,63 @@
package shared
import (
"context"
"errors"
"net/http"
"online-back/internal/appresult"
"online-back/pkg/logging"
"github.com/gin-gonic/gin"
"github.com/jackc/pgx/v4"
)
// AssocRepository is the storage contract shared by "association table"
// modules (role-users, permission-roles, permission-users, ...): a plain
// upsert-by-create plus a hard delete, with no list/get.
type AssocRepository[C any, T any] interface {
Create(ctx context.Context, dto C) (T, error)
Delete(ctx context.Context, id int64) error
}
// CreateAssoc handles the POST side of the association-table CRUD pattern:
// bind the body, create/upsert, respond. entityName is used in log lines
// only (e.g. "role user").
func CreateAssoc[C any, T any](c *gin.Context, logger *logging.Logger, repo AssocRepository[C, T], entityName string) {
var dto C
if err := c.ShouldBindJSON(&dto); err != nil {
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
return
}
item, err := repo.Create(c.Request.Context(), dto)
if err != nil {
logger.Errorf("create %s failed: %v", entityName, err)
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return
}
c.JSON(http.StatusCreated, appresult.SuccessWithData(item))
}
// DeleteAssoc handles the DELETE side of the association-table CRUD pattern:
// parse the id, delete, respond. entityName is used in both the log line and
// the success message (e.g. "role user" -> "role user removed").
func DeleteAssoc[C any, T any](c *gin.Context, logger *logging.Logger, repo AssocRepository[C, T], entityName string) {
id, ok := ParseID(c.Param("id"))
if !ok {
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
return
}
if err := repo.Delete(c.Request.Context(), id); errors.Is(err, pgx.ErrNoRows) {
c.JSON(http.StatusNotFound, appresult.ErrNotFound)
return
} else if err != nil {
logger.Errorf("delete %s failed: %v", entityName, err)
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return
}
c.JSON(http.StatusOK, appresult.SuccessWithData(entityName+" removed"))
}

View File

@@ -56,12 +56,9 @@ func ParsePageLimit(c *gin.Context) (page, limit int, ok bool) {
if raw := QueryValue(c, "limit"); raw != "" { if raw := QueryValue(c, "limit"); raw != "" {
l, err := strconv.Atoi(raw) l, err := strconv.Atoi(raw)
if err != nil || l < 1 { if err != nil || l < 1 || l > MaxLimit {
return 0, 0, false return 0, 0, false
} }
if l > MaxLimit {
l = MaxLimit
}
limit = l limit = l
} }

11
internal/shared/query.go Normal file
View File

@@ -0,0 +1,11 @@
package shared
import "strings"
// LikePattern escapes SQL LIKE metacharacters and wraps term for a %term% match.
func LikePattern(term string) string {
term = strings.ReplaceAll(term, `\`, `\\`)
term = strings.ReplaceAll(term, `%`, `\%`)
term = strings.ReplaceAll(term, `_`, `\_`)
return "%" + term + "%"
}

View File

@@ -8,6 +8,8 @@ import (
const UserDisplaySQL = `COALESCE(NULLIF(TRIM(CONCAT_WS(' ', u.first_name, u.last_name)), ''), NULLIF(u.name, ''), u.username, '')` const UserDisplaySQL = `COALESCE(NULLIF(TRIM(CONCAT_WS(' ', u.first_name, u.last_name)), ''), NULLIF(u.name, ''), u.username, '')`
const UserInfoSQL = UserDisplaySQL + `, COALESCE(u.username, ''), COALESCE(u.phone, ''), COALESCE(u.email, '')`
func PrefixedColumns(alias string, cols []string) string { func PrefixedColumns(alias string, cols []string) string {
parts := make([]string, len(cols)) parts := make([]string, len(cols))
for i, col := range cols { for i, col := range cols {

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