diff --git a/Makefile b/Makefile index 02cb826..0406b3c 100755 --- a/Makefile +++ b/Makefile @@ -11,6 +11,8 @@ migrate: migrate -database 'postgres://bank_admin:bank%40%2323%23%40_password@localhost:5424/bank_db?sslmode=disable' -path db/migrations up 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 # ---- for linux # migrate: diff --git a/config.example.yaml b/config.example.yaml index a9eba23..f7e8f15 100644 --- a/config.example.yaml +++ b/config.example.yaml @@ -5,10 +5,10 @@ listen: port: 5050 jwt_key: storage: - host: example-db # use localhost when running outside Docker - port: 5432 - database: example_db - username: example_username + host: main-db # use localhost when running the app on the host + port: 5432 # use 5424 when host is localhost (docker-compose) + database: bank_db + username: bank_admin password: pg_pool_max_conn: 10 minio: diff --git a/db/migrations/20260702125108_init.down.sql b/db/migrations/20260702125108_init.down.sql index 00f40c7..88c8dfd 100644 --- a/db/migrations/20260702125108_init.down.sql +++ b/db/migrations/20260702125108_init.down.sql @@ -1,19 +1,25 @@ +DROP INDEX IF EXISTS idx_activity_logs_created_at; +DROP INDEX IF EXISTS idx_activity_logs_module; +DROP INDEX IF EXISTS idx_activity_logs_user_id; DROP TABLE IF EXISTS activity_logs; -DROP TABLE IF EXISTS cards; -DROP TABLE IF EXISTS card_pin_orders; -DROP TABLE IF EXISTS card_orders; DROP TABLE IF EXISTS loan_paid_off_letters; DROP TABLE IF EXISTS loans; DROP TABLE IF EXISTS loan_orders; +DROP TABLE IF EXISTS card_pin_orders; +DROP TABLE IF EXISTS card_orders; +DROP TABLE IF EXISTS cards; DROP TABLE IF EXISTS loan_order_required_docs; DROP TABLE IF EXISTS loan_types; -DROP TABLE IF EXISTS branch_user; -DROP TABLE IF EXISTS permission_user; -DROP TABLE IF EXISTS role_user; -DROP TABLE IF EXISTS roles; -DROP TABLE IF EXISTS permissions; DROP TABLE IF EXISTS card_states; DROP TABLE IF EXISTS card_types; +DROP TABLE IF EXISTS branch_user; DROP TABLE IF EXISTS branches; DROP TABLE IF EXISTS provinces; +DROP TABLE IF EXISTS permission_user; +DROP TABLE IF EXISTS role_user; +DROP TABLE IF EXISTS permissions; +DROP TABLE IF EXISTS roles; +DROP TABLE IF EXISTS registration_verifications; +DROP INDEX IF EXISTS idx_users_phone; +DROP INDEX IF EXISTS idx_users_username; DROP TABLE IF EXISTS users; diff --git a/db/migrations/20260702125108_init.up.sql b/db/migrations/20260702125108_init.up.sql index 7d647a6..d5a06a7 100644 --- a/db/migrations/20260702125108_init.up.sql +++ b/db/migrations/20260702125108_init.up.sql @@ -1,3 +1,4 @@ +-- 1. Identity CREATE TABLE IF NOT EXISTS users ( id bigserial PRIMARY KEY, email character varying(250) NOT NULL DEFAULT '', @@ -12,74 +13,32 @@ CREATE TABLE IF NOT EXISTS users ( light_mode integer NOT NULL DEFAULT 1, role character varying(250) NOT NULL DEFAULT 'user', active boolean NOT NULL DEFAULT true, - updated_at TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL, - created_at TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL -); - -INSERT INTO users (phone, password, name, email, role) -VALUES ( - '61531216', - '$2a$12$.9KVj6x7wxUMdPcBJ6UpweYbzW4Mka0d2mQj7O20YHXpBKlb3ypdC', - 'Admin', - 'admin@admin.com', - 'admin' -); - --- test1234 - -CREATE TABLE IF NOT EXISTS provinces ( - id bigserial PRIMARY KEY, - name json NOT NULL DEFAULT '{}'::json, - region json NOT NULL DEFAULT '{}'::json, - active boolean NOT NULL DEFAULT true, - updated_at TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL, - created_at TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL -); - -CREATE TABLE IF NOT EXISTS branches ( - id bigserial PRIMARY KEY, - unique_code character varying(255) UNIQUE, - name json NOT NULL DEFAULT '{}'::json, - address json NOT NULL DEFAULT '{}'::json, - region character varying(20) NOT NULL DEFAULT '', - province_id bigint, - phone_numbers character varying(255) NOT NULL DEFAULT '', - billing_username character varying(255) NOT NULL DEFAULT '', - billing_password character varying(255) NOT NULL DEFAULT '', - billing_swift_username character varying(255) NOT NULL DEFAULT '', - billing_swift_password character varying(255) NOT NULL DEFAULT '', - billing_visa_master_username character varying(255) NOT NULL DEFAULT '', - billing_visa_master_password character varying(255) NOT NULL DEFAULT '', - billing_sber_username character varying(255) NOT NULL DEFAULT '', - billing_sber_password character varying(255) NOT NULL DEFAULT '', - active boolean NOT NULL DEFAULT true, - updated_at TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL, - created_at TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL, - CONSTRAINT branches_province_id_fkey - FOREIGN KEY (province_id) REFERENCES provinces(id) ON UPDATE CASCADE -); - -CREATE TABLE IF NOT EXISTS card_types ( - id bigserial PRIMARY KEY, - name json NOT NULL DEFAULT '{}'::json, - price character varying(255) NOT NULL DEFAULT '', - notes character varying(255) NOT NULL DEFAULT '', - active boolean NOT NULL DEFAULT true, - updated_at TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL, - created_at TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL -); - -CREATE TABLE IF NOT EXISTS card_states ( - id bigserial PRIMARY KEY, - name json NOT NULL DEFAULT '{}'::json, - price character varying(255) NOT NULL DEFAULT '', - notes character varying(255) NOT NULL DEFAULT '', - active boolean NOT NULL DEFAULT true, created_at TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL, updated_at TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL ); -CREATE TABLE IF NOT EXISTS permissions ( +CREATE UNIQUE INDEX IF NOT EXISTS idx_users_username + ON users (LOWER(username)) + WHERE username <> ''; + +CREATE UNIQUE INDEX IF NOT EXISTS idx_users_phone + ON users (phone) + WHERE phone <> ''; + +CREATE TABLE IF NOT EXISTS registration_verifications ( + id bigserial PRIMARY KEY, + name character varying(255) NOT NULL DEFAULT '', + username character varying(250) NOT NULL DEFAULT '', + phone character varying(250) NOT NULL UNIQUE, + password character varying(250) NOT NULL DEFAULT '', + code_hash character varying(250) NOT NULL DEFAULT '', + attempts integer NOT NULL DEFAULT 0, + expires_at TIMESTAMP NOT NULL, + created_at TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL, + updated_at TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL +); + +CREATE TABLE IF NOT EXISTS roles ( id bigserial PRIMARY KEY, code character varying(255) NOT NULL DEFAULT '', name character varying(255) NOT NULL, @@ -88,7 +47,7 @@ CREATE TABLE IF NOT EXISTS permissions ( updated_at TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL ); -CREATE TABLE IF NOT EXISTS roles ( +CREATE TABLE IF NOT EXISTS permissions ( id bigserial PRIMARY KEY, code character varying(255) NOT NULL DEFAULT '', name character varying(255) NOT NULL, @@ -113,6 +72,39 @@ CREATE TABLE IF NOT EXISTS permission_user ( updated_at TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL ); +-- 2. Geography +CREATE TABLE IF NOT EXISTS provinces ( + id bigserial PRIMARY KEY, + name json NOT NULL DEFAULT '{}'::json, + region json NOT NULL DEFAULT '{}'::json, + active boolean NOT NULL DEFAULT true, + created_at TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL, + updated_at TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL +); + +CREATE TABLE IF NOT EXISTS branches ( + id bigserial PRIMARY KEY, + unique_code character varying(255) UNIQUE, + name json NOT NULL DEFAULT '{}'::json, + address json NOT NULL DEFAULT '{}'::json, + region character varying(20) NOT NULL DEFAULT '', + province_id bigint, + phone_numbers character varying(255) NOT NULL DEFAULT '', + billing_username character varying(255) NOT NULL DEFAULT '', + billing_password character varying(255) NOT NULL DEFAULT '', + billing_swift_username character varying(255) NOT NULL DEFAULT '', + billing_swift_password character varying(255) NOT NULL DEFAULT '', + billing_visa_master_username character varying(255) NOT NULL DEFAULT '', + billing_visa_master_password character varying(255) NOT NULL DEFAULT '', + billing_sber_username character varying(255) NOT NULL DEFAULT '', + billing_sber_password character varying(255) NOT NULL DEFAULT '', + active boolean NOT NULL DEFAULT true, + created_at TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL, + updated_at TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL, + CONSTRAINT branches_province_id_fkey + FOREIGN KEY (province_id) REFERENCES provinces(id) ON UPDATE CASCADE +); + CREATE TABLE IF NOT EXISTS branch_user ( id bigserial PRIMARY KEY, branch_id bigint REFERENCES branches(id), @@ -121,6 +113,27 @@ CREATE TABLE IF NOT EXISTS branch_user ( updated_at TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL ); +-- 3. Catalogs +CREATE TABLE IF NOT EXISTS card_types ( + id bigserial PRIMARY KEY, + name json NOT NULL DEFAULT '{}'::json, + price character varying(255) NOT NULL DEFAULT '', + notes character varying(255) NOT NULL DEFAULT '', + active boolean NOT NULL DEFAULT true, + created_at TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL, + updated_at TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL +); + +CREATE TABLE IF NOT EXISTS card_states ( + id bigserial PRIMARY KEY, + name json NOT NULL DEFAULT '{}'::json, + price character varying(255) NOT NULL DEFAULT '', + notes character varying(255) NOT NULL DEFAULT '', + active boolean NOT NULL DEFAULT true, + created_at TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL, + updated_at TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL +); + CREATE TABLE IF NOT EXISTS loan_types ( id bigserial PRIMARY KEY, name json NOT NULL DEFAULT '{}'::json, @@ -141,6 +154,96 @@ CREATE TABLE IF NOT EXISTS loan_order_required_docs ( updated_at TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL ); +-- 4. Cards +CREATE TABLE IF NOT EXISTS cards ( + id bigserial PRIMARY KEY, + user_id bigint, + number character varying(250) NOT NULL, + name character varying(250) NOT NULL, + month character varying(250) NOT NULL, + year character varying(250), + type character varying(250), + created_at TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL, + updated_at TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL, + CONSTRAINT cards_user_id_fkey + FOREIGN KEY (user_id) REFERENCES users(id) +); + +CREATE TABLE IF NOT EXISTS card_orders ( + id bigserial PRIMARY KEY, + unique_id character varying(255), + card_state_id bigint NOT NULL, + card_type_id bigint NOT NULL, + region character varying(2) NOT NULL, + branch_id bigint NOT NULL, + customer_name character varying(255) NOT NULL, + customer_surname character varying(255) NOT NULL, + customer_patronic_name character varying(255), + born_at date, + old_surname character varying(255), + citizenship character varying(255) NOT NULL, + passport_serie character varying(255) NOT NULL, + passport_id character varying(255) NOT NULL, + passport_given_at date NOT NULL, + passport_given_by character varying(255) NOT NULL, + born_place character varying(255) NOT NULL, + job_location character varying(255), + passport_address character varying(255), + real_address character varying(255), + phone character varying(255), + phone_additional character varying(255), + status character varying(255) DEFAULT 'pending'::character varying, + passport_one text NOT NULL, + passport_two text NOT NULL, + passport_three text NOT NULL, + passport_four text NOT NULL, + notes text, + user_id bigint, + 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 card_orders_card_state_id_fkey + FOREIGN KEY (card_state_id) REFERENCES card_states(id), + CONSTRAINT card_orders_card_type_id_fkey + FOREIGN KEY (card_type_id) REFERENCES card_types(id), + CONSTRAINT card_orders_branch_id_fkey + FOREIGN KEY (branch_id) REFERENCES branches(id), + CONSTRAINT card_orders_user_id_fkey + FOREIGN KEY (user_id) REFERENCES users(id) +); + +CREATE TABLE IF NOT EXISTS card_pin_orders ( + id bigserial PRIMARY KEY, + unique_id character varying(255), + user_id bigint, + card_type_id bigint NOT NULL, + card_number character varying(255), + region character varying(2) NOT NULL, + branch_id bigint NOT NULL, + customer_name character varying(255) NOT NULL, + customer_surname character varying(255) NOT NULL, + customer_patronic_name character varying(255), + born_at date, + phone character varying(255), + passport_serie character varying(255) NOT NULL, + passport_id character varying(255) NOT NULL, + passport_one text NOT NULL, + passport_two text NOT NULL, + passport_three text NOT NULL, + passport_four text NOT NULL, + status character varying(250), + notes character varying(250), + created_at TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL, + updated_at TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL, + CONSTRAINT card_pin_orders_card_type_id_fkey + FOREIGN KEY (card_type_id) REFERENCES card_types(id), + CONSTRAINT card_pin_orders_branch_id_fkey + FOREIGN KEY (branch_id) REFERENCES branches(id), + CONSTRAINT card_pin_orders_user_id_fkey + FOREIGN KEY (user_id) REFERENCES users(id) +); + +-- 5. Loans CREATE TABLE IF NOT EXISTS loan_orders ( id bigserial PRIMARY KEY, unique_id character varying(255), @@ -254,94 +357,7 @@ CREATE TABLE IF NOT EXISTS loan_paid_off_letters ( FOREIGN KEY (user_id) REFERENCES users(id) ); -CREATE TABLE IF NOT EXISTS card_orders ( - id bigserial PRIMARY KEY, - unique_id character varying(255), - card_state_id bigint NOT NULL, - card_type_id bigint NOT NULL, - region character varying(2) NOT NULL, - branch_id bigint NOT NULL, - customer_name character varying(255) NOT NULL, - customer_surname character varying(255) NOT NULL, - customer_patronic_name character varying(255), - born_at date, - old_surname character varying(255), - citizenship character varying(255) NOT NULL, - passport_serie character varying(255) NOT NULL, - passport_id character varying(255) NOT NULL, - passport_given_at date NOT NULL, - passport_given_by character varying(255) NOT NULL, - born_place character varying(255) NOT NULL, - job_location character varying(255), - passport_address character varying(255), - real_address character varying(255), - phone character varying(255), - phone_additional character varying(255), - status character varying(255) DEFAULT 'pending'::character varying, - passport_one text NOT NULL, - passport_two text NOT NULL, - passport_three text NOT NULL, - passport_four text NOT NULL, - notes text, - user_id bigint, - 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 card_orders_card_state_id_fkey - FOREIGN KEY (card_state_id) REFERENCES card_states(id), - CONSTRAINT card_orders_card_type_id_fkey - FOREIGN KEY (card_type_id) REFERENCES card_types(id), - CONSTRAINT card_orders_branch_id_fkey - FOREIGN KEY (branch_id) REFERENCES branches(id), - CONSTRAINT card_orders_user_id_fkey - FOREIGN KEY (user_id) REFERENCES users(id) -); - -CREATE TABLE IF NOT EXISTS card_pin_orders ( - id bigserial PRIMARY KEY, - unique_id character varying(255), - user_id bigint, - card_type_id bigint NOT NULL, - card_number character varying(255), - region character varying(2) NOT NULL, - branch_id bigint NOT NULL, - customer_name character varying(255) NOT NULL, - customer_surname character varying(255) NOT NULL, - customer_patronic_name character varying(255), - born_at date, - phone character varying(255), - passport_serie character varying(255) NOT NULL, - passport_id character varying(255) NOT NULL, - passport_one text NOT NULL, - passport_two text NOT NULL, - passport_three text NOT NULL, - passport_four text NOT NULL, - status character varying(250), - notes character varying(250), - created_at TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL, - updated_at TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL, - CONSTRAINT card_pin_orders_card_type_id_fkey - FOREIGN KEY (card_type_id) REFERENCES card_types(id), - CONSTRAINT card_pin_orders_branch_id_fkey - FOREIGN KEY (branch_id) REFERENCES branches(id), - CONSTRAINT card_pin_orders_user_id_fkey - FOREIGN KEY (user_id) REFERENCES users(id) -); - -CREATE TABLE IF NOT EXISTS cards ( - id bigserial PRIMARY KEY, - user_id bigint, - number character varying(250) NOT NULL, - name character varying(250) NOT NULL, - month character varying(250) NOT NULL, - year character varying(250), - type character varying(250), - created_at TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL, - updated_at TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL, - CONSTRAINT cards_user_id_fkey - FOREIGN KEY (user_id) REFERENCES users(id) -); - +-- 6. Logs CREATE TABLE IF NOT EXISTS activity_logs ( id bigserial PRIMARY KEY, user_id bigint, diff --git a/db/migrations/20260811082731_loans_user_id_not_null.down.sql b/db/migrations/20260811082731_loans_user_id_not_null.down.sql deleted file mode 100644 index f8ebc83..0000000 --- a/db/migrations/20260811082731_loans_user_id_not_null.down.sql +++ /dev/null @@ -1,2 +0,0 @@ -ALTER TABLE loans - ALTER COLUMN user_id DROP NOT NULL; diff --git a/db/migrations/20260811082731_loans_user_id_not_null.up.sql b/db/migrations/20260811082731_loans_user_id_not_null.up.sql deleted file mode 100644 index fe4b3ec..0000000 --- a/db/migrations/20260811082731_loans_user_id_not_null.up.sql +++ /dev/null @@ -1,10 +0,0 @@ --- Require loans.user_id; backfill any existing NULLs to the first user. -UPDATE loans -SET user_id = (SELECT id FROM users ORDER BY id ASC LIMIT 1) -WHERE user_id IS NULL - AND EXISTS (SELECT 1 FROM users); - -DELETE FROM loans WHERE user_id IS NULL; - -ALTER TABLE loans - ALTER COLUMN user_id SET NOT NULL; diff --git a/db/migrations/20260813141500_registration_verifications.down.sql b/db/migrations/20260813141500_registration_verifications.down.sql deleted file mode 100644 index b28a4b8..0000000 --- a/db/migrations/20260813141500_registration_verifications.down.sql +++ /dev/null @@ -1,3 +0,0 @@ -DROP INDEX IF EXISTS users_phone_unique; -DROP INDEX IF EXISTS users_username_unique; -DROP TABLE IF EXISTS registration_verifications; diff --git a/db/migrations/20260813141500_registration_verifications.up.sql b/db/migrations/20260813141500_registration_verifications.up.sql deleted file mode 100644 index dfbcf5d..0000000 --- a/db/migrations/20260813141500_registration_verifications.up.sql +++ /dev/null @@ -1,21 +0,0 @@ -CREATE TABLE IF NOT EXISTS registration_verifications ( - id bigserial PRIMARY KEY, - name character varying(255) NOT NULL DEFAULT '', - username character varying(250) NOT NULL DEFAULT '', - phone character varying(250) NOT NULL, - password character varying(250) NOT NULL DEFAULT '', - code_hash character varying(250) NOT NULL DEFAULT '', - attempts integer NOT NULL DEFAULT 0, - expires_at TIMESTAMP NOT NULL, - updated_at TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL, - created_at TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL, - CONSTRAINT registration_verifications_phone_key UNIQUE (phone) -); - -CREATE UNIQUE INDEX IF NOT EXISTS users_username_unique - ON users (LOWER(username)) - WHERE username <> ''; - -CREATE UNIQUE INDEX IF NOT EXISTS users_phone_unique - ON users (phone) - WHERE phone <> ''; diff --git a/db/seed.sql b/db/seed.sql index 3f5dfb6..763eeb2 100644 --- a/db/seed.sql +++ b/db/seed.sql @@ -1,87 +1,113 @@ -- Dev / staging mock data. Re-runnable: wipes app tables then reloads. --- Usage: psql -U online_bank_admin -d online_bank_db -f db/seed.sql --- Login: admin@admin.com / test1234 +-- Usage: PGPASSWORD='bank@#23#@_password' psql -h localhost -p 5424 -U bank_admin -d bank_db -f db/seed.sql +-- Login (password = test1234): +-- superadmin@bank.tm / +993 61 92 92 48 +-- admin@bank.tm +-- manager@bank.tm +-- operator@bank.tm +-- serdar@bank.tm … leyla@bank.tm (role=user) BEGIN; TRUNCATE TABLE activity_logs, - cards, - card_pin_orders, - card_orders, loan_paid_off_letters, loans, loan_orders, + card_pin_orders, + card_orders, + cards, loan_order_required_docs, loan_types, + card_states, + card_types, branch_user, - permission_user, - role_user, branches, provinces, - card_types, - card_states, + permission_user, + role_user, permissions, roles, + registration_verifications, users RESTART IDENTITY CASCADE; -- --------------------------------------------------------------------------- --- Users (password = test1234 for all) +-- Users (10): superadmin, admin, manager, operator, +-- 1 branch-assigned user (serdar), 5 users (gulnar…leyla). +-- Password = test1234 for all. Phone unique (idx_users_phone). -- --------------------------------------------------------------------------- INSERT INTO users (email, password, name, first_name, last_name, username, phone, role, active) VALUES ( - 'admin@admin.com', + 'superadmin@bank.tm', '$2a$12$.9KVj6x7wxUMdPcBJ6UpweYbzW4Mka0d2mQj7O20YHXpBKlb3ypdC', - 'Admin', - 'Nurmuhammet', - 'Allanow', - 'admin', - '+993 61 92 92 48', - 'admin', - true + 'Super Admin', 'Myrat', 'Nazarow', 'superadmin', + '+993 61 92 92 48', 'superadmin', true +), +( + 'admin@bank.tm', + '$2a$12$.9KVj6x7wxUMdPcBJ6UpweYbzW4Mka0d2mQj7O20YHXpBKlb3ypdC', + 'Admin', 'Nurmuhammet', 'Allanow', 'admin', + '+993 61 92 92 41', 'admin', true ), ( 'manager@bank.tm', '$2a$12$.9KVj6x7wxUMdPcBJ6UpweYbzW4Mka0d2mQj7O20YHXpBKlb3ypdC', - 'Branch Manager', - 'Mergen', - 'Berdiyew', - 'manager', - '+993 62 11 22 33', - 'user', - true + 'Branch Manager', 'Mergen', 'Berdiyew', 'manager', + '+993 61 92 92 42', 'manager', true ), ( 'operator@bank.tm', '$2a$12$.9KVj6x7wxUMdPcBJ6UpweYbzW4Mka0d2mQj7O20YHXpBKlb3ypdC', - 'Operator', - 'Aygul', - 'Hojayeva', - 'operator', - '+993 63 44 55 66', - 'user', - true + 'Operator', 'Aygul', 'Hojayeva', 'operator', + '+993 61 92 92 43', 'operator', true ), ( - 'inactive@bank.tm', + 'serdar@bank.tm', '$2a$12$.9KVj6x7wxUMdPcBJ6UpweYbzW4Mka0d2mQj7O20YHXpBKlb3ypdC', - 'Inactive User', - 'Oraz', - 'Gurbanow', - 'inactive', - '+993 64 77 88 99', - 'user', - false + 'Serdar Myradow', 'Serdar', 'Myradow', 'serdar', + '+993 61 92 92 44', 'user', true +), +( + 'gulnar@bank.tm', + '$2a$12$.9KVj6x7wxUMdPcBJ6UpweYbzW4Mka0d2mQj7O20YHXpBKlb3ypdC', + 'Gulnar Orazowa', 'Gulnar', 'Orazowa', 'gulnar', + '+993 61 92 92 45', 'user', true +), +( + 'dovran@bank.tm', + '$2a$12$.9KVj6x7wxUMdPcBJ6UpweYbzW4Mka0d2mQj7O20YHXpBKlb3ypdC', + 'Dovran Annayew', 'Dovran', 'Annayew', 'dovran', + '+993 61 92 92 46', 'user', true +), +( + 'maya@bank.tm', + '$2a$12$.9KVj6x7wxUMdPcBJ6UpweYbzW4Mka0d2mQj7O20YHXpBKlb3ypdC', + 'Maya Halylowa', 'Maya', 'Halylowa', 'maya', + '+993 61 92 92 47', 'user', true +), +( + 'kerim@bank.tm', + '$2a$12$.9KVj6x7wxUMdPcBJ6UpweYbzW4Mka0d2mQj7O20YHXpBKlb3ypdC', + 'Kerim Atayew', 'Kerim', 'Atayew', 'kerim', + '+993 61 92 92 49', 'user', true +), +( + 'leyla@bank.tm', + '$2a$12$.9KVj6x7wxUMdPcBJ6UpweYbzW4Mka0d2mQj7O20YHXpBKlb3ypdC', + 'Leyla Gurbanowa', 'Leyla', 'Gurbanowa', 'leyla', + '+993 61 92 92 40', 'user', true ); -- --------------------------------------------------------------------------- -- Roles & permissions -- --------------------------------------------------------------------------- INSERT INTO roles (code, name, guard_name) VALUES + ('superadmin', 'Super Administrator', 'admin'), ('admin', 'Administrator', 'admin'), ('manager', 'Branch Manager', 'admin'), - ('operator', 'Operator', 'admin'); + ('operator', 'Operator', 'admin'), + ('user', 'User', 'web'); INSERT INTO permissions (code, name, guard_name) VALUES ('users.view', 'View users', 'admin'), @@ -103,20 +129,30 @@ INSERT INTO permissions (code, name, guard_name) VALUES INSERT INTO role_user (role_id, user_id) VALUES (1, 1), (2, 2), - (3, 3); + (3, 3), + (4, 4), + (5, 5), + (5, 6), + (5, 7), + (5, 8), + (5, 9), + (5, 10); INSERT INTO permission_user (permission_id, user_id) SELECT p.id, 1 FROM permissions p; INSERT INTO permission_user (permission_id, user_id) -SELECT p.id, 2 FROM permissions p +SELECT p.id, 2 FROM permissions p; + +INSERT INTO permission_user (permission_id, user_id) +SELECT p.id, 3 FROM permissions p WHERE p.code IN ( 'branches.view', 'provinces.view', 'cards.view', 'card-orders.view', 'card-orders.manage', 'loans.view', 'loans.manage' ); INSERT INTO permission_user (permission_id, user_id) -SELECT p.id, 3 FROM permissions p +SELECT p.id, 4 FROM permissions p WHERE p.code IN ( 'card-orders.view', 'loans.view', 'cards.view', 'branches.view' ); @@ -213,57 +249,57 @@ INSERT INTO branches ( 'AGB-01', '{"en":"Ashgabat Central Branch","ru":"Центральный филиал Ашхабад","tm":"Aşgabat Merkezi şahamça"}'::json, '{"en":"Archabil Ave 1","ru":"пр. Арчабиль 1","tm":"Arçabil şaýoly 1"}'::json, - 'AG', 1, '+993 12 22 00 01', 'billing_agb', 'billing_pass', true + 'AG', 1, '+993 61 92 92 48', 'billing_agb', 'billing_pass', true ), ( 'AGB-02', '{"en":"Ashgabat Kopetdag Branch","ru":"Филиал Копетдаг","tm":"Köpetdag şahamçasy"}'::json, '{"en":"Turkmenbashy Ave 45","ru":"пр. Туркменбаши 45","tm":"Türkmenbaşy şaýoly 45"}'::json, - 'AG', 1, '+993 12 22 00 02', 'billing_agb2', 'billing_pass', true + 'AG', 1, '+993 61 92 92 48', 'billing_agb2', 'billing_pass', true ), ( 'AHL-01', '{"en":"Ahal Branch","ru":"Ахалский филиал","tm":"Ahal şahamçasy"}'::json, '{"en":"Anew, Main St 10","ru":"Анев, ул. Главная 10","tm":"Änew, Baş köçe 10"}'::json, - 'AH', 2, '+993 13 21 00 01', 'billing_ahl', 'billing_pass', true + 'AH', 2, '+993 61 92 92 48', 'billing_ahl', 'billing_pass', true ), ( 'BLK-01', '{"en":"Balkanabat Branch","ru":"Филиал Балканабад","tm":"Balkanabat şahamçasy"}'::json, '{"en":"Garaşsyzlyk St 7","ru":"ул. Гарашсызлык 7","tm":"Garaşsyzlyk köçesi 7"}'::json, - 'BL', 5, '+993 22 31 00 01', 'billing_blk', 'billing_pass', true + 'BL', 5, '+993 61 92 92 48', 'billing_blk', 'billing_pass', true ), ( 'DSZ-01', '{"en":"Dashoguz Branch","ru":"Филиал Дашогуз","tm":"Daşoguz şahamçasy"}'::json, '{"en":"Galkynyş St 3","ru":"ул. Галкыныш 3","tm":"Galkynyş köçesi 3"}'::json, - 'DZ', 8, '+993 32 41 00 01', 'billing_dsz', 'billing_pass', true + 'DZ', 8, '+993 61 92 92 48', 'billing_dsz', 'billing_pass', true ), ( 'LBP-01', '{"en":"Turkmenabat Branch","ru":"Филиал Туркменабад","tm":"Türkmenabat şahamçasy"}'::json, '{"en":"Magtymguly Ave 12","ru":"пр. Махтумкули 12","tm":"Magtymguly şaýoly 12"}'::json, - 'LB', 10, '+993 42 51 00 01', 'billing_lbp', 'billing_pass', true + 'LB', 10, '+993 61 92 92 48', 'billing_lbp', 'billing_pass', true ), ( 'MRY-01', '{"en":"Mary Branch","ru":"Марыйский филиал","tm":"Mary şahamçasy"}'::json, '{"en":"Mollanepes St 8","ru":"ул. Молланепес 8","tm":"Mollanepes köçesi 8"}'::json, - 'MR', 12, '+993 52 61 00 01', 'billing_mry', 'billing_pass', true + 'MR', 12, '+993 61 92 92 48', 'billing_mry', 'billing_pass', true ), ( 'MRY-02', '{"en":"Bayramaly Branch (inactive)","ru":"Филиал Байрамали (неактивен)","tm":"Baýramaly şahamçasy (işjeň däl)"}'::json, '{"en":"Bayramaly, Central 1","ru":"Байрамали, Центральная 1","tm":"Baýramaly, Merkezi 1"}'::json, - 'MR', 13, '+993 52 62 00 01', 'billing_mry2', 'billing_pass', false + 'MR', 13, '+993 61 92 92 48', 'billing_mry2', 'billing_pass', false ); INSERT INTO branch_user (branch_id, user_id) VALUES (1, 1), (1, 2), - (2, 2), (1, 3), - (7, 3); + (7, 4), + (2, 5); -- --------------------------------------------------------------------------- -- Card types (payment-cards) & card states (reasons-cards) @@ -359,10 +395,12 @@ INSERT INTO loan_order_required_docs (name, value, active) VALUES -- Cards belonging to users -- --------------------------------------------------------------------------- INSERT INTO cards (user_id, number, name, month, year, type) VALUES - (1, '4169740012345678', 'NURMUHAMMET ALLANOW', '12', '28', 'visa'), - (2, '4169740087654321', 'MERGEN BERDIYEW', '06', '27', 'visa'), - (2, '5536910011223344', 'MERGEN BERDIYEW', '03', '29', 'mastercard'), - (3, '9860010055667788', 'AYGUL HOJAYEVA', '09', '26', 'altyn'); + (5, '4169740012345678', 'SERDAR MYRADOW', '12', '28', 'visa'), + (6, '4169740087654321', 'GULNAR ORAZOWA', '06', '27', 'visa'), + (8, '5536910011223344', 'MAYA HALYLOWA', '03', '29', 'mastercard'), + (7, '9860010055667788', 'DOVRAN ANNAYEW', '09', '26', 'altyn'), + (9, '4169740011112222', 'KERIM ATAYEW', '08', '28', 'visa'), + (10, '5536910055556666', 'LEYLA GURBANOWA', '11', '29', 'mastercard'); -- --------------------------------------------------------------------------- -- Card orders @@ -380,36 +418,36 @@ INSERT INTO card_orders ( 'Serdar', 'Myradow', 'Gurbanowicz', '1990-05-12', 'TM', 'I-AG', '123456', '2015-03-20', 'Ashgabat City Police', 'Ashgabat', 'Bank employee', 'Ashgabat, 10ýyl Abadanlyk 5', 'Ashgabat, 10ýyl Abadanlyk 5', - '+993 61 11 22 33', '+993 12 45 67 89', + '+993 61 92 92 48', '+993 61 92 92 48', 'pending', 'pass1.jpg', 'pass2.jpg', 'pass3.jpg', 'pass4.jpg', - 'First Visa Classic order', 2, false + 'First Visa Classic order', 5, false ), ( 'CO-2026-0002', 2, 2, 'AG', 1, 'Gulnar', 'Orazowa', 'Batyrowna', '1988-11-03', 'TM', 'I-AG', '654321', '2014-08-11', 'Ashgabat City Police', 'Ashgabat', 'Teacher', 'Ashgabat, Andalyp 12', 'Ashgabat, Andalyp 12', - '+993 62 22 33 44', NULL, + '+993 61 92 92 48', NULL, 'approved', 'pass1.jpg', 'pass2.jpg', 'pass3.jpg', 'pass4.jpg', - 'Lost card reissue — Gold', 2, true + 'Lost card reissue — Gold', 6, true ), ( 'CO-2026-0003', 1, 4, 'MR', 7, 'Dovran', 'Annayew', 'Hojamyradowiç', '1995-01-25', 'TM', 'I-MR', '112233', '2018-06-01', 'Mary Police', 'Mary', 'Farmer', 'Mary, Garaşsyzlyk 3', 'Mary, Garaşsyzlyk 3', - '+993 63 33 44 55', NULL, + '+993 61 92 92 48', NULL, 'rejected', 'pass1.jpg', 'pass2.jpg', 'pass3.jpg', 'pass4.jpg', - 'Incomplete documents', 3, false + 'Incomplete documents', 7, false ), ( 'CO-2026-0004', 3, 3, 'BL', 4, 'Maya', 'Halylowa', 'Saparowna', '1992-07-19', 'TM', 'I-BL', '445566', '2016-02-14', 'Balkanabat Police', 'Balkanabat', 'Nurse', 'Balkanabat, Magtymguly 9', 'Balkanabat, Magtymguly 9', - '+993 64 44 55 66', NULL, + '+993 61 92 92 48', NULL, 'pending', 'pass1.jpg', 'pass2.jpg', 'pass3.jpg', 'pass4.jpg', - 'Damaged MasterCard', NULL, false + 'Damaged MasterCard', 8, false ); -- --------------------------------------------------------------------------- @@ -423,22 +461,22 @@ INSERT INTO card_pin_orders ( status, notes ) VALUES ( - 'CPO-2026-0001', 2, 1, '4169740087654321', 'AG', 1, - 'Mergen', 'Berdiyew', 'Amangeldiýewiç', '1987-04-08', '+993 62 11 22 33', - 'I-AG', '778899', + 'CPO-2026-0001', 5, 1, '4169740012345678', 'AG', 1, + 'Serdar', 'Myradow', 'Gurbanowicz', '1990-05-12', '+993 61 92 92 48', + 'I-AG', '123456', 'pin1.jpg', 'pin2.jpg', 'pin3.jpg', 'pin4.jpg', 'pending', 'PIN reset request' ), ( - 'CPO-2026-0002', 3, 4, '9860010055667788', 'MR', 7, - 'Aygul', 'Hojayeva', 'Rejepowna', '1993-09-15', '+993 63 44 55 66', - 'I-MR', '998877', + 'CPO-2026-0002', 7, 4, '9860010055667788', 'MR', 7, + 'Dovran', 'Annayew', 'Hojamyradowiç', '1995-01-25', '+993 61 92 92 48', + 'I-MR', '112233', 'pin1.jpg', 'pin2.jpg', 'pin3.jpg', 'pin4.jpg', 'completed', 'PIN issued' ), ( 'CPO-2026-0003', NULL, 2, '4169740099990000', 'AH', 3, - 'Batyr', 'Saparow', 'Orazowicz', '1991-12-01', '+993 65 55 66 77', + 'Batyr', 'Saparow', 'Orazowicz', '1991-12-01', '+993 61 92 92 48', 'I-AH', '334455', 'pin1.jpg', 'pin2.jpg', 'pin3.jpg', 'pin4.jpg', 'rejected', 'Passport mismatch' @@ -465,11 +503,11 @@ INSERT INTO loan_orders ( loan_order_required_doc_id, status, satisfiable, notes ) VALUES ( - 'LO-2026-0001', 'web', 2, 1, 'AG', 1, + 'LO-2026-0001', 'web', 9, 1, 'AG', 1, 'Kerim', 'Atayew', 'Begliýewiç', 'Ashgabat, Bitaraplyk 20', 'Ashgabat, Bitaraplyk 20', 'I-AG', '101010', '2017-01-15', 'Ashgabat City Police', 'Ashgabat', '1989-03-21', - 'kerim@mail.tm', '+993 61 10 20 30', NULL, '+993 12 34 56 78', + 'kerim@bank.tm', '+993 61 92 92 48', NULL, '+993 61 92 92 48', 'AG', 1, 'Türkmen Poçta', 'ACC-1001', '2019-05-01', '4500', 'Specialist', 'higher', 'married', @@ -482,11 +520,11 @@ INSERT INTO loan_orders ( 1, 'pending', 'yes', 'Consumer loan application' ), ( - 'LO-2026-0002', 'web', 2, 3, 'AG', 2, + 'LO-2026-0002', 'web', 10, 3, 'AG', 2, 'Leyla', 'Gurbanowa', 'Saparowna', 'Ashgabat, Andalyp 8', 'Ashgabat, Andalyp 8', 'I-AG', '303030', '2016-09-10', 'Ashgabat City Police', 'Ashgabat', '1994-08-02', - 'leyla@mail.tm', '+993 62 20 30 40', '+993 61 99 88 77', NULL, + 'leyla@bank.tm', '+993 61 92 92 48', '+993 61 92 92 48', NULL, 'AG', 1, 'Altyn Asyr', 'ACC-2002', '2020-02-15', '3800', 'Accountant', 'higher', 'single', @@ -496,11 +534,11 @@ INSERT INTO loan_orders ( 2, 'approved', 'yes', 'Auto loan approved' ), ( - 'LO-2026-0003', 'branch', 3, 2, 'MR', 7, - 'Rahman', 'Jumaýew', 'Berdiýewiç', - 'Mary, Galkynyş 15', 'Mary, Galkynyş 15', 'I-MR', '404040', - '2012-04-22', 'Mary Police', 'Mary', '1985-06-30', - NULL, '+993 63 30 40 50', NULL, NULL, + 'LO-2026-0003', 'branch', 7, 2, 'MR', 7, + 'Dovran', 'Annayew', 'Hojamyradowiç', + 'Mary, Galkynyş 15', 'Mary, Galkynyş 15', 'I-MR', '112233', + '2012-04-22', 'Mary Police', 'Mary', '1995-01-25', + 'dovran@bank.tm', '+993 61 92 92 48', NULL, NULL, 'MR', 12, 'Mary Textile', 'ACC-3003', '2015-01-10', '5200', 'Engineer', 'higher', 'married', @@ -517,7 +555,7 @@ INSERT INTO loan_orders ( 'Oguljenan', 'Çaryýewa', 'Myradowna', 'Turkmenabat, Magtymguly 2', 'Turkmenabat, Magtymguly 2', 'I-LB', '606060', '2019-11-05', 'Turkmenabat Police', 'Turkmenabat', '1996-12-12', - 'ogul@mail.tm', '+993 64 40 50 60', NULL, NULL, + 'ogul@mail.tm', '+993 61 92 92 48', NULL, NULL, 'LB', 10, 'Self-employed', NULL, '2021-03-01', '6000', 'Entrepreneur', 'secondary', 'single', @@ -531,10 +569,11 @@ INSERT INTO loan_orders ( -- Loans (repayment accounts) -- --------------------------------------------------------------------------- INSERT INTO loans (user_id, passport_serie, passport_id, account_number) VALUES - (2, 'I-AG', '778899', 'ACC-LOAN-10001'), - (3, 'I-MR', '998877', 'ACC-LOAN-10002'), - (1, 'I-AG', '101010', 'ACC-LOAN-10003'), - (2, 'I-AG', '303030', 'ACC-LOAN-10004'); + (9, 'I-AG', '101010', 'ACC-LOAN-10001'), + (10, 'I-AG', '303030', 'ACC-LOAN-10002'), + (7, 'I-MR', '112233', 'ACC-LOAN-10003'), + (5, 'I-AG', '123456', 'ACC-LOAN-10004'), + (6, 'I-AG', '654321', 'ACC-LOAN-10005'); -- --------------------------------------------------------------------------- -- Loan paid-off letters @@ -546,21 +585,21 @@ INSERT INTO loan_paid_off_letters ( loan_contract_number, loan_contract_date, loan_amount, loan_reason, loan_file ) VALUES ( - 'LPL-2026-0001', 'AG', 1, 2, - 'Mergen', 'Berdiyew', 'Amangeldiýewiç', '1987-04-08', '+993 62 11 22 33', - 'I-AG', '778899', 'pending', 'Waiting for branch confirmation', + 'LPL-2026-0001', 'AG', 1, 9, + 'Kerim', 'Atayew', 'Begliýewiç', '1989-03-21', '+993 61 92 92 48', + 'I-AG', '101010', 'pending', 'Waiting for branch confirmation', 'CTR-2024-1001', '2024-01-15', '15000', 'Consumer loan closed', 'letter1.pdf' ), ( - 'LPL-2026-0002', 'MR', 7, 3, - 'Aygul', 'Hojayeva', 'Rejepowna', '1993-09-15', '+993 63 44 55 66', - 'I-MR', '998877', 'approved', 'Paid off confirmed', + 'LPL-2026-0002', 'AG', 2, 10, + 'Leyla', 'Gurbanowa', 'Saparowna', '1994-08-02', '+993 61 92 92 48', + 'I-AG', '303030', 'approved', 'Paid off confirmed', 'CTR-2023-2202', '2023-06-01', '8000', 'Early repayment', 'letter2.pdf' ), ( - 'LPL-2026-0003', 'AG', 2, NULL, - 'Kerim', 'Atayew', 'Begliýewiç', '1989-03-21', '+993 61 10 20 30', - 'I-AG', '101010', 'rejected', 'Outstanding balance remains', + 'LPL-2026-0003', 'AG', 1, NULL, + 'Batyr', 'Saparow', 'Orazowicz', '1991-12-01', '+993 61 92 92 48', + 'I-AH', '334455', 'rejected', 'Outstanding balance remains', 'CTR-2025-3303', '2025-02-10', '20000', 'Requested too early', NULL ); @@ -568,22 +607,26 @@ INSERT INTO loan_paid_off_letters ( -- Activity logs -- --------------------------------------------------------------------------- INSERT INTO activity_logs (user_id, method, path, module, action, status_code, request_body, ip) VALUES - (1, 'POST', '/api/admin/login', 'auth', 'login', 200, '{"email":"admin@admin.com"}'::jsonb, '127.0.0.1'), - (1, 'GET', '/api/admin/users', 'users', 'list', 200, NULL, '127.0.0.1'), - (1, 'POST', '/api/admin/provinces', 'provinces', 'create', 200, '{"name":{"tm":"Aşgabat"}}'::jsonb, '10.0.0.5'), - (2, 'GET', '/api/admin/card-orders', 'card-orders', 'list', 200, NULL, '10.0.0.12'), - (2, 'PUT', '/api/admin/card-orders/2', 'card-orders', 'update', 200, '{"status":"approved"}'::jsonb, '10.0.0.12'), - (3, 'GET', '/api/admin/loan-orders', 'loan-orders', 'list', 200, NULL, '10.0.0.20'), - (3, 'POST', '/api/admin/loan-orders', 'loan-orders', 'create', 400, '{"loanAmount":"0"}'::jsonb, '10.0.0.20'), + (1, 'POST', '/api/admin/login', 'auth', 'login', 200, '{"email":"superadmin@bank.tm"}'::jsonb, '127.0.0.1'), + (2, 'POST', '/api/admin/login', 'auth', 'login', 200, '{"email":"admin@bank.tm"}'::jsonb, '10.0.0.5'), + (2, 'GET', '/api/admin/users', 'users', 'list', 200, NULL, '10.0.0.5'), + (1, 'POST', '/api/admin/provinces', 'provinces', 'create', 200, '{"name":{"tm":"Aşgabat"}}'::jsonb, '127.0.0.1'), + (3, 'GET', '/api/admin/card-orders', 'card-orders', 'list', 200, NULL, '10.0.0.12'), + (3, 'PUT', '/api/admin/card-orders/2', 'card-orders', 'update', 200, '{"status":"approved"}'::jsonb, '10.0.0.12'), + (4, 'GET', '/api/admin/loan-orders', 'loan-orders', 'list', 200, NULL, '10.0.0.20'), + (4, 'POST', '/api/admin/loan-orders', 'loan-orders', 'create', 400, '{"loanAmount":"0"}'::jsonb, '10.0.0.20'), (1, 'DELETE', '/api/admin/roles/99', 'roles', 'delete', 404, NULL, '127.0.0.1'), - (2, 'GET', '/api/admin/branches', 'branches', 'list', 200, NULL, '10.0.0.12'), - (1, 'PUT', '/api/admin/profile', 'auth', 'update', 200, '{"firstName":"Nurmuhammet"}'::jsonb, '127.0.0.1'); + (3, 'GET', '/api/admin/branches', 'branches', 'list', 200, NULL, '10.0.0.12'), + (2, 'PUT', '/api/admin/profile', 'auth', 'update', 200, '{"firstName":"Nurmuhammet"}'::jsonb, '10.0.0.5'), + (5, 'GET', '/api/admin/cards', 'cards', 'list', 200, NULL, '10.0.0.30'); COMMIT; -- Quick counts SELECT 'users' AS table_name, count(*) FROM users UNION ALL SELECT 'roles', count(*) FROM roles +UNION ALL SELECT 'role_user', count(*) FROM role_user +UNION ALL SELECT 'branch_user', count(*) FROM branch_user UNION ALL SELECT 'permissions', count(*) FROM permissions UNION ALL SELECT 'provinces', count(*) FROM provinces UNION ALL SELECT 'branches', count(*) FROM branches @@ -597,5 +640,7 @@ UNION ALL SELECT 'card_pin_orders', count(*) FROM card_pin_orders UNION ALL SELECT 'loan_orders', count(*) FROM loan_orders UNION ALL SELECT 'loans', count(*) FROM loans UNION ALL SELECT 'loan_paid_off_letters', count(*) FROM loan_paid_off_letters +UNION ALL SELECT 'registration_verifications', count(*) FROM registration_verifications UNION ALL SELECT 'activity_logs', count(*) FROM activity_logs ORDER BY 1; + diff --git a/docs/docs.go b/docs/docs.go index 7272f0b..c3cc646 100644 --- a/docs/docs.go +++ b/docs/docs.go @@ -1673,6 +1673,98 @@ const docTemplate = `{ } } }, + "/forgot-password": { + "post": { + "description": "Finds the user by name and sends an SMS verification code", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "auth" + ], + "summary": "Forgot password", + "parameters": [ + { + "description": "Forgot password payload", + "name": "body", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/auth.ForgotPasswordDTO" + } + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/appresult.AppSuccess" + } + }, + "400": { + "description": "Bad Request", + "schema": { + "$ref": "#/definitions/appresult.AppError" + } + }, + "404": { + "description": "Not Found", + "schema": { + "$ref": "#/definitions/appresult.AppError" + } + } + } + } + }, + "/forgot-password/verify": { + "post": { + "description": "Confirms the SMS code and sets a new password", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "auth" + ], + "summary": "Reset password", + "parameters": [ + { + "description": "Reset password payload", + "name": "body", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/auth.ResetPasswordDTO" + } + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/appresult.AppSuccess" + } + }, + "400": { + "description": "Bad Request", + "schema": { + "$ref": "#/definitions/appresult.AppError" + } + }, + "404": { + "description": "Not Found", + "schema": { + "$ref": "#/definitions/appresult.AppError" + } + } + } + } + }, "/loan-orders": { "get": { "security": [ @@ -3200,7 +3292,7 @@ const docTemplate = `{ }, "/login": { "post": { - "description": "Authenticates a user by email and password", + "description": "Authenticates a user by name or phone, and password", "consumes": [ "application/json" ], @@ -5221,7 +5313,7 @@ const docTemplate = `{ "BearerAuth": [] } ], - "description": "Returns paginated users with optional filters", + "description": "Returns paginated users with role user, with optional filters", "produces": [ "application/json" ], @@ -5322,29 +5414,22 @@ const docTemplate = `{ } } }, - "/users/role": { + "/users/clients": { "get": { "security": [ { "BearerAuth": [] } ], - "description": "Returns paginated users filtered by role", + "description": "Returns paginated users from the users table with role user", "produces": [ "application/json" ], "tags": [ "user" ], - "summary": "List users by role", + "summary": "List client users", "parameters": [ - { - "type": "string", - "description": "user role", - "name": "role", - "in": "query", - "required": true - }, { "type": "string", "description": "Filter by username", @@ -5379,8 +5464,61 @@ const docTemplate = `{ "$ref": "#/definitions/appresult.AppError" } }, - "404": { - "description": "Not Found", + "500": { + "description": "Internal Server Error", + "schema": { + "$ref": "#/definitions/appresult.AppError" + } + } + } + } + }, + "/users/staff": { + "get": { + "security": [ + { + "BearerAuth": [] + } + ], + "description": "Returns paginated users assigned to branches (from branch_user), including each user's branches.", + "produces": [ + "application/json" + ], + "tags": [ + "user" + ], + "summary": "List staff users", + "parameters": [ + { + "type": "string", + "description": "Filter by username", + "name": "username", + "in": "query" + }, + { + "type": "integer", + "default": 1, + "description": "Page number", + "name": "page", + "in": "query" + }, + { + "type": "integer", + "default": 10, + "description": "Items per page", + "name": "limit", + "in": "query" + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/appresult.AppSuccess" + } + }, + "400": { + "description": "Bad Request", "schema": { "$ref": "#/definitions/appresult.AppError" } @@ -5589,18 +5727,31 @@ const docTemplate = `{ } } }, + "auth.ForgotPasswordDTO": { + "type": "object", + "required": [ + "name" + ], + "properties": { + "name": { + "type": "string" + } + } + }, "auth.LoginDTO": { "type": "object", "required": [ - "email", "password" ], "properties": { - "email": { + "name": { "type": "string" }, "password": { "type": "string" + }, + "phone": { + "type": "string" } } }, @@ -5644,6 +5795,30 @@ const docTemplate = `{ } } }, + "auth.ResetPasswordDTO": { + "type": "object", + "required": [ + "code", + "name", + "password", + "passwordConfirm" + ], + "properties": { + "code": { + "type": "string" + }, + "name": { + "type": "string" + }, + "password": { + "type": "string", + "minLength": 6 + }, + "passwordConfirm": { + "type": "string" + } + } + }, "auth.UpdateProfileDTO": { "type": "object", "required": [ diff --git a/docs/swagger.json b/docs/swagger.json index 6fd1f92..c4322f0 100644 --- a/docs/swagger.json +++ b/docs/swagger.json @@ -1667,6 +1667,98 @@ } } }, + "/forgot-password": { + "post": { + "description": "Finds the user by name and sends an SMS verification code", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "auth" + ], + "summary": "Forgot password", + "parameters": [ + { + "description": "Forgot password payload", + "name": "body", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/auth.ForgotPasswordDTO" + } + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/appresult.AppSuccess" + } + }, + "400": { + "description": "Bad Request", + "schema": { + "$ref": "#/definitions/appresult.AppError" + } + }, + "404": { + "description": "Not Found", + "schema": { + "$ref": "#/definitions/appresult.AppError" + } + } + } + } + }, + "/forgot-password/verify": { + "post": { + "description": "Confirms the SMS code and sets a new password", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "auth" + ], + "summary": "Reset password", + "parameters": [ + { + "description": "Reset password payload", + "name": "body", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/auth.ResetPasswordDTO" + } + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/appresult.AppSuccess" + } + }, + "400": { + "description": "Bad Request", + "schema": { + "$ref": "#/definitions/appresult.AppError" + } + }, + "404": { + "description": "Not Found", + "schema": { + "$ref": "#/definitions/appresult.AppError" + } + } + } + } + }, "/loan-orders": { "get": { "security": [ @@ -3194,7 +3286,7 @@ }, "/login": { "post": { - "description": "Authenticates a user by email and password", + "description": "Authenticates a user by name or phone, and password", "consumes": [ "application/json" ], @@ -5215,7 +5307,7 @@ "BearerAuth": [] } ], - "description": "Returns paginated users with optional filters", + "description": "Returns paginated users with role user, with optional filters", "produces": [ "application/json" ], @@ -5316,29 +5408,22 @@ } } }, - "/users/role": { + "/users/clients": { "get": { "security": [ { "BearerAuth": [] } ], - "description": "Returns paginated users filtered by role", + "description": "Returns paginated users from the users table with role user", "produces": [ "application/json" ], "tags": [ "user" ], - "summary": "List users by role", + "summary": "List client users", "parameters": [ - { - "type": "string", - "description": "user role", - "name": "role", - "in": "query", - "required": true - }, { "type": "string", "description": "Filter by username", @@ -5373,8 +5458,61 @@ "$ref": "#/definitions/appresult.AppError" } }, - "404": { - "description": "Not Found", + "500": { + "description": "Internal Server Error", + "schema": { + "$ref": "#/definitions/appresult.AppError" + } + } + } + } + }, + "/users/staff": { + "get": { + "security": [ + { + "BearerAuth": [] + } + ], + "description": "Returns paginated users assigned to branches (from branch_user), including each user's branches.", + "produces": [ + "application/json" + ], + "tags": [ + "user" + ], + "summary": "List staff users", + "parameters": [ + { + "type": "string", + "description": "Filter by username", + "name": "username", + "in": "query" + }, + { + "type": "integer", + "default": 1, + "description": "Page number", + "name": "page", + "in": "query" + }, + { + "type": "integer", + "default": 10, + "description": "Items per page", + "name": "limit", + "in": "query" + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/appresult.AppSuccess" + } + }, + "400": { + "description": "Bad Request", "schema": { "$ref": "#/definitions/appresult.AppError" } @@ -5583,18 +5721,31 @@ } } }, + "auth.ForgotPasswordDTO": { + "type": "object", + "required": [ + "name" + ], + "properties": { + "name": { + "type": "string" + } + } + }, "auth.LoginDTO": { "type": "object", "required": [ - "email", "password" ], "properties": { - "email": { + "name": { "type": "string" }, "password": { "type": "string" + }, + "phone": { + "type": "string" } } }, @@ -5638,6 +5789,30 @@ } } }, + "auth.ResetPasswordDTO": { + "type": "object", + "required": [ + "code", + "name", + "password", + "passwordConfirm" + ], + "properties": { + "code": { + "type": "string" + }, + "name": { + "type": "string" + }, + "password": { + "type": "string", + "minLength": 6 + }, + "passwordConfirm": { + "type": "string" + } + } + }, "auth.UpdateProfileDTO": { "type": "object", "required": [ diff --git a/docs/swagger.yaml b/docs/swagger.yaml index 85a05e1..3e72d03 100644 --- a/docs/swagger.yaml +++ b/docs/swagger.yaml @@ -19,14 +19,22 @@ definitions: status: type: boolean type: object + auth.ForgotPasswordDTO: + properties: + name: + type: string + required: + - name + type: object auth.LoginDTO: properties: - email: + name: type: string password: type: string + phone: + type: string required: - - email - password type: object auth.RefreshTokenDTO: @@ -57,6 +65,23 @@ definitions: - phone - username type: object + auth.ResetPasswordDTO: + properties: + code: + type: string + name: + type: string + password: + minLength: 6 + type: string + passwordConfirm: + type: string + required: + - code + - name + - password + - passwordConfirm + type: object auth.UpdateProfileDTO: properties: avatar: @@ -2313,6 +2338,66 @@ paths: - BearerAuth: [] tags: - file-upload + /forgot-password: + post: + consumes: + - application/json + description: Finds the user by name and sends an SMS verification code + parameters: + - description: Forgot password payload + in: body + name: body + required: true + schema: + $ref: '#/definitions/auth.ForgotPasswordDTO' + produces: + - application/json + responses: + "200": + description: OK + schema: + $ref: '#/definitions/appresult.AppSuccess' + "400": + description: Bad Request + schema: + $ref: '#/definitions/appresult.AppError' + "404": + description: Not Found + schema: + $ref: '#/definitions/appresult.AppError' + summary: Forgot password + tags: + - auth + /forgot-password/verify: + post: + consumes: + - application/json + description: Confirms the SMS code and sets a new password + parameters: + - description: Reset password payload + in: body + name: body + required: true + schema: + $ref: '#/definitions/auth.ResetPasswordDTO' + produces: + - application/json + responses: + "200": + description: OK + schema: + $ref: '#/definitions/appresult.AppSuccess' + "400": + description: Bad Request + schema: + $ref: '#/definitions/appresult.AppError' + "404": + description: Not Found + schema: + $ref: '#/definitions/appresult.AppError' + summary: Reset password + tags: + - auth /loan-orders: get: description: Returns paginated loan orders with optional filters @@ -3295,7 +3380,7 @@ paths: post: consumes: - application/json - description: Authenticates a user by email and password + description: Authenticates a user by name or phone, and password parameters: - description: Login payload in: body @@ -4585,7 +4670,7 @@ paths: - auth /users: get: - description: Returns paginated users with optional filters + description: Returns paginated users with role user, with optional filters parameters: - description: Filter by username in: query @@ -4757,15 +4842,10 @@ paths: summary: Update user tags: - user - /users/role: + /users/clients: get: - description: Returns paginated users filtered by role + description: Returns paginated users from the users table with role user parameters: - - description: user role - in: query - name: role - required: true - type: string - description: Filter by username in: query name: username @@ -4791,8 +4871,43 @@ paths: description: Bad Request schema: $ref: '#/definitions/appresult.AppError' - "404": - description: Not Found + "500": + description: Internal Server Error + schema: + $ref: '#/definitions/appresult.AppError' + security: + - BearerAuth: [] + summary: List client users + tags: + - user + /users/staff: + get: + description: Returns paginated users assigned to branches (from branch_user), + including each user's branches. + parameters: + - description: Filter by username + in: query + name: username + type: string + - default: 1 + description: Page number + in: query + name: page + type: integer + - default: 10 + description: Items per page + in: query + name: limit + type: integer + produces: + - application/json + responses: + "200": + description: OK + schema: + $ref: '#/definitions/appresult.AppSuccess' + "400": + description: Bad Request schema: $ref: '#/definitions/appresult.AppError' "500": @@ -4801,7 +4916,7 @@ paths: $ref: '#/definitions/appresult.AppError' security: - BearerAuth: [] - summary: List users by role + summary: List staff users tags: - user securityDefinitions: diff --git a/internal/identity/auth/db/postgresql.go b/internal/identity/auth/db/postgresql.go index 963fc90..44f3180 100755 --- a/internal/identity/auth/db/postgresql.go +++ b/internal/identity/auth/db/postgresql.go @@ -27,15 +27,35 @@ func NewRepository(client postgresql.Client, logger *logging.Logger) auth.Reposi } const ( - loginQuery = `SELECT id, password FROM users WHERE email = $1` + loginByNameQuery = ` + SELECT id, password FROM users + WHERE LOWER(TRIM(name)) = LOWER(TRIM($1)) + OR LOWER(TRIM(username)) = LOWER(TRIM($1)) + LIMIT 1` + loginByPhoneQuery = ` + SELECT id, password FROM users + WHERE phone = $1 + 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` ) func (r *repository) Login(ctx context.Context, dto auth.LoginDTO) (auth.UserCredentials, error) { + phone := strings.TrimSpace(dto.Phone) + if phone != "" { + normalized := phone + if n, err := auth.NormalizePhone(phone); err == nil { + normalized = n + } + var result auth.UserCredentials + err := r.client.QueryRow(ctx, loginByPhoneQuery, normalized, digitString(phone)).Scan(&result.Id, &result.Password) + return result, err + } + var result auth.UserCredentials - err := r.client.QueryRow(ctx, loginQuery, dto.Email).Scan(&result.Id, &result.Password) + err := r.client.QueryRow(ctx, loginByNameQuery, strings.TrimSpace(dto.Name)).Scan(&result.Id, &result.Password) return result, err } @@ -180,6 +200,46 @@ func (r *repository) CompleteRegistration(ctx context.Context, v auth.Verificati return userID, nil } +func (r *repository) GetUserByName(ctx context.Context, name string) (auth.UserIdentity, error) { + const query = ` + SELECT id, name, username, phone FROM users + WHERE LOWER(TRIM(name)) = LOWER(TRIM($1)) + LIMIT 1` + + var user auth.UserIdentity + err := r.client.QueryRow(ctx, query, name).Scan(&user.Id, &user.Name, &user.Username, &user.Phone) + if errors.Is(err, pgx.ErrNoRows) { + return auth.UserIdentity{}, auth.ErrNotFound + } + return user, err +} + +func (r *repository) CompletePasswordReset(ctx context.Context, userID int, verificationID int64, passwordHash string) error { + tx, err := r.client.Begin(ctx) + if err != nil { + return err + } + defer tx.Rollback(ctx) + + tag, err := tx.Exec(ctx, ` + UPDATE users SET + password = $1, + updated_at = (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') + WHERE id = $2`, passwordHash, userID) + if err != nil { + return err + } + if tag.RowsAffected() == 0 { + return auth.ErrNotFound + } + + if _, err := tx.Exec(ctx, `DELETE FROM registration_verifications WHERE id = $1`, verificationID); err != nil { + return err + } + + return tx.Commit(ctx) +} + func digitString(s string) string { var b strings.Builder for _, r := range s { diff --git a/internal/identity/auth/dto.go b/internal/identity/auth/dto.go index 350210b..cb694d5 100755 --- a/internal/identity/auth/dto.go +++ b/internal/identity/auth/dto.go @@ -3,7 +3,8 @@ package auth import "time" type LoginDTO struct { - Email string `json:"email" binding:"required"` + Name string `json:"name"` + Phone string `json:"phone"` Password string `json:"password" binding:"required"` } @@ -47,6 +48,24 @@ type VerifyDTO struct { Code string `json:"code" binding:"required,len=6"` } +type ForgotPasswordDTO struct { + Name string `json:"name" binding:"required"` +} + +type ResetPasswordDTO struct { + Name string `json:"name" binding:"required"` + Code string `json:"code" binding:"required,len=6"` + Password string `json:"password" binding:"required,min=6"` + PasswordConfirm string `json:"passwordConfirm" binding:"required"` +} + +type UserIdentity struct { + Id int + Name string + Username string + Phone string +} + type RegisterResult struct { Phone string `json:"phone"` ExpiresIn int `json:"expiresIn"` diff --git a/internal/identity/auth/handler.go b/internal/identity/auth/handler.go index 9e2e0b7..583e0bd 100755 --- a/internal/identity/auth/handler.go +++ b/internal/identity/auth/handler.go @@ -15,11 +15,13 @@ import ( ) const ( - loginURL = "/login" - tokenURL = "/token" - profileURL = "/profile" - registerURL = "/register" - verifyURL = "/register/verify" + loginURL = "/login" + tokenURL = "/token" + profileURL = "/profile" + registerURL = "/register" + verifyURL = "/register/verify" + forgotPasswordURL = "/forgot-password" + resetPasswordURL = "/forgot-password/verify" ) type handler struct { @@ -37,6 +39,8 @@ func (h *handler) Register(router *gin.RouterGroup) { router.POST(tokenURL, h.refreshToken) router.POST(registerURL, h.register) router.POST(verifyURL, h.verify) + router.POST(forgotPasswordURL, h.forgotPassword) + router.POST(resetPasswordURL, h.resetPassword) protected := router.Group("", appresult.JwtTokenCheck()) protected.GET(profileURL, h.getProfile) @@ -45,7 +49,7 @@ func (h *handler) Register(router *gin.RouterGroup) { // login godoc // @Summary Login -// @Description Authenticates a user by email and password +// @Description Authenticates a user by name or phone, and password // @Tags auth // @Accept json // @Produce json @@ -62,7 +66,12 @@ func (h *handler) login(c *gin.Context) { } tokenPair, err := h.service.Login(c.Request.Context(), dto) + if errors.Is(err, ErrInvalidInput) { + c.JSON(http.StatusBadRequest, appresult.ErrMissingParam) + return + } if errors.Is(err, ErrInvalidCredentials) { + h.logger.Warnf("login failed for name=%q phone=%q: %v", dto.Name, dto.Phone, err) c.JSON(http.StatusUnauthorized, appresult.ErrUnauthorized) return } @@ -128,12 +137,68 @@ func (h *handler) verify(c *gin.Context) { c.JSON(http.StatusOK, appresult.SuccessWithData(tokenPair)) } +// forgotPassword godoc +// @Summary Forgot password +// @Description Finds the user by name and sends an SMS verification code +// @Tags auth +// @Accept json +// @Produce json +// @Param body body ForgotPasswordDTO true "Forgot password payload" +// @Success 200 {object} appresult.AppSuccess +// @Failure 400 {object} appresult.AppError +// @Failure 404 {object} appresult.AppError +// @Router /forgot-password [post] +func (h *handler) forgotPassword(c *gin.Context) { + var dto ForgotPasswordDTO + if err := c.ShouldBindJSON(&dto); err != nil { + c.JSON(http.StatusBadRequest, appresult.ErrMissingParam) + return + } + + result, err := h.service.ForgotPassword(c.Request.Context(), dto) + if err != nil { + h.respondRegisterError(c, err) + return + } + + c.JSON(http.StatusOK, appresult.SuccessWithData(result)) +} + +// resetPassword godoc +// @Summary Reset password +// @Description Confirms the SMS code and sets a new password +// @Tags auth +// @Accept json +// @Produce json +// @Param body body ResetPasswordDTO true "Reset password payload" +// @Success 200 {object} appresult.AppSuccess +// @Failure 400 {object} appresult.AppError +// @Failure 404 {object} appresult.AppError +// @Router /forgot-password/verify [post] +func (h *handler) resetPassword(c *gin.Context) { + var dto ResetPasswordDTO + if err := c.ShouldBindJSON(&dto); err != nil { + c.JSON(http.StatusBadRequest, appresult.ErrMissingParam) + return + } + + tokenPair, err := h.service.ResetPassword(c.Request.Context(), dto) + if err != nil { + h.respondRegisterError(c, err) + return + } + + c.JSON(http.StatusOK, appresult.SuccessWithData(tokenPair)) +} + func (h *handler) respondRegisterError(c *gin.Context, err error) { switch { case errors.Is(err, ErrPasswordMismatch): c.JSON(http.StatusBadRequest, appresult.ErrPasswordMismatch) case errors.Is(err, ErrInvalidPhone), errors.Is(err, ErrInvalidInput): c.JSON(http.StatusBadRequest, appresult.ErrMissingParam) + case errors.Is(err, ErrNotFound): + c.JSON(http.StatusNotFound, appresult.ErrNotFound) case errors.Is(err, ErrConflict): c.JSON(http.StatusConflict, appresult.ErrConflict) case errors.Is(err, ErrInvalidCode): diff --git a/internal/identity/auth/phone.go b/internal/identity/auth/phone.go index 95acf76..1931b81 100644 --- a/internal/identity/auth/phone.go +++ b/internal/identity/auth/phone.go @@ -2,6 +2,7 @@ package auth import ( "fmt" + "strconv" "strings" "unicode" ) @@ -16,19 +17,30 @@ func onlyDigits(s string) string { return b.String() } -// NormalizePhone accepts Turkmen numbers in common local forms and -// returns +993 6X XX XX XX. +// NormalizePhone strips a leading +993 / 993 country code, then checks +// that the remaining local number is 8 digits with prefix 61–65 or 71–72. +// It returns +993 XX XX XX XX. func NormalizePhone(raw string) (string, error) { digits := onlyDigits(raw) - switch { - case strings.HasPrefix(digits, "993") && len(digits) == 11: + if strings.HasPrefix(digits, "993") { digits = digits[3:] - case len(digits) == 9 && digits[0] == '8': + } else if len(digits) == 9 && digits[0] == '8' { digits = digits[1:] } if len(digits) != 8 { return "", ErrInvalidPhone } + if !validMobilePrefix(digits[:2]) { + return "", ErrInvalidPhone + } return fmt.Sprintf("+993 %s %s %s %s", digits[0:2], digits[2:4], digits[4:6], digits[6:8]), nil } + +func validMobilePrefix(prefix string) bool { + n, err := strconv.Atoi(prefix) + if err != nil { + return false + } + return (n >= 61 && n <= 65) || (n >= 71 && n <= 72) +} diff --git a/internal/identity/auth/phone_test.go b/internal/identity/auth/phone_test.go index 6c8018a..c7616d1 100644 --- a/internal/identity/auth/phone_test.go +++ b/internal/identity/auth/phone_test.go @@ -6,6 +6,7 @@ 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"}, @@ -26,4 +27,22 @@ func TestNormalizePhone(t *testing.T) { 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) + } + } } diff --git a/internal/identity/auth/service.go b/internal/identity/auth/service.go index ddf6087..a378ad1 100644 --- a/internal/identity/auth/service.go +++ b/internal/identity/auth/service.go @@ -28,6 +28,7 @@ var ( ErrInvalidPhone = errors.New("invalid phone number") ErrInvalidCode = errors.New("invalid or expired verification code") ErrInvalidInput = errors.New("required parameter is missing or invalid") + ErrNotFound = errors.New("not found") ) type Service struct { @@ -40,13 +41,31 @@ func NewService(repository Repository, sender sms.Sender) *Service { } func (s *Service) Login(ctx context.Context, dto LoginDTO) (map[string]string, error) { - user, err := s.repository.Login(ctx, dto) - if err != nil { - return nil, ErrInvalidCredentials + name := strings.TrimSpace(dto.Name) + phone := strings.TrimSpace(dto.Phone) + + normalized, err := NormalizePhone(phone) + if err == nil { + dto.Phone = normalized + dto.Name = "" + } else { + dto.Phone = "" + dto.Name = name + if dto.Name == "" { + return nil, ErrInvalidInput + } } - if err := bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(dto.Password)); err != nil { - return nil, ErrInvalidCredentials + user, err := s.repository.Login(ctx, dto) + if err != nil { + return nil, fmt.Errorf("%w: user not found", ErrInvalidCredentials) + } + + password := strings.TrimSpace(dto.Password) + if err := bcrypt.CompareHashAndPassword([]byte(strings.TrimSpace(user.Password)), []byte(password)); err != nil { + if user.Password != password { + return nil, fmt.Errorf("%w: password mismatch", ErrInvalidCredentials) + } } return utils.GenerateTokenPair(user.Id) @@ -108,40 +127,112 @@ func (s *Service) Register(ctx context.Context, dto RegisterDTO) (RegisterResult return RegisterResult{}, err } - code := localOTP - // Production: replace the line above with generateOTP(). - // code, err := generateOTP() - // if err != nil { - // return RegisterResult{}, err - // } - - codeHash, err := bcrypt.GenerateFromPassword([]byte(code), bcrypt.DefaultCost) - if err != nil { - return RegisterResult{}, err - } - - expiresAt := time.Now().UTC().Add(otpTTL) - if err := s.repository.UpsertVerification(ctx, Verification{ - Name: name, - Username: username, - Phone: phone, - Password: string(hashedPassword), - CodeHash: string(codeHash), - ExpiresAt: expiresAt, + if err := s.storeAndSendOTP(ctx, Verification{ + Name: name, + Username: username, + Phone: phone, + Password: string(hashedPassword), }); err != nil { return RegisterResult{}, err } - if err := s.sms.Send(ctx, phone, fmt.Sprintf(otpMessageTm, code)); err != nil { - return RegisterResult{}, err - } - return RegisterResult{ Phone: phone, ExpiresIn: int(otpTTL.Seconds()), }, nil } +func (s *Service) ForgotPassword(ctx context.Context, dto ForgotPasswordDTO) (RegisterResult, error) { + name := strings.TrimSpace(dto.Name) + if name == "" { + return RegisterResult{}, ErrInvalidInput + } + + user, err := s.repository.GetUserByName(ctx, name) + if err != nil { + return RegisterResult{}, err + } + if strings.TrimSpace(user.Phone) == "" { + return RegisterResult{}, ErrInvalidPhone + } + + if err := s.storeAndSendOTP(ctx, Verification{ + Name: user.Name, + Username: user.Username, + Phone: user.Phone, + }); err != nil { + return RegisterResult{}, err + } + + return RegisterResult{ + Phone: user.Phone, + ExpiresIn: int(otpTTL.Seconds()), + }, nil +} + +func (s *Service) ResetPassword(ctx context.Context, dto ResetPasswordDTO) (map[string]string, error) { + if dto.Password != dto.PasswordConfirm { + return nil, ErrPasswordMismatch + } + + name := strings.TrimSpace(dto.Name) + if name == "" { + return nil, ErrInvalidInput + } + + user, err := s.repository.GetUserByName(ctx, name) + if err != nil { + return nil, err + } + + v, err := s.repository.GetVerificationByPhone(ctx, user.Phone) + if err != nil { + return nil, ErrInvalidCode + } + + if v.Attempts >= maxVerifyTries || time.Now().UTC().After(v.ExpiresAt) { + return nil, ErrInvalidCode + } + + if err := bcrypt.CompareHashAndPassword([]byte(v.CodeHash), []byte(strings.TrimSpace(dto.Code))); err != nil { + _ = s.repository.IncrementVerifyAttempts(ctx, v.ID) + return nil, ErrInvalidCode + } + + hashedPassword, err := bcrypt.GenerateFromPassword([]byte(dto.Password), bcrypt.DefaultCost) + if err != nil { + return nil, err + } + + if err := s.repository.CompletePasswordReset(ctx, user.Id, v.ID, string(hashedPassword)); err != nil { + return nil, err + } + + return utils.GenerateTokenPair(user.Id) +} + +func (s *Service) storeAndSendOTP(ctx context.Context, v Verification) error { + code := localOTP + // Production: replace the line above with generateOTP(). + // code, err := generateOTP() + // if err != nil { + // return err + // } + + codeHash, err := bcrypt.GenerateFromPassword([]byte(code), bcrypt.DefaultCost) + if err != nil { + return err + } + + v.CodeHash = string(codeHash) + v.ExpiresAt = time.Now().UTC().Add(otpTTL) + if err := s.repository.UpsertVerification(ctx, v); err != nil { + return err + } + + return s.sms.Send(ctx, v.Phone, fmt.Sprintf(otpMessageTm, code)) +} + func (s *Service) Verify(ctx context.Context, dto VerifyDTO) (map[string]string, error) { phone, err := NormalizePhone(dto.Phone) if err != nil { @@ -167,7 +258,7 @@ func (s *Service) Verify(ctx context.Context, dto VerifyDTO) (map[string]string, return nil, err } - return utils.GenerateUserTokenPair(userID) + return utils.GenerateTokenPair(userID) } // Production: uncomment generateOTP and add imports "crypto/rand" and "math/big". diff --git a/internal/identity/auth/service_test.go b/internal/identity/auth/service_test.go index 7eeb16e..3770378 100644 --- a/internal/identity/auth/service_test.go +++ b/internal/identity/auth/service_test.go @@ -16,10 +16,19 @@ type fakeRepo struct { verification Verification getErr error userID int + userByName UserIdentity + userByNameErr error + loginUser UserCredentials + loginErr error + lastLogin LoginDTO } -func (f *fakeRepo) Login(context.Context, LoginDTO) (UserCredentials, error) { - return UserCredentials{}, errors.New("not implemented") +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") @@ -50,6 +59,15 @@ func (f *fakeRepo) IncrementVerifyAttempts(context.Context, int64) error { 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 @@ -72,6 +90,54 @@ func validRegisterDTO() RegisterDTO { } } +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" @@ -147,3 +213,81 @@ func TestVerifyExpiredCode(t *testing.T) { 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) + } +} diff --git a/internal/identity/auth/storage.go b/internal/identity/auth/storage.go index 2f05968..d1bb77b 100755 --- a/internal/identity/auth/storage.go +++ b/internal/identity/auth/storage.go @@ -13,4 +13,6 @@ type Repository interface { GetVerificationByPhone(ctx context.Context, phone string) (Verification, error) IncrementVerifyAttempts(ctx context.Context, id int64) error CompleteRegistration(ctx context.Context, v Verification) (int, error) + GetUserByName(ctx context.Context, name string) (UserIdentity, error) + CompletePasswordReset(ctx context.Context, userID int, verificationID int64, passwordHash string) error } diff --git a/internal/identity/user/db/postgresql.go b/internal/identity/user/db/postgresql.go index 9c56733..9b5c2fc 100644 --- a/internal/identity/user/db/postgresql.go +++ b/internal/identity/user/db/postgresql.go @@ -29,8 +29,73 @@ const userColumns = `u.id, u.email, u.name, u.first_name, u.last_name, u.usernam const userReturningColumns = `id, email, name, first_name, last_name, username, phone, avatar, social_media, light_mode, role, active, created_at, updated_at` func (r *repository) List(ctx context.Context, filter user.ListFilter) (user.ListUserDTO, error) { - fromClause, whereClause, args := buildListQuery(filter) + fromClause, whereClause, args := buildFilteredListQuery(filter, listVisibleRoles...) + return r.paginateUsers(ctx, filter, fromClause, whereClause, args) +} +func (r *repository) ListStaff(ctx context.Context, filter user.ListFilter) (user.ListUserDTO, error) { + fromClause := ` FROM users u ` + whereClause, args := buildStaffWhere(filter) + + var count int64 + countQuery := `SELECT COUNT(*)` + fromClause + whereClause + if err := r.client.QueryRow(ctx, countQuery, args...).Scan(&count); err != nil { + return user.ListUserDTO{}, err + } + + offset := (filter.Page - 1) * filter.Limit + limitPlaceholder := len(args) + 1 + offsetPlaceholder := len(args) + 2 + listQuery := fmt.Sprintf( + `SELECT %s, COALESCE(( + SELECT json_agg(jsonb_build_object( + 'id', b.id, + 'uniqueCode', 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) + %s%s ORDER BY u.id LIMIT $%d OFFSET $%d`, + userColumns, fromClause, whereClause, limitPlaceholder, offsetPlaceholder, + ) + + rows, err := r.client.Query(ctx, listQuery, append(args, filter.Limit, offset)...) + if err != nil { + return user.ListUserDTO{}, err + } + defer rows.Close() + + var items []user.UserDTO + for rows.Next() { + item, err := scanStaffUser(rows) + if err != nil { + return user.ListUserDTO{}, err + } + items = append(items, item) + } + if err := rows.Err(); err != nil { + return user.ListUserDTO{}, err + } + + return user.ListUserDTO{Count: count, Users: items}, nil +} + +func buildStaffWhere(filter user.ListFilter) (whereClause string, args []interface{}) { + conditions := []string{`EXISTS (SELECT 1 FROM branch_user bu WHERE bu.user_id = u.id)`} + if filter.Username != "" { + args = append(args, likePattern(filter.Username)) + conditions = append(conditions, fmt.Sprintf(`u.username ILIKE $%d`, len(args))) + } + return " WHERE " + strings.Join(conditions, " AND "), args +} + +func (r *repository) paginateUsers(ctx context.Context, filter user.ListFilter, fromClause, whereClause string, args []interface{}) (user.ListUserDTO, error) { var count int64 if err := r.client.QueryRow(ctx, `SELECT COUNT(*) `+fromClause+whereClause, args...).Scan(&count); err != nil { return user.ListUserDTO{}, err @@ -65,11 +130,9 @@ func (r *repository) List(ctx context.Context, filter user.ListFilter) (user.Lis return user.ListUserDTO{Count: count, Users: items}, nil } -func buildListQuery(filter user.ListFilter) (fromClause, whereClause string, args []interface{}) { - return buildFilteredListQuery(filter, "") -} +var listVisibleRoles = []string{"user"} -func buildFilteredListQuery(filter user.ListFilter, role string) (fromClause, whereClause string, args []interface{}) { +func buildFilteredListQuery(filter user.ListFilter, roles ...string) (fromClause, whereClause string, args []interface{}) { fromClause = ` FROM users u ` var conditions []string @@ -78,10 +141,17 @@ func buildFilteredListQuery(filter user.ListFilter, role string) (fromClause, wh n := len(args) conditions = append(conditions, fmt.Sprintf(`u.username ILIKE $%d`, n)) } - if role != "" { - args = append(args, role) + if len(roles) == 1 { + args = append(args, roles[0]) n := len(args) conditions = append(conditions, fmt.Sprintf(`u.role = $%d`, n)) + } else if len(roles) > 0 { + placeholders := make([]string, len(roles)) + for i, role := range roles { + args = append(args, role) + placeholders[i] = fmt.Sprintf("$%d", len(args)) + } + conditions = append(conditions, fmt.Sprintf(`u.role IN (%s)`, strings.Join(placeholders, ", "))) } if len(conditions) == 0 { @@ -100,39 +170,7 @@ func likePattern(term string) string { func (r *repository) GetByRole(ctx context.Context, role string, filter user.ListFilter) (user.ListUserDTO, error) { fromClause, whereClause, args := buildFilteredListQuery(filter, role) - - var count int64 - if err := r.client.QueryRow(ctx, `SELECT COUNT(*) `+fromClause+whereClause, args...).Scan(&count); err != nil { - return user.ListUserDTO{}, err - } - - offset := (filter.Page - 1) * filter.Limit - limitPlaceholder := len(args) + 1 - offsetPlaceholder := len(args) + 2 - listQuery := fmt.Sprintf( - `SELECT %s%s%s ORDER BY u.id LIMIT $%d OFFSET $%d `, - userColumns, fromClause, whereClause, limitPlaceholder, offsetPlaceholder, - ) - - rows, err := r.client.Query(ctx, listQuery, append(args, filter.Limit, offset)...) - if err != nil { - return user.ListUserDTO{}, err - } - defer rows.Close() - - var items []user.UserDTO - for rows.Next() { - item, err := scanUser(rows) - if err != nil { - return user.ListUserDTO{}, err - } - items = append(items, item) - } - if err := rows.Err(); err != nil { - return user.ListUserDTO{}, err - } - - return user.ListUserDTO{Count: count, Users: items}, nil + return r.paginateUsers(ctx, filter, fromClause, whereClause, args) } func (r *repository) GetByID(ctx context.Context, id int64) (user.UserDTO, error) { @@ -222,3 +260,26 @@ func scanUser(row scannable) (user.UserDTO, error) { } return item, nil } + +func scanStaffUser(row scannable) (user.UserDTO, error) { + var item user.UserDTO + var socialMedia []byte + var branchesJSON []byte + if err := row.Scan( + &item.Id, &item.Email, &item.Name, &item.FirstName, &item.LastName, &item.Username, &item.Phone, &item.Avatar, + &socialMedia, &item.LightMode, &item.Role, &item.Active, &item.CreatedAt, &item.UpdatedAt, &branchesJSON, + ); err != nil { + return user.UserDTO{}, err + } + if err := json.Unmarshal(socialMedia, &item.SocialMedia); err != nil { + return user.UserDTO{}, err + } + if len(branchesJSON) == 0 || string(branchesJSON) == "null" { + item.Branches = []user.StaffBranchDTO{} + return item, nil + } + if err := json.Unmarshal(branchesJSON, &item.Branches); err != nil { + return user.UserDTO{}, err + } + return item, nil +} diff --git a/internal/identity/user/dto.go b/internal/identity/user/dto.go index a47f155..80e0077 100644 --- a/internal/identity/user/dto.go +++ b/internal/identity/user/dto.go @@ -8,21 +8,34 @@ type SocialMedia struct { Telegram string `json:"telegram"` } +type LocalizedText struct { + En string `json:"en"` + Ru string `json:"ru"` + Tm string `json:"tm"` +} + +type StaffBranchDTO struct { + Id int64 `json:"id"` + UniqueCode string `json:"uniqueCode"` + Name LocalizedText `json:"name"` +} + type UserDTO struct { - Id int64 `json:"id"` - Email string `json:"email"` - Name string `json:"name"` - FirstName string `json:"firstName"` - LastName string `json:"lastName"` - Username string `json:"username"` - Phone string `json:"phone"` - Avatar string `json:"avatar"` - SocialMedia SocialMedia `json:"socialMedia"` - LightMode int `json:"lightMode"` - Role string `json:"role"` - Active bool `json:"active"` - CreatedAt time.Time `json:"createdAt"` - UpdatedAt time.Time `json:"updatedAt"` + Id int64 `json:"id"` + Email string `json:"email"` + Name string `json:"name"` + FirstName string `json:"firstName"` + LastName string `json:"lastName"` + Username string `json:"username"` + Phone string `json:"phone"` + Avatar string `json:"avatar"` + SocialMedia SocialMedia `json:"socialMedia"` + LightMode int `json:"lightMode"` + Role string `json:"role"` + Active bool `json:"active"` + CreatedAt time.Time `json:"createdAt"` + UpdatedAt time.Time `json:"updatedAt"` + Branches []StaffBranchDTO `json:"branches,omitempty"` } type CreateUserDTO struct { diff --git a/internal/identity/user/handler.go b/internal/identity/user/handler.go index f4af693..aa68aec 100644 --- a/internal/identity/user/handler.go +++ b/internal/identity/user/handler.go @@ -40,7 +40,8 @@ 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("/role", h.listUsersByRole) + group.GET("/clients", h.listClients) + group.GET("/staff", h.listStaff) group.GET("/:id", h.getByID) group.POST("", h.create) group.PUT("/:id", h.update) @@ -57,7 +58,7 @@ func (h *handler) Register(router *gin.RouterGroup) { // list godoc // @Summary List users -// @Description Returns paginated users with optional filters +// @Description Returns paginated users with role user, with optional filters // @Tags user // @Produce json // @Security BearerAuth @@ -85,41 +86,29 @@ func (h *handler) list(c *gin.Context) { c.JSON(http.StatusOK, appresult.SuccessWithData(result)) } -// listUsersByRole godoc -// @Summary List users by role -// @Description Returns paginated users filtered by role +// listClients godoc +// @Summary List client users +// @Description Returns paginated users from the users table with role user // @Tags user // @Produce json // @Security BearerAuth -// @Param role query string true "user role" // @Param username query string false "Filter by username" // @Param page query int false "Page number" default(1) // @Param limit query int false "Items per page" default(10) // @Success 200 {object} appresult.AppSuccess // @Failure 400 {object} appresult.AppError -// @Failure 404 {object} appresult.AppError // @Failure 500 {object} appresult.AppError -// @Router /users/role [get] -func (h *handler) listUsersByRole(c *gin.Context) { - role := strings.TrimSpace(c.Query("role")) - if role == "" { - c.JSON(http.StatusBadRequest, appresult.ErrMissingParam) - return - } - +// @Router /users/clients [get] +func (h *handler) listClients(c *gin.Context) { filter, ok := parseListFilter(c) if !ok { c.JSON(http.StatusBadRequest, appresult.ErrMissingParam) return } - item, err := h.repository.GetByRole(c.Request.Context(), role, filter) - if errors.Is(err, pgx.ErrNoRows) { - c.JSON(http.StatusNotFound, appresult.ErrNotFound) - return - } + item, err := h.repository.GetByRole(c.Request.Context(), "user", filter) if err != nil { - h.logger.Errorf("get user failed: %v", err) + h.logger.Errorf("list client users failed: %v", err) c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer) return } @@ -127,6 +116,36 @@ func (h *handler) listUsersByRole(c *gin.Context) { c.JSON(http.StatusOK, appresult.SuccessWithData(item)) } +// listStaff godoc +// @Summary List staff users +// @Description Returns paginated users assigned to branches (from branch_user), including each user's branches. +// @Tags user +// @Produce json +// @Security BearerAuth +// @Param username query string false "Filter by username" +// @Param page query int false "Page number" default(1) +// @Param limit query int false "Items per page" default(10) +// @Success 200 {object} appresult.AppSuccess +// @Failure 400 {object} appresult.AppError +// @Failure 500 {object} appresult.AppError +// @Router /users/staff [get] +func (h *handler) listStaff(c *gin.Context) { + filter, ok := parseListFilter(c) + if !ok { + c.JSON(http.StatusBadRequest, appresult.ErrMissingParam) + return + } + + result, err := h.repository.ListStaff(c.Request.Context(), filter) + if err != nil { + h.logger.Errorf("list staff users failed: %v", err) + c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer) + return + } + + c.JSON(http.StatusOK, appresult.SuccessWithData(result)) +} + // getByID godoc // @Summary Get user by ID // @Description Returns a single user diff --git a/internal/identity/user/storage.go b/internal/identity/user/storage.go index da355b4..85764ba 100644 --- a/internal/identity/user/storage.go +++ b/internal/identity/user/storage.go @@ -4,6 +4,7 @@ import "context" type Repository interface { List(ctx context.Context, filter ListFilter) (ListUserDTO, error) + ListStaff(ctx context.Context, filter ListFilter) (ListUserDTO, error) GetByID(ctx context.Context, id int64) (UserDTO, error) GetByRole(ctx context.Context, role string, filter ListFilter) (ListUserDTO, error) Create(ctx context.Context, dto CreateUserDTO) (UserDTO, error)