Put the user's role and branch on GET /profile, upsert role_user and branch_user on POST, and drop their list endpoints.
Also accept flexible card-order form values, move mock seed under db/mock, and regenerate Swagger. Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
2
Makefile
2
Makefile
@@ -12,7 +12,7 @@ migrate:
|
||||
migrate-rollback:
|
||||
migrate -database 'postgres://bank_admin:bank%40%2323%23%40_password@localhost:5424/bank_db?sslmode=disable' -path db/migrations down
|
||||
seed:
|
||||
docker exec -i main-db psql -U bank_admin -d bank_db -f - < db/seed.sql
|
||||
docker exec -i main-db psql -U bank_admin -d bank_db -f - < db/mock/seed.sql
|
||||
|
||||
# ---- for linux
|
||||
# migrate:
|
||||
|
||||
@@ -47,6 +47,10 @@ CREATE TABLE IF NOT EXISTS roles (
|
||||
updated_at TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL
|
||||
);
|
||||
|
||||
INSERT INTO roles (code, name, guard_name)
|
||||
SELECT 'user', 'User', 'web'
|
||||
WHERE NOT EXISTS (SELECT 1 FROM roles WHERE code = 'user');
|
||||
|
||||
CREATE TABLE IF NOT EXISTS permissions (
|
||||
id bigserial PRIMARY KEY,
|
||||
code character varying(255) NOT NULL DEFAULT '',
|
||||
@@ -174,7 +178,7 @@ CREATE TABLE IF NOT EXISTS card_orders (
|
||||
unique_id character varying(255),
|
||||
card_state_id bigint NOT NULL,
|
||||
card_type_id bigint NOT NULL,
|
||||
region character varying(2) NOT NULL,
|
||||
region character varying(255) NOT NULL,
|
||||
branch_id bigint NOT NULL,
|
||||
customer_name character varying(255) NOT NULL,
|
||||
customer_surname character varying(255) NOT NULL,
|
||||
|
||||
@@ -1 +0,0 @@
|
||||
DROP TABLE IF EXISTS visa_master_payment_orders;
|
||||
@@ -1,33 +0,0 @@
|
||||
CREATE TABLE IF NOT EXISTS visa_master_payment_orders (
|
||||
id bigserial PRIMARY KEY,
|
||||
unique_id character varying(255),
|
||||
type character varying(255),
|
||||
passport_name character varying(255) NOT NULL,
|
||||
passport_surname character varying(255) NOT NULL,
|
||||
phone character varying(255) NOT NULL,
|
||||
email character varying(255),
|
||||
region character varying(255) NOT NULL,
|
||||
branch_id bigint NOT NULL,
|
||||
user_id bigint,
|
||||
address character varying(255) NOT NULL,
|
||||
sender_datas json DEFAULT '{}'::json,
|
||||
payment_reciever json DEFAULT '[]'::json,
|
||||
documents json DEFAULT '{}'::json,
|
||||
status character varying(255) DEFAULT 'pending',
|
||||
notes character varying(255),
|
||||
sender_full_name character varying(255) NOT NULL,
|
||||
sender_passport_serie character varying(255) NOT NULL,
|
||||
sender_passport_number character varying(255) NOT NULL,
|
||||
sender_deposit_account character varying(255) NOT NULL,
|
||||
reciever_full_name character varying(255),
|
||||
reciever_passport_serie character varying(255),
|
||||
reciever_passport_number character varying(255),
|
||||
reciever_deposit_account character varying(255),
|
||||
paid boolean NOT NULL DEFAULT false,
|
||||
created_at TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL,
|
||||
updated_at TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL,
|
||||
CONSTRAINT visa_master_payment_orders_branch_id_fkey
|
||||
FOREIGN KEY (branch_id) REFERENCES branches(id),
|
||||
CONSTRAINT visa_master_payment_orders_user_id_fkey
|
||||
FOREIGN KEY (user_id) REFERENCES users(id)
|
||||
);
|
||||
@@ -1,5 +1,5 @@
|
||||
-- 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/seed.sql
|
||||
-- Usage: PGPASSWORD='bank@#23#@_password' psql -h localhost -p 5424 -U bank_admin -d bank_db -f db/mock/seed.sql
|
||||
-- Login (password = test1234):
|
||||
-- superadmin@bank.tm / +993 61 92 92 48
|
||||
-- admin@bank.tm
|
||||
57
db/mock/seed_branches.sql
Normal file
57
db/mock/seed_branches.sql
Normal file
@@ -0,0 +1,57 @@
|
||||
-- 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
|
||||
);
|
||||
54
db/mock/seed_card_states.sql
Normal file
54
db/mock/seed_card_states.sql
Normal file
@@ -0,0 +1,54 @@
|
||||
-- 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'
|
||||
);
|
||||
54
db/mock/seed_card_types.sql
Normal file
54
db/mock/seed_card_types.sql
Normal file
@@ -0,0 +1,54 @@
|
||||
-- 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'
|
||||
);
|
||||
22
db/mock/seed_loan_order_required_docs.sql
Normal file
22
db/mock/seed_loan_order_required_docs.sql
Normal file
@@ -0,0 +1,22 @@
|
||||
-- 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
|
||||
);
|
||||
47
db/mock/seed_loan_types.sql
Normal file
47
db/mock/seed_loan_types.sql
Normal file
@@ -0,0 +1,47 @@
|
||||
-- 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'
|
||||
);
|
||||
280
db/mock/seed_provinces.sql
Normal file
280
db/mock/seed_provinces.sql
Normal file
@@ -0,0 +1,280 @@
|
||||
-- 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'
|
||||
);
|
||||
161
docs/docs.go
161
docs/docs.go
@@ -22,7 +22,7 @@ const docTemplate = `{
|
||||
"BearerAuth": []
|
||||
}
|
||||
],
|
||||
"description": "Returns a paginated audit trail of user actions (create/update/delete)",
|
||||
"description": "Returns a paginated audit trail of user actions (create/update/delete). Each log includes the actor's username and role from role_user.",
|
||||
"produces": [
|
||||
"application/json"
|
||||
],
|
||||
@@ -139,56 +139,13 @@ const docTemplate = `{
|
||||
}
|
||||
},
|
||||
"/branch-users": {
|
||||
"get": {
|
||||
"security": [
|
||||
{
|
||||
"BearerAuth": []
|
||||
}
|
||||
],
|
||||
"description": "Returns the authenticated user's branch-user assignments with the related user and branch",
|
||||
"produces": [
|
||||
"application/json"
|
||||
],
|
||||
"tags": [
|
||||
"branch-users"
|
||||
],
|
||||
"summary": "List branch users",
|
||||
"parameters": [
|
||||
{
|
||||
"type": "string",
|
||||
"description": "Filter by branch name (en, ru, tm)",
|
||||
"name": "branch_name",
|
||||
"in": "query"
|
||||
}
|
||||
],
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "OK",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/appresult.AppSuccess"
|
||||
}
|
||||
},
|
||||
"401": {
|
||||
"description": "Unauthorized",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/appresult.AppError"
|
||||
}
|
||||
},
|
||||
"500": {
|
||||
"description": "Internal Server Error",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/appresult.AppError"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"post": {
|
||||
"security": [
|
||||
{
|
||||
"BearerAuth": []
|
||||
}
|
||||
],
|
||||
"description": "Creates a branch-user assignment",
|
||||
"description": "Creates a branch-user assignment, or updates the user's existing branch if one is already assigned",
|
||||
"consumes": [
|
||||
"application/json"
|
||||
],
|
||||
@@ -4112,7 +4069,7 @@ const docTemplate = `{
|
||||
"BearerAuth": []
|
||||
}
|
||||
],
|
||||
"description": "Returns the authenticated user's profile",
|
||||
"description": "Returns the authenticated user's profile with role and branches",
|
||||
"produces": [
|
||||
"application/json"
|
||||
],
|
||||
@@ -4852,56 +4809,13 @@ const docTemplate = `{
|
||||
}
|
||||
},
|
||||
"/role-users": {
|
||||
"get": {
|
||||
"security": [
|
||||
{
|
||||
"BearerAuth": []
|
||||
}
|
||||
],
|
||||
"description": "Returns the authenticated user's role-user assignments with the related user and role",
|
||||
"produces": [
|
||||
"application/json"
|
||||
],
|
||||
"tags": [
|
||||
"role-users"
|
||||
],
|
||||
"summary": "List role users",
|
||||
"parameters": [
|
||||
{
|
||||
"type": "string",
|
||||
"description": "Filter by role name",
|
||||
"name": "role_name",
|
||||
"in": "query"
|
||||
}
|
||||
],
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "OK",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/appresult.AppSuccess"
|
||||
}
|
||||
},
|
||||
"401": {
|
||||
"description": "Unauthorized",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/appresult.AppError"
|
||||
}
|
||||
},
|
||||
"500": {
|
||||
"description": "Internal Server Error",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/appresult.AppError"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"post": {
|
||||
"security": [
|
||||
{
|
||||
"BearerAuth": []
|
||||
}
|
||||
],
|
||||
"description": "Creates a role-user assignment",
|
||||
"description": "Creates a role-user assignment, or updates the user's existing role if one is already assigned",
|
||||
"consumes": [
|
||||
"application/json"
|
||||
],
|
||||
@@ -5855,59 +5769,6 @@ const docTemplate = `{
|
||||
}
|
||||
}
|
||||
},
|
||||
"/visa-master-payment-orders/branches": {
|
||||
"get": {
|
||||
"security": [
|
||||
{
|
||||
"BearerAuth": []
|
||||
}
|
||||
],
|
||||
"description": "Returns branches for the selected province for visa/master payment order forms",
|
||||
"produces": [
|
||||
"application/json"
|
||||
],
|
||||
"tags": [
|
||||
"visa-master-payment-orders"
|
||||
],
|
||||
"summary": "List branches by province",
|
||||
"parameters": [
|
||||
{
|
||||
"type": "integer",
|
||||
"description": "Province ID",
|
||||
"name": "province_id",
|
||||
"in": "query",
|
||||
"required": true
|
||||
},
|
||||
{
|
||||
"type": "boolean",
|
||||
"default": true,
|
||||
"description": "Only active branches",
|
||||
"name": "active",
|
||||
"in": "query"
|
||||
}
|
||||
],
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "OK",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/appresult.AppSuccess"
|
||||
}
|
||||
},
|
||||
"400": {
|
||||
"description": "Bad Request",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/appresult.AppError"
|
||||
}
|
||||
},
|
||||
"500": {
|
||||
"description": "Internal Server Error",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/appresult.AppError"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"/visa-master-payment-orders/{id}": {
|
||||
"get": {
|
||||
"security": [
|
||||
@@ -6368,7 +6229,6 @@ const docTemplate = `{
|
||||
"customerName",
|
||||
"customerSurname",
|
||||
"passportFour",
|
||||
"passportGivenAt",
|
||||
"passportGivenBy",
|
||||
"passportId",
|
||||
"passportOne",
|
||||
@@ -6379,7 +6239,8 @@ const docTemplate = `{
|
||||
],
|
||||
"properties": {
|
||||
"bornAt": {
|
||||
"type": "string"
|
||||
"type": "string",
|
||||
"format": "date"
|
||||
},
|
||||
"bornPlace": {
|
||||
"type": "string"
|
||||
@@ -6424,7 +6285,8 @@ const docTemplate = `{
|
||||
"type": "string"
|
||||
},
|
||||
"passportGivenAt": {
|
||||
"type": "string"
|
||||
"type": "string",
|
||||
"format": "date"
|
||||
},
|
||||
"passportGivenBy": {
|
||||
"type": "string"
|
||||
@@ -6478,7 +6340,6 @@ const docTemplate = `{
|
||||
"customerName",
|
||||
"customerSurname",
|
||||
"passportFour",
|
||||
"passportGivenAt",
|
||||
"passportGivenBy",
|
||||
"passportId",
|
||||
"passportOne",
|
||||
@@ -6489,7 +6350,8 @@ const docTemplate = `{
|
||||
],
|
||||
"properties": {
|
||||
"bornAt": {
|
||||
"type": "string"
|
||||
"type": "string",
|
||||
"format": "date"
|
||||
},
|
||||
"bornPlace": {
|
||||
"type": "string"
|
||||
@@ -6534,7 +6396,8 @@ const docTemplate = `{
|
||||
"type": "string"
|
||||
},
|
||||
"passportGivenAt": {
|
||||
"type": "string"
|
||||
"type": "string",
|
||||
"format": "date"
|
||||
},
|
||||
"passportGivenBy": {
|
||||
"type": "string"
|
||||
|
||||
@@ -16,7 +16,7 @@
|
||||
"BearerAuth": []
|
||||
}
|
||||
],
|
||||
"description": "Returns a paginated audit trail of user actions (create/update/delete)",
|
||||
"description": "Returns a paginated audit trail of user actions (create/update/delete). Each log includes the actor's username and role from role_user.",
|
||||
"produces": [
|
||||
"application/json"
|
||||
],
|
||||
@@ -133,56 +133,13 @@
|
||||
}
|
||||
},
|
||||
"/branch-users": {
|
||||
"get": {
|
||||
"security": [
|
||||
{
|
||||
"BearerAuth": []
|
||||
}
|
||||
],
|
||||
"description": "Returns the authenticated user's branch-user assignments with the related user and branch",
|
||||
"produces": [
|
||||
"application/json"
|
||||
],
|
||||
"tags": [
|
||||
"branch-users"
|
||||
],
|
||||
"summary": "List branch users",
|
||||
"parameters": [
|
||||
{
|
||||
"type": "string",
|
||||
"description": "Filter by branch name (en, ru, tm)",
|
||||
"name": "branch_name",
|
||||
"in": "query"
|
||||
}
|
||||
],
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "OK",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/appresult.AppSuccess"
|
||||
}
|
||||
},
|
||||
"401": {
|
||||
"description": "Unauthorized",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/appresult.AppError"
|
||||
}
|
||||
},
|
||||
"500": {
|
||||
"description": "Internal Server Error",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/appresult.AppError"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"post": {
|
||||
"security": [
|
||||
{
|
||||
"BearerAuth": []
|
||||
}
|
||||
],
|
||||
"description": "Creates a branch-user assignment",
|
||||
"description": "Creates a branch-user assignment, or updates the user's existing branch if one is already assigned",
|
||||
"consumes": [
|
||||
"application/json"
|
||||
],
|
||||
@@ -4106,7 +4063,7 @@
|
||||
"BearerAuth": []
|
||||
}
|
||||
],
|
||||
"description": "Returns the authenticated user's profile",
|
||||
"description": "Returns the authenticated user's profile with role and branches",
|
||||
"produces": [
|
||||
"application/json"
|
||||
],
|
||||
@@ -4846,56 +4803,13 @@
|
||||
}
|
||||
},
|
||||
"/role-users": {
|
||||
"get": {
|
||||
"security": [
|
||||
{
|
||||
"BearerAuth": []
|
||||
}
|
||||
],
|
||||
"description": "Returns the authenticated user's role-user assignments with the related user and role",
|
||||
"produces": [
|
||||
"application/json"
|
||||
],
|
||||
"tags": [
|
||||
"role-users"
|
||||
],
|
||||
"summary": "List role users",
|
||||
"parameters": [
|
||||
{
|
||||
"type": "string",
|
||||
"description": "Filter by role name",
|
||||
"name": "role_name",
|
||||
"in": "query"
|
||||
}
|
||||
],
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "OK",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/appresult.AppSuccess"
|
||||
}
|
||||
},
|
||||
"401": {
|
||||
"description": "Unauthorized",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/appresult.AppError"
|
||||
}
|
||||
},
|
||||
"500": {
|
||||
"description": "Internal Server Error",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/appresult.AppError"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"post": {
|
||||
"security": [
|
||||
{
|
||||
"BearerAuth": []
|
||||
}
|
||||
],
|
||||
"description": "Creates a role-user assignment",
|
||||
"description": "Creates a role-user assignment, or updates the user's existing role if one is already assigned",
|
||||
"consumes": [
|
||||
"application/json"
|
||||
],
|
||||
@@ -5849,59 +5763,6 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
"/visa-master-payment-orders/branches": {
|
||||
"get": {
|
||||
"security": [
|
||||
{
|
||||
"BearerAuth": []
|
||||
}
|
||||
],
|
||||
"description": "Returns branches for the selected province for visa/master payment order forms",
|
||||
"produces": [
|
||||
"application/json"
|
||||
],
|
||||
"tags": [
|
||||
"visa-master-payment-orders"
|
||||
],
|
||||
"summary": "List branches by province",
|
||||
"parameters": [
|
||||
{
|
||||
"type": "integer",
|
||||
"description": "Province ID",
|
||||
"name": "province_id",
|
||||
"in": "query",
|
||||
"required": true
|
||||
},
|
||||
{
|
||||
"type": "boolean",
|
||||
"default": true,
|
||||
"description": "Only active branches",
|
||||
"name": "active",
|
||||
"in": "query"
|
||||
}
|
||||
],
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "OK",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/appresult.AppSuccess"
|
||||
}
|
||||
},
|
||||
"400": {
|
||||
"description": "Bad Request",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/appresult.AppError"
|
||||
}
|
||||
},
|
||||
"500": {
|
||||
"description": "Internal Server Error",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/appresult.AppError"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"/visa-master-payment-orders/{id}": {
|
||||
"get": {
|
||||
"security": [
|
||||
@@ -6362,7 +6223,6 @@
|
||||
"customerName",
|
||||
"customerSurname",
|
||||
"passportFour",
|
||||
"passportGivenAt",
|
||||
"passportGivenBy",
|
||||
"passportId",
|
||||
"passportOne",
|
||||
@@ -6373,7 +6233,8 @@
|
||||
],
|
||||
"properties": {
|
||||
"bornAt": {
|
||||
"type": "string"
|
||||
"type": "string",
|
||||
"format": "date"
|
||||
},
|
||||
"bornPlace": {
|
||||
"type": "string"
|
||||
@@ -6418,7 +6279,8 @@
|
||||
"type": "string"
|
||||
},
|
||||
"passportGivenAt": {
|
||||
"type": "string"
|
||||
"type": "string",
|
||||
"format": "date"
|
||||
},
|
||||
"passportGivenBy": {
|
||||
"type": "string"
|
||||
@@ -6472,7 +6334,6 @@
|
||||
"customerName",
|
||||
"customerSurname",
|
||||
"passportFour",
|
||||
"passportGivenAt",
|
||||
"passportGivenBy",
|
||||
"passportId",
|
||||
"passportOne",
|
||||
@@ -6483,7 +6344,8 @@
|
||||
],
|
||||
"properties": {
|
||||
"bornAt": {
|
||||
"type": "string"
|
||||
"type": "string",
|
||||
"format": "date"
|
||||
},
|
||||
"bornPlace": {
|
||||
"type": "string"
|
||||
@@ -6528,7 +6390,8 @@
|
||||
"type": "string"
|
||||
},
|
||||
"passportGivenAt": {
|
||||
"type": "string"
|
||||
"type": "string",
|
||||
"format": "date"
|
||||
},
|
||||
"passportGivenBy": {
|
||||
"type": "string"
|
||||
|
||||
@@ -193,6 +193,7 @@ definitions:
|
||||
cardorder.CreateCardOrderDTO:
|
||||
properties:
|
||||
bornAt:
|
||||
format: date
|
||||
type: string
|
||||
bornPlace:
|
||||
type: string
|
||||
@@ -223,6 +224,7 @@ definitions:
|
||||
passportFour:
|
||||
type: string
|
||||
passportGivenAt:
|
||||
format: date
|
||||
type: string
|
||||
passportGivenBy:
|
||||
type: string
|
||||
@@ -259,7 +261,6 @@ definitions:
|
||||
- customerName
|
||||
- customerSurname
|
||||
- passportFour
|
||||
- passportGivenAt
|
||||
- passportGivenBy
|
||||
- passportId
|
||||
- passportOne
|
||||
@@ -271,6 +272,7 @@ definitions:
|
||||
cardorder.UpdateCardOrderDTO:
|
||||
properties:
|
||||
bornAt:
|
||||
format: date
|
||||
type: string
|
||||
bornPlace:
|
||||
type: string
|
||||
@@ -301,6 +303,7 @@ definitions:
|
||||
passportFour:
|
||||
type: string
|
||||
passportGivenAt:
|
||||
format: date
|
||||
type: string
|
||||
passportGivenBy:
|
||||
type: string
|
||||
@@ -337,7 +340,6 @@ definitions:
|
||||
- customerName
|
||||
- customerSurname
|
||||
- passportFour
|
||||
- passportGivenAt
|
||||
- passportGivenBy
|
||||
- passportId
|
||||
- passportOne
|
||||
@@ -1390,7 +1392,8 @@ info:
|
||||
paths:
|
||||
/activity-logs:
|
||||
get:
|
||||
description: Returns a paginated audit trail of user actions (create/update/delete)
|
||||
description: Returns a paginated audit trail of user actions (create/update/delete).
|
||||
Each log includes the actor's username and role from role_user.
|
||||
parameters:
|
||||
- description: Filter by user ID
|
||||
in: query
|
||||
@@ -1468,38 +1471,11 @@ paths:
|
||||
tags:
|
||||
- activity-logs
|
||||
/branch-users:
|
||||
get:
|
||||
description: Returns the authenticated user's branch-user assignments with the
|
||||
related user and branch
|
||||
parameters:
|
||||
- description: Filter by branch name (en, ru, tm)
|
||||
in: query
|
||||
name: branch_name
|
||||
type: string
|
||||
produces:
|
||||
- application/json
|
||||
responses:
|
||||
"200":
|
||||
description: OK
|
||||
schema:
|
||||
$ref: '#/definitions/appresult.AppSuccess'
|
||||
"401":
|
||||
description: Unauthorized
|
||||
schema:
|
||||
$ref: '#/definitions/appresult.AppError'
|
||||
"500":
|
||||
description: Internal Server Error
|
||||
schema:
|
||||
$ref: '#/definitions/appresult.AppError'
|
||||
security:
|
||||
- BearerAuth: []
|
||||
summary: List branch users
|
||||
tags:
|
||||
- branch-users
|
||||
post:
|
||||
consumes:
|
||||
- application/json
|
||||
description: Creates a branch-user assignment
|
||||
description: Creates a branch-user assignment, or updates the user's existing
|
||||
branch if one is already assigned
|
||||
parameters:
|
||||
- description: Branch-user payload
|
||||
in: body
|
||||
@@ -4012,7 +3988,7 @@ paths:
|
||||
- permission
|
||||
/profile:
|
||||
get:
|
||||
description: Returns the authenticated user's profile
|
||||
description: Returns the authenticated user's profile with role and branches
|
||||
produces:
|
||||
- application/json
|
||||
responses:
|
||||
@@ -4490,38 +4466,11 @@ paths:
|
||||
tags:
|
||||
- auth
|
||||
/role-users:
|
||||
get:
|
||||
description: Returns the authenticated user's role-user assignments with the
|
||||
related user and role
|
||||
parameters:
|
||||
- description: Filter by role name
|
||||
in: query
|
||||
name: role_name
|
||||
type: string
|
||||
produces:
|
||||
- application/json
|
||||
responses:
|
||||
"200":
|
||||
description: OK
|
||||
schema:
|
||||
$ref: '#/definitions/appresult.AppSuccess'
|
||||
"401":
|
||||
description: Unauthorized
|
||||
schema:
|
||||
$ref: '#/definitions/appresult.AppError'
|
||||
"500":
|
||||
description: Internal Server Error
|
||||
schema:
|
||||
$ref: '#/definitions/appresult.AppError'
|
||||
security:
|
||||
- BearerAuth: []
|
||||
summary: List role users
|
||||
tags:
|
||||
- role-users
|
||||
post:
|
||||
consumes:
|
||||
- application/json
|
||||
description: Creates a role-user assignment
|
||||
description: Creates a role-user assignment, or updates the user's existing
|
||||
role if one is already assigned
|
||||
parameters:
|
||||
- description: Role-user payload
|
||||
in: body
|
||||
@@ -5242,41 +5191,6 @@ paths:
|
||||
summary: Update visa/master payment order
|
||||
tags:
|
||||
- visa-master-payment-orders
|
||||
/visa-master-payment-orders/branches:
|
||||
get:
|
||||
description: Returns branches for the selected province for visa/master payment
|
||||
order forms
|
||||
parameters:
|
||||
- description: Province ID
|
||||
in: query
|
||||
name: province_id
|
||||
required: true
|
||||
type: integer
|
||||
- default: true
|
||||
description: Only active branches
|
||||
in: query
|
||||
name: active
|
||||
type: boolean
|
||||
produces:
|
||||
- application/json
|
||||
responses:
|
||||
"200":
|
||||
description: OK
|
||||
schema:
|
||||
$ref: '#/definitions/appresult.AppSuccess'
|
||||
"400":
|
||||
description: Bad Request
|
||||
schema:
|
||||
$ref: '#/definitions/appresult.AppError'
|
||||
"500":
|
||||
description: Internal Server Error
|
||||
schema:
|
||||
$ref: '#/definitions/appresult.AppError'
|
||||
security:
|
||||
- BearerAuth: []
|
||||
summary: List branches by province
|
||||
tags:
|
||||
- visa-master-payment-orders
|
||||
securityDefinitions:
|
||||
BearerAuth:
|
||||
in: header
|
||||
|
||||
@@ -4,6 +4,7 @@ import (
|
||||
"context"
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"online-back/internal/cards/cardorder"
|
||||
"online-back/pkg/client/postgresql"
|
||||
@@ -25,8 +26,6 @@ func NewRepository(client postgresql.Client, logger *logging.Logger) cardorder.R
|
||||
}
|
||||
}
|
||||
|
||||
// cardOrderWritableColumns lists every card_orders column except id, created_at and
|
||||
// updated_at, in the exact order CreateCardOrderDTO/UpdateCardOrderDTO fields are read.
|
||||
var cardOrderWritableColumns = []string{
|
||||
"unique_id", "card_state_id", "card_type_id", "region", "branch_id",
|
||||
"customer_name", "customer_surname", "customer_patronic_name", "born_at", "old_surname", "citizenship",
|
||||
@@ -58,24 +57,40 @@ func resolvePaid(paid *bool) bool {
|
||||
|
||||
func createArgs(dto cardorder.CreateCardOrderDTO) []interface{} {
|
||||
return []interface{}{
|
||||
dto.UniqueId, dto.CardStateId, dto.CardTypeId, dto.Region, dto.BranchId,
|
||||
dto.CustomerName, dto.CustomerSurname, dto.CustomerPatronicName, dto.BornAt, dto.OldSurname, dto.Citizenship,
|
||||
dto.PassportSerie, dto.PassportId, dto.PassportGivenAt, dto.PassportGivenBy, dto.BornPlace,
|
||||
dto.UniqueId, dto.CardStateId.Int64(), dto.CardTypeId.Int64(), dto.Region, dto.BranchId.Int64(),
|
||||
dto.CustomerName, dto.CustomerSurname, dto.CustomerPatronicName, optionalTime(dto.BornAt), dto.OldSurname, dto.Citizenship,
|
||||
dto.PassportSerie, dto.PassportId, dto.PassportGivenAt.Time(), dto.PassportGivenBy, dto.BornPlace,
|
||||
dto.JobLocation, dto.PassportAddress, dto.RealAddress, dto.Phone, dto.PhoneAdditional,
|
||||
resolveStatus(dto.Status), dto.PassportOne, dto.PassportTwo, dto.PassportThree, dto.PassportFour, dto.Notes, dto.UserId, resolvePaid(dto.Paid),
|
||||
resolveStatus(dto.Status), dto.PassportOne, dto.PassportTwo, dto.PassportThree, dto.PassportFour, dto.Notes, optionalInt64(dto.UserId), resolvePaid(dto.Paid),
|
||||
}
|
||||
}
|
||||
|
||||
func updateArgs(dto cardorder.UpdateCardOrderDTO) []interface{} {
|
||||
return []interface{}{
|
||||
dto.UniqueId, dto.CardStateId, dto.CardTypeId, dto.Region, dto.BranchId,
|
||||
dto.CustomerName, dto.CustomerSurname, dto.CustomerPatronicName, dto.BornAt, dto.OldSurname, dto.Citizenship,
|
||||
dto.PassportSerie, dto.PassportId, dto.PassportGivenAt, dto.PassportGivenBy, dto.BornPlace,
|
||||
dto.UniqueId, dto.CardStateId.Int64(), dto.CardTypeId.Int64(), dto.Region, dto.BranchId.Int64(),
|
||||
dto.CustomerName, dto.CustomerSurname, dto.CustomerPatronicName, optionalTime(dto.BornAt), dto.OldSurname, dto.Citizenship,
|
||||
dto.PassportSerie, dto.PassportId, dto.PassportGivenAt.Time(), dto.PassportGivenBy, dto.BornPlace,
|
||||
dto.JobLocation, dto.PassportAddress, dto.RealAddress, dto.Phone, dto.PhoneAdditional,
|
||||
resolveStatus(dto.Status), dto.PassportOne, dto.PassportTwo, dto.PassportThree, dto.PassportFour, dto.Notes, dto.UserId, dto.Paid,
|
||||
resolveStatus(dto.Status), dto.PassportOne, dto.PassportTwo, dto.PassportThree, dto.PassportFour, dto.Notes, optionalInt64(dto.UserId), dto.Paid,
|
||||
}
|
||||
}
|
||||
|
||||
func optionalTime(t *cardorder.FlexibleTime) *time.Time {
|
||||
if t == nil || t.IsZero() {
|
||||
return nil
|
||||
}
|
||||
tt := t.Time()
|
||||
return &tt
|
||||
}
|
||||
|
||||
func optionalInt64(n *cardorder.FlexibleInt64) *int64 {
|
||||
if n == nil {
|
||||
return nil
|
||||
}
|
||||
v := n.Int64()
|
||||
return &v
|
||||
}
|
||||
|
||||
func (r *repository) List(ctx context.Context, filter cardorder.ListFilter) (cardorder.ListCardOrderDTO, error) {
|
||||
whereClause, args := buildListQuery(filter)
|
||||
|
||||
|
||||
@@ -1,6 +1,114 @@
|
||||
package cardorder
|
||||
|
||||
import "time"
|
||||
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
|
||||
}
|
||||
|
||||
type CardOrderDTO struct {
|
||||
Id int64 `json:"id"`
|
||||
@@ -38,67 +146,67 @@ type CardOrderDTO struct {
|
||||
}
|
||||
|
||||
type CreateCardOrderDTO struct {
|
||||
UniqueId *string `json:"uniqueId"`
|
||||
CardStateId int64 `json:"cardStateId" binding:"required"`
|
||||
CardTypeId int64 `json:"cardTypeId" binding:"required"`
|
||||
Region string `json:"region" binding:"required"`
|
||||
BranchId int64 `json:"branchId" binding:"required"`
|
||||
CustomerName string `json:"customerName" binding:"required"`
|
||||
CustomerSurname string `json:"customerSurname" binding:"required"`
|
||||
CustomerPatronicName *string `json:"customerPatronicName"`
|
||||
BornAt *time.Time `json:"bornAt"`
|
||||
OldSurname *string `json:"oldSurname"`
|
||||
Citizenship string `json:"citizenship" binding:"required"`
|
||||
PassportSerie string `json:"passportSerie" binding:"required"`
|
||||
PassportId string `json:"passportId" binding:"required"`
|
||||
PassportGivenAt time.Time `json:"passportGivenAt" binding:"required"`
|
||||
PassportGivenBy string `json:"passportGivenBy" binding:"required"`
|
||||
BornPlace string `json:"bornPlace" binding:"required"`
|
||||
JobLocation *string `json:"jobLocation"`
|
||||
PassportAddress *string `json:"passportAddress"`
|
||||
RealAddress *string `json:"realAddress"`
|
||||
Phone *string `json:"phone"`
|
||||
PhoneAdditional *string `json:"phoneAdditional"`
|
||||
Status *string `json:"status"`
|
||||
PassportOne string `json:"passportOne" binding:"required"`
|
||||
PassportTwo string `json:"passportTwo" binding:"required"`
|
||||
PassportThree string `json:"passportThree" binding:"required"`
|
||||
PassportFour string `json:"passportFour" binding:"required"`
|
||||
Notes *string `json:"notes"`
|
||||
UserId *int64 `json:"userId"`
|
||||
Paid *bool `json:"paid"`
|
||||
UniqueId *string `json:"uniqueId"`
|
||||
CardStateId FlexibleInt64 `json:"cardStateId" binding:"required" swaggertype:"integer"`
|
||||
CardTypeId FlexibleInt64 `json:"cardTypeId" binding:"required" swaggertype:"integer"`
|
||||
Region string `json:"region" binding:"required"`
|
||||
BranchId FlexibleInt64 `json:"branchId" binding:"required" swaggertype:"integer"`
|
||||
CustomerName string `json:"customerName" binding:"required"`
|
||||
CustomerSurname string `json:"customerSurname" binding:"required"`
|
||||
CustomerPatronicName *string `json:"customerPatronicName"`
|
||||
BornAt *FlexibleTime `json:"bornAt" swaggertype:"string" format:"date"`
|
||||
OldSurname *string `json:"oldSurname"`
|
||||
Citizenship string `json:"citizenship" binding:"required"`
|
||||
PassportSerie string `json:"passportSerie" binding:"required"`
|
||||
PassportId string `json:"passportId" binding:"required"`
|
||||
PassportGivenAt FlexibleTime `json:"passportGivenAt" swaggertype:"string" format:"date"`
|
||||
PassportGivenBy string `json:"passportGivenBy" binding:"required"`
|
||||
BornPlace string `json:"bornPlace" binding:"required"`
|
||||
JobLocation *string `json:"jobLocation"`
|
||||
PassportAddress *string `json:"passportAddress"`
|
||||
RealAddress *string `json:"realAddress"`
|
||||
Phone *string `json:"phone"`
|
||||
PhoneAdditional *string `json:"phoneAdditional"`
|
||||
Status *string `json:"status"`
|
||||
PassportOne string `json:"passportOne" binding:"required"`
|
||||
PassportTwo string `json:"passportTwo" binding:"required"`
|
||||
PassportThree string `json:"passportThree" binding:"required"`
|
||||
PassportFour string `json:"passportFour" binding:"required"`
|
||||
Notes *string `json:"notes"`
|
||||
UserId *FlexibleInt64 `json:"userId" swaggertype:"integer"`
|
||||
Paid *bool `json:"paid"`
|
||||
}
|
||||
|
||||
type UpdateCardOrderDTO struct {
|
||||
UniqueId *string `json:"uniqueId"`
|
||||
CardStateId int64 `json:"cardStateId" binding:"required"`
|
||||
CardTypeId int64 `json:"cardTypeId" binding:"required"`
|
||||
Region string `json:"region" binding:"required"`
|
||||
BranchId int64 `json:"branchId" binding:"required"`
|
||||
CustomerName string `json:"customerName" binding:"required"`
|
||||
CustomerSurname string `json:"customerSurname" binding:"required"`
|
||||
CustomerPatronicName *string `json:"customerPatronicName"`
|
||||
BornAt *time.Time `json:"bornAt"`
|
||||
OldSurname *string `json:"oldSurname"`
|
||||
Citizenship string `json:"citizenship" binding:"required"`
|
||||
PassportSerie string `json:"passportSerie" binding:"required"`
|
||||
PassportId string `json:"passportId" binding:"required"`
|
||||
PassportGivenAt time.Time `json:"passportGivenAt" binding:"required"`
|
||||
PassportGivenBy string `json:"passportGivenBy" binding:"required"`
|
||||
BornPlace string `json:"bornPlace" binding:"required"`
|
||||
JobLocation *string `json:"jobLocation"`
|
||||
PassportAddress *string `json:"passportAddress"`
|
||||
RealAddress *string `json:"realAddress"`
|
||||
Phone *string `json:"phone"`
|
||||
PhoneAdditional *string `json:"phoneAdditional"`
|
||||
Status *string `json:"status"`
|
||||
PassportOne string `json:"passportOne" binding:"required"`
|
||||
PassportTwo string `json:"passportTwo" binding:"required"`
|
||||
PassportThree string `json:"passportThree" binding:"required"`
|
||||
PassportFour string `json:"passportFour" binding:"required"`
|
||||
Notes *string `json:"notes"`
|
||||
UserId *int64 `json:"userId"`
|
||||
Paid bool `json:"paid"`
|
||||
UniqueId *string `json:"uniqueId"`
|
||||
CardStateId FlexibleInt64 `json:"cardStateId" binding:"required" swaggertype:"integer"`
|
||||
CardTypeId FlexibleInt64 `json:"cardTypeId" binding:"required" swaggertype:"integer"`
|
||||
Region string `json:"region" binding:"required"`
|
||||
BranchId FlexibleInt64 `json:"branchId" binding:"required" swaggertype:"integer"`
|
||||
CustomerName string `json:"customerName" binding:"required"`
|
||||
CustomerSurname string `json:"customerSurname" binding:"required"`
|
||||
CustomerPatronicName *string `json:"customerPatronicName"`
|
||||
BornAt *FlexibleTime `json:"bornAt" swaggertype:"string" format:"date"`
|
||||
OldSurname *string `json:"oldSurname"`
|
||||
Citizenship string `json:"citizenship" binding:"required"`
|
||||
PassportSerie string `json:"passportSerie" binding:"required"`
|
||||
PassportId string `json:"passportId" binding:"required"`
|
||||
PassportGivenAt FlexibleTime `json:"passportGivenAt" swaggertype:"string" format:"date"`
|
||||
PassportGivenBy string `json:"passportGivenBy" binding:"required"`
|
||||
BornPlace string `json:"bornPlace" binding:"required"`
|
||||
JobLocation *string `json:"jobLocation"`
|
||||
PassportAddress *string `json:"passportAddress"`
|
||||
RealAddress *string `json:"realAddress"`
|
||||
Phone *string `json:"phone"`
|
||||
PhoneAdditional *string `json:"phoneAdditional"`
|
||||
Status *string `json:"status"`
|
||||
PassportOne string `json:"passportOne" binding:"required"`
|
||||
PassportTwo string `json:"passportTwo" binding:"required"`
|
||||
PassportThree string `json:"passportThree" binding:"required"`
|
||||
PassportFour string `json:"passportFour" binding:"required"`
|
||||
Notes *string `json:"notes"`
|
||||
UserId *FlexibleInt64 `json:"userId" swaggertype:"integer"`
|
||||
Paid bool `json:"paid"`
|
||||
}
|
||||
|
||||
type ListFilter struct {
|
||||
|
||||
@@ -116,7 +116,8 @@ func (h *handler) getByID(c *gin.Context) {
|
||||
// @Router /card-orders [post]
|
||||
func (h *handler) create(c *gin.Context) {
|
||||
var dto CreateCardOrderDTO
|
||||
if err := c.ShouldBindJSON(&dto); err != nil {
|
||||
if err := c.ShouldBindBodyWithJSON(&dto); err != nil {
|
||||
h.logger.Errorf("create card order bind failed: %v", err)
|
||||
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
|
||||
return
|
||||
}
|
||||
@@ -153,7 +154,8 @@ func (h *handler) update(c *gin.Context) {
|
||||
}
|
||||
|
||||
var dto UpdateCardOrderDTO
|
||||
if err := c.ShouldBindJSON(&dto); err != nil {
|
||||
if err := c.ShouldBindBodyWithJSON(&dto); err != nil {
|
||||
h.logger.Errorf("update card order bind failed: %v", err)
|
||||
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
|
||||
return
|
||||
}
|
||||
@@ -223,39 +225,31 @@ func parseListFilter(c *gin.Context) (ListFilter, bool) {
|
||||
Limit: defaultLimit,
|
||||
}
|
||||
|
||||
if raw := c.Query("branch_id"); raw != "" {
|
||||
id, ok := parseID(raw)
|
||||
if !ok {
|
||||
return ListFilter{}, false
|
||||
}
|
||||
filter.BranchId = &id
|
||||
if id, ok := optionalQueryID(c, "branch_id", "branchId"); !ok {
|
||||
return ListFilter{}, false
|
||||
} else if id != nil {
|
||||
filter.BranchId = id
|
||||
}
|
||||
|
||||
if raw := c.Query("user_id"); raw != "" {
|
||||
id, ok := parseID(raw)
|
||||
if !ok {
|
||||
return ListFilter{}, false
|
||||
}
|
||||
filter.UserId = &id
|
||||
if id, ok := optionalQueryID(c, "user_id", "userId"); !ok {
|
||||
return ListFilter{}, false
|
||||
} else if id != nil {
|
||||
filter.UserId = id
|
||||
}
|
||||
|
||||
if raw := c.Query("card_state_id"); raw != "" {
|
||||
id, ok := parseID(raw)
|
||||
if !ok {
|
||||
return ListFilter{}, false
|
||||
}
|
||||
filter.CardStateId = &id
|
||||
if id, ok := optionalQueryID(c, "card_state_id", "cardStateId"); !ok {
|
||||
return ListFilter{}, false
|
||||
} else if id != nil {
|
||||
filter.CardStateId = id
|
||||
}
|
||||
|
||||
if raw := c.Query("card_type_id"); raw != "" {
|
||||
id, ok := parseID(raw)
|
||||
if !ok {
|
||||
return ListFilter{}, false
|
||||
}
|
||||
filter.CardTypeId = &id
|
||||
if id, ok := optionalQueryID(c, "card_type_id", "cardTypeId"); !ok {
|
||||
return ListFilter{}, false
|
||||
} else if id != nil {
|
||||
filter.CardTypeId = id
|
||||
}
|
||||
|
||||
if raw := c.Query("page"); raw != "" {
|
||||
if raw := queryValue(c, "page"); raw != "" {
|
||||
page, err := strconv.Atoi(raw)
|
||||
if err != nil || page < 1 {
|
||||
return ListFilter{}, false
|
||||
@@ -263,21 +257,45 @@ func parseListFilter(c *gin.Context) (ListFilter, bool) {
|
||||
filter.Page = page
|
||||
}
|
||||
|
||||
if raw := c.Query("limit"); raw != "" {
|
||||
if raw := queryValue(c, "limit"); raw != "" {
|
||||
limit, err := strconv.Atoi(raw)
|
||||
if err != nil || limit < 1 || limit > maxLimit {
|
||||
if err != nil || limit < 1 {
|
||||
return ListFilter{}, false
|
||||
}
|
||||
if limit > maxLimit {
|
||||
limit = maxLimit
|
||||
}
|
||||
filter.Limit = limit
|
||||
}
|
||||
|
||||
if raw := strings.TrimSpace(c.Query("status")); raw != "" {
|
||||
if raw := queryValue(c, "status"); raw != "" {
|
||||
filter.Status = &raw
|
||||
}
|
||||
|
||||
if raw := strings.TrimSpace(c.Query("region")); raw != "" {
|
||||
if raw := queryValue(c, "region"); raw != "" {
|
||||
filter.Region = raw
|
||||
}
|
||||
|
||||
return filter, true
|
||||
}
|
||||
|
||||
func queryValue(c *gin.Context, keys ...string) string {
|
||||
for _, key := range keys {
|
||||
if raw := strings.TrimSpace(c.Query(key)); raw != "" && raw != "undefined" && raw != "null" {
|
||||
return raw
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func optionalQueryID(c *gin.Context, keys ...string) (*int64, bool) {
|
||||
raw := queryValue(c, keys...)
|
||||
if raw == "" {
|
||||
return nil, true
|
||||
}
|
||||
id, ok := parseID(raw)
|
||||
if !ok {
|
||||
return nil, false
|
||||
}
|
||||
return &id, true
|
||||
}
|
||||
|
||||
@@ -188,46 +188,6 @@ func likePattern(term string) string {
|
||||
return "%" + term + "%"
|
||||
}
|
||||
|
||||
func (r *repository) ListBranchesByProvince(ctx context.Context, provinceID int64, activeOnly bool) (visamaster.ListBranchesByProvinceDTO, error) {
|
||||
args := []interface{}{provinceID}
|
||||
where := ` WHERE province_id = $1`
|
||||
if activeOnly {
|
||||
where += ` AND active = true`
|
||||
}
|
||||
|
||||
query := `
|
||||
SELECT id, COALESCE(unique_code, ''), name, region, province_id, active
|
||||
FROM branches` + where + `
|
||||
ORDER BY name->>'tm', name->>'en', id`
|
||||
|
||||
rows, err := r.client.Query(ctx, query, args...)
|
||||
if err != nil {
|
||||
return visamaster.ListBranchesByProvinceDTO{}, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
branches := make([]visamaster.BranchByProvinceDTO, 0)
|
||||
for rows.Next() {
|
||||
var item visamaster.BranchByProvinceDTO
|
||||
var nameJSON []byte
|
||||
if err := rows.Scan(&item.Id, &item.UniqueCode, &nameJSON, &item.Region, &item.ProvinceId, &item.Active); err != nil {
|
||||
return visamaster.ListBranchesByProvinceDTO{}, err
|
||||
}
|
||||
if err := json.Unmarshal(nameJSON, &item.Name); err != nil {
|
||||
return visamaster.ListBranchesByProvinceDTO{}, err
|
||||
}
|
||||
branches = append(branches, item)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return visamaster.ListBranchesByProvinceDTO{}, err
|
||||
}
|
||||
|
||||
return visamaster.ListBranchesByProvinceDTO{
|
||||
Count: int64(len(branches)),
|
||||
Branches: branches,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (r *repository) GetByID(ctx context.Context, id int64) (visamaster.VisaMasterPaymentOrderDTO, error) {
|
||||
query := `SELECT ` + orderSelectColumns + orderFromClause + ` WHERE o.id = $1`
|
||||
return scanOrder(r.client.QueryRow(ctx, query, id))
|
||||
|
||||
@@ -1,86 +0,0 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"online-back/internal/cards/visamaster"
|
||||
"online-back/internal/config"
|
||||
"online-back/pkg/client/postgresql"
|
||||
"online-back/pkg/logging"
|
||||
)
|
||||
|
||||
func testRepo(t *testing.T) (visamaster.Repository, func()) {
|
||||
t.Helper()
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 8*time.Second)
|
||||
t.Cleanup(cancel)
|
||||
|
||||
pool, err := postgresql.NewClient(ctx, 2, config.StorageConfig{
|
||||
Host: "localhost",
|
||||
Port: "5424",
|
||||
Database: "bank_db",
|
||||
Username: "bank_admin",
|
||||
Password: "bank@#23#@_password",
|
||||
PgPoolMaxConn: 4,
|
||||
})
|
||||
if err != nil {
|
||||
t.Skipf("postgres unavailable: %v", err)
|
||||
}
|
||||
|
||||
return NewRepository(pool, logging.GetLogger()), func() { pool.Close() }
|
||||
}
|
||||
|
||||
func TestGetByIDIncludesBranchAndUser(t *testing.T) {
|
||||
repo, closeRepo := testRepo(t)
|
||||
defer closeRepo()
|
||||
ctx := context.Background()
|
||||
|
||||
item, err := repo.GetByID(ctx, 1)
|
||||
if err != nil {
|
||||
t.Fatalf("GetByID: %v", err)
|
||||
}
|
||||
|
||||
if item.BranchId == 0 {
|
||||
t.Fatal("branchId is empty")
|
||||
}
|
||||
if item.Branch.Id != item.BranchId {
|
||||
t.Fatalf("branch.id=%d does not match branchId=%d", item.Branch.Id, item.BranchId)
|
||||
}
|
||||
if item.Branch.Name.Tm == "" && item.Branch.Name.En == "" {
|
||||
t.Fatalf("branchId=%d but branch.name is empty: %+v", item.BranchId, item.Branch.Name)
|
||||
}
|
||||
if item.UserId != nil {
|
||||
if item.User == nil {
|
||||
t.Fatalf("userId=%d but user object is nil", *item.UserId)
|
||||
}
|
||||
if item.User.Name == "" && item.User.Username == "" {
|
||||
t.Fatalf("userId=%d but user name/username are empty", *item.UserId)
|
||||
}
|
||||
}
|
||||
|
||||
t.Logf("id=%d branchId=%d branch=%q userId=%v user=%v",
|
||||
item.Id, item.BranchId, item.Branch.Name.Tm, item.UserId, item.User)
|
||||
}
|
||||
|
||||
func TestListIncludesBranchAndUser(t *testing.T) {
|
||||
repo, closeRepo := testRepo(t)
|
||||
defer closeRepo()
|
||||
|
||||
list, err := repo.List(context.Background(), visamaster.ListFilter{Page: 1, Limit: 10})
|
||||
if err != nil {
|
||||
t.Fatalf("List: %v", err)
|
||||
}
|
||||
if list.Count == 0 || len(list.VisaMasterPaymentOrders) == 0 {
|
||||
t.Fatal("List returned no orders")
|
||||
}
|
||||
|
||||
for _, item := range list.VisaMasterPaymentOrders {
|
||||
if item.BranchId != 0 && item.Branch.Name.Tm == "" && item.Branch.Name.En == "" {
|
||||
t.Errorf("order %d branchId=%d missing branch.name", item.Id, item.BranchId)
|
||||
}
|
||||
if item.UserId != nil && (item.User == nil || (item.User.Name == "" && item.User.Username == "")) {
|
||||
t.Errorf("order %d userId=%d missing user details", item.Id, *item.UserId)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -129,17 +129,3 @@ type ListVisaMasterPaymentOrderDTO struct {
|
||||
Count int64 `json:"count"`
|
||||
VisaMasterPaymentOrders []VisaMasterPaymentOrderDTO `json:"visaMasterPaymentOrders"`
|
||||
}
|
||||
|
||||
type BranchByProvinceDTO struct {
|
||||
Id int64 `json:"id"`
|
||||
UniqueCode string `json:"uniqueCode"`
|
||||
Name LocalizedText `json:"name"`
|
||||
Region string `json:"region"`
|
||||
ProvinceId *int64 `json:"provinceId"`
|
||||
Active bool `json:"active"`
|
||||
}
|
||||
|
||||
type ListBranchesByProvinceDTO struct {
|
||||
Count int64 `json:"count"`
|
||||
Branches []BranchByProvinceDTO `json:"branches"`
|
||||
}
|
||||
|
||||
@@ -28,7 +28,6 @@ func NewHandler(logger *logging.Logger, repository Repository) handlers.Handler
|
||||
func (h *handler) Register(router *gin.RouterGroup) {
|
||||
group := router.Group(baseURL, appresult.JwtTokenCheck())
|
||||
group.GET("", h.list)
|
||||
group.GET("/branches", h.listBranchesByProvince)
|
||||
group.GET("/:id", h.getByID)
|
||||
group.POST("", h.create)
|
||||
group.PUT("/:id", h.update)
|
||||
@@ -69,45 +68,6 @@ func (h *handler) list(c *gin.Context) {
|
||||
c.JSON(http.StatusOK, appresult.SuccessWithData(result))
|
||||
}
|
||||
|
||||
// listBranchesByProvince godoc
|
||||
// @Summary List branches by province
|
||||
// @Description Returns branches for the selected province for visa/master payment order forms
|
||||
// @Tags visa-master-payment-orders
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param province_id query int true "Province ID"
|
||||
// @Param active query bool false "Only active branches" default(true)
|
||||
// @Success 200 {object} appresult.AppSuccess
|
||||
// @Failure 400 {object} appresult.AppError
|
||||
// @Failure 500 {object} appresult.AppError
|
||||
// @Router /visa-master-payment-orders/branches [get]
|
||||
func (h *handler) listBranchesByProvince(c *gin.Context) {
|
||||
provinceID, ok := parseID(c.Query("province_id"))
|
||||
if !ok {
|
||||
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
|
||||
return
|
||||
}
|
||||
|
||||
activeOnly := true
|
||||
if raw := c.Query("active"); raw != "" {
|
||||
active, err := strconv.ParseBool(raw)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
|
||||
return
|
||||
}
|
||||
activeOnly = active
|
||||
}
|
||||
|
||||
result, err := h.repository.ListBranchesByProvince(c.Request.Context(), provinceID, activeOnly)
|
||||
if err != nil {
|
||||
h.logger.Errorf("list branches by province failed: %v", err)
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, appresult.SuccessWithData(result))
|
||||
}
|
||||
|
||||
// getByID godoc
|
||||
// @Summary Get visa/master payment order by ID
|
||||
// @Description Returns a single visa/master payment order with branch and user details
|
||||
|
||||
@@ -4,7 +4,6 @@ import "context"
|
||||
|
||||
type Repository interface {
|
||||
List(ctx context.Context, filter ListFilter) (ListVisaMasterPaymentOrderDTO, error)
|
||||
ListBranchesByProvince(ctx context.Context, provinceID int64, activeOnly bool) (ListBranchesByProvinceDTO, error)
|
||||
GetByID(ctx context.Context, id int64) (VisaMasterPaymentOrderDTO, error)
|
||||
Create(ctx context.Context, dto CreateVisaMasterPaymentOrderDTO) (VisaMasterPaymentOrderDTO, error)
|
||||
Update(ctx context.Context, id int64, dto UpdateVisaMasterPaymentOrderDTO) (VisaMasterPaymentOrderDTO, error)
|
||||
|
||||
@@ -12,16 +12,14 @@ import (
|
||||
)
|
||||
|
||||
type repository struct {
|
||||
client postgresql.Client
|
||||
generic *genericrepo.Repository[activitylog.ActivityLogDTO]
|
||||
logger *logging.Logger
|
||||
client postgresql.Client
|
||||
logger *logging.Logger
|
||||
}
|
||||
|
||||
func NewRepository(client postgresql.Client, logger *logging.Logger) activitylog.Repository {
|
||||
return &repository{
|
||||
client: client,
|
||||
generic: genericrepo.New(client, "activity_logs", activityLogColumnsSQL, scanActivityLog),
|
||||
logger: logger,
|
||||
client: client,
|
||||
logger: logger,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -31,13 +29,52 @@ var activityLogColumns = []string{
|
||||
|
||||
var activityLogColumnsSQL = strings.Join(activityLogColumns, ", ")
|
||||
|
||||
const activityLogFromClause = ` FROM activity_logs al
|
||||
LEFT JOIN users u ON u.id = al.user_id
|
||||
LEFT JOIN LATERAL (
|
||||
SELECT ru.role_id
|
||||
FROM role_user ru
|
||||
WHERE ru.user_id = u.id
|
||||
ORDER BY ru.id
|
||||
LIMIT 1
|
||||
) ru ON true
|
||||
LEFT JOIN roles r ON r.id = ru.role_id`
|
||||
|
||||
const activityLogSelectColumns = `al.id, al.user_id, al.method, al.path, al.module, al.action, al.status_code, al.request_body, al.ip, al.created_at, COALESCE(u.username, ''), COALESCE(r.code, '')`
|
||||
|
||||
func (r *repository) List(ctx context.Context, filter activitylog.ListFilter) (activitylog.ListActivityLogDTO, error) {
|
||||
whereClause, args := buildListQuery(filter)
|
||||
|
||||
items, count, err := r.generic.List(ctx, whereClause, args, filter.Page, filter.Limit, "id DESC")
|
||||
var count int64
|
||||
if err := r.client.QueryRow(ctx, `SELECT COUNT(*) FROM activity_logs al`+whereClause, args...).Scan(&count); err != nil {
|
||||
return activitylog.ListActivityLogDTO{}, err
|
||||
}
|
||||
|
||||
offset := (filter.Page - 1) * filter.Limit
|
||||
limitPlaceholder := len(args) + 1
|
||||
offsetPlaceholder := len(args) + 2
|
||||
query := fmt.Sprintf(
|
||||
`SELECT %s%s%s ORDER BY al.id DESC LIMIT $%d OFFSET $%d`,
|
||||
activityLogSelectColumns, activityLogFromClause, whereClause, limitPlaceholder, offsetPlaceholder,
|
||||
)
|
||||
|
||||
rows, err := r.client.Query(ctx, query, append(args, filter.Limit, offset)...)
|
||||
if err != nil {
|
||||
return activitylog.ListActivityLogDTO{}, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var items []activitylog.ActivityLogDTO
|
||||
for rows.Next() {
|
||||
item, err := scanActivityLog(rows)
|
||||
if err != nil {
|
||||
return activitylog.ListActivityLogDTO{}, err
|
||||
}
|
||||
items = append(items, item)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return activitylog.ListActivityLogDTO{}, err
|
||||
}
|
||||
|
||||
return activitylog.ListActivityLogDTO{Count: count, Logs: items}, nil
|
||||
}
|
||||
@@ -47,17 +84,17 @@ func buildListQuery(filter activitylog.ListFilter) (whereClause string, args []i
|
||||
|
||||
if filter.UserId != nil {
|
||||
args = append(args, *filter.UserId)
|
||||
conditions = append(conditions, fmt.Sprintf("user_id = $%d", len(args)))
|
||||
conditions = append(conditions, fmt.Sprintf("al.user_id = $%d", len(args)))
|
||||
}
|
||||
|
||||
if filter.Module != "" {
|
||||
args = append(args, filter.Module)
|
||||
conditions = append(conditions, fmt.Sprintf("module = $%d", len(args)))
|
||||
conditions = append(conditions, fmt.Sprintf("al.module = $%d", len(args)))
|
||||
}
|
||||
|
||||
if filter.Action != "" {
|
||||
args = append(args, filter.Action)
|
||||
conditions = append(conditions, fmt.Sprintf("action = $%d", len(args)))
|
||||
conditions = append(conditions, fmt.Sprintf("al.action = $%d", len(args)))
|
||||
}
|
||||
|
||||
if len(conditions) == 0 {
|
||||
@@ -68,12 +105,28 @@ func buildListQuery(filter activitylog.ListFilter) (whereClause string, args []i
|
||||
}
|
||||
|
||||
func (r *repository) GetByID(ctx context.Context, id int64) (activitylog.ActivityLogDTO, error) {
|
||||
return r.generic.GetByID(ctx, id)
|
||||
query := `SELECT ` + activityLogSelectColumns + activityLogFromClause + ` WHERE al.id = $1`
|
||||
return scanActivityLog(r.client.QueryRow(ctx, query, id))
|
||||
}
|
||||
|
||||
func (r *repository) Create(ctx context.Context, dto activitylog.CreateActivityLogDTO) (activitylog.ActivityLogDTO, error) {
|
||||
query := `INSERT INTO activity_logs (user_id, method, path, module, action, status_code, request_body, ip)
|
||||
VALUES ($1,$2,$3,$4,$5,$6,$7,$8) RETURNING ` + activityLogColumnsSQL
|
||||
query := `
|
||||
WITH inserted AS (
|
||||
INSERT INTO activity_logs (user_id, method, path, module, action, status_code, request_body, ip)
|
||||
VALUES ($1,$2,$3,$4,$5,$6,$7,$8)
|
||||
RETURNING ` + activityLogColumnsSQL + `
|
||||
)
|
||||
SELECT ` + activityLogSelectColumns + `
|
||||
FROM inserted al
|
||||
LEFT JOIN users u ON u.id = al.user_id
|
||||
LEFT JOIN LATERAL (
|
||||
SELECT ru.role_id
|
||||
FROM role_user ru
|
||||
WHERE ru.user_id = u.id
|
||||
ORDER BY ru.id
|
||||
LIMIT 1
|
||||
) ru ON true
|
||||
LEFT JOIN roles r ON r.id = ru.role_id`
|
||||
|
||||
row := r.client.QueryRow(ctx, query,
|
||||
dto.UserId, dto.Method, dto.Path, dto.Module, dto.Action, dto.StatusCode, dto.RequestBody, dto.Ip,
|
||||
@@ -84,14 +137,23 @@ func (r *repository) Create(ctx context.Context, dto activitylog.CreateActivityL
|
||||
func scanActivityLog(row genericrepo.Scanner) (activitylog.ActivityLogDTO, error) {
|
||||
var item activitylog.ActivityLogDTO
|
||||
var requestBody []byte
|
||||
var username, role string
|
||||
|
||||
err := row.Scan(
|
||||
&item.Id, &item.UserId, &item.Method, &item.Path, &item.Module, &item.Action,
|
||||
&item.StatusCode, &requestBody, &item.Ip, &item.CreatedAt,
|
||||
&username, &role,
|
||||
)
|
||||
if err != nil {
|
||||
return activitylog.ActivityLogDTO{}, err
|
||||
}
|
||||
item.RequestBody = requestBody
|
||||
if item.UserId != nil {
|
||||
item.User = &activitylog.UserInfo{
|
||||
Id: *item.UserId,
|
||||
Username: username,
|
||||
Role: role,
|
||||
}
|
||||
}
|
||||
return item, nil
|
||||
}
|
||||
|
||||
@@ -5,9 +5,16 @@ import (
|
||||
"time"
|
||||
)
|
||||
|
||||
type UserInfo struct {
|
||||
Id int64 `json:"id"`
|
||||
Username string `json:"username"`
|
||||
Role string `json:"role"`
|
||||
}
|
||||
|
||||
type ActivityLogDTO struct {
|
||||
Id int64 `json:"id"`
|
||||
UserId *int64 `json:"userId"`
|
||||
User *UserInfo `json:"user"`
|
||||
Method string `json:"method"`
|
||||
Path string `json:"path"`
|
||||
Module string `json:"module"`
|
||||
|
||||
@@ -4,6 +4,7 @@ import (
|
||||
"errors"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"online-back/internal/appresult"
|
||||
"online-back/internal/handlers"
|
||||
@@ -34,7 +35,7 @@ func (h *handler) Register(router *gin.RouterGroup) {
|
||||
|
||||
// list godoc
|
||||
// @Summary List activity logs
|
||||
// @Description Returns a paginated audit trail of user actions (create/update/delete)
|
||||
// @Description Returns a paginated audit trail of user actions (create/update/delete). Each log includes the actor's username and role from role_user.
|
||||
// @Tags activity-logs
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
@@ -79,7 +80,13 @@ func (h *handler) list(c *gin.Context) {
|
||||
func (h *handler) getByID(c *gin.Context) {
|
||||
id, ok := parseID(c.Param("id"))
|
||||
if !ok {
|
||||
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
|
||||
// GET /activity-logs/card-orders → list that module instead of 400.
|
||||
q := c.Request.URL.Query()
|
||||
if q.Get("module") == "" {
|
||||
q.Set("module", c.Param("id"))
|
||||
c.Request.URL.RawQuery = q.Encode()
|
||||
}
|
||||
h.list(c)
|
||||
return
|
||||
}
|
||||
|
||||
@@ -117,18 +124,16 @@ func parseListFilter(c *gin.Context) (ListFilter, bool) {
|
||||
Limit: defaultLimit,
|
||||
}
|
||||
|
||||
if raw := c.Query("user_id"); raw != "" {
|
||||
id, ok := parseID(raw)
|
||||
if !ok {
|
||||
return ListFilter{}, false
|
||||
}
|
||||
filter.UserId = &id
|
||||
if id, ok := optionalQueryID(c, "user_id", "userId"); !ok {
|
||||
return ListFilter{}, false
|
||||
} else if id != nil {
|
||||
filter.UserId = id
|
||||
}
|
||||
|
||||
filter.Module = c.Query("module")
|
||||
filter.Action = c.Query("action")
|
||||
filter.Module = queryValue(c, "module")
|
||||
filter.Action = queryValue(c, "action")
|
||||
|
||||
if raw := c.Query("page"); raw != "" {
|
||||
if raw := queryValue(c, "page"); raw != "" {
|
||||
page, err := strconv.Atoi(raw)
|
||||
if err != nil || page < 1 {
|
||||
return ListFilter{}, false
|
||||
@@ -136,13 +141,37 @@ func parseListFilter(c *gin.Context) (ListFilter, bool) {
|
||||
filter.Page = page
|
||||
}
|
||||
|
||||
if raw := c.Query("limit"); raw != "" {
|
||||
if raw := queryValue(c, "limit"); raw != "" {
|
||||
limit, err := strconv.Atoi(raw)
|
||||
if err != nil || limit < 1 || limit > maxLimit {
|
||||
if err != nil || limit < 1 {
|
||||
return ListFilter{}, false
|
||||
}
|
||||
if limit > maxLimit {
|
||||
limit = maxLimit
|
||||
}
|
||||
filter.Limit = limit
|
||||
}
|
||||
|
||||
return filter, true
|
||||
}
|
||||
|
||||
func queryValue(c *gin.Context, keys ...string) string {
|
||||
for _, key := range keys {
|
||||
if raw := strings.TrimSpace(c.Query(key)); raw != "" && raw != "undefined" && raw != "null" {
|
||||
return raw
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func optionalQueryID(c *gin.Context, keys ...string) (*int64, bool) {
|
||||
raw := queryValue(c, keys...)
|
||||
if raw == "" {
|
||||
return nil, true
|
||||
}
|
||||
id, ok := parseID(raw)
|
||||
if !ok {
|
||||
return nil, false
|
||||
}
|
||||
return &id, true
|
||||
}
|
||||
|
||||
96
internal/identity/activitylog/handler_test.go
Normal file
96
internal/identity/activitylog/handler_test.go
Normal file
@@ -0,0 +1,96 @@
|
||||
package activitylog
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"sync"
|
||||
"testing"
|
||||
|
||||
"online-back/pkg/logging"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
type stubRepository struct {
|
||||
mu sync.Mutex
|
||||
listFilter ListFilter
|
||||
listResult ListActivityLogDTO
|
||||
created []CreateActivityLogDTO
|
||||
}
|
||||
|
||||
func (s *stubRepository) List(_ context.Context, filter ListFilter) (ListActivityLogDTO, error) {
|
||||
s.listFilter = filter
|
||||
return s.listResult, nil
|
||||
}
|
||||
|
||||
func (s *stubRepository) GetByID(_ context.Context, _ int64) (ActivityLogDTO, error) {
|
||||
return ActivityLogDTO{}, nil
|
||||
}
|
||||
|
||||
func (s *stubRepository) Create(_ context.Context, dto CreateActivityLogDTO) (ActivityLogDTO, error) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
s.created = append(s.created, dto)
|
||||
return ActivityLogDTO{Id: 1}, nil
|
||||
}
|
||||
|
||||
func (s *stubRepository) createdEntries() []CreateActivityLogDTO {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
out := make([]CreateActivityLogDTO, len(s.created))
|
||||
copy(out, s.created)
|
||||
return out
|
||||
}
|
||||
|
||||
func TestParseListFilterIgnoresUndefinedAndCapsLimit(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
|
||||
w := httptest.NewRecorder()
|
||||
c, _ := gin.CreateTestContext(w)
|
||||
req := httptest.NewRequest(http.MethodGet, "/activity-logs?user_id=undefined&module=card-orders&limit=1000&page=2", nil)
|
||||
c.Request = req
|
||||
|
||||
filter, ok := parseListFilter(c)
|
||||
if !ok {
|
||||
t.Fatal("expected filter to parse")
|
||||
}
|
||||
if filter.UserId != nil {
|
||||
t.Fatalf("user_id should be ignored, got %v", *filter.UserId)
|
||||
}
|
||||
if filter.Module != "card-orders" {
|
||||
t.Fatalf("module=%q", filter.Module)
|
||||
}
|
||||
if filter.Limit != maxLimit {
|
||||
t.Fatalf("limit=%d", filter.Limit)
|
||||
}
|
||||
if filter.Page != 2 {
|
||||
t.Fatalf("page=%d", filter.Page)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGetByIDListsModuleWhenPathIsNotNumeric(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
|
||||
repo := &stubRepository{listResult: ListActivityLogDTO{Count: 0, Logs: []ActivityLogDTO{}}}
|
||||
h := &handler{logger: logging.GetLogger(), repository: repo}
|
||||
|
||||
r := gin.New()
|
||||
group := r.Group("/activity-logs")
|
||||
group.GET("", h.list)
|
||||
group.GET("/:id", h.getByID)
|
||||
|
||||
w := httptest.NewRecorder()
|
||||
req := httptest.NewRequest(http.MethodGet, "/activity-logs/card-orders?limit=1000", nil)
|
||||
r.ServeHTTP(w, req)
|
||||
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("status=%d body=%s", w.Code, w.Body.String())
|
||||
}
|
||||
if repo.listFilter.Module != "card-orders" {
|
||||
t.Fatalf("module=%q", repo.listFilter.Module)
|
||||
}
|
||||
if repo.listFilter.Limit != maxLimit {
|
||||
t.Fatalf("limit=%d", repo.listFilter.Limit)
|
||||
}
|
||||
}
|
||||
@@ -15,53 +15,87 @@ import (
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// sensitiveFieldSubstrings marks request body keys that must never be
|
||||
// persisted verbatim (login passwords, branch billing credentials, etc).
|
||||
var sensitiveFieldSubstrings = []string{"password", "token", "secret"}
|
||||
|
||||
const writeTimeout = 5 * time.Second
|
||||
const (
|
||||
writeTimeout = 5 * time.Second
|
||||
queueSize = 1024
|
||||
workers = 2
|
||||
)
|
||||
|
||||
type recorder struct {
|
||||
repository Repository
|
||||
logger *logging.Logger
|
||||
queue chan CreateActivityLogDTO
|
||||
}
|
||||
|
||||
// Record returns a global gin middleware that persists every mutating
|
||||
// (POST/PUT/PATCH/DELETE) request made by an authenticated user into
|
||||
// activity_logs - e.g. creating a card or attaching a user to a branch.
|
||||
// Read-only (GET) requests are not recorded. It must run after
|
||||
// appresult.JwtTokenCheck has set "id" in the context, which happens
|
||||
// naturally here since c.Next() runs the rest of the chain first.
|
||||
// Read-only (GET) requests are not recorded. After the handler finishes
|
||||
// the entry is queued (the client is not blocked) and a small worker
|
||||
// pool writes it. JwtTokenCheck sets "id" during c.Next(), which is why
|
||||
// the user is read afterwards.
|
||||
func Record(repository Repository, logger *logging.Logger) gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
if !shouldRecord(c.Request.Method) {
|
||||
c.Next()
|
||||
return
|
||||
}
|
||||
return newRecorder(repository, logger).handle
|
||||
}
|
||||
|
||||
body := readAndRestoreBody(c)
|
||||
func newRecorder(repository Repository, logger *logging.Logger) *recorder {
|
||||
r := &recorder{
|
||||
repository: repository,
|
||||
logger: logger,
|
||||
queue: make(chan CreateActivityLogDTO, queueSize),
|
||||
}
|
||||
for i := 0; i < workers; i++ {
|
||||
go r.worker()
|
||||
}
|
||||
return r
|
||||
}
|
||||
|
||||
func (r *recorder) handle(c *gin.Context) {
|
||||
if !shouldRecord(c.Request.Method) {
|
||||
c.Next()
|
||||
return
|
||||
}
|
||||
|
||||
userID := currentUserID(c)
|
||||
if userID == nil {
|
||||
return
|
||||
body := readAndRestoreBody(c)
|
||||
|
||||
c.Next()
|
||||
|
||||
userID := currentUserID(c)
|
||||
if userID == nil {
|
||||
return
|
||||
}
|
||||
|
||||
id := *userID
|
||||
module, action := describeRoute(c)
|
||||
r.enqueue(CreateActivityLogDTO{
|
||||
UserId: &id,
|
||||
Method: c.Request.Method,
|
||||
Path: c.Request.URL.Path,
|
||||
Module: module,
|
||||
Action: action,
|
||||
StatusCode: c.Writer.Status(),
|
||||
RequestBody: redact(body),
|
||||
Ip: c.ClientIP(),
|
||||
})
|
||||
}
|
||||
|
||||
func (r *recorder) enqueue(entry CreateActivityLogDTO) {
|
||||
select {
|
||||
case r.queue <- entry:
|
||||
default:
|
||||
r.logger.Errorf("activity log queue full, dropping %s %s", entry.Method, entry.Path)
|
||||
}
|
||||
}
|
||||
|
||||
func (r *recorder) worker() {
|
||||
for entry := range r.queue {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), writeTimeout)
|
||||
if _, err := r.repository.Create(ctx, entry); err != nil {
|
||||
r.logger.Errorf("record activity log failed: %v", err)
|
||||
}
|
||||
|
||||
module, action := describeRoute(c)
|
||||
entry := CreateActivityLogDTO{
|
||||
UserId: userID,
|
||||
Method: c.Request.Method,
|
||||
Path: c.Request.URL.Path,
|
||||
Module: module,
|
||||
Action: action,
|
||||
StatusCode: c.Writer.Status(),
|
||||
RequestBody: redact(body),
|
||||
Ip: c.ClientIP(),
|
||||
}
|
||||
|
||||
go func() {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), writeTimeout)
|
||||
defer cancel()
|
||||
if _, err := repository.Create(ctx, entry); err != nil {
|
||||
logger.Errorf("record activity log failed: %v", err)
|
||||
}
|
||||
}()
|
||||
cancel()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -80,9 +114,13 @@ func readAndRestoreBody(c *gin.Context) []byte {
|
||||
}
|
||||
data, err := io.ReadAll(c.Request.Body)
|
||||
if err != nil {
|
||||
c.Request.Body = io.NopCloser(bytes.NewReader(nil))
|
||||
return nil
|
||||
}
|
||||
// Restore Body for ShouldBindJSON and cache it so ShouldBindBodyWithJSON
|
||||
// still works after this middleware has already consumed the stream.
|
||||
c.Request.Body = io.NopCloser(bytes.NewReader(data))
|
||||
c.Set(gin.BodyBytesKey, data)
|
||||
return data
|
||||
}
|
||||
|
||||
|
||||
71
internal/identity/activitylog/middleware_test.go
Normal file
71
internal/identity/activitylog/middleware_test.go
Normal file
@@ -0,0 +1,71 @@
|
||||
package activitylog
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"online-back/pkg/logging"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
func TestRecordLeavesJSONBodyForHandler(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
|
||||
repo := &stubRepository{}
|
||||
r := gin.New()
|
||||
r.Use(Record(repo, logging.GetLogger()))
|
||||
r.POST("/api/admin/card-orders", func(c *gin.Context) {
|
||||
c.Set("id", "3")
|
||||
var dto struct {
|
||||
CustomerName string `json:"customerName" binding:"required"`
|
||||
Region string `json:"region" binding:"required"`
|
||||
}
|
||||
if err := c.ShouldBindBodyWithJSON(&dto); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusCreated, dto)
|
||||
})
|
||||
|
||||
body := `{"customerName":"Simple","region":"Aşgabat"}`
|
||||
w := httptest.NewRecorder()
|
||||
req := httptest.NewRequest(http.MethodPost, "/api/admin/card-orders", bytes.NewBufferString(body))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
r.ServeHTTP(w, req)
|
||||
|
||||
if w.Code != http.StatusCreated {
|
||||
t.Fatalf("status=%d body=%s", w.Code, w.Body.String())
|
||||
}
|
||||
|
||||
deadline := time.Now().Add(time.Second)
|
||||
var created []CreateActivityLogDTO
|
||||
for time.Now().Before(deadline) {
|
||||
created = repo.createdEntries()
|
||||
if len(created) > 0 {
|
||||
break
|
||||
}
|
||||
time.Sleep(10 * time.Millisecond)
|
||||
}
|
||||
if len(created) == 0 {
|
||||
t.Fatal("expected activity log to be recorded")
|
||||
}
|
||||
if created[0].Module != "card-orders" {
|
||||
t.Fatalf("module=%q", created[0].Module)
|
||||
}
|
||||
if created[0].StatusCode != http.StatusCreated {
|
||||
t.Fatalf("statusCode=%d", created[0].StatusCode)
|
||||
}
|
||||
|
||||
var logged map[string]interface{}
|
||||
if err := json.Unmarshal(created[0].RequestBody, &logged); err != nil {
|
||||
t.Fatalf("request body: %v", err)
|
||||
}
|
||||
if logged["customerName"] != "Simple" {
|
||||
t.Fatalf("logged body=%v", logged)
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,8 @@ package db
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"strings"
|
||||
"unicode"
|
||||
@@ -38,10 +40,36 @@ const (
|
||||
OR ($2 <> '' AND regexp_replace(phone, '[^0-9]', '', 'g') = $2)
|
||||
LIMIT 1`
|
||||
userByIDQuery = `SELECT id, password FROM users WHERE id = $1`
|
||||
profileQuery = `SELECT id, name, first_name, last_name, phone, avatar, created_at
|
||||
FROM users WHERE id = $1`
|
||||
)
|
||||
|
||||
const profileFromClause = ` FROM users u
|
||||
LEFT JOIN LATERAL (
|
||||
SELECT ru.role_id
|
||||
FROM role_user ru
|
||||
WHERE ru.user_id = u.id
|
||||
ORDER BY ru.id
|
||||
LIMIT 1
|
||||
) ru ON true
|
||||
LEFT JOIN roles r ON r.id = ru.role_id`
|
||||
|
||||
const profileBranchesJSON = `COALESCE((
|
||||
SELECT json_agg(jsonb_build_object(
|
||||
'id', b.id,
|
||||
'uniqueCode', COALESCE(b.unique_code, ''),
|
||||
'name', b.name
|
||||
) ORDER BY b.id)
|
||||
FROM (
|
||||
SELECT DISTINCT ON (b.id) b.id, b.unique_code, b.name
|
||||
FROM branch_user bu
|
||||
JOIN branches b ON b.id = bu.branch_id
|
||||
WHERE bu.user_id = u.id
|
||||
ORDER BY b.id
|
||||
) b
|
||||
), '[]'::json)`
|
||||
|
||||
const profileQuery = `SELECT u.id, u.name, u.first_name, u.last_name, u.phone, u.avatar, u.created_at,
|
||||
r.id, r.code, r.name, ` + profileBranchesJSON + profileFromClause + ` WHERE u.id = $1`
|
||||
|
||||
func (r *repository) Login(ctx context.Context, dto auth.LoginDTO) (auth.UserCredentials, error) {
|
||||
phone := strings.TrimSpace(dto.Phone)
|
||||
if phone != "" {
|
||||
@@ -66,31 +94,39 @@ func (r *repository) GetUserByID(ctx context.Context, id int) (auth.UserCredenti
|
||||
}
|
||||
|
||||
func (r *repository) GetProfile(ctx context.Context, id int) (auth.UserProfileDTO, error) {
|
||||
var profile auth.UserProfileDTO
|
||||
err := r.client.QueryRow(ctx, profileQuery, id).Scan(
|
||||
&profile.Id,
|
||||
&profile.Name,
|
||||
&profile.FirstName,
|
||||
&profile.LastName,
|
||||
&profile.Phone,
|
||||
&profile.Avatar,
|
||||
&profile.CreatedAt,
|
||||
)
|
||||
return profile, err
|
||||
return scanProfile(r.client.QueryRow(ctx, profileQuery, id))
|
||||
}
|
||||
|
||||
const updateProfileQuery = `
|
||||
UPDATE users SET
|
||||
name = $1, first_name = $2, last_name = $3, phone = $4, avatar = $5,
|
||||
updated_at = (CURRENT_TIMESTAMP AT TIME ZONE 'UTC')
|
||||
WHERE id = $6
|
||||
RETURNING id, name, first_name, last_name, phone, avatar, created_at`
|
||||
WHERE id = $6`
|
||||
|
||||
func (r *repository) UpdateProfile(ctx context.Context, id int, dto auth.UpdateProfileDTO) (auth.UserProfileDTO, error) {
|
||||
var profile auth.UserProfileDTO
|
||||
err := r.client.QueryRow(ctx, updateProfileQuery,
|
||||
tag, err := r.client.Exec(ctx, updateProfileQuery,
|
||||
dto.Name, dto.FirstName, dto.LastName, dto.Phone, dto.Avatar, id,
|
||||
).Scan(
|
||||
)
|
||||
if err != nil {
|
||||
return auth.UserProfileDTO{}, err
|
||||
}
|
||||
if tag.RowsAffected() == 0 {
|
||||
return auth.UserProfileDTO{}, pgx.ErrNoRows
|
||||
}
|
||||
return r.GetProfile(ctx, id)
|
||||
}
|
||||
|
||||
type scannable interface {
|
||||
Scan(dest ...interface{}) error
|
||||
}
|
||||
|
||||
func scanProfile(row scannable) (auth.UserProfileDTO, error) {
|
||||
var profile auth.UserProfileDTO
|
||||
var roleID sql.NullInt64
|
||||
var roleCode, roleName sql.NullString
|
||||
var branchesJSON []byte
|
||||
|
||||
err := row.Scan(
|
||||
&profile.Id,
|
||||
&profile.Name,
|
||||
&profile.FirstName,
|
||||
@@ -98,11 +134,31 @@ func (r *repository) UpdateProfile(ctx context.Context, id int, dto auth.UpdateP
|
||||
&profile.Phone,
|
||||
&profile.Avatar,
|
||||
&profile.CreatedAt,
|
||||
&roleID,
|
||||
&roleCode,
|
||||
&roleName,
|
||||
&branchesJSON,
|
||||
)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
if err != nil {
|
||||
return auth.UserProfileDTO{}, err
|
||||
}
|
||||
return profile, err
|
||||
|
||||
if roleID.Valid {
|
||||
profile.Role = &auth.ProfileRoleDTO{
|
||||
Id: roleID.Int64,
|
||||
Code: roleCode.String,
|
||||
Name: roleName.String,
|
||||
}
|
||||
}
|
||||
|
||||
if len(branchesJSON) == 0 || string(branchesJSON) == "null" {
|
||||
profile.Branches = []auth.ProfileBranchDTO{}
|
||||
return profile, nil
|
||||
}
|
||||
if err := json.Unmarshal(branchesJSON, &profile.Branches); err != nil {
|
||||
return auth.UserProfileDTO{}, err
|
||||
}
|
||||
return profile, nil
|
||||
}
|
||||
|
||||
func (r *repository) UserExists(ctx context.Context, username, phone string) (bool, error) {
|
||||
|
||||
@@ -12,14 +12,34 @@ type RefreshTokenDTO struct {
|
||||
RefreshToken string `json:"refreshToken" binding:"required"`
|
||||
}
|
||||
|
||||
type LocalizedText struct {
|
||||
En string `json:"en"`
|
||||
Ru string `json:"ru"`
|
||||
Tm string `json:"tm"`
|
||||
}
|
||||
|
||||
type ProfileRoleDTO struct {
|
||||
Id int64 `json:"id"`
|
||||
Code string `json:"code"`
|
||||
Name string `json:"name"`
|
||||
}
|
||||
|
||||
type ProfileBranchDTO struct {
|
||||
Id int64 `json:"id"`
|
||||
UniqueCode string `json:"uniqueCode"`
|
||||
Name LocalizedText `json:"name"`
|
||||
}
|
||||
|
||||
type UserProfileDTO struct {
|
||||
Id int `json:"id"`
|
||||
Name string `json:"name"`
|
||||
FirstName string `json:"firstName"`
|
||||
LastName string `json:"lastName"`
|
||||
Phone string `json:"phone"`
|
||||
Avatar string `json:"avatar"`
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
Id int `json:"id"`
|
||||
Name string `json:"name"`
|
||||
FirstName string `json:"firstName"`
|
||||
LastName string `json:"lastName"`
|
||||
Phone string `json:"phone"`
|
||||
Avatar string `json:"avatar"`
|
||||
Role *ProfileRoleDTO `json:"role"`
|
||||
Branches []ProfileBranchDTO `json:"branches"`
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
}
|
||||
|
||||
type UpdateProfileDTO struct {
|
||||
|
||||
@@ -242,7 +242,7 @@ func (h *handler) refreshToken(c *gin.Context) {
|
||||
|
||||
// getProfile godoc
|
||||
// @Summary Get profile
|
||||
// @Description Returns the authenticated user's profile
|
||||
// @Description Returns the authenticated user's profile with role and branches
|
||||
// @Tags auth
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
|
||||
@@ -1,48 +0,0 @@
|
||||
package auth
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestNormalizePhone(t *testing.T) {
|
||||
tests := []struct {
|
||||
in, want string
|
||||
}{
|
||||
{"+99361531216", "+993 61 53 12 16"},
|
||||
{"+993 61 92 92 48", "+993 61 92 92 48"},
|
||||
{"+99361929248", "+993 61 92 92 48"},
|
||||
{"99361929248", "+993 61 92 92 48"},
|
||||
{"61929248", "+993 61 92 92 48"},
|
||||
{"8 61929248", "+993 61 92 92 48"},
|
||||
{"61 92 92 48", "+993 61 92 92 48"},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
got, err := NormalizePhone(tt.in)
|
||||
if err != nil {
|
||||
t.Fatalf("NormalizePhone(%q) unexpected error: %v", tt.in, err)
|
||||
}
|
||||
if got != tt.want {
|
||||
t.Errorf("NormalizePhone(%q) = %q, want %q", tt.in, got, tt.want)
|
||||
}
|
||||
}
|
||||
|
||||
if _, err := NormalizePhone("123"); err != ErrInvalidPhone {
|
||||
t.Errorf("NormalizePhone(123) error = %v, want ErrInvalidPhone", err)
|
||||
}
|
||||
|
||||
validPrefixes := []string{"61", "62", "63", "64", "65", "71", "72"}
|
||||
for _, prefix := range validPrefixes {
|
||||
in := prefix + "929248"
|
||||
if _, err := NormalizePhone(in); err != nil {
|
||||
t.Errorf("NormalizePhone(%q) unexpected error: %v", in, err)
|
||||
}
|
||||
}
|
||||
|
||||
invalid := []string{
|
||||
"60929248", "66929248", "70929248", "73929248", "81929248",
|
||||
"+99366531216", "+99360929248",
|
||||
}
|
||||
for _, in := range invalid {
|
||||
if _, err := NormalizePhone(in); err != ErrInvalidPhone {
|
||||
t.Errorf("NormalizePhone(%q) error = %v, want ErrInvalidPhone", in, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,293 +0,0 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
)
|
||||
|
||||
type fakeRepo struct {
|
||||
exists bool
|
||||
usernameTaken bool
|
||||
verification Verification
|
||||
getErr error
|
||||
userID int
|
||||
userByName UserIdentity
|
||||
userByNameErr error
|
||||
loginUser UserCredentials
|
||||
loginErr error
|
||||
lastLogin LoginDTO
|
||||
}
|
||||
|
||||
func (f *fakeRepo) Login(_ context.Context, dto LoginDTO) (UserCredentials, error) {
|
||||
f.lastLogin = dto
|
||||
if f.loginErr != nil {
|
||||
return UserCredentials{}, f.loginErr
|
||||
}
|
||||
return f.loginUser, nil
|
||||
}
|
||||
func (f *fakeRepo) GetUserByID(context.Context, int) (UserCredentials, error) {
|
||||
return UserCredentials{}, errors.New("not implemented")
|
||||
}
|
||||
func (f *fakeRepo) GetProfile(context.Context, int) (UserProfileDTO, error) {
|
||||
return UserProfileDTO{}, errors.New("not implemented")
|
||||
}
|
||||
func (f *fakeRepo) UpdateProfile(context.Context, int, UpdateProfileDTO) (UserProfileDTO, error) {
|
||||
return UserProfileDTO{}, errors.New("not implemented")
|
||||
}
|
||||
func (f *fakeRepo) UserExists(context.Context, string, string) (bool, error) {
|
||||
return f.exists, nil
|
||||
}
|
||||
func (f *fakeRepo) UsernameTaken(context.Context, string, string) (bool, error) {
|
||||
return f.usernameTaken, nil
|
||||
}
|
||||
func (f *fakeRepo) UpsertVerification(_ context.Context, v Verification) error {
|
||||
f.verification = v
|
||||
return nil
|
||||
}
|
||||
func (f *fakeRepo) GetVerificationByPhone(context.Context, string) (Verification, error) {
|
||||
return f.verification, f.getErr
|
||||
}
|
||||
func (f *fakeRepo) IncrementVerifyAttempts(context.Context, int64) error {
|
||||
f.verification.Attempts++
|
||||
return nil
|
||||
}
|
||||
func (f *fakeRepo) CompleteRegistration(context.Context, Verification) (int, error) {
|
||||
return f.userID, nil
|
||||
}
|
||||
func (f *fakeRepo) GetUserByName(context.Context, string) (UserIdentity, error) {
|
||||
if f.userByNameErr != nil {
|
||||
return UserIdentity{}, f.userByNameErr
|
||||
}
|
||||
return f.userByName, nil
|
||||
}
|
||||
func (f *fakeRepo) CompletePasswordReset(context.Context, int, int64, string) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
type fakeSMS struct {
|
||||
phone, message string
|
||||
err error
|
||||
}
|
||||
|
||||
func (f *fakeSMS) Send(_ context.Context, phone, message string) error {
|
||||
f.phone = phone
|
||||
f.message = message
|
||||
return f.err
|
||||
}
|
||||
|
||||
func validRegisterDTO() RegisterDTO {
|
||||
return RegisterDTO{
|
||||
Name: "Berdi Berdiyew",
|
||||
Phone: "+993 61 92 92 48",
|
||||
Username: "berdi",
|
||||
Password: "secret1",
|
||||
PasswordConfirm: "secret1",
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoginRequiresNameOrPhone(t *testing.T) {
|
||||
_, err := NewService(&fakeRepo{}, &fakeSMS{}).Login(context.Background(), LoginDTO{
|
||||
Password: "secret1",
|
||||
})
|
||||
if !errors.Is(err, ErrInvalidInput) {
|
||||
t.Fatalf("error = %v, want ErrInvalidInput", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoginIgnoresInvalidPhoneWhenNamePresent(t *testing.T) {
|
||||
repo := &fakeRepo{loginErr: errors.New("stop after lookup")}
|
||||
_, _ = NewService(repo, &fakeSMS{}).Login(context.Background(), LoginDTO{
|
||||
Name: "admin",
|
||||
Phone: "string",
|
||||
Password: "Test1234!",
|
||||
})
|
||||
if repo.lastLogin.Name != "admin" {
|
||||
t.Fatalf("name = %q, want admin", repo.lastLogin.Name)
|
||||
}
|
||||
if repo.lastLogin.Phone != "" {
|
||||
t.Fatalf("phone = %q, want empty", repo.lastLogin.Phone)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoginInvalidPhoneWithoutName(t *testing.T) {
|
||||
_, err := NewService(&fakeRepo{}, &fakeSMS{}).Login(context.Background(), LoginDTO{
|
||||
Phone: "string",
|
||||
Password: "secret1",
|
||||
})
|
||||
if !errors.Is(err, ErrInvalidInput) {
|
||||
t.Fatalf("error = %v, want ErrInvalidInput", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoginWrongPassword(t *testing.T) {
|
||||
hash, err := bcrypt.GenerateFromPassword([]byte("secret1"), bcrypt.MinCost)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_, err = NewService(&fakeRepo{loginUser: UserCredentials{Id: 7, Password: string(hash)}}, &fakeSMS{}).Login(context.Background(), LoginDTO{
|
||||
Name: "Berdi Berdiyew",
|
||||
Password: "wrong",
|
||||
})
|
||||
if !errors.Is(err, ErrInvalidCredentials) {
|
||||
t.Fatalf("error = %v, want ErrInvalidCredentials", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRegisterPasswordMismatch(t *testing.T) {
|
||||
dto := validRegisterDTO()
|
||||
dto.PasswordConfirm = "other"
|
||||
_, err := NewService(&fakeRepo{}, &fakeSMS{}).Register(context.Background(), dto)
|
||||
if !errors.Is(err, ErrPasswordMismatch) {
|
||||
t.Fatalf("error = %v, want ErrPasswordMismatch", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRegisterConflict(t *testing.T) {
|
||||
_, err := NewService(&fakeRepo{exists: true}, &fakeSMS{}).Register(context.Background(), validRegisterDTO())
|
||||
if !errors.Is(err, ErrConflict) {
|
||||
t.Fatalf("error = %v, want ErrConflict", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRegisterSendsSMS(t *testing.T) {
|
||||
repo := &fakeRepo{}
|
||||
sender := &fakeSMS{}
|
||||
result, err := NewService(repo, sender).Register(context.Background(), validRegisterDTO())
|
||||
if err != nil {
|
||||
t.Fatalf("Register: %v", err)
|
||||
}
|
||||
if result.Phone != "+993 61 92 92 48" {
|
||||
t.Errorf("phone = %q", result.Phone)
|
||||
}
|
||||
if result.ExpiresIn != 60 {
|
||||
t.Errorf("expiresIn = %d", result.ExpiresIn)
|
||||
}
|
||||
if sender.phone != result.Phone {
|
||||
t.Errorf("sms phone = %q", sender.phone)
|
||||
}
|
||||
if !strings.Contains(sender.message, "123456") {
|
||||
t.Errorf("sms message = %q", sender.message)
|
||||
}
|
||||
if repo.verification.Password == "secret1" {
|
||||
t.Fatal("password stored in plaintext")
|
||||
}
|
||||
}
|
||||
|
||||
func TestVerifyWrongCode(t *testing.T) {
|
||||
hash, err := bcrypt.GenerateFromPassword([]byte("123456"), bcrypt.MinCost)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
repo := &fakeRepo{verification: Verification{
|
||||
ID: 1,
|
||||
Phone: "+993 61 92 92 48",
|
||||
CodeHash: string(hash),
|
||||
ExpiresAt: time.Now().UTC().Add(time.Minute),
|
||||
}}
|
||||
_, err = NewService(repo, &fakeSMS{}).Verify(context.Background(), VerifyDTO{
|
||||
Phone: "+993 61 92 92 48",
|
||||
Code: "000000",
|
||||
})
|
||||
if !errors.Is(err, ErrInvalidCode) {
|
||||
t.Fatalf("error = %v, want ErrInvalidCode", err)
|
||||
}
|
||||
if repo.verification.Attempts != 1 {
|
||||
t.Errorf("attempts = %d, want 1", repo.verification.Attempts)
|
||||
}
|
||||
}
|
||||
|
||||
func TestVerifyExpiredCode(t *testing.T) {
|
||||
repo := &fakeRepo{verification: Verification{
|
||||
ExpiresAt: time.Now().UTC().Add(-time.Minute),
|
||||
}}
|
||||
_, err := NewService(repo, &fakeSMS{}).Verify(context.Background(), VerifyDTO{
|
||||
Phone: "+993 61 92 92 48",
|
||||
Code: "123456",
|
||||
})
|
||||
if !errors.Is(err, ErrInvalidCode) {
|
||||
t.Fatalf("error = %v, want ErrInvalidCode", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestForgotPasswordRequiresName(t *testing.T) {
|
||||
_, err := NewService(&fakeRepo{}, &fakeSMS{}).ForgotPassword(context.Background(), ForgotPasswordDTO{})
|
||||
if !errors.Is(err, ErrInvalidInput) {
|
||||
t.Fatalf("error = %v, want ErrInvalidInput", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestForgotPasswordNotFound(t *testing.T) {
|
||||
_, err := NewService(&fakeRepo{userByNameErr: ErrNotFound}, &fakeSMS{}).ForgotPassword(context.Background(), ForgotPasswordDTO{
|
||||
Name: "Berdi Berdiyew",
|
||||
})
|
||||
if !errors.Is(err, ErrNotFound) {
|
||||
t.Fatalf("error = %v, want ErrNotFound", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestForgotPasswordSendsSMS(t *testing.T) {
|
||||
repo := &fakeRepo{userByName: UserIdentity{
|
||||
Id: 7,
|
||||
Name: "Berdi Berdiyew",
|
||||
Username: "berdi",
|
||||
Phone: "+993 61 92 92 48",
|
||||
}}
|
||||
sender := &fakeSMS{}
|
||||
result, err := NewService(repo, sender).ForgotPassword(context.Background(), ForgotPasswordDTO{
|
||||
Name: "Berdi Berdiyew",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("ForgotPassword: %v", err)
|
||||
}
|
||||
if result.Phone != "+993 61 92 92 48" {
|
||||
t.Errorf("phone = %q", result.Phone)
|
||||
}
|
||||
if sender.phone != result.Phone {
|
||||
t.Errorf("sms phone = %q", sender.phone)
|
||||
}
|
||||
if !strings.Contains(sender.message, "123456") {
|
||||
t.Errorf("sms message = %q", sender.message)
|
||||
}
|
||||
}
|
||||
|
||||
func TestResetPasswordMismatch(t *testing.T) {
|
||||
_, err := NewService(&fakeRepo{}, &fakeSMS{}).ResetPassword(context.Background(), ResetPasswordDTO{
|
||||
Name: "Berdi Berdiyew",
|
||||
Code: "123456",
|
||||
Password: "secret1",
|
||||
PasswordConfirm: "other",
|
||||
})
|
||||
if !errors.Is(err, ErrPasswordMismatch) {
|
||||
t.Fatalf("error = %v, want ErrPasswordMismatch", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestResetPasswordWrongCode(t *testing.T) {
|
||||
hash, err := bcrypt.GenerateFromPassword([]byte("123456"), bcrypt.MinCost)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
repo := &fakeRepo{
|
||||
userByName: UserIdentity{Id: 7, Phone: "+993 61 92 92 48"},
|
||||
verification: Verification{
|
||||
ID: 1,
|
||||
Phone: "+993 61 92 92 48",
|
||||
CodeHash: string(hash),
|
||||
ExpiresAt: time.Now().UTC().Add(time.Minute),
|
||||
},
|
||||
}
|
||||
_, err = NewService(repo, &fakeSMS{}).ResetPassword(context.Background(), ResetPasswordDTO{
|
||||
Name: "Berdi Berdiyew",
|
||||
Code: "000000",
|
||||
Password: "secret1",
|
||||
PasswordConfirm: "secret1",
|
||||
})
|
||||
if !errors.Is(err, ErrInvalidCode) {
|
||||
t.Fatalf("error = %v, want ErrInvalidCode", err)
|
||||
}
|
||||
}
|
||||
@@ -3,8 +3,6 @@ package db
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"online-back/internal/identity/roleusers"
|
||||
"online-back/pkg/client/postgresql"
|
||||
@@ -22,80 +20,30 @@ func NewRepository(client postgresql.Client, logger *logging.Logger) roleusers.R
|
||||
return &repository{client: client, logger: logger}
|
||||
}
|
||||
|
||||
const roleUserFromClause = ` FROM role_user ru
|
||||
JOIN roles r ON r.id = ru.role_id
|
||||
JOIN users u ON u.id = ru.user_id`
|
||||
|
||||
const roleUserSelectColumns = `ru.id, ru.role_id, r.name, ru.user_id, u.name, ru.created_at, ru.updated_at`
|
||||
|
||||
func (r *repository) List(ctx context.Context, filter roleusers.ListFilter) (roleusers.ListRoleUserDTO, error) {
|
||||
whereClause, args := buildListQuery(filter)
|
||||
|
||||
var count int64
|
||||
if err := r.client.QueryRow(ctx, `SELECT COUNT(*)`+roleUserFromClause+whereClause, args...).Scan(&count); err != nil {
|
||||
return roleusers.ListRoleUserDTO{}, err
|
||||
}
|
||||
|
||||
query := `SELECT ` + roleUserSelectColumns + roleUserFromClause + whereClause + ` ORDER BY ru.id DESC`
|
||||
rows, err := r.client.Query(ctx, query, args...)
|
||||
if err != nil {
|
||||
return roleusers.ListRoleUserDTO{}, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var items []roleusers.RoleUserDTO
|
||||
for rows.Next() {
|
||||
item, err := scanRoleUser(rows)
|
||||
if err != nil {
|
||||
return roleusers.ListRoleUserDTO{}, err
|
||||
}
|
||||
items = append(items, item)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return roleusers.ListRoleUserDTO{}, err
|
||||
}
|
||||
|
||||
return roleusers.ListRoleUserDTO{Count: count, Items: items}, nil
|
||||
}
|
||||
|
||||
func buildListQuery(filter roleusers.ListFilter) (whereClause string, args []interface{}) {
|
||||
var conditions []string
|
||||
|
||||
if filter.UserId != nil {
|
||||
args = append(args, *filter.UserId)
|
||||
conditions = append(conditions, fmt.Sprintf("ru.user_id = $%d", len(args)))
|
||||
}
|
||||
|
||||
if filter.RoleName != "" {
|
||||
args = append(args, likePattern(filter.RoleName))
|
||||
conditions = append(conditions, fmt.Sprintf("r.name ILIKE $%d", len(args)))
|
||||
}
|
||||
|
||||
if len(conditions) == 0 {
|
||||
return "", args
|
||||
}
|
||||
|
||||
return " WHERE " + strings.Join(conditions, " AND "), args
|
||||
}
|
||||
|
||||
func likePattern(term string) string {
|
||||
term = strings.ReplaceAll(term, `\`, `\\`)
|
||||
term = strings.ReplaceAll(term, `%`, `\%`)
|
||||
term = strings.ReplaceAll(term, `_`, `\_`)
|
||||
return "%" + term + "%"
|
||||
}
|
||||
|
||||
func (r *repository) Create(ctx context.Context, dto roleusers.CreateRoleUserDTO) (roleusers.RoleUserDTO, error) {
|
||||
query := `
|
||||
WITH inserted AS (
|
||||
INSERT INTO role_user (role_id, user_id)
|
||||
VALUES ($1, $2)
|
||||
WITH existing AS (
|
||||
SELECT id FROM role_user WHERE user_id = $2 ORDER BY id LIMIT 1
|
||||
), updated AS (
|
||||
UPDATE role_user SET
|
||||
role_id = $1,
|
||||
updated_at = (CURRENT_TIMESTAMP AT TIME ZONE 'UTC')
|
||||
WHERE id = (SELECT id FROM existing)
|
||||
RETURNING id, role_id, user_id, created_at, updated_at
|
||||
), inserted AS (
|
||||
INSERT INTO role_user (role_id, user_id)
|
||||
SELECT $1, $2
|
||||
WHERE NOT EXISTS (SELECT 1 FROM existing)
|
||||
RETURNING id, role_id, user_id, created_at, updated_at
|
||||
), upserted AS (
|
||||
SELECT * FROM updated
|
||||
UNION ALL
|
||||
SELECT * FROM inserted
|
||||
)
|
||||
SELECT inserted.id, inserted.role_id, r.name, inserted.user_id, u.name, inserted.created_at, inserted.updated_at
|
||||
FROM inserted
|
||||
JOIN roles r ON r.id = inserted.role_id
|
||||
JOIN users u ON u.id = inserted.user_id`
|
||||
SELECT upserted.id, upserted.role_id, r.name, upserted.user_id, u.name, upserted.created_at, upserted.updated_at
|
||||
FROM upserted
|
||||
JOIN roles r ON r.id = upserted.role_id
|
||||
JOIN users u ON u.id = upserted.user_id`
|
||||
|
||||
row := r.client.QueryRow(ctx, query, dto.RoleId, dto.UserId)
|
||||
return scanRoleUser(row)
|
||||
|
||||
@@ -12,16 +12,6 @@ type RoleUserDTO struct {
|
||||
UpdatedAt time.Time `json:"updatedAt"`
|
||||
}
|
||||
|
||||
type ListRoleUserDTO struct {
|
||||
Count int64 `json:"count"`
|
||||
Items []RoleUserDTO `json:"items"`
|
||||
}
|
||||
|
||||
type ListFilter struct {
|
||||
UserId *int64
|
||||
RoleName string
|
||||
}
|
||||
|
||||
type CreateRoleUserDTO struct {
|
||||
RoleId int64 `json:"roleId" binding:"required"`
|
||||
UserId int64 `json:"userId" binding:"required"`
|
||||
|
||||
@@ -4,7 +4,6 @@ import (
|
||||
"errors"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"online-back/internal/appresult"
|
||||
"online-back/internal/handlers"
|
||||
@@ -27,47 +26,13 @@ func NewHandler(logger *logging.Logger, repository Repository) handlers.Handler
|
||||
|
||||
func (h *handler) Register(router *gin.RouterGroup) {
|
||||
group := router.Group(baseURL, appresult.JwtTokenCheck())
|
||||
group.GET("", h.list)
|
||||
group.POST("", h.create)
|
||||
group.DELETE("/:id", h.delete)
|
||||
}
|
||||
|
||||
// list godoc
|
||||
// @Summary List role users
|
||||
// @Description Returns the authenticated user's role-user assignments with the related user and role
|
||||
// @Tags role-users
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param role_name query string false "Filter by role name"
|
||||
// @Success 200 {object} appresult.AppSuccess
|
||||
// @Failure 401 {object} appresult.AppError
|
||||
// @Failure 500 {object} appresult.AppError
|
||||
// @Router /role-users [get]
|
||||
func (h *handler) list(c *gin.Context) {
|
||||
userID, ok := currentUserID(c)
|
||||
if !ok {
|
||||
c.JSON(http.StatusUnauthorized, appresult.ErrUnauthorized)
|
||||
return
|
||||
}
|
||||
|
||||
filter := ListFilter{
|
||||
UserId: &userID,
|
||||
RoleName: strings.TrimSpace(c.Query("role_name")),
|
||||
}
|
||||
|
||||
result, err := h.repository.List(c.Request.Context(), filter)
|
||||
if err != nil {
|
||||
h.logger.Errorf("list role users failed: %v", err)
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, appresult.SuccessWithData(result))
|
||||
}
|
||||
|
||||
// create godoc
|
||||
// @Summary Assign user to role
|
||||
// @Description Creates a role-user assignment
|
||||
// @Description Creates a role-user assignment, or updates the user's existing role if one is already assigned
|
||||
// @Tags role-users
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
@@ -132,21 +97,3 @@ func parseID(raw string) (int64, bool) {
|
||||
}
|
||||
return id, true
|
||||
}
|
||||
|
||||
func currentUserID(c *gin.Context) (int64, bool) {
|
||||
rawID, exists := c.Get("id")
|
||||
if !exists {
|
||||
return 0, false
|
||||
}
|
||||
|
||||
switch id := rawID.(type) {
|
||||
case int64:
|
||||
return id, id > 0
|
||||
case int:
|
||||
return int64(id), id > 0
|
||||
case string:
|
||||
return parseID(id)
|
||||
default:
|
||||
return 0, false
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,7 +3,6 @@ package roleusers
|
||||
import "context"
|
||||
|
||||
type Repository interface {
|
||||
List(ctx context.Context, filter ListFilter) (ListRoleUserDTO, error)
|
||||
Create(ctx context.Context, dto CreateRoleUserDTO) (RoleUserDTO, error)
|
||||
Delete(ctx context.Context, id int64) error
|
||||
}
|
||||
|
||||
@@ -28,8 +28,7 @@ import (
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// Register wires every identity module's handler onto router.
|
||||
// engine is the root gin engine so public file GET can live at /file/:file_name.
|
||||
|
||||
func Register(router *gin.RouterGroup, engine *gin.Engine, client postgresql.Client, logger *logging.Logger) {
|
||||
userH := user.NewHandler(logger, userdb.NewRepository(client, logger))
|
||||
userH.Register(router)
|
||||
@@ -43,8 +42,6 @@ func Register(router *gin.RouterGroup, engine *gin.Engine, client postgresql.Cli
|
||||
func Handlers(client postgresql.Client, logger *logging.Logger) []handlers.Handler {
|
||||
return []handlers.Handler{
|
||||
activitylog.NewHandler(logger, activitylogdb.NewRepository(client, logger)),
|
||||
// Swap sms.NewLogSender for your SMS provider: it only needs to
|
||||
// implement sms.Sender (Send(ctx, phone, message)).
|
||||
auth.NewHandler(logger, authdb.NewRepository(client, logger), sms.NewLogSender(logger)),
|
||||
role.NewHandler(logger, roledb.NewRepository(client, logger)),
|
||||
permission.NewHandler(logger, permissiondb.NewRepository(client, logger)),
|
||||
|
||||
@@ -1,133 +0,0 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"online-back/internal/config"
|
||||
"online-back/internal/identity/user"
|
||||
"online-back/pkg/client/postgresql"
|
||||
"online-back/pkg/logging"
|
||||
)
|
||||
|
||||
func testRepo(t *testing.T) (user.Repository, func()) {
|
||||
t.Helper()
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 8*time.Second)
|
||||
t.Cleanup(cancel)
|
||||
|
||||
pool, err := postgresql.NewClient(ctx, 2, config.StorageConfig{
|
||||
Host: "localhost",
|
||||
Port: "5424",
|
||||
Database: "bank_db",
|
||||
Username: "bank_admin",
|
||||
Password: "bank@#23#@_password",
|
||||
PgPoolMaxConn: 4,
|
||||
})
|
||||
if err != nil {
|
||||
t.Skipf("postgres unavailable: %v", err)
|
||||
}
|
||||
|
||||
return NewRepository(pool, logging.GetLogger()), func() { pool.Close() }
|
||||
}
|
||||
|
||||
func assignedRole(t *testing.T, ctx context.Context, repo user.Repository, userID int64) (id int64, code string) {
|
||||
t.Helper()
|
||||
poolRepo, ok := repo.(*repository)
|
||||
if !ok {
|
||||
t.Fatal("unexpected repository type")
|
||||
}
|
||||
err := poolRepo.client.QueryRow(ctx, `
|
||||
SELECT r.id, r.code
|
||||
FROM role_user ru
|
||||
JOIN roles r ON r.id = ru.role_id
|
||||
WHERE ru.user_id = $1
|
||||
ORDER BY ru.id
|
||||
LIMIT 1`, userID).Scan(&id, &code)
|
||||
if err != nil {
|
||||
t.Fatalf("lookup role_user for user %d: %v", userID, err)
|
||||
}
|
||||
return id, code
|
||||
}
|
||||
|
||||
func assertJoinedRole(t *testing.T, ctx context.Context, repo user.Repository, item user.UserDTO) {
|
||||
t.Helper()
|
||||
wantID, wantCode := assignedRole(t, ctx, repo, item.Id)
|
||||
if item.Role != wantCode {
|
||||
t.Errorf("user %d role=%q, want roles.code %q", item.Id, item.Role, wantCode)
|
||||
}
|
||||
if item.RoleId == nil {
|
||||
t.Fatalf("user %d missing roleId", item.Id)
|
||||
}
|
||||
if *item.RoleId != wantID {
|
||||
t.Errorf("user %d roleId=%d, want roles.id %d", item.Id, *item.RoleId, wantID)
|
||||
}
|
||||
}
|
||||
|
||||
func TestListUsersRoleComesFromJoin(t *testing.T) {
|
||||
repo, closeRepo := testRepo(t)
|
||||
defer closeRepo()
|
||||
ctx := context.Background()
|
||||
filter := user.ListFilter{Page: 1, Limit: 100}
|
||||
|
||||
list, err := repo.List(ctx, filter)
|
||||
if err != nil {
|
||||
t.Fatalf("List: %v", err)
|
||||
}
|
||||
if list.Count == 0 || len(list.Users) == 0 {
|
||||
t.Fatal("List returned no users")
|
||||
}
|
||||
for _, item := range list.Users {
|
||||
if item.Role != "user" {
|
||||
t.Errorf("List user %d role=%q, want user", item.Id, item.Role)
|
||||
}
|
||||
assertJoinedRole(t, ctx, repo, item)
|
||||
}
|
||||
|
||||
clients, err := repo.GetByRole(ctx, "user", filter)
|
||||
if err != nil {
|
||||
t.Fatalf("GetByRole: %v", err)
|
||||
}
|
||||
if clients.Count == 0 {
|
||||
t.Fatal("clients list empty")
|
||||
}
|
||||
for _, item := range clients.Users {
|
||||
assertJoinedRole(t, ctx, repo, item)
|
||||
}
|
||||
|
||||
staff, err := repo.ListStaff(ctx, filter)
|
||||
if err != nil {
|
||||
t.Fatalf("ListStaff: %v", err)
|
||||
}
|
||||
if staff.Count == 0 {
|
||||
t.Fatal("staff list empty")
|
||||
}
|
||||
for _, item := range staff.Users {
|
||||
assertJoinedRole(t, ctx, repo, item)
|
||||
if item.Branches == nil {
|
||||
t.Errorf("staff user %d missing branches", item.Id)
|
||||
}
|
||||
}
|
||||
|
||||
got, err := repo.GetByID(ctx, staff.Users[0].Id)
|
||||
if err != nil {
|
||||
t.Fatalf("GetByID: %v", err)
|
||||
}
|
||||
assertJoinedRole(t, ctx, repo, got)
|
||||
|
||||
raw, err := json.Marshal(list.Users[0])
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var payload map[string]any
|
||||
if err := json.Unmarshal(raw, &payload); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, ok := payload["role"]; !ok {
|
||||
t.Errorf("json missing role: %s", raw)
|
||||
}
|
||||
if _, ok := payload["roleId"]; !ok {
|
||||
t.Errorf("json missing roleId: %s", raw)
|
||||
}
|
||||
}
|
||||
@@ -4,8 +4,6 @@ import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"online-back/internal/identity/userbranch"
|
||||
"online-back/pkg/client/postgresql"
|
||||
@@ -23,83 +21,30 @@ func NewRepository(client postgresql.Client, logger *logging.Logger) userbranch.
|
||||
return &repository{client: client, logger: logger}
|
||||
}
|
||||
|
||||
const userBranchFromClause = ` FROM branch_user bu
|
||||
JOIN branches b ON b.id = bu.branch_id
|
||||
JOIN users u ON u.id = bu.user_id`
|
||||
|
||||
const userBranchSelectColumns = `bu.id, bu.branch_id, b.name, bu.user_id, u.name, bu.created_at, bu.updated_at`
|
||||
|
||||
func (r *repository) List(ctx context.Context, filter userbranch.ListFilter) (userbranch.ListUserBranchDTO, error) {
|
||||
whereClause, args := buildListQuery(filter)
|
||||
|
||||
var count int64
|
||||
if err := r.client.QueryRow(ctx, `SELECT COUNT(*)`+userBranchFromClause+whereClause, args...).Scan(&count); err != nil {
|
||||
return userbranch.ListUserBranchDTO{}, err
|
||||
}
|
||||
|
||||
query := `SELECT ` + userBranchSelectColumns + userBranchFromClause + whereClause + ` ORDER BY bu.id DESC`
|
||||
rows, err := r.client.Query(ctx, query, args...)
|
||||
if err != nil {
|
||||
return userbranch.ListUserBranchDTO{}, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var items []userbranch.UserBranchDTO
|
||||
for rows.Next() {
|
||||
item, err := scanUserBranch(rows)
|
||||
if err != nil {
|
||||
return userbranch.ListUserBranchDTO{}, err
|
||||
}
|
||||
items = append(items, item)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return userbranch.ListUserBranchDTO{}, err
|
||||
}
|
||||
|
||||
return userbranch.ListUserBranchDTO{Count: count, Items: items}, nil
|
||||
}
|
||||
|
||||
func buildListQuery(filter userbranch.ListFilter) (whereClause string, args []interface{}) {
|
||||
var conditions []string
|
||||
|
||||
if filter.UserId != nil {
|
||||
args = append(args, *filter.UserId)
|
||||
conditions = append(conditions, fmt.Sprintf("bu.user_id = $%d", len(args)))
|
||||
}
|
||||
|
||||
if filter.BranchName != "" {
|
||||
args = append(args, likePattern(filter.BranchName))
|
||||
n := len(args)
|
||||
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
|
||||
)`, n))
|
||||
}
|
||||
|
||||
if len(conditions) == 0 {
|
||||
return "", args
|
||||
}
|
||||
|
||||
return " WHERE " + strings.Join(conditions, " AND "), args
|
||||
}
|
||||
|
||||
func likePattern(term string) string {
|
||||
term = strings.ReplaceAll(term, `\`, `\\`)
|
||||
term = strings.ReplaceAll(term, `%`, `\%`)
|
||||
term = strings.ReplaceAll(term, `_`, `\_`)
|
||||
return "%" + term + "%"
|
||||
}
|
||||
|
||||
func (r *repository) Create(ctx context.Context, dto userbranch.CreateUserBranchDTO) (userbranch.UserBranchDTO, error) {
|
||||
query := `
|
||||
WITH inserted AS (
|
||||
INSERT INTO branch_user (branch_id, user_id)
|
||||
VALUES ($1, $2)
|
||||
WITH existing AS (
|
||||
SELECT id FROM branch_user WHERE user_id = $2 ORDER BY id LIMIT 1
|
||||
), updated AS (
|
||||
UPDATE branch_user SET
|
||||
branch_id = $1,
|
||||
updated_at = (CURRENT_TIMESTAMP AT TIME ZONE 'UTC')
|
||||
WHERE id = (SELECT id FROM existing)
|
||||
RETURNING id, branch_id, user_id, created_at, updated_at
|
||||
), inserted AS (
|
||||
INSERT INTO branch_user (branch_id, user_id)
|
||||
SELECT $1, $2
|
||||
WHERE NOT EXISTS (SELECT 1 FROM existing)
|
||||
RETURNING id, branch_id, user_id, created_at, updated_at
|
||||
), upserted AS (
|
||||
SELECT * FROM updated
|
||||
UNION ALL
|
||||
SELECT * FROM inserted
|
||||
)
|
||||
SELECT inserted.id, inserted.branch_id, b.name, inserted.user_id, u.name, inserted.created_at, inserted.updated_at
|
||||
FROM inserted
|
||||
JOIN branches b ON b.id = inserted.branch_id
|
||||
JOIN users u ON u.id = inserted.user_id`
|
||||
SELECT upserted.id, upserted.branch_id, b.name, upserted.user_id, u.name, upserted.created_at, upserted.updated_at
|
||||
FROM upserted
|
||||
JOIN branches b ON b.id = upserted.branch_id
|
||||
JOIN users u ON u.id = upserted.user_id`
|
||||
|
||||
row := r.client.QueryRow(ctx, query, dto.BranchId, dto.UserId)
|
||||
return scanUserBranch(row)
|
||||
|
||||
@@ -18,16 +18,6 @@ type UserBranchDTO struct {
|
||||
UpdatedAt time.Time `json:"updatedAt"`
|
||||
}
|
||||
|
||||
type ListUserBranchDTO struct {
|
||||
Count int64 `json:"count"`
|
||||
Items []UserBranchDTO `json:"items"`
|
||||
}
|
||||
|
||||
type ListFilter struct {
|
||||
UserId *int64
|
||||
BranchName string
|
||||
}
|
||||
|
||||
type CreateUserBranchDTO struct {
|
||||
BranchId int64 `json:"branchId" binding:"required"`
|
||||
UserId int64 `json:"userId" binding:"required"`
|
||||
|
||||
@@ -4,7 +4,6 @@ import (
|
||||
"errors"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"online-back/internal/appresult"
|
||||
"online-back/internal/handlers"
|
||||
@@ -27,47 +26,13 @@ func NewHandler(logger *logging.Logger, repository Repository) handlers.Handler
|
||||
|
||||
func (h *handler) Register(router *gin.RouterGroup) {
|
||||
group := router.Group(baseURL, appresult.JwtTokenCheck())
|
||||
group.GET("", h.list)
|
||||
group.POST("", h.create)
|
||||
group.DELETE("/:id", h.delete)
|
||||
}
|
||||
|
||||
// list godoc
|
||||
// @Summary List branch users
|
||||
// @Description Returns the authenticated user's branch-user assignments with the related user and branch
|
||||
// @Tags branch-users
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param branch_name query string false "Filter by branch name (en, ru, tm)"
|
||||
// @Success 200 {object} appresult.AppSuccess
|
||||
// @Failure 401 {object} appresult.AppError
|
||||
// @Failure 500 {object} appresult.AppError
|
||||
// @Router /branch-users [get]
|
||||
func (h *handler) list(c *gin.Context) {
|
||||
userID, ok := currentUserID(c)
|
||||
if !ok {
|
||||
c.JSON(http.StatusUnauthorized, appresult.ErrUnauthorized)
|
||||
return
|
||||
}
|
||||
|
||||
filter := ListFilter{
|
||||
UserId: &userID,
|
||||
BranchName: strings.TrimSpace(c.Query("branch_name")),
|
||||
}
|
||||
|
||||
result, err := h.repository.List(c.Request.Context(), filter)
|
||||
if err != nil {
|
||||
h.logger.Errorf("list branch users failed: %v", err)
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, appresult.SuccessWithData(result))
|
||||
}
|
||||
|
||||
// create godoc
|
||||
// @Summary Assign user to branch
|
||||
// @Description Creates a branch-user assignment
|
||||
// @Description Creates a branch-user assignment, or updates the user's existing branch if one is already assigned
|
||||
// @Tags branch-users
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
@@ -132,21 +97,3 @@ func parseID(raw string) (int64, bool) {
|
||||
}
|
||||
return id, true
|
||||
}
|
||||
|
||||
func currentUserID(c *gin.Context) (int64, bool) {
|
||||
rawID, exists := c.Get("id")
|
||||
if !exists {
|
||||
return 0, false
|
||||
}
|
||||
|
||||
switch id := rawID.(type) {
|
||||
case int64:
|
||||
return id, id > 0
|
||||
case int:
|
||||
return int64(id), id > 0
|
||||
case string:
|
||||
return parseID(id)
|
||||
default:
|
||||
return 0, false
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,7 +3,6 @@ package userbranch
|
||||
import "context"
|
||||
|
||||
type Repository interface {
|
||||
List(ctx context.Context, filter ListFilter) (ListUserBranchDTO, error)
|
||||
Create(ctx context.Context, dto CreateUserBranchDTO) (UserBranchDTO, error)
|
||||
Delete(ctx context.Context, id int64) error
|
||||
}
|
||||
|
||||
@@ -1,93 +0,0 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"online-back/internal/config"
|
||||
"online-back/internal/lending/loanpaidletter"
|
||||
"online-back/pkg/client/postgresql"
|
||||
"online-back/pkg/logging"
|
||||
)
|
||||
|
||||
func testRepo(t *testing.T) (loanpaidletter.Repository, func()) {
|
||||
t.Helper()
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 8*time.Second)
|
||||
t.Cleanup(cancel)
|
||||
|
||||
pool, err := postgresql.NewClient(ctx, 2, config.StorageConfig{
|
||||
Host: "localhost",
|
||||
Port: "5424",
|
||||
Database: "bank_db",
|
||||
Username: "bank_admin",
|
||||
Password: "bank@#23#@_password",
|
||||
PgPoolMaxConn: 4,
|
||||
})
|
||||
if err != nil {
|
||||
t.Skipf("postgres unavailable: %v", err)
|
||||
}
|
||||
|
||||
return NewRepository(pool, logging.GetLogger()), func() { pool.Close() }
|
||||
}
|
||||
|
||||
func TestGetByIDIncludesNamesNextToIDs(t *testing.T) {
|
||||
repo, closeRepo := testRepo(t)
|
||||
defer closeRepo()
|
||||
ctx := context.Background()
|
||||
|
||||
item, err := repo.GetByID(ctx, 1)
|
||||
if err != nil {
|
||||
t.Fatalf("GetByID: %v", err)
|
||||
}
|
||||
|
||||
if item.BranchId == 0 {
|
||||
t.Fatal("branchId is empty")
|
||||
}
|
||||
if item.BranchName.Tm == "" && item.BranchName.En == "" {
|
||||
t.Fatalf("branchId=%d but branchName is empty: %+v", item.BranchId, item.BranchName)
|
||||
}
|
||||
if item.BranchUniqueCode == "" {
|
||||
t.Fatalf("branchId=%d but branchUniqueCode is empty", item.BranchId)
|
||||
}
|
||||
if item.ProvinceId == nil || *item.ProvinceId == 0 {
|
||||
t.Fatal("provinceId is empty")
|
||||
}
|
||||
if item.ProvinceName.Tm == "" && item.ProvinceName.En == "" {
|
||||
t.Fatalf("provinceId=%d but provinceName is empty: %+v", *item.ProvinceId, item.ProvinceName)
|
||||
}
|
||||
if item.RegionName.Tm == "" && item.RegionName.En == "" {
|
||||
t.Fatalf("region=%q but regionName is empty: %+v", item.Region, item.RegionName)
|
||||
}
|
||||
if item.UserId != nil {
|
||||
if item.UserName == "" && item.UserUsername == "" {
|
||||
t.Fatalf("userId=%d but userName and userUsername are empty", *item.UserId)
|
||||
}
|
||||
}
|
||||
|
||||
t.Logf("id=%d branchId=%d branch=%q/%s provinceId=%d province=%q userId=%v user=%q",
|
||||
item.Id, item.BranchId, item.BranchName.Tm, item.BranchUniqueCode,
|
||||
*item.ProvinceId, item.ProvinceName.Tm, item.UserId, item.UserName)
|
||||
}
|
||||
|
||||
func TestListIncludesNamesNextToIDs(t *testing.T) {
|
||||
repo, closeRepo := testRepo(t)
|
||||
defer closeRepo()
|
||||
|
||||
list, err := repo.List(context.Background(), loanpaidletter.ListFilter{Page: 1, Limit: 10})
|
||||
if err != nil {
|
||||
t.Fatalf("List: %v", err)
|
||||
}
|
||||
if list.Count == 0 || len(list.LoanPaidLetters) == 0 {
|
||||
t.Fatal("List returned no letters")
|
||||
}
|
||||
|
||||
for _, item := range list.LoanPaidLetters {
|
||||
if item.BranchId != 0 && item.BranchName.Tm == "" && item.BranchName.En == "" {
|
||||
t.Errorf("letter %d branchId=%d missing branchName", item.Id, item.BranchId)
|
||||
}
|
||||
if item.UserId != nil && item.UserName == "" && item.UserUsername == "" {
|
||||
t.Errorf("letter %d userId=%d missing userName", item.Id, *item.UserId)
|
||||
}
|
||||
}
|
||||
}
|
||||
BIN
kickbacks.vsix
BIN
kickbacks.vsix
Binary file not shown.
@@ -1,19 +0,0 @@
|
||||
# Public file download (MinIO objects).
|
||||
# Copy into the HTTPS server block, or:
|
||||
# sudo cp nginx/file.conf /etc/nginx/snippets/online-back-file.conf
|
||||
# include /etc/nginx/snippets/online-back-file.conf;
|
||||
#
|
||||
# URL: https://<host>/file/<file_name>
|
||||
# App: GET http://127.0.0.1:5005/file/<file_name>
|
||||
|
||||
location /file/ {
|
||||
proxy_pass http://127.0.0.1:5005/file/;
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
|
||||
expires 7d;
|
||||
add_header Cache-Control "public, max-age=604800";
|
||||
}
|
||||
@@ -1,116 +0,0 @@
|
||||
# /etc/nginx/sites-available/test.webulgam.com.conf
|
||||
# ln -s /etc/nginx/sites-available/test.webulgam.com.conf /etc/nginx/sites-enabled/
|
||||
|
||||
server {
|
||||
listen 80;
|
||||
server_name test.webulgam.com;
|
||||
|
||||
if ($host = test.webulgam.com) {
|
||||
return 301 https://$host$request_uri;
|
||||
}
|
||||
|
||||
return 404;
|
||||
}
|
||||
|
||||
server {
|
||||
listen 443 ssl;
|
||||
server_name test.webulgam.com;
|
||||
|
||||
root /var/www/tbbank.gov.tm/frontend/src;
|
||||
index index.html;
|
||||
|
||||
charset utf-8;
|
||||
client_max_body_size 100M;
|
||||
|
||||
add_header X-Frame-Options "SAMEORIGIN";
|
||||
add_header X-Content-Type-Options "nosniff";
|
||||
|
||||
ssl_certificate /etc/letsencrypt/live/test.webulgam.com/fullchain.pem;
|
||||
ssl_certificate_key /etc/letsencrypt/live/test.webulgam.com/privkey.pem;
|
||||
include /etc/letsencrypt/options-ssl-nginx.conf;
|
||||
ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem;
|
||||
|
||||
# Public MinIO files: https://test.webulgam.com/file/<file_name>
|
||||
# Snippet lives at nginx/file.conf — copy to snippets if you prefer include.
|
||||
location /file/ {
|
||||
proxy_pass http://127.0.0.1:5005/file/;
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
expires 7d;
|
||||
add_header Cache-Control "public, max-age=604800";
|
||||
}
|
||||
|
||||
# --- existing project → :5050 ---
|
||||
location /admin {
|
||||
proxy_pass http://127.0.0.1:5050;
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
}
|
||||
|
||||
location /public/ {
|
||||
proxy_pass http://127.0.0.1:5050;
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
}
|
||||
|
||||
location /api {
|
||||
proxy_pass http://127.0.0.1:5050;
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
}
|
||||
|
||||
# --- online frontend (Vite) → :5173 ---
|
||||
# Example: https://test.webulgam.com/online/
|
||||
# Do NOT strip /online — Vite base is /online/, stripping causes a 302 loop.
|
||||
location = /online {
|
||||
return 301 /online/;
|
||||
}
|
||||
|
||||
location /online/ {
|
||||
proxy_pass http://127.0.0.1:5173;
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
# Vite HMR / WebSocket
|
||||
proxy_set_header Upgrade $http_upgrade;
|
||||
proxy_set_header Connection "upgrade";
|
||||
}
|
||||
|
||||
# --- online-backend → :5005 ---
|
||||
# Example: https://test.webulgam.com/online-backend/api/admin/...
|
||||
location /online-backend/ {
|
||||
rewrite ^/online-backend/(.*)$ /$1 break;
|
||||
proxy_pass http://127.0.0.1:5005;
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
# The prefix is stripped above, so tell the app what it was: Swagger
|
||||
# needs it to build URLs the browser can actually reach.
|
||||
proxy_set_header X-Forwarded-Prefix /online-backend;
|
||||
}
|
||||
|
||||
location = /favicon.ico { access_log off; log_not_found off; }
|
||||
location = /robots.txt { access_log off; log_not_found off; }
|
||||
|
||||
error_page 404 /index.php;
|
||||
|
||||
location ~ /\.(?!well-known).* {
|
||||
deny all;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user