Compare commits
10
Commits
4350915b30
...
30bcfefc1e
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
30bcfefc1e | ||
|
|
3636e1ca53 | ||
|
|
585ba63bc2 | ||
|
|
7e3a5cebcc | ||
|
|
6705c4ce91 | ||
|
|
c29c72fd92 | ||
|
|
d6555e1133 | ||
|
|
be3dc28e68 | ||
|
|
77bc4025d3 | ||
|
|
1337175e5d |
No files matched your search
@@ -1,5 +1,6 @@
|
||||
# Binaries
|
||||
online-back
|
||||
myapp
|
||||
*.exe
|
||||
*.exe~
|
||||
*.dll
|
||||
@@ -21,6 +22,7 @@ coverage.html
|
||||
!.env.example
|
||||
config.local.yaml
|
||||
config.yaml
|
||||
!config.example.yaml
|
||||
|
||||
# Logs
|
||||
logs/
|
||||
|
||||
@@ -8,12 +8,12 @@ create-migration:
|
||||
|
||||
# --- for Macos
|
||||
migrate:
|
||||
migrate -database 'postgres://bank_admin:bank@#23#@_password@localhost:5424/bank_db?sslmode=disable' -path db/migrations up
|
||||
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@#23#@_password@localhost:5424/bank_db?sslmode=disable' -path db/migrations down
|
||||
migrate -database 'postgres://bank_admin:bank%40%2323%23%40_password@localhost:5424/bank_db?sslmode=disable' -path db/migrations down
|
||||
|
||||
# ---- for linux
|
||||
# migrate:
|
||||
# migrate -database 'postgresql://bank_admin:bank@#23#@_password@localhost:5454/bank_db?sslmode=disable' -path db/migrations up
|
||||
# migrate -database 'postgresql://bank_admin:bank%40%2323%23%40_password@localhost:5454/bank_db?sslmode=disable' -path db/migrations up
|
||||
# migrate-rollback:
|
||||
# migrate -database 'postgresql://bank_admin:bank@#23#@_password@localhost:5454/bank_db?sslmode=disable' -path db/migrations down
|
||||
# migrate -database 'postgresql://bank_admin:bank%40%2323%23%40_password@localhost:5454/bank_db?sslmode=disable' -path db/migrations down
|
||||
@@ -110,7 +110,7 @@ The API will be available at `http://localhost:5050`.
|
||||
|
||||
1. Start PostgreSQL (or use `docker compose up main-db -d`).
|
||||
|
||||
2. Update `config.yaml` — set `storage.host` to `localhost` and match your database credentials.
|
||||
2. Copy `config.example.yaml` to `config.yaml`, set `storage.host` to `localhost`, and fill in your database credentials and a JWT secret.
|
||||
|
||||
3. Apply migrations:
|
||||
|
||||
@@ -130,26 +130,6 @@ The API will be available at `http://localhost:5050`.
|
||||
go run app.go
|
||||
```
|
||||
|
||||
## Configuration
|
||||
|
||||
Settings are loaded from `config.yaml`:
|
||||
|
||||
```yaml
|
||||
is_debug: true
|
||||
listen:
|
||||
port: 5050
|
||||
jwt_key: <your-jwt-secret>
|
||||
storage:
|
||||
host: main-db # use localhost when running outside Docker
|
||||
port: 5432
|
||||
database: bank_db
|
||||
username: bank_admin
|
||||
password: <password>
|
||||
pg_pool_max_conn: 10
|
||||
public_file_path: ./public
|
||||
app_version: 0.0.1
|
||||
```
|
||||
|
||||
> **Note:** Replace default credentials before deploying to production.
|
||||
|
||||
|
||||
|
||||
@@ -37,6 +37,12 @@ import (
|
||||
// @tag.description Loan types
|
||||
// @tag.name loan-document
|
||||
// @tag.description Loan required documents
|
||||
// @tag.name loans-repayment
|
||||
// @tag.description Loan repayments
|
||||
// @tag.name card-orders
|
||||
// @tag.description Card orders
|
||||
// @tag.name activity-logs
|
||||
// @tag.description User activity audit trail
|
||||
func main() {
|
||||
docs.SwaggerInfo.Title = "Service APIs"
|
||||
docs.SwaggerInfo.Version = "1.0"
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
is_debug: true
|
||||
listen:
|
||||
type: port
|
||||
bind_ip: 0.0.0.0
|
||||
port: 5050
|
||||
jwt_key: <your-jwt-secret>
|
||||
storage:
|
||||
host: example-db # use localhost when running outside Docker
|
||||
port: 5432
|
||||
database: example_db
|
||||
username: example_username
|
||||
password: <your-db-password>
|
||||
pg_pool_max_conn: 10
|
||||
minio:
|
||||
endpoint: example-minio:9000 # use localhost:9003 when running outside Docker
|
||||
access_key: <your-minio-access-key>
|
||||
secret_key: <your-minio-secret-key>
|
||||
bucket: dev-minio
|
||||
use_ssl: false
|
||||
app_version: 0.0.1
|
||||
public_file_path: ./public
|
||||
-16
@@ -1,16 +0,0 @@
|
||||
is_debug: true
|
||||
listen:
|
||||
type: port
|
||||
port: 5050
|
||||
jwt_key: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpX@VCJ9.yueyJzdWIiOiIyNTEyNzMiLCJpYXQiOjE1MTYy#MzkwMjJ9.o_LoJm03CaE6!0dugdR8sjIuFgPxGT7I2W8NvugFqHRY
|
||||
storage:
|
||||
# host: localhost
|
||||
host: main-db
|
||||
# port: 5424
|
||||
port: 5432
|
||||
database: bank_db
|
||||
username: bank_admin
|
||||
password: bank@#23#@_password
|
||||
pg_pool_max_conn: 10
|
||||
app_version: 0.0.1
|
||||
public_file_path: ./public
|
||||
@@ -1,6 +1,17 @@
|
||||
DROP TABLE IF EXISTS roles;
|
||||
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 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 branches;
|
||||
|
||||
@@ -1,36 +1,37 @@
|
||||
CREATE TABLE IF NOT EXISTS users (
|
||||
"id" bigserial primary key,
|
||||
"email" character varying(250) NOT NULL DEFAULT '',
|
||||
"name" character varying(250) NOT NULL DEFAULT '',
|
||||
"password" character varying(250) NOT NULL DEFAULT '',
|
||||
"first_name" character varying(250) NOT NULL DEFAULT '',
|
||||
"last_name" character varying(250) NOT NULL DEFAULT '',
|
||||
"username" character varying(250) NOT NULL DEFAULT '',
|
||||
"phone" character varying(250) NOT NULL DEFAULT '',
|
||||
"light_mode" integer DEFAULT 1 NOT NULL,
|
||||
"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
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS users (
|
||||
id bigserial PRIMARY KEY,
|
||||
email character varying(250) NOT NULL DEFAULT '',
|
||||
password character varying(250) NOT NULL DEFAULT '',
|
||||
name character varying(255) NOT NULL DEFAULT '',
|
||||
first_name character varying(255) NOT NULL DEFAULT '',
|
||||
last_name character varying(255) NOT NULL DEFAULT '',
|
||||
username character varying(250) NOT NULL DEFAULT '',
|
||||
phone character varying(250) NOT NULL DEFAULT '',
|
||||
avatar character varying(250) NOT NULL DEFAULT '',
|
||||
social_media json NOT NULL DEFAULT '{}'::json,
|
||||
light_mode integer NOT NULL DEFAULT 1,
|
||||
role character varying(250) NOT NULL DEFAULT 'user',
|
||||
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$8ZbKmoSwna4CASQptM2/SubwvsBUR1YhABULd.2/QJB.13Wi2v55m',
|
||||
'Admin',
|
||||
'admin@admin.com',
|
||||
'admin'
|
||||
);
|
||||
INSERT INTO users (phone, password, name, email, role)
|
||||
VALUES (
|
||||
'61531216',
|
||||
'$2a$12$8ZbKmoSwna4CASQptM2/SubwvsBUR1YhABULd.2/QJB.13Wi2v55m',
|
||||
'Admin',
|
||||
'admin@admin.com',
|
||||
'admin'
|
||||
);
|
||||
|
||||
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
|
||||
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 (
|
||||
@@ -38,9 +39,9 @@ CREATE TABLE IF NOT EXISTS branches (
|
||||
unique_code character varying(255) UNIQUE,
|
||||
name json NOT NULL DEFAULT '{}'::json,
|
||||
address json NOT NULL DEFAULT '{}'::json,
|
||||
region character varying(2) NOT NULL DEFAULT '',
|
||||
province_id bigint REFERENCES provinces(id) ON DELETE SET NULL,
|
||||
phone_numbers 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 '',
|
||||
@@ -50,8 +51,10 @@ CREATE TABLE IF NOT EXISTS branches (
|
||||
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
|
||||
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 (
|
||||
@@ -60,8 +63,8 @@ CREATE TABLE IF NOT EXISTS card_types (
|
||||
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
|
||||
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 (
|
||||
@@ -74,6 +77,48 @@ CREATE TABLE IF NOT EXISTS card_states (
|
||||
updated_at TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS permissions (
|
||||
id bigserial PRIMARY KEY,
|
||||
code character varying(255) NOT NULL DEFAULT '',
|
||||
name character varying(255) NOT NULL,
|
||||
guard_name character varying(255) NOT NULL,
|
||||
created_at TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL,
|
||||
updated_at TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS roles (
|
||||
id bigserial PRIMARY KEY,
|
||||
code character varying(255) NOT NULL DEFAULT '',
|
||||
name character varying(255) NOT NULL,
|
||||
guard_name character varying(255) NOT NULL,
|
||||
created_at TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL,
|
||||
updated_at TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS role_user (
|
||||
id bigserial PRIMARY KEY,
|
||||
role_id bigint REFERENCES roles(id),
|
||||
user_id bigint REFERENCES users(id),
|
||||
created_at TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL,
|
||||
updated_at TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS permission_user (
|
||||
id bigserial PRIMARY KEY,
|
||||
permission_id bigint REFERENCES permissions(id),
|
||||
user_id bigint REFERENCES users(id),
|
||||
created_at TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL,
|
||||
updated_at TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS branch_user (
|
||||
id bigserial PRIMARY KEY,
|
||||
branch_id bigint REFERENCES branches(id),
|
||||
user_id bigint REFERENCES users(id),
|
||||
created_at TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL,
|
||||
updated_at TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS loan_types (
|
||||
id bigserial PRIMARY KEY,
|
||||
name json NOT NULL DEFAULT '{}'::json,
|
||||
@@ -94,20 +139,222 @@ CREATE TABLE IF NOT EXISTS loan_order_required_docs (
|
||||
updated_at TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS roles (
|
||||
CREATE TABLE IF NOT EXISTS loan_orders (
|
||||
id bigserial PRIMARY KEY,
|
||||
code character varying(255) NOT NULL DEFAULT '',
|
||||
name character varying(255) NOT NULL,
|
||||
guard_name character varying(255) NOT NULL,
|
||||
unique_id character varying(255),
|
||||
source character varying(255) DEFAULT 'web'::character varying,
|
||||
user_id bigint,
|
||||
loan_type bigint NOT NULL,
|
||||
region character varying(2) NOT NULL,
|
||||
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),
|
||||
passport_address character varying(255) NOT NULL,
|
||||
real_address 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,
|
||||
born_at date NOT NULL,
|
||||
email character varying(255),
|
||||
phone character varying(255) NOT NULL,
|
||||
phone_additional character varying(255),
|
||||
phone_home character varying(255),
|
||||
work_region character varying(255),
|
||||
work_province_id bigint,
|
||||
work_company character varying(255),
|
||||
work_company_accountant_number character varying(255),
|
||||
work_started_at date,
|
||||
work_salary character varying(255),
|
||||
work_position character varying(255),
|
||||
education character varying(255) NOT NULL,
|
||||
marriage_status 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,
|
||||
loan_amount character varying(255),
|
||||
card_number character varying(255),
|
||||
card_name character varying(255),
|
||||
card_month character varying(255),
|
||||
card_year character varying(255),
|
||||
guarantor_name character varying(255),
|
||||
guarantor_surname character varying(255),
|
||||
guarantor_patronic_name character varying(255),
|
||||
guarantor_passport_serie character varying(255),
|
||||
guarantor_passport_id character varying(255),
|
||||
guarantor_card_number character varying(255),
|
||||
guarantor_card_name character varying(255),
|
||||
guarantor_card_month character varying(255),
|
||||
guarantor_card_year character varying(255),
|
||||
guarantor_note character varying(255),
|
||||
guarantor_2_name character varying(255),
|
||||
guarantor_2_surname character varying(255),
|
||||
guarantor_2_patronic_name character varying(255),
|
||||
guarantor_2_passport_serie character varying(255),
|
||||
guarantor_2_passport_id character varying(255),
|
||||
guarantor_2_card_number character varying(255),
|
||||
guarantor_2_card_name character varying(255),
|
||||
guarantor_2_card_month character varying(255),
|
||||
guarantor_2_card_year character varying(255),
|
||||
guarantor_2_note character varying(255),
|
||||
loan_card_number character varying(255),
|
||||
loan_card_name character varying(255),
|
||||
loan_card_month character varying(255),
|
||||
loan_card_year character varying(255),
|
||||
loan_order_required_doc_id bigint,
|
||||
status character varying(255),
|
||||
satisfiable character varying(255),
|
||||
notes text,
|
||||
created_at TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL,
|
||||
updated_at TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS permissions (
|
||||
CREATE TABLE IF NOT EXISTS loans (
|
||||
id bigserial PRIMARY KEY,
|
||||
code character varying(255) NOT NULL DEFAULT '',
|
||||
name character varying(255) NOT NULL,
|
||||
guard_name character varying(255) NOT NULL,
|
||||
user_id bigint,
|
||||
passport_serie character varying(255) NOT NULL,
|
||||
passport_id character varying(255) NOT NULL,
|
||||
account_number character varying(255) NOT NULL,
|
||||
created_at TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL,
|
||||
updated_at TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL
|
||||
);
|
||||
updated_at TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL,
|
||||
CONSTRAINT loans_user_id_fkey
|
||||
FOREIGN KEY (user_id) REFERENCES users(id)
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS loan_paid_off_letters (
|
||||
id bigserial PRIMARY KEY,
|
||||
unique_id character varying(255),
|
||||
region character varying(2) NOT NULL,
|
||||
branch_id bigint NOT NULL,
|
||||
user_id bigint,
|
||||
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) NOT NULL,
|
||||
passport_serie character varying(255) NOT NULL,
|
||||
passport_id character varying(255) NOT NULL,
|
||||
status character varying(255),
|
||||
notes text,
|
||||
loan_contract_number character varying(255),
|
||||
loan_contract_date date,
|
||||
loan_amount character varying(255),
|
||||
loan_reason character varying(255),
|
||||
loan_file text,
|
||||
created_at TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL,
|
||||
updated_at TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL,
|
||||
CONSTRAINT loan_paid_off_letters_branch_id_fkey
|
||||
FOREIGN KEY (branch_id) REFERENCES branches(id),
|
||||
CONSTRAINT loan_paid_off_letters_user_id_fkey
|
||||
FOREIGN KEY (user_id) REFERENCES users(id)
|
||||
);
|
||||
|
||||
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)
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS activity_logs (
|
||||
id bigserial PRIMARY KEY,
|
||||
user_id bigint,
|
||||
method character varying(10) NOT NULL DEFAULT '',
|
||||
path character varying(255) NOT NULL DEFAULT '',
|
||||
module character varying(100) NOT NULL DEFAULT '',
|
||||
action character varying(50) NOT NULL DEFAULT '',
|
||||
status_code integer NOT NULL DEFAULT 0,
|
||||
request_body jsonb,
|
||||
ip character varying(50) NOT NULL DEFAULT '',
|
||||
created_at TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL,
|
||||
CONSTRAINT activity_logs_user_id_fkey
|
||||
FOREIGN KEY (user_id) REFERENCES users(id)
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_activity_logs_user_id ON activity_logs(user_id);
|
||||
CREATE INDEX IF NOT EXISTS idx_activity_logs_module ON activity_logs(module);
|
||||
CREATE INDEX IF NOT EXISTS idx_activity_logs_created_at ON activity_logs(created_at);
|
||||
Executable
+11
@@ -0,0 +1,11 @@
|
||||
FROM quay.io/minio/minio
|
||||
|
||||
RUN mkdir /storage
|
||||
|
||||
VOLUME /storage
|
||||
|
||||
ENV MINIO_VOLUMES="/storage"
|
||||
EXPOSE 9000
|
||||
EXPOSE 9093
|
||||
|
||||
CMD ["minio", "server", "/storage", "--console-address", ":9093"]
|
||||
+36
-19
@@ -1,5 +1,3 @@
|
||||
version: '3.4'
|
||||
|
||||
services:
|
||||
main-db:
|
||||
image: postgres:14.1-alpine
|
||||
@@ -15,26 +13,45 @@ services:
|
||||
- main-db-storage:/var/lib/postgresql/data
|
||||
networks:
|
||||
- myNetwork
|
||||
|
||||
main-server:
|
||||
image: main-app
|
||||
restart: unless-stopped
|
||||
container_name: "main-app"
|
||||
build:
|
||||
context: .
|
||||
dockerfile: Dockerfile
|
||||
ports:
|
||||
- "5050:5050"
|
||||
volumes:
|
||||
- ./public:/app/public
|
||||
depends_on:
|
||||
- main-db
|
||||
networks:
|
||||
- myNetwork
|
||||
image: main-app
|
||||
restart: unless-stopped
|
||||
container_name: "main-app"
|
||||
build:
|
||||
context: .
|
||||
dockerfile: Dockerfile
|
||||
ports:
|
||||
- "5050:5050"
|
||||
volumes:
|
||||
- ./public:/app/public
|
||||
depends_on:
|
||||
- main-db
|
||||
- main-minio
|
||||
networks:
|
||||
- myNetwork
|
||||
|
||||
main-minio:
|
||||
container_name: "main-minio"
|
||||
build:
|
||||
context: .
|
||||
dockerfile: deployment/Dockerfile.minio
|
||||
restart: unless-stopped
|
||||
environment:
|
||||
- MINIO_ROOT_USER=TX3H1H6XTS288QW07S8Z
|
||||
- MINIO_ROOT_PASSWORD=FWWspiI4n4LMknnxYCmzFTCY1ObkGiuaU9SNwOCU
|
||||
ports:
|
||||
- '9003:9000'
|
||||
- '9093:9093'
|
||||
volumes:
|
||||
- main-minio-storage:/storage
|
||||
networks:
|
||||
- myNetwork
|
||||
|
||||
volumes:
|
||||
main-db-storage:
|
||||
main-db-storage:
|
||||
main-minio-storage:
|
||||
|
||||
networks:
|
||||
myNetwork:
|
||||
driver: bridge
|
||||
|
||||
driver: bridge
|
||||
+3727
-15
File diff suppressed because it is too large.
Load diff
+3727
-15
File diff suppressed because it is too large.
Load diff
+2452
-13
File diff suppressed because it is too large.
Load diff
@@ -10,10 +10,27 @@ var swaggerTagOrder = []struct {
|
||||
{Name: "auth", Description: "Authentication"},
|
||||
{Name: "province", Description: "Provinces"},
|
||||
{Name: "branches", Description: "Branches"},
|
||||
{Name: "branch-users", Description: "Branch users"},
|
||||
{Name: "user", Description: "Users"},
|
||||
{Name: "role", Description: "Roles"},
|
||||
{Name: "role-users", Description: "Role users"},
|
||||
{Name: "permission", Description: "Permissions"},
|
||||
{Name: "permission-users", Description: "Permission users"},
|
||||
{Name: "payment-card", Description: "Payment cards"},
|
||||
{Name: "reason-card", Description: "Reason cards"},
|
||||
{Name: "cards", Description: "Cards"},
|
||||
{Name: "card-orders", Description: "Card orders"},
|
||||
{Name: "card-pin-orders", Description: "Card pin orders"},
|
||||
{Name: "loan-type", Description: "Loan types"},
|
||||
{Name: "loan-document", Description: "Loan required documents"},
|
||||
{Name: "loan-orders", Description: "Loan orders"},
|
||||
{Name: "loans-repayment", Description: "Loan repayments"},
|
||||
{Name: "loan-paid-off-letters", Description: "Loan paid-off letters"},
|
||||
{Name: "file-upload", Description: "File upload"},
|
||||
}
|
||||
|
||||
func init() {
|
||||
applySwaggerTagOrder()
|
||||
}
|
||||
|
||||
func applySwaggerTagOrder() {
|
||||
|
||||
@@ -9,6 +9,7 @@ require (
|
||||
github.com/ilyakaznacheev/cleanenv v1.5.0
|
||||
github.com/jackc/pgconn v1.14.3
|
||||
github.com/jackc/pgx/v4 v4.18.3
|
||||
github.com/minio/minio-go/v7 v7.2.1
|
||||
github.com/sirupsen/logrus v1.9.4
|
||||
github.com/swaggo/files v1.0.1
|
||||
github.com/swaggo/gin-swagger v1.6.1
|
||||
@@ -24,7 +25,9 @@ require (
|
||||
github.com/bytedance/gopkg v0.1.3 // indirect
|
||||
github.com/bytedance/sonic v1.15.0 // indirect
|
||||
github.com/bytedance/sonic/loader v0.5.0 // indirect
|
||||
github.com/cespare/xxhash/v2 v2.3.0 // indirect
|
||||
github.com/cloudwego/base64x v0.1.6 // indirect
|
||||
github.com/dustin/go-humanize v1.0.1 // indirect
|
||||
github.com/gabriel-vasile/mimetype v1.4.12 // indirect
|
||||
github.com/gin-contrib/sse v1.1.0 // indirect
|
||||
github.com/go-openapi/jsonpointer v0.19.5 // indirect
|
||||
@@ -36,6 +39,7 @@ require (
|
||||
github.com/go-playground/validator/v10 v10.30.1 // indirect
|
||||
github.com/goccy/go-json v0.10.5 // indirect
|
||||
github.com/goccy/go-yaml v1.19.2 // indirect
|
||||
github.com/google/uuid v1.6.0 // indirect
|
||||
github.com/jackc/chunkreader/v2 v2.0.1 // indirect
|
||||
github.com/jackc/pgio v1.0.0 // indirect
|
||||
github.com/jackc/pgpassfile v1.0.0 // indirect
|
||||
@@ -46,20 +50,28 @@ require (
|
||||
github.com/joho/godotenv v1.5.1 // indirect
|
||||
github.com/josharian/intern v1.0.0 // indirect
|
||||
github.com/json-iterator/go v1.1.12 // indirect
|
||||
github.com/klauspost/compress v1.18.6 // indirect
|
||||
github.com/klauspost/cpuid/v2 v2.3.0 // indirect
|
||||
github.com/klauspost/crc32 v1.3.0 // indirect
|
||||
github.com/leodido/go-urn v1.4.0 // indirect
|
||||
github.com/lib/pq v1.12.3 // indirect
|
||||
github.com/mailru/easyjson v0.7.6 // indirect
|
||||
github.com/mattn/go-isatty v0.0.20 // indirect
|
||||
github.com/minio/crc64nvme v1.1.1 // indirect
|
||||
github.com/minio/md5-simd v1.1.2 // indirect
|
||||
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
|
||||
github.com/modern-go/reflect2 v1.0.2 // indirect
|
||||
github.com/pelletier/go-toml/v2 v2.3.1 // indirect
|
||||
github.com/philhofer/fwd v1.2.0 // indirect
|
||||
github.com/quic-go/qpack v0.6.0 // indirect
|
||||
github.com/quic-go/quic-go v0.59.0 // indirect
|
||||
github.com/rogpeppe/go-internal v1.14.1 // indirect
|
||||
github.com/rs/xid v1.6.0 // indirect
|
||||
github.com/tinylib/msgp v1.6.1 // indirect
|
||||
github.com/twitchyliquid64/golang-asm v0.15.1 // indirect
|
||||
github.com/ugorji/go/codec v1.3.1 // indirect
|
||||
github.com/zeebo/xxh3 v1.1.0 // indirect
|
||||
go.mongodb.org/mongo-driver/v2 v2.5.0 // indirect
|
||||
go.yaml.in/yaml/v3 v3.0.4 // indirect
|
||||
golang.org/x/arch v0.23.0 // indirect
|
||||
golang.org/x/mod v0.36.0 // indirect
|
||||
golang.org/x/net v0.56.0 // indirect
|
||||
@@ -68,6 +80,7 @@ require (
|
||||
golang.org/x/text v0.38.0 // indirect
|
||||
golang.org/x/tools v0.45.0 // indirect
|
||||
google.golang.org/protobuf v1.36.10 // indirect
|
||||
gopkg.in/ini.v1 v1.67.2 // indirect
|
||||
gopkg.in/yaml.v2 v2.4.0 // indirect
|
||||
gopkg.in/yaml.v3 v3.0.1 // indirect
|
||||
olympos.io/encoding/edn v0.0.0-20201019073823-d3554ca0b0a3 // indirect
|
||||
|
||||
@@ -15,6 +15,8 @@ github.com/bytedance/sonic v1.15.0 h1:/PXeWFaR5ElNcVE84U0dOHjiMHQOwNIx3K4ymzh/uS
|
||||
github.com/bytedance/sonic v1.15.0/go.mod h1:tFkWrPz0/CUCLEF4ri4UkHekCIcdnkqXw9VduqpJh0k=
|
||||
github.com/bytedance/sonic/loader v0.5.0 h1:gXH3KVnatgY7loH5/TkeVyXPfESoqSBSBEiDd5VjlgE=
|
||||
github.com/bytedance/sonic/loader v0.5.0/go.mod h1:AR4NYCk5DdzZizZ5djGqQ92eEhCCcdf5x77udYiSJRo=
|
||||
github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=
|
||||
github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
|
||||
github.com/cloudwego/base64x v0.1.6 h1:t11wG9AECkCDk5fMSoxmufanudBtJ+/HemLstXDLI2M=
|
||||
github.com/cloudwego/base64x v0.1.6/go.mod h1:OFcloc187FXDaYHvrNIjxSe8ncn0OOM8gEHfghB2IPU=
|
||||
github.com/cockroachdb/apd v1.1.0 h1:3LFP3629v+1aKXU5Q37mxmRxX/pIu1nijXydLShEq5I=
|
||||
@@ -26,6 +28,8 @@ github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ3
|
||||
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
|
||||
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY=
|
||||
github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto=
|
||||
github.com/gabriel-vasile/mimetype v1.4.12 h1:e9hWvmLYvtp846tLHam2o++qitpguFiYCKbn0w9jyqw=
|
||||
github.com/gabriel-vasile/mimetype v1.4.12/go.mod h1:d+9Oxyo1wTzWdyVUPMmXFvp4F9tea18J8ufA774AB3s=
|
||||
github.com/gin-contrib/cors v1.7.7 h1:Oh9joP463x7Mw72vhvJ61YQm8ODh9b04YR7vsOErD0Q=
|
||||
@@ -69,6 +73,8 @@ github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
|
||||
github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
|
||||
github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
|
||||
github.com/google/renameio v0.1.0/go.mod h1:KWCgfxg9yswjAJkECMjeO8J8rahYeXnNhOm40UhjYkI=
|
||||
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
|
||||
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
||||
github.com/ilyakaznacheev/cleanenv v1.5.0 h1:0VNZXggJE2OYdXE87bfSSwGxeiGt9moSR2lOrsHHvr4=
|
||||
github.com/ilyakaznacheev/cleanenv v1.5.0/go.mod h1:a5aDzaJrLCQZsazHol1w8InnDcOX0OColm64SlIi6gk=
|
||||
github.com/jackc/chunkreader v1.0.0/go.mod h1:RT6O25fNZIuasFJRyZ4R/Y2BbhasbmZXF9QQ7T3kePo=
|
||||
@@ -127,8 +133,13 @@ github.com/josharian/intern v1.0.0/go.mod h1:5DoeVV0s6jJacbCEi61lwdGj/aVlrQvzHFF
|
||||
github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=
|
||||
github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=
|
||||
github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck=
|
||||
github.com/klauspost/compress v1.18.6 h1:2jupLlAwFm95+YDR+NwD2MEfFO9d4z4Prjl1XXDjuao=
|
||||
github.com/klauspost/compress v1.18.6/go.mod h1:cwPg85FWrGar70rWktvGQj8/hthj3wpl0PGDogxkrSQ=
|
||||
github.com/klauspost/cpuid/v2 v2.0.1/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg=
|
||||
github.com/klauspost/cpuid/v2 v2.3.0 h1:S4CRMLnYUhGeDFDqkGriYKdfoFlDnMtqTiI/sFzhA9Y=
|
||||
github.com/klauspost/cpuid/v2 v2.3.0/go.mod h1:hqwkgyIinND0mEev00jJYCxPNVRVXFQeu1XKlok6oO0=
|
||||
github.com/klauspost/crc32 v1.3.0 h1:sSmTt3gUt81RP655XGZPElI0PelVTZ6YwCRnPSupoFM=
|
||||
github.com/klauspost/crc32 v1.3.0/go.mod h1:D7kQaZhnkX/Y0tstFGf8VUzv2UofNGqCjnC3zdHB0Hw=
|
||||
github.com/konsorten/go-windows-terminal-sequences v1.0.1/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ=
|
||||
github.com/konsorten/go-windows-terminal-sequences v1.0.2/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ=
|
||||
github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo=
|
||||
@@ -158,6 +169,12 @@ github.com/mattn/go-isatty v0.0.7/go.mod h1:Iq45c/XA43vh69/j3iqttzPXn0bhXyGjM0Hd
|
||||
github.com/mattn/go-isatty v0.0.12/go.mod h1:cbi8OIDigv2wuxKPP5vlRcQ1OAZbq2CE4Kysco4FUpU=
|
||||
github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
|
||||
github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
|
||||
github.com/minio/crc64nvme v1.1.1 h1:8dwx/Pz49suywbO+auHCBpCtlW1OfpcLN7wYgVR6wAI=
|
||||
github.com/minio/crc64nvme v1.1.1/go.mod h1:eVfm2fAzLlxMdUGc0EEBGSMmPwmXD5XiNRpnu9J3bvg=
|
||||
github.com/minio/md5-simd v1.1.2 h1:Gdi1DZK69+ZVMoNHRXJyNcxrMA4dSxoYHZSQbirFg34=
|
||||
github.com/minio/md5-simd v1.1.2/go.mod h1:MzdKDxYpY2BT9XQFocsiZf/NKVtR7nkE4RoEpN+20RM=
|
||||
github.com/minio/minio-go/v7 v7.2.1 h1:PfBfwvKB/MmqyN8Vb1G9voWisaM9OrLv+WwOvMwS9Dw=
|
||||
github.com/minio/minio-go/v7 v7.2.1/go.mod h1:EU9hENAStx/xXduNdrGO5e4X5vk19NtgB+RIPjZO8o0=
|
||||
github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
|
||||
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg=
|
||||
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
|
||||
@@ -166,6 +183,8 @@ github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjY
|
||||
github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e/go.mod h1:zD1mROLANZcx1PVRCS0qkT7pwLkGfwJo4zjcN/Tysno=
|
||||
github.com/pelletier/go-toml/v2 v2.3.1 h1:MYEvvGnQjeNkRF1qUuGolNtNExTDwct51yp7olPtrEc=
|
||||
github.com/pelletier/go-toml/v2 v2.3.1/go.mod h1:2gIqNv+qfxSVS7cM2xJQKtLSTLUE9V8t9Stt+h56mCY=
|
||||
github.com/philhofer/fwd v1.2.0 h1:e6DnBTl7vGY+Gz322/ASL4Gyp1FspeMvx1RNDoToZuM=
|
||||
github.com/philhofer/fwd v1.2.0/go.mod h1:RqIHx9QI14HlwKwm98g9Re5prTQ6LdeRQn+gXJFxsJM=
|
||||
github.com/pkg/errors v0.8.1 h1:iURUrRGxPUNPdy5/HRSm+Yj6okJ6UtLINN0Q9M4+h3I=
|
||||
github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
|
||||
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
||||
@@ -178,6 +197,8 @@ github.com/rogpeppe/go-internal v1.3.0/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFR
|
||||
github.com/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0tI/otEQ=
|
||||
github.com/rogpeppe/go-internal v1.14.1/go.mod h1:MaRKkUm5W0goXpeCfT7UZI6fk/L7L7so1lCWt35ZSgc=
|
||||
github.com/rs/xid v1.2.1/go.mod h1:+uKXf+4Djp6Md1KODXJxgGQPKngRmWyn10oCKFzNHOQ=
|
||||
github.com/rs/xid v1.6.0 h1:fV591PaemRlL6JfRxGDEPl69wICngIQ3shQtzfy2gxU=
|
||||
github.com/rs/xid v1.6.0/go.mod h1:7XoLgs4eV+QndskICGsho+ADou8ySMSjJKDIan90Nz0=
|
||||
github.com/rs/zerolog v1.13.0/go.mod h1:YbFCdg8HfsridGWAh22vktObvhZbQsZXe4/zB0OKkWU=
|
||||
github.com/rs/zerolog v1.15.0/go.mod h1:xYTKnLHcpfU2225ny5qZjxnj9NvkumZYjJHlAThCjNc=
|
||||
github.com/satori/go.uuid v1.2.0/go.mod h1:dA0hQrYB0VpLJoorglMZABFdXlWrHn1NEOzdhQKdks0=
|
||||
@@ -212,11 +233,17 @@ github.com/swaggo/gin-swagger v1.6.1 h1:Ri06G4gc9N4t4k8hekMigJ9zKTFSlqj/9paAQCQs
|
||||
github.com/swaggo/gin-swagger v1.6.1/go.mod h1:LQ+hJStHakCWRiK/YNYtJOu4mR2FP+pxLnILT/qNiTw=
|
||||
github.com/swaggo/swag v1.16.6 h1:qBNcx53ZaX+M5dxVyTrgQ0PJ/ACK+NzhwcbieTt+9yI=
|
||||
github.com/swaggo/swag v1.16.6/go.mod h1:ngP2etMK5a0P3QBizic5MEwpRmluJZPHjXcMoj4Xesg=
|
||||
github.com/tinylib/msgp v1.6.1 h1:ESRv8eL3u+DNHUoSAAQRE50Hm162zqAnBoGv9PzScPY=
|
||||
github.com/tinylib/msgp v1.6.1/go.mod h1:RSp0LW9oSxFut3KzESt5Voq4GVWyS+PSulT77roAqEA=
|
||||
github.com/twitchyliquid64/golang-asm v0.15.1 h1:SU5vSMR7hnwNxj24w34ZyCi/FmDZTkS4MhqMhdFk5YI=
|
||||
github.com/twitchyliquid64/golang-asm v0.15.1/go.mod h1:a1lVb/DtPvCB8fslRZhAngC2+aY1QWCk3Cedj/Gdt08=
|
||||
github.com/ugorji/go/codec v1.3.1 h1:waO7eEiFDwidsBN6agj1vJQ4AG7lh2yqXyOXqhgQuyY=
|
||||
github.com/ugorji/go/codec v1.3.1/go.mod h1:pRBVtBSKl77K30Bv8R2P+cLSGaTtex6fsA2Wjqmfxj4=
|
||||
github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY=
|
||||
github.com/zeebo/assert v1.3.0 h1:g7C04CbJuIDKNPFHmsk4hwZDO5O+kntRxzaUoNXj+IQ=
|
||||
github.com/zeebo/assert v1.3.0/go.mod h1:Pq9JiuJQpG8JLJdtkwrJESF0Foym2/D9XMU5ciN/wJ0=
|
||||
github.com/zeebo/xxh3 v1.1.0 h1:s7DLGDK45Dyfg7++yxI0khrfwq9661w9EN78eP/UZVs=
|
||||
github.com/zeebo/xxh3 v1.1.0/go.mod h1:IisAie1LELR4xhVinxWS5+zf1lA4p0MW4T+w+W07F5s=
|
||||
github.com/zenazn/goji v0.9.0/go.mod h1:7S9M489iMyHBNxwZnk9/EHS098H4/F6TATF2mIxtB1Q=
|
||||
go.mongodb.org/mongo-driver/v2 v2.5.0 h1:yXUhImUjjAInNcpTcAlPHiT7bIXhshCTL3jVBkF3xaE=
|
||||
go.mongodb.org/mongo-driver/v2 v2.5.0/go.mod h1:yOI9kBsufol30iFsl1slpdq1I0eHPzybRWdyYUs8K/0=
|
||||
@@ -233,6 +260,8 @@ go.uber.org/tools v0.0.0-20190618225709-2cfd321de3ee/go.mod h1:vJERXedbb3MVM5f9E
|
||||
go.uber.org/zap v1.9.1/go.mod h1:vwi/ZaCAaUcBkycHslxD9B2zi4UTXhF60s6SWpuDF0Q=
|
||||
go.uber.org/zap v1.10.0/go.mod h1:vwi/ZaCAaUcBkycHslxD9B2zi4UTXhF60s6SWpuDF0Q=
|
||||
go.uber.org/zap v1.13.0/go.mod h1:zwrFLgMcdUuIBviXEYEH1YKNaOBnKXsx2IPda5bBwHM=
|
||||
go.yaml.in/yaml/v3 v3.0.4 h1:tfq32ie2Jv2UxXFdLJdh3jXuOzWiL1fo0bu/FbuKpbc=
|
||||
go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg=
|
||||
golang.org/x/arch v0.23.0 h1:lKF64A2jF6Zd8L0knGltUnegD62JMFBiCPBmQpToHhg=
|
||||
golang.org/x/arch v0.23.0/go.mod h1:dNHoOeKiyja7GTvF9NJS1l3Z2yntpQNzgrjh1cU103A=
|
||||
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
|
||||
@@ -325,6 +354,8 @@ gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntN
|
||||
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=
|
||||
gopkg.in/errgo.v2 v2.1.0/go.mod h1:hNsd1EY+bozCKY1Ytp96fpM3vjJbqLJn88ws8XvfDNI=
|
||||
gopkg.in/inconshreveable/log15.v2 v2.0.0-20180818164646-67afb5ed74ec/go.mod h1:aPpfJ7XW+gOuirDoZ8gHhLh3kZ1B08FtV2bbmy7Jv3s=
|
||||
gopkg.in/ini.v1 v1.67.2 h1:JtOSMb9OuaCZKr7h5D/h6iii14sK0hLbplTc6frx4Ss=
|
||||
gopkg.in/ini.v1 v1.67.2/go.mod h1:x/cyOwCgZqOkJoDIJ3c1KNHMo10+nLGAhh+kn3Zizss=
|
||||
gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
|
||||
gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY=
|
||||
gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ=
|
||||
|
||||
Vendored
BIN
Binary file not shown.
@@ -1,25 +0,0 @@
|
||||
package auth
|
||||
|
||||
import "time"
|
||||
|
||||
type LoginDTO struct {
|
||||
Email string `json:"email" binding:"required"`
|
||||
Password string `json:"password" binding:"required"`
|
||||
}
|
||||
|
||||
type RefreshTokenDTO struct {
|
||||
RefreshToken string `json:"refreshToken" binding:"required"`
|
||||
}
|
||||
|
||||
type UserProfileDTO struct {
|
||||
Id int `json:"id"`
|
||||
FullName string `json:"fullName"`
|
||||
PhoneNumber string `json:"phoneNumber"`
|
||||
Avatar string `json:"avatar"`
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
}
|
||||
|
||||
type UserCredentials struct {
|
||||
Id int
|
||||
Password string
|
||||
}
|
||||
@@ -0,0 +1,189 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"online-back/internal/cards/cardorder"
|
||||
"online-back/pkg/client/postgresql"
|
||||
"online-back/pkg/logging"
|
||||
"online-back/pkg/repository/genericrepo"
|
||||
)
|
||||
|
||||
type repository struct {
|
||||
client postgresql.Client
|
||||
generic *genericrepo.Repository[cardorder.CardOrderDTO]
|
||||
logger *logging.Logger
|
||||
}
|
||||
|
||||
func NewRepository(client postgresql.Client, logger *logging.Logger) cardorder.Repository {
|
||||
return &repository{
|
||||
client: client,
|
||||
generic: genericrepo.New(client, "card_orders", cardOrderColumnsSQL, scanCardOrder),
|
||||
logger: logger,
|
||||
}
|
||||
}
|
||||
|
||||
// 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",
|
||||
"passport_serie", "passport_id", "passport_given_at", "passport_given_by", "born_place",
|
||||
"job_location", "passport_address", "real_address", "phone", "phone_additional",
|
||||
"status", "passport_one", "passport_two", "passport_three", "passport_four", "notes", "user_id", "paid",
|
||||
}
|
||||
|
||||
var cardOrderColumns = append(append([]string{"id"}, cardOrderWritableColumns...), "created_at", "updated_at")
|
||||
|
||||
var cardOrderColumnsSQL = strings.Join(cardOrderColumns, ", ")
|
||||
|
||||
var cardOrderWritableColumnsSQL = strings.Join(cardOrderWritableColumns, ", ")
|
||||
|
||||
func resolveStatus(status *string) *string {
|
||||
if status == nil || strings.TrimSpace(*status) == "" {
|
||||
pending := "pending"
|
||||
return &pending
|
||||
}
|
||||
return status
|
||||
}
|
||||
|
||||
func resolvePaid(paid *bool) bool {
|
||||
if paid == nil {
|
||||
return false
|
||||
}
|
||||
return *paid
|
||||
}
|
||||
|
||||
func 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.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),
|
||||
}
|
||||
}
|
||||
|
||||
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.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,
|
||||
}
|
||||
}
|
||||
|
||||
func (r *repository) List(ctx context.Context, filter cardorder.ListFilter) (cardorder.ListCardOrderDTO, error) {
|
||||
whereClause, args := buildListQuery(filter)
|
||||
|
||||
items, count, err := r.generic.List(ctx, whereClause, args, filter.Page, filter.Limit, "id")
|
||||
if err != nil {
|
||||
return cardorder.ListCardOrderDTO{}, err
|
||||
}
|
||||
|
||||
return cardorder.ListCardOrderDTO{Count: count, CardOrders: items}, nil
|
||||
}
|
||||
|
||||
func buildListQuery(filter cardorder.ListFilter) (whereClause string, args []interface{}) {
|
||||
var conditions []string
|
||||
|
||||
if filter.Status != nil {
|
||||
args = append(args, *filter.Status)
|
||||
conditions = append(conditions, fmt.Sprintf("status = $%d", len(args)))
|
||||
}
|
||||
|
||||
if filter.BranchId != nil {
|
||||
args = append(args, *filter.BranchId)
|
||||
conditions = append(conditions, fmt.Sprintf("branch_id = $%d", len(args)))
|
||||
}
|
||||
|
||||
if filter.UserId != nil {
|
||||
args = append(args, *filter.UserId)
|
||||
conditions = append(conditions, fmt.Sprintf("user_id = $%d", len(args)))
|
||||
}
|
||||
|
||||
if filter.CardStateId != nil {
|
||||
args = append(args, *filter.CardStateId)
|
||||
conditions = append(conditions, fmt.Sprintf("card_state_id = $%d", len(args)))
|
||||
}
|
||||
|
||||
if filter.CardTypeId != nil {
|
||||
args = append(args, *filter.CardTypeId)
|
||||
conditions = append(conditions, fmt.Sprintf("card_type_id = $%d", len(args)))
|
||||
}
|
||||
|
||||
if filter.Region != "" {
|
||||
args = append(args, filter.Region)
|
||||
conditions = append(conditions, fmt.Sprintf("region = $%d", len(args)))
|
||||
}
|
||||
|
||||
if len(conditions) == 0 {
|
||||
return "", args
|
||||
}
|
||||
|
||||
return " WHERE " + strings.Join(conditions, " AND "), args
|
||||
}
|
||||
|
||||
func (r *repository) GetByID(ctx context.Context, id int64) (cardorder.CardOrderDTO, error) {
|
||||
return r.generic.GetByID(ctx, id)
|
||||
}
|
||||
|
||||
func (r *repository) Create(ctx context.Context, dto cardorder.CreateCardOrderDTO) (cardorder.CardOrderDTO, error) {
|
||||
args := createArgs(dto)
|
||||
|
||||
placeholders := make([]string, len(args))
|
||||
for i := range args {
|
||||
placeholders[i] = fmt.Sprintf("$%d", i+1)
|
||||
}
|
||||
|
||||
query := fmt.Sprintf(
|
||||
`INSERT INTO card_orders (%s) VALUES (%s) RETURNING %s`,
|
||||
cardOrderWritableColumnsSQL, strings.Join(placeholders, ", "), cardOrderColumnsSQL,
|
||||
)
|
||||
|
||||
return scanCardOrder(r.client.QueryRow(ctx, query, args...))
|
||||
}
|
||||
|
||||
func (r *repository) Update(ctx context.Context, id int64, dto cardorder.UpdateCardOrderDTO) (cardorder.CardOrderDTO, error) {
|
||||
args := updateArgs(dto)
|
||||
|
||||
assignments := make([]string, len(cardOrderWritableColumns))
|
||||
for i, column := range cardOrderWritableColumns {
|
||||
assignments[i] = fmt.Sprintf("%s = $%d", column, i+1)
|
||||
}
|
||||
args = append(args, id)
|
||||
|
||||
query := fmt.Sprintf(
|
||||
`UPDATE card_orders SET %s, updated_at = (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') WHERE id = $%d RETURNING %s`,
|
||||
strings.Join(assignments, ", "), len(args), cardOrderColumnsSQL,
|
||||
)
|
||||
|
||||
item, err := scanCardOrder(r.client.QueryRow(ctx, query, args...))
|
||||
if err != nil {
|
||||
return cardorder.CardOrderDTO{}, err
|
||||
}
|
||||
return item, nil
|
||||
}
|
||||
|
||||
func (r *repository) Delete(ctx context.Context, id int64) error {
|
||||
return r.generic.Delete(ctx, id)
|
||||
}
|
||||
|
||||
func scanCardOrder(row genericrepo.Scanner) (cardorder.CardOrderDTO, error) {
|
||||
var item cardorder.CardOrderDTO
|
||||
err := row.Scan(
|
||||
&item.Id, &item.UniqueId, &item.CardStateId, &item.CardTypeId, &item.Region, &item.BranchId,
|
||||
&item.CustomerName, &item.CustomerSurname, &item.CustomerPatronicName, &item.BornAt, &item.OldSurname, &item.Citizenship,
|
||||
&item.PassportSerie, &item.PassportId, &item.PassportGivenAt, &item.PassportGivenBy, &item.BornPlace,
|
||||
&item.JobLocation, &item.PassportAddress, &item.RealAddress, &item.Phone, &item.PhoneAdditional,
|
||||
&item.Status, &item.PassportOne, &item.PassportTwo, &item.PassportThree, &item.PassportFour, &item.Notes, &item.UserId, &item.Paid,
|
||||
&item.CreatedAt, &item.UpdatedAt,
|
||||
)
|
||||
if err != nil {
|
||||
return cardorder.CardOrderDTO{}, err
|
||||
}
|
||||
return item, nil
|
||||
}
|
||||
@@ -0,0 +1,118 @@
|
||||
package cardorder
|
||||
|
||||
import "time"
|
||||
|
||||
type CardOrderDTO struct {
|
||||
Id int64 `json:"id"`
|
||||
UniqueId *string `json:"uniqueId"`
|
||||
CardStateId int64 `json:"cardStateId"`
|
||||
CardTypeId int64 `json:"cardTypeId"`
|
||||
Region string `json:"region"`
|
||||
BranchId int64 `json:"branchId"`
|
||||
CustomerName string `json:"customerName"`
|
||||
CustomerSurname string `json:"customerSurname"`
|
||||
CustomerPatronicName *string `json:"customerPatronicName"`
|
||||
BornAt *time.Time `json:"bornAt"`
|
||||
OldSurname *string `json:"oldSurname"`
|
||||
Citizenship string `json:"citizenship"`
|
||||
PassportSerie string `json:"passportSerie"`
|
||||
PassportId string `json:"passportId"`
|
||||
PassportGivenAt time.Time `json:"passportGivenAt"`
|
||||
PassportGivenBy string `json:"passportGivenBy"`
|
||||
BornPlace string `json:"bornPlace"`
|
||||
JobLocation *string `json:"jobLocation"`
|
||||
PassportAddress *string `json:"passportAddress"`
|
||||
RealAddress *string `json:"realAddress"`
|
||||
Phone *string `json:"phone"`
|
||||
PhoneAdditional *string `json:"phoneAdditional"`
|
||||
Status *string `json:"status"`
|
||||
PassportOne string `json:"passportOne"`
|
||||
PassportTwo string `json:"passportTwo"`
|
||||
PassportThree string `json:"passportThree"`
|
||||
PassportFour string `json:"passportFour"`
|
||||
Notes *string `json:"notes"`
|
||||
UserId *int64 `json:"userId"`
|
||||
Paid bool `json:"paid"`
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
UpdatedAt time.Time `json:"updatedAt"`
|
||||
}
|
||||
|
||||
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"`
|
||||
}
|
||||
|
||||
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"`
|
||||
}
|
||||
|
||||
type ListFilter struct {
|
||||
Status *string
|
||||
BranchId *int64
|
||||
UserId *int64
|
||||
CardStateId *int64
|
||||
CardTypeId *int64
|
||||
Region string
|
||||
Page int
|
||||
Limit int
|
||||
}
|
||||
|
||||
type ListCardOrderDTO struct {
|
||||
Count int64 `json:"count"`
|
||||
CardOrders []CardOrderDTO `json:"cardOrders"`
|
||||
}
|
||||
@@ -0,0 +1,283 @@
|
||||
package cardorder
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"online-back/internal/appresult"
|
||||
"online-back/internal/handlers"
|
||||
"online-back/pkg/logging"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/jackc/pgx/v4"
|
||||
)
|
||||
|
||||
const baseURL = "/card-orders"
|
||||
|
||||
type handler struct {
|
||||
logger *logging.Logger
|
||||
repository Repository
|
||||
}
|
||||
|
||||
func NewHandler(logger *logging.Logger, repository Repository) handlers.Handler {
|
||||
return &handler{logger: logger, repository: repository}
|
||||
}
|
||||
|
||||
func (h *handler) Register(router *gin.RouterGroup) {
|
||||
group := router.Group(baseURL, appresult.JwtTokenCheck())
|
||||
group.GET("", h.list)
|
||||
group.GET("/:id", h.getByID)
|
||||
group.POST("", h.create)
|
||||
group.PUT("/:id", h.update)
|
||||
group.DELETE("/:id", h.delete)
|
||||
}
|
||||
|
||||
// list godoc
|
||||
// @Summary List card orders
|
||||
// @Description Returns paginated card orders with optional filters
|
||||
// @Tags card-orders
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param status query string false "Filter by status"
|
||||
// @Param branch_id query int false "Filter by branch ID"
|
||||
// @Param user_id query int false "Filter by user ID"
|
||||
// @Param card_state_id query int false "Filter by card state ID"
|
||||
// @Param card_type_id query int false "Filter by card type ID"
|
||||
// @Param region query string false "Filter by region"
|
||||
// @Param page query int false "Page number" default(1)
|
||||
// @Param limit query int false "Items per page" default(10)
|
||||
// @Success 200 {object} appresult.AppSuccess
|
||||
// @Failure 400 {object} appresult.AppError
|
||||
// @Failure 500 {object} appresult.AppError
|
||||
// @Router /card-orders [get]
|
||||
func (h *handler) list(c *gin.Context) {
|
||||
filter, ok := parseListFilter(c)
|
||||
if !ok {
|
||||
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
|
||||
return
|
||||
}
|
||||
|
||||
result, err := h.repository.List(c.Request.Context(), filter)
|
||||
if err != nil {
|
||||
h.logger.Errorf("list card orders failed: %v", err)
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, appresult.SuccessWithData(result))
|
||||
}
|
||||
|
||||
// getByID godoc
|
||||
// @Summary Get card order by ID
|
||||
// @Description Returns a single card order
|
||||
// @Tags card-orders
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param id path int true "Card order ID"
|
||||
// @Success 200 {object} appresult.AppSuccess
|
||||
// @Failure 400 {object} appresult.AppError
|
||||
// @Failure 404 {object} appresult.AppError
|
||||
// @Failure 500 {object} appresult.AppError
|
||||
// @Router /card-orders/{id} [get]
|
||||
func (h *handler) getByID(c *gin.Context) {
|
||||
id, ok := parseID(c.Param("id"))
|
||||
if !ok {
|
||||
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
|
||||
return
|
||||
}
|
||||
|
||||
item, err := h.repository.GetByID(c.Request.Context(), id)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
c.JSON(http.StatusNotFound, appresult.ErrNotFound)
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
h.logger.Errorf("get card order failed: %v", err)
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, appresult.SuccessWithData(item))
|
||||
}
|
||||
|
||||
// create godoc
|
||||
// @Summary Create card order
|
||||
// @Description Creates a new card order
|
||||
// @Tags card-orders
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param body body CreateCardOrderDTO true "Card order payload"
|
||||
// @Success 201 {object} appresult.AppSuccess
|
||||
// @Failure 400 {object} appresult.AppError
|
||||
// @Failure 500 {object} appresult.AppError
|
||||
// @Router /card-orders [post]
|
||||
func (h *handler) create(c *gin.Context) {
|
||||
var dto CreateCardOrderDTO
|
||||
if err := c.ShouldBindJSON(&dto); err != nil {
|
||||
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
|
||||
return
|
||||
}
|
||||
|
||||
item, err := h.repository.Create(c.Request.Context(), dto)
|
||||
if err != nil {
|
||||
h.logger.Errorf("create card order failed: %v", err)
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusCreated, appresult.SuccessWithData(item))
|
||||
}
|
||||
|
||||
// update godoc
|
||||
// @Summary Update card order
|
||||
// @Description Updates an existing card order
|
||||
// @Tags card-orders
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param id path int true "Card order ID"
|
||||
// @Param body body UpdateCardOrderDTO true "Card order payload"
|
||||
// @Success 200 {object} appresult.AppSuccess
|
||||
// @Failure 400 {object} appresult.AppError
|
||||
// @Failure 404 {object} appresult.AppError
|
||||
// @Failure 500 {object} appresult.AppError
|
||||
// @Router /card-orders/{id} [put]
|
||||
func (h *handler) update(c *gin.Context) {
|
||||
id, ok := parseID(c.Param("id"))
|
||||
if !ok {
|
||||
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
|
||||
return
|
||||
}
|
||||
|
||||
var dto UpdateCardOrderDTO
|
||||
if err := c.ShouldBindJSON(&dto); err != nil {
|
||||
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
|
||||
return
|
||||
}
|
||||
|
||||
item, err := h.repository.Update(c.Request.Context(), id, dto)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
c.JSON(http.StatusNotFound, appresult.ErrNotFound)
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
h.logger.Errorf("update card order failed: %v", err)
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, appresult.SuccessWithData(item))
|
||||
}
|
||||
|
||||
// delete godoc
|
||||
// @Summary Delete card order
|
||||
// @Description Deletes a card order
|
||||
// @Tags card-orders
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param id path int true "Card order ID"
|
||||
// @Success 200 {object} appresult.AppSuccess
|
||||
// @Failure 400 {object} appresult.AppError
|
||||
// @Failure 404 {object} appresult.AppError
|
||||
// @Failure 500 {object} appresult.AppError
|
||||
// @Router /card-orders/{id} [delete]
|
||||
func (h *handler) delete(c *gin.Context) {
|
||||
id, ok := parseID(c.Param("id"))
|
||||
if !ok {
|
||||
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
|
||||
return
|
||||
}
|
||||
|
||||
if err := h.repository.Delete(c.Request.Context(), id); errors.Is(err, pgx.ErrNoRows) {
|
||||
c.JSON(http.StatusNotFound, appresult.ErrNotFound)
|
||||
return
|
||||
} else if err != nil {
|
||||
h.logger.Errorf("delete card order failed: %v", err)
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, appresult.SuccessWithData("card order removed"))
|
||||
}
|
||||
|
||||
func parseID(raw string) (int64, bool) {
|
||||
id, err := strconv.ParseInt(raw, 10, 64)
|
||||
if err != nil || id <= 0 {
|
||||
return 0, false
|
||||
}
|
||||
return id, true
|
||||
}
|
||||
|
||||
const (
|
||||
defaultPage = 1
|
||||
defaultLimit = 10
|
||||
maxLimit = 100
|
||||
)
|
||||
|
||||
func parseListFilter(c *gin.Context) (ListFilter, bool) {
|
||||
filter := ListFilter{
|
||||
Page: defaultPage,
|
||||
Limit: defaultLimit,
|
||||
}
|
||||
|
||||
if raw := c.Query("branch_id"); raw != "" {
|
||||
id, ok := parseID(raw)
|
||||
if !ok {
|
||||
return ListFilter{}, false
|
||||
}
|
||||
filter.BranchId = &id
|
||||
}
|
||||
|
||||
if raw := c.Query("user_id"); raw != "" {
|
||||
id, ok := parseID(raw)
|
||||
if !ok {
|
||||
return ListFilter{}, false
|
||||
}
|
||||
filter.UserId = &id
|
||||
}
|
||||
|
||||
if raw := c.Query("card_state_id"); raw != "" {
|
||||
id, ok := parseID(raw)
|
||||
if !ok {
|
||||
return ListFilter{}, false
|
||||
}
|
||||
filter.CardStateId = &id
|
||||
}
|
||||
|
||||
if raw := c.Query("card_type_id"); raw != "" {
|
||||
id, ok := parseID(raw)
|
||||
if !ok {
|
||||
return ListFilter{}, false
|
||||
}
|
||||
filter.CardTypeId = &id
|
||||
}
|
||||
|
||||
if raw := c.Query("page"); raw != "" {
|
||||
page, err := strconv.Atoi(raw)
|
||||
if err != nil || page < 1 {
|
||||
return ListFilter{}, false
|
||||
}
|
||||
filter.Page = page
|
||||
}
|
||||
|
||||
if raw := c.Query("limit"); raw != "" {
|
||||
limit, err := strconv.Atoi(raw)
|
||||
if err != nil || limit < 1 || limit > maxLimit {
|
||||
return ListFilter{}, false
|
||||
}
|
||||
filter.Limit = limit
|
||||
}
|
||||
|
||||
if raw := strings.TrimSpace(c.Query("status")); raw != "" {
|
||||
filter.Status = &raw
|
||||
}
|
||||
|
||||
if raw := strings.TrimSpace(c.Query("region")); raw != "" {
|
||||
filter.Region = raw
|
||||
}
|
||||
|
||||
return filter, true
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
package cardorder
|
||||
|
||||
import "context"
|
||||
|
||||
type Repository interface {
|
||||
List(ctx context.Context, filter ListFilter) (ListCardOrderDTO, error)
|
||||
GetByID(ctx context.Context, id int64) (CardOrderDTO, error)
|
||||
Create(ctx context.Context, dto CreateCardOrderDTO) (CardOrderDTO, error)
|
||||
Update(ctx context.Context, id int64, dto UpdateCardOrderDTO) (CardOrderDTO, error)
|
||||
Delete(ctx context.Context, id int64) error
|
||||
}
|
||||
@@ -0,0 +1,165 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"online-back/internal/cards/cardpinorders"
|
||||
"online-back/pkg/client/postgresql"
|
||||
"online-back/pkg/logging"
|
||||
"online-back/pkg/repository/genericrepo"
|
||||
)
|
||||
|
||||
type repository struct {
|
||||
client postgresql.Client
|
||||
generic *genericrepo.Repository[cardpinorders.CardPinOrderDTO]
|
||||
logger *logging.Logger
|
||||
}
|
||||
|
||||
func NewRepository(client postgresql.Client, logger *logging.Logger) cardpinorders.Repository {
|
||||
return &repository{
|
||||
client: client,
|
||||
generic: genericrepo.New(client, "card_pin_orders", cardPinOrderColumnsSQL, scanCardPinOrder),
|
||||
logger: logger,
|
||||
}
|
||||
}
|
||||
|
||||
// cardPinOrderWritableColumns lists every card_pin_orders column except id, created_at and
|
||||
// updated_at, in the exact order CreateCardPinOrderDTO/UpdateCardPinOrderDTO fields are read.
|
||||
var cardPinOrderWritableColumns = []string{
|
||||
"unique_id", "user_id", "card_type_id", "card_number", "region", "branch_id",
|
||||
"customer_name", "customer_surname", "customer_patronic_name", "born_at", "phone",
|
||||
"passport_serie", "passport_id", "passport_one", "passport_two", "passport_three", "passport_four",
|
||||
"status", "notes",
|
||||
}
|
||||
|
||||
var cardPinOrderColumns = append(append([]string{"id"}, cardPinOrderWritableColumns...), "created_at", "updated_at")
|
||||
|
||||
var cardPinOrderColumnsSQL = strings.Join(cardPinOrderColumns, ", ")
|
||||
|
||||
var cardPinOrderWritableColumnsSQL = strings.Join(cardPinOrderWritableColumns, ", ")
|
||||
|
||||
func createArgs(dto cardpinorders.CreateCardPinOrderDTO) []interface{} {
|
||||
return []interface{}{
|
||||
dto.UniqueId, dto.UserId, dto.CardTypeId, dto.CardNumber, dto.Region, dto.BranchId,
|
||||
dto.CustomerName, dto.CustomerSurname, dto.CustomerPatronicName, dto.BornAt, dto.Phone,
|
||||
dto.PassportSerie, dto.PassportId, dto.PassportOne, dto.PassportTwo, dto.PassportThree, dto.PassportFour,
|
||||
dto.Status, dto.Notes,
|
||||
}
|
||||
}
|
||||
|
||||
func updateArgs(dto cardpinorders.UpdateCardPinOrderDTO) []interface{} {
|
||||
return []interface{}{
|
||||
dto.UniqueId, dto.UserId, dto.CardTypeId, dto.CardNumber, dto.Region, dto.BranchId,
|
||||
dto.CustomerName, dto.CustomerSurname, dto.CustomerPatronicName, dto.BornAt, dto.Phone,
|
||||
dto.PassportSerie, dto.PassportId, dto.PassportOne, dto.PassportTwo, dto.PassportThree, dto.PassportFour,
|
||||
dto.Status, dto.Notes,
|
||||
}
|
||||
}
|
||||
|
||||
func (r *repository) List(ctx context.Context, filter cardpinorders.ListFilter) (cardpinorders.ListCardPinOrderDTO, error) {
|
||||
whereClause, args := buildListQuery(filter)
|
||||
|
||||
items, count, err := r.generic.List(ctx, whereClause, args, filter.Page, filter.Limit, "id")
|
||||
if err != nil {
|
||||
return cardpinorders.ListCardPinOrderDTO{}, err
|
||||
}
|
||||
|
||||
return cardpinorders.ListCardPinOrderDTO{Count: count, CardPinOrders: items}, nil
|
||||
}
|
||||
|
||||
func buildListQuery(filter cardpinorders.ListFilter) (whereClause string, args []interface{}) {
|
||||
var conditions []string
|
||||
|
||||
if filter.Status != nil {
|
||||
args = append(args, *filter.Status)
|
||||
conditions = append(conditions, fmt.Sprintf("status = $%d", len(args)))
|
||||
}
|
||||
|
||||
if filter.BranchId != nil {
|
||||
args = append(args, *filter.BranchId)
|
||||
conditions = append(conditions, fmt.Sprintf("branch_id = $%d", len(args)))
|
||||
}
|
||||
|
||||
if filter.UserId != nil {
|
||||
args = append(args, *filter.UserId)
|
||||
conditions = append(conditions, fmt.Sprintf("user_id = $%d", len(args)))
|
||||
}
|
||||
|
||||
if filter.CardTypeId != nil {
|
||||
args = append(args, *filter.CardTypeId)
|
||||
conditions = append(conditions, fmt.Sprintf("card_type_id = $%d", len(args)))
|
||||
}
|
||||
|
||||
if filter.Region != "" {
|
||||
args = append(args, filter.Region)
|
||||
conditions = append(conditions, fmt.Sprintf("region = $%d", len(args)))
|
||||
}
|
||||
|
||||
if len(conditions) == 0 {
|
||||
return "", args
|
||||
}
|
||||
|
||||
return " WHERE " + strings.Join(conditions, " AND "), args
|
||||
}
|
||||
|
||||
func (r *repository) GetByID(ctx context.Context, id int64) (cardpinorders.CardPinOrderDTO, error) {
|
||||
return r.generic.GetByID(ctx, id)
|
||||
}
|
||||
|
||||
func (r *repository) Create(ctx context.Context, dto cardpinorders.CreateCardPinOrderDTO) (cardpinorders.CardPinOrderDTO, error) {
|
||||
args := createArgs(dto)
|
||||
|
||||
placeholders := make([]string, len(args))
|
||||
for i := range args {
|
||||
placeholders[i] = fmt.Sprintf("$%d", i+1)
|
||||
}
|
||||
|
||||
query := fmt.Sprintf(
|
||||
`INSERT INTO card_pin_orders (%s) VALUES (%s) RETURNING %s`,
|
||||
cardPinOrderWritableColumnsSQL, strings.Join(placeholders, ", "), cardPinOrderColumnsSQL,
|
||||
)
|
||||
|
||||
return scanCardPinOrder(r.client.QueryRow(ctx, query, args...))
|
||||
}
|
||||
|
||||
func (r *repository) Update(ctx context.Context, id int64, dto cardpinorders.UpdateCardPinOrderDTO) (cardpinorders.CardPinOrderDTO, error) {
|
||||
args := updateArgs(dto)
|
||||
|
||||
assignments := make([]string, len(cardPinOrderWritableColumns))
|
||||
for i, column := range cardPinOrderWritableColumns {
|
||||
assignments[i] = fmt.Sprintf("%s = $%d", column, i+1)
|
||||
}
|
||||
args = append(args, id)
|
||||
|
||||
query := fmt.Sprintf(
|
||||
`UPDATE card_pin_orders SET %s, updated_at = (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') WHERE id = $%d RETURNING %s`,
|
||||
strings.Join(assignments, ", "), len(args), cardPinOrderColumnsSQL,
|
||||
)
|
||||
|
||||
item, err := scanCardPinOrder(r.client.QueryRow(ctx, query, args...))
|
||||
if err != nil {
|
||||
return cardpinorders.CardPinOrderDTO{}, err
|
||||
}
|
||||
return item, nil
|
||||
}
|
||||
|
||||
func (r *repository) Delete(ctx context.Context, id int64) error {
|
||||
return r.generic.Delete(ctx, id)
|
||||
}
|
||||
|
||||
func scanCardPinOrder(row genericrepo.Scanner) (cardpinorders.CardPinOrderDTO, error) {
|
||||
var item cardpinorders.CardPinOrderDTO
|
||||
err := row.Scan(
|
||||
&item.Id, &item.UniqueId, &item.UserId, &item.CardTypeId, &item.CardNumber, &item.Region, &item.BranchId,
|
||||
&item.CustomerName, &item.CustomerSurname, &item.CustomerPatronicName, &item.BornAt, &item.Phone,
|
||||
&item.PassportSerie, &item.PassportId, &item.PassportOne, &item.PassportTwo, &item.PassportThree, &item.PassportFour,
|
||||
&item.Status, &item.Notes,
|
||||
&item.CreatedAt, &item.UpdatedAt,
|
||||
)
|
||||
if err != nil {
|
||||
return cardpinorders.CardPinOrderDTO{}, err
|
||||
}
|
||||
return item, nil
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
package cardpinorders
|
||||
|
||||
import "time"
|
||||
|
||||
type CardPinOrderDTO struct {
|
||||
Id int64 `json:"id"`
|
||||
UniqueId *string `json:"uniqueId"`
|
||||
UserId *int64 `json:"userId"`
|
||||
CardTypeId int64 `json:"cardTypeId"`
|
||||
CardNumber *string `json:"cardNumber"`
|
||||
Region string `json:"region"`
|
||||
BranchId int64 `json:"branchId"`
|
||||
CustomerName string `json:"customerName"`
|
||||
CustomerSurname string `json:"customerSurname"`
|
||||
CustomerPatronicName *string `json:"customerPatronicName"`
|
||||
BornAt *time.Time `json:"bornAt"`
|
||||
Phone *string `json:"phone"`
|
||||
PassportSerie string `json:"passportSerie"`
|
||||
PassportId string `json:"passportId"`
|
||||
PassportOne string `json:"passportOne"`
|
||||
PassportTwo string `json:"passportTwo"`
|
||||
PassportThree string `json:"passportThree"`
|
||||
PassportFour string `json:"passportFour"`
|
||||
Status *string `json:"status"`
|
||||
Notes *string `json:"notes"`
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
UpdatedAt time.Time `json:"updatedAt"`
|
||||
}
|
||||
|
||||
type CreateCardPinOrderDTO struct {
|
||||
UniqueId *string `json:"uniqueId"`
|
||||
UserId *int64 `json:"userId"`
|
||||
CardTypeId int64 `json:"cardTypeId" binding:"required"`
|
||||
CardNumber *string `json:"cardNumber"`
|
||||
Region string `json:"region" binding:"required"`
|
||||
BranchId int64 `json:"branchId" binding:"required"`
|
||||
CustomerName string `json:"customerName" binding:"required"`
|
||||
CustomerSurname string `json:"customerSurname" binding:"required"`
|
||||
CustomerPatronicName *string `json:"customerPatronicName"`
|
||||
BornAt *time.Time `json:"bornAt"`
|
||||
Phone *string `json:"phone"`
|
||||
PassportSerie string `json:"passportSerie" binding:"required"`
|
||||
PassportId string `json:"passportId" binding:"required"`
|
||||
PassportOne string `json:"passportOne" binding:"required"`
|
||||
PassportTwo string `json:"passportTwo" binding:"required"`
|
||||
PassportThree string `json:"passportThree" binding:"required"`
|
||||
PassportFour string `json:"passportFour" binding:"required"`
|
||||
Status *string `json:"status"`
|
||||
Notes *string `json:"notes"`
|
||||
}
|
||||
|
||||
type UpdateCardPinOrderDTO struct {
|
||||
UniqueId *string `json:"uniqueId"`
|
||||
UserId *int64 `json:"userId"`
|
||||
CardTypeId int64 `json:"cardTypeId" binding:"required"`
|
||||
CardNumber *string `json:"cardNumber"`
|
||||
Region string `json:"region" binding:"required"`
|
||||
BranchId int64 `json:"branchId" binding:"required"`
|
||||
CustomerName string `json:"customerName" binding:"required"`
|
||||
CustomerSurname string `json:"customerSurname" binding:"required"`
|
||||
CustomerPatronicName *string `json:"customerPatronicName"`
|
||||
BornAt *time.Time `json:"bornAt"`
|
||||
Phone *string `json:"phone"`
|
||||
PassportSerie string `json:"passportSerie" binding:"required"`
|
||||
PassportId string `json:"passportId" binding:"required"`
|
||||
PassportOne string `json:"passportOne" binding:"required"`
|
||||
PassportTwo string `json:"passportTwo" binding:"required"`
|
||||
PassportThree string `json:"passportThree" binding:"required"`
|
||||
PassportFour string `json:"passportFour" binding:"required"`
|
||||
Status *string `json:"status"`
|
||||
Notes *string `json:"notes"`
|
||||
}
|
||||
|
||||
type ListFilter struct {
|
||||
Status *string
|
||||
BranchId *int64
|
||||
UserId *int64
|
||||
CardTypeId *int64
|
||||
Region string
|
||||
Page int
|
||||
Limit int
|
||||
}
|
||||
|
||||
type ListCardPinOrderDTO struct {
|
||||
Count int64 `json:"count"`
|
||||
CardPinOrders []CardPinOrderDTO `json:"cardPinOrders"`
|
||||
}
|
||||
@@ -0,0 +1,274 @@
|
||||
package cardpinorders
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"online-back/internal/appresult"
|
||||
"online-back/internal/handlers"
|
||||
"online-back/pkg/logging"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/jackc/pgx/v4"
|
||||
)
|
||||
|
||||
const baseURL = "/card-pin-orders"
|
||||
|
||||
type handler struct {
|
||||
logger *logging.Logger
|
||||
repository Repository
|
||||
}
|
||||
|
||||
func NewHandler(logger *logging.Logger, repository Repository) handlers.Handler {
|
||||
return &handler{logger: logger, repository: repository}
|
||||
}
|
||||
|
||||
func (h *handler) Register(router *gin.RouterGroup) {
|
||||
group := router.Group(baseURL, appresult.JwtTokenCheck())
|
||||
group.GET("", h.list)
|
||||
group.GET("/:id", h.getByID)
|
||||
group.POST("", h.create)
|
||||
group.PUT("/:id", h.update)
|
||||
group.DELETE("/:id", h.delete)
|
||||
}
|
||||
|
||||
// list godoc
|
||||
// @Summary List card pin orders
|
||||
// @Description Returns paginated card pin orders with optional filters
|
||||
// @Tags card-pin-orders
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param status query string false "Filter by status"
|
||||
// @Param branch_id query int false "Filter by branch ID"
|
||||
// @Param user_id query int false "Filter by user ID"
|
||||
// @Param card_type_id query int false "Filter by card type ID"
|
||||
// @Param region query string false "Filter by region"
|
||||
// @Param page query int false "Page number" default(1)
|
||||
// @Param limit query int false "Items per page" default(10)
|
||||
// @Success 200 {object} appresult.AppSuccess
|
||||
// @Failure 400 {object} appresult.AppError
|
||||
// @Failure 500 {object} appresult.AppError
|
||||
// @Router /card-pin-orders [get]
|
||||
func (h *handler) list(c *gin.Context) {
|
||||
filter, ok := parseListFilter(c)
|
||||
if !ok {
|
||||
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
|
||||
return
|
||||
}
|
||||
|
||||
result, err := h.repository.List(c.Request.Context(), filter)
|
||||
if err != nil {
|
||||
h.logger.Errorf("list card pin orders failed: %v", err)
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, appresult.SuccessWithData(result))
|
||||
}
|
||||
|
||||
// getByID godoc
|
||||
// @Summary Get card pin order by ID
|
||||
// @Description Returns a single card pin order
|
||||
// @Tags card-pin-orders
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param id path int true "Card pin order ID"
|
||||
// @Success 200 {object} appresult.AppSuccess
|
||||
// @Failure 400 {object} appresult.AppError
|
||||
// @Failure 404 {object} appresult.AppError
|
||||
// @Failure 500 {object} appresult.AppError
|
||||
// @Router /card-pin-orders/{id} [get]
|
||||
func (h *handler) getByID(c *gin.Context) {
|
||||
id, ok := parseID(c.Param("id"))
|
||||
if !ok {
|
||||
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
|
||||
return
|
||||
}
|
||||
|
||||
item, err := h.repository.GetByID(c.Request.Context(), id)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
c.JSON(http.StatusNotFound, appresult.ErrNotFound)
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
h.logger.Errorf("get card pin order failed: %v", err)
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, appresult.SuccessWithData(item))
|
||||
}
|
||||
|
||||
// create godoc
|
||||
// @Summary Create card pin order
|
||||
// @Description Creates a new card pin order
|
||||
// @Tags card-pin-orders
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param body body CreateCardPinOrderDTO true "Card pin order payload"
|
||||
// @Success 201 {object} appresult.AppSuccess
|
||||
// @Failure 400 {object} appresult.AppError
|
||||
// @Failure 500 {object} appresult.AppError
|
||||
// @Router /card-pin-orders [post]
|
||||
func (h *handler) create(c *gin.Context) {
|
||||
var dto CreateCardPinOrderDTO
|
||||
if err := c.ShouldBindJSON(&dto); err != nil {
|
||||
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
|
||||
return
|
||||
}
|
||||
|
||||
item, err := h.repository.Create(c.Request.Context(), dto)
|
||||
if err != nil {
|
||||
h.logger.Errorf("create card pin order failed: %v", err)
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusCreated, appresult.SuccessWithData(item))
|
||||
}
|
||||
|
||||
// update godoc
|
||||
// @Summary Update card pin order
|
||||
// @Description Updates an existing card pin order
|
||||
// @Tags card-pin-orders
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param id path int true "Card pin order ID"
|
||||
// @Param body body UpdateCardPinOrderDTO true "Card pin order payload"
|
||||
// @Success 200 {object} appresult.AppSuccess
|
||||
// @Failure 400 {object} appresult.AppError
|
||||
// @Failure 404 {object} appresult.AppError
|
||||
// @Failure 500 {object} appresult.AppError
|
||||
// @Router /card-pin-orders/{id} [put]
|
||||
func (h *handler) update(c *gin.Context) {
|
||||
id, ok := parseID(c.Param("id"))
|
||||
if !ok {
|
||||
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
|
||||
return
|
||||
}
|
||||
|
||||
var dto UpdateCardPinOrderDTO
|
||||
if err := c.ShouldBindJSON(&dto); err != nil {
|
||||
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
|
||||
return
|
||||
}
|
||||
|
||||
item, err := h.repository.Update(c.Request.Context(), id, dto)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
c.JSON(http.StatusNotFound, appresult.ErrNotFound)
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
h.logger.Errorf("update card pin order failed: %v", err)
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, appresult.SuccessWithData(item))
|
||||
}
|
||||
|
||||
// delete godoc
|
||||
// @Summary Delete card pin order
|
||||
// @Description Deletes a card pin order
|
||||
// @Tags card-pin-orders
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param id path int true "Card pin order ID"
|
||||
// @Success 200 {object} appresult.AppSuccess
|
||||
// @Failure 400 {object} appresult.AppError
|
||||
// @Failure 404 {object} appresult.AppError
|
||||
// @Failure 500 {object} appresult.AppError
|
||||
// @Router /card-pin-orders/{id} [delete]
|
||||
func (h *handler) delete(c *gin.Context) {
|
||||
id, ok := parseID(c.Param("id"))
|
||||
if !ok {
|
||||
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
|
||||
return
|
||||
}
|
||||
|
||||
if err := h.repository.Delete(c.Request.Context(), id); errors.Is(err, pgx.ErrNoRows) {
|
||||
c.JSON(http.StatusNotFound, appresult.ErrNotFound)
|
||||
return
|
||||
} else if err != nil {
|
||||
h.logger.Errorf("delete card pin order failed: %v", err)
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, appresult.SuccessWithData("card pin order removed"))
|
||||
}
|
||||
|
||||
func parseID(raw string) (int64, bool) {
|
||||
id, err := strconv.ParseInt(raw, 10, 64)
|
||||
if err != nil || id <= 0 {
|
||||
return 0, false
|
||||
}
|
||||
return id, true
|
||||
}
|
||||
|
||||
const (
|
||||
defaultPage = 1
|
||||
defaultLimit = 10
|
||||
maxLimit = 100
|
||||
)
|
||||
|
||||
func parseListFilter(c *gin.Context) (ListFilter, bool) {
|
||||
filter := ListFilter{
|
||||
Page: defaultPage,
|
||||
Limit: defaultLimit,
|
||||
}
|
||||
|
||||
if raw := c.Query("branch_id"); raw != "" {
|
||||
id, ok := parseID(raw)
|
||||
if !ok {
|
||||
return ListFilter{}, false
|
||||
}
|
||||
filter.BranchId = &id
|
||||
}
|
||||
|
||||
if raw := c.Query("user_id"); raw != "" {
|
||||
id, ok := parseID(raw)
|
||||
if !ok {
|
||||
return ListFilter{}, false
|
||||
}
|
||||
filter.UserId = &id
|
||||
}
|
||||
|
||||
if raw := c.Query("card_type_id"); raw != "" {
|
||||
id, ok := parseID(raw)
|
||||
if !ok {
|
||||
return ListFilter{}, false
|
||||
}
|
||||
filter.CardTypeId = &id
|
||||
}
|
||||
|
||||
if raw := c.Query("page"); raw != "" {
|
||||
page, err := strconv.Atoi(raw)
|
||||
if err != nil || page < 1 {
|
||||
return ListFilter{}, false
|
||||
}
|
||||
filter.Page = page
|
||||
}
|
||||
|
||||
if raw := c.Query("limit"); raw != "" {
|
||||
limit, err := strconv.Atoi(raw)
|
||||
if err != nil || limit < 1 || limit > maxLimit {
|
||||
return ListFilter{}, false
|
||||
}
|
||||
filter.Limit = limit
|
||||
}
|
||||
|
||||
if raw := strings.TrimSpace(c.Query("status")); raw != "" {
|
||||
filter.Status = &raw
|
||||
}
|
||||
|
||||
if raw := strings.TrimSpace(c.Query("region")); raw != "" {
|
||||
filter.Region = raw
|
||||
}
|
||||
|
||||
return filter, true
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
package cardpinorders
|
||||
|
||||
import "context"
|
||||
|
||||
type Repository interface {
|
||||
List(ctx context.Context, filter ListFilter) (ListCardPinOrderDTO, error)
|
||||
GetByID(ctx context.Context, id int64) (CardPinOrderDTO, error)
|
||||
Create(ctx context.Context, dto CreateCardPinOrderDTO) (CardPinOrderDTO, error)
|
||||
Update(ctx context.Context, id int64, dto UpdateCardPinOrderDTO) (CardPinOrderDTO, error)
|
||||
Delete(ctx context.Context, id int64) error
|
||||
}
|
||||
@@ -0,0 +1,138 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"online-back/internal/cards/cards"
|
||||
"online-back/pkg/client/postgresql"
|
||||
"online-back/pkg/logging"
|
||||
"online-back/pkg/repository/genericrepo"
|
||||
)
|
||||
|
||||
type repository struct {
|
||||
client postgresql.Client
|
||||
generic *genericrepo.Repository[cards.CardDTO]
|
||||
logger *logging.Logger
|
||||
}
|
||||
|
||||
func NewRepository(client postgresql.Client, logger *logging.Logger) cards.Repository {
|
||||
return &repository{
|
||||
client: client,
|
||||
generic: genericrepo.New(client, "cards", cardColumnsSQL, scanCard),
|
||||
logger: logger,
|
||||
}
|
||||
}
|
||||
|
||||
// cardWritableColumns lists every cards column except id, created_at and
|
||||
// updated_at, in the exact order CreateCardDTO/UpdateCardDTO fields are read.
|
||||
var cardWritableColumns = []string{
|
||||
"user_id", "number", "name", "month", "year", "type",
|
||||
}
|
||||
|
||||
var cardColumns = append(append([]string{"id"}, cardWritableColumns...), "created_at", "updated_at")
|
||||
|
||||
var cardColumnsSQL = strings.Join(cardColumns, ", ")
|
||||
|
||||
var cardWritableColumnsSQL = strings.Join(cardWritableColumns, ", ")
|
||||
|
||||
func createArgs(dto cards.CreateCardDTO) []interface{} {
|
||||
return []interface{}{
|
||||
dto.UserId, dto.Number, dto.Name, dto.Month, dto.Year, dto.Type,
|
||||
}
|
||||
}
|
||||
|
||||
func updateArgs(dto cards.UpdateCardDTO) []interface{} {
|
||||
return []interface{}{
|
||||
dto.UserId, dto.Number, dto.Name, dto.Month, dto.Year, dto.Type,
|
||||
}
|
||||
}
|
||||
|
||||
func (r *repository) List(ctx context.Context, filter cards.ListFilter) (cards.ListCardDTO, error) {
|
||||
whereClause, args := buildListQuery(filter)
|
||||
|
||||
items, count, err := r.generic.List(ctx, whereClause, args, filter.Page, filter.Limit, "id")
|
||||
if err != nil {
|
||||
return cards.ListCardDTO{}, err
|
||||
}
|
||||
|
||||
return cards.ListCardDTO{Count: count, Cards: items}, nil
|
||||
}
|
||||
|
||||
func buildListQuery(filter cards.ListFilter) (whereClause string, args []interface{}) {
|
||||
var conditions []string
|
||||
|
||||
if filter.UserId != nil {
|
||||
args = append(args, *filter.UserId)
|
||||
conditions = append(conditions, fmt.Sprintf("user_id = $%d", len(args)))
|
||||
}
|
||||
|
||||
if filter.Type != nil {
|
||||
args = append(args, *filter.Type)
|
||||
conditions = append(conditions, fmt.Sprintf("type = $%d", len(args)))
|
||||
}
|
||||
|
||||
if len(conditions) == 0 {
|
||||
return "", args
|
||||
}
|
||||
|
||||
return " WHERE " + strings.Join(conditions, " AND "), args
|
||||
}
|
||||
|
||||
func (r *repository) GetByID(ctx context.Context, id int64) (cards.CardDTO, error) {
|
||||
return r.generic.GetByID(ctx, id)
|
||||
}
|
||||
|
||||
func (r *repository) Create(ctx context.Context, dto cards.CreateCardDTO) (cards.CardDTO, error) {
|
||||
args := createArgs(dto)
|
||||
|
||||
placeholders := make([]string, len(args))
|
||||
for i := range args {
|
||||
placeholders[i] = fmt.Sprintf("$%d", i+1)
|
||||
}
|
||||
|
||||
query := fmt.Sprintf(
|
||||
`INSERT INTO cards (%s) VALUES (%s) RETURNING %s`,
|
||||
cardWritableColumnsSQL, strings.Join(placeholders, ", "), cardColumnsSQL,
|
||||
)
|
||||
|
||||
return scanCard(r.client.QueryRow(ctx, query, args...))
|
||||
}
|
||||
|
||||
func (r *repository) Update(ctx context.Context, id int64, dto cards.UpdateCardDTO) (cards.CardDTO, error) {
|
||||
args := updateArgs(dto)
|
||||
|
||||
assignments := make([]string, len(cardWritableColumns))
|
||||
for i, column := range cardWritableColumns {
|
||||
assignments[i] = fmt.Sprintf("%s = $%d", column, i+1)
|
||||
}
|
||||
args = append(args, id)
|
||||
|
||||
query := fmt.Sprintf(
|
||||
`UPDATE cards SET %s, updated_at = (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') WHERE id = $%d RETURNING %s`,
|
||||
strings.Join(assignments, ", "), len(args), cardColumnsSQL,
|
||||
)
|
||||
|
||||
item, err := scanCard(r.client.QueryRow(ctx, query, args...))
|
||||
if err != nil {
|
||||
return cards.CardDTO{}, err
|
||||
}
|
||||
return item, nil
|
||||
}
|
||||
|
||||
func (r *repository) Delete(ctx context.Context, id int64) error {
|
||||
return r.generic.Delete(ctx, id)
|
||||
}
|
||||
|
||||
func scanCard(row genericrepo.Scanner) (cards.CardDTO, error) {
|
||||
var item cards.CardDTO
|
||||
err := row.Scan(
|
||||
&item.Id, &item.UserId, &item.Number, &item.Name, &item.Month, &item.Year, &item.Type,
|
||||
&item.CreatedAt, &item.UpdatedAt,
|
||||
)
|
||||
if err != nil {
|
||||
return cards.CardDTO{}, err
|
||||
}
|
||||
return item, nil
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
package cards
|
||||
|
||||
import "time"
|
||||
|
||||
type CardDTO struct {
|
||||
Id int64 `json:"id"`
|
||||
UserId *int64 `json:"userId"`
|
||||
Number string `json:"number"`
|
||||
Name string `json:"name"`
|
||||
Month string `json:"month"`
|
||||
Year *string `json:"year"`
|
||||
Type *string `json:"type"`
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
UpdatedAt time.Time `json:"updatedAt"`
|
||||
}
|
||||
|
||||
type CreateCardDTO struct {
|
||||
UserId *int64 `json:"userId"`
|
||||
Number string `json:"number" binding:"required"`
|
||||
Name string `json:"name" binding:"required"`
|
||||
Month string `json:"month" binding:"required"`
|
||||
Year *string `json:"year"`
|
||||
Type *string `json:"type"`
|
||||
}
|
||||
|
||||
type UpdateCardDTO struct {
|
||||
UserId *int64 `json:"userId"`
|
||||
Number string `json:"number" binding:"required"`
|
||||
Name string `json:"name" binding:"required"`
|
||||
Month string `json:"month" binding:"required"`
|
||||
Year *string `json:"year"`
|
||||
Type *string `json:"type"`
|
||||
}
|
||||
|
||||
type ListFilter struct {
|
||||
UserId *int64
|
||||
Type *string
|
||||
Page int
|
||||
Limit int
|
||||
}
|
||||
|
||||
type ListCardDTO struct {
|
||||
Count int64 `json:"count"`
|
||||
Cards []CardDTO `json:"cards"`
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
package user
|
||||
package cards
|
||||
|
||||
import (
|
||||
"errors"
|
||||
@@ -14,7 +14,7 @@ import (
|
||||
"github.com/jackc/pgx/v4"
|
||||
)
|
||||
|
||||
const baseURL = "/users"
|
||||
const baseURL = "/cards"
|
||||
|
||||
type handler struct {
|
||||
logger *logging.Logger
|
||||
@@ -35,18 +35,19 @@ func (h *handler) Register(router *gin.RouterGroup) {
|
||||
}
|
||||
|
||||
// list godoc
|
||||
// @Summary List users
|
||||
// @Description Returns paginated users with optional filters
|
||||
// @Tags user
|
||||
// @Summary List cards
|
||||
// @Description Returns paginated cards with optional filters
|
||||
// @Tags cards
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param username query string false "Filter by username"
|
||||
// @Param user_id query int false "Filter by user ID"
|
||||
// @Param type query string false "Filter by card type"
|
||||
// @Param page query int false "Page number" default(1)
|
||||
// @Param limit query int false "Items per page" default(10)
|
||||
// @Success 200 {object} appresult.AppSuccess
|
||||
// @Failure 400 {object} appresult.AppError
|
||||
// @Failure 500 {object} appresult.AppError
|
||||
// @Router /users [get]
|
||||
// @Router /cards [get]
|
||||
func (h *handler) list(c *gin.Context) {
|
||||
filter, ok := parseListFilter(c)
|
||||
if !ok {
|
||||
@@ -56,7 +57,7 @@ func (h *handler) list(c *gin.Context) {
|
||||
|
||||
result, err := h.repository.List(c.Request.Context(), filter)
|
||||
if err != nil {
|
||||
h.logger.Errorf("list users failed: %v", err)
|
||||
h.logger.Errorf("list cards failed: %v", err)
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
@@ -65,17 +66,17 @@ func (h *handler) list(c *gin.Context) {
|
||||
}
|
||||
|
||||
// getByID godoc
|
||||
// @Summary Get user by ID
|
||||
// @Description Returns a single user
|
||||
// @Tags user
|
||||
// @Summary Get card by ID
|
||||
// @Description Returns a single card
|
||||
// @Tags cards
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param id path int true "User ID"
|
||||
// @Param id path int true "Card ID"
|
||||
// @Success 200 {object} appresult.AppSuccess
|
||||
// @Failure 400 {object} appresult.AppError
|
||||
// @Failure 404 {object} appresult.AppError
|
||||
// @Failure 500 {object} appresult.AppError
|
||||
// @Router /users/{id} [get]
|
||||
// @Router /cards/{id} [get]
|
||||
func (h *handler) getByID(c *gin.Context) {
|
||||
id, ok := parseID(c.Param("id"))
|
||||
if !ok {
|
||||
@@ -89,7 +90,7 @@ func (h *handler) getByID(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
h.logger.Errorf("get user failed: %v", err)
|
||||
h.logger.Errorf("get card failed: %v", err)
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
@@ -98,19 +99,19 @@ func (h *handler) getByID(c *gin.Context) {
|
||||
}
|
||||
|
||||
// create godoc
|
||||
// @Summary Create user
|
||||
// @Description Creates a new user
|
||||
// @Tags user
|
||||
// @Summary Create card
|
||||
// @Description Creates a new card
|
||||
// @Tags cards
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param body body CreateUserDTO true "User payload"
|
||||
// @Param body body CreateCardDTO true "Card payload"
|
||||
// @Success 201 {object} appresult.AppSuccess
|
||||
// @Failure 400 {object} appresult.AppError
|
||||
// @Failure 500 {object} appresult.AppError
|
||||
// @Router /users [post]
|
||||
// @Router /cards [post]
|
||||
func (h *handler) create(c *gin.Context) {
|
||||
var dto CreateUserDTO
|
||||
var dto CreateCardDTO
|
||||
if err := c.ShouldBindJSON(&dto); err != nil {
|
||||
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
|
||||
return
|
||||
@@ -118,7 +119,7 @@ func (h *handler) create(c *gin.Context) {
|
||||
|
||||
item, err := h.repository.Create(c.Request.Context(), dto)
|
||||
if err != nil {
|
||||
h.logger.Errorf("create user failed: %v", err)
|
||||
h.logger.Errorf("create card failed: %v", err)
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
@@ -127,19 +128,19 @@ func (h *handler) create(c *gin.Context) {
|
||||
}
|
||||
|
||||
// update godoc
|
||||
// @Summary Update user
|
||||
// @Description Updates an existing user
|
||||
// @Tags user
|
||||
// @Summary Update card
|
||||
// @Description Updates an existing card
|
||||
// @Tags cards
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param id path int true "User ID"
|
||||
// @Param body body UpdateUserDTO true "User payload"
|
||||
// @Param id path int true "Card ID"
|
||||
// @Param body body UpdateCardDTO true "Card payload"
|
||||
// @Success 200 {object} appresult.AppSuccess
|
||||
// @Failure 400 {object} appresult.AppError
|
||||
// @Failure 404 {object} appresult.AppError
|
||||
// @Failure 500 {object} appresult.AppError
|
||||
// @Router /users/{id} [put]
|
||||
// @Router /cards/{id} [put]
|
||||
func (h *handler) update(c *gin.Context) {
|
||||
id, ok := parseID(c.Param("id"))
|
||||
if !ok {
|
||||
@@ -147,7 +148,7 @@ func (h *handler) update(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
var dto UpdateUserDTO
|
||||
var dto UpdateCardDTO
|
||||
if err := c.ShouldBindJSON(&dto); err != nil {
|
||||
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
|
||||
return
|
||||
@@ -159,7 +160,7 @@ func (h *handler) update(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
h.logger.Errorf("update user failed: %v", err)
|
||||
h.logger.Errorf("update card failed: %v", err)
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
@@ -168,17 +169,17 @@ func (h *handler) update(c *gin.Context) {
|
||||
}
|
||||
|
||||
// delete godoc
|
||||
// @Summary Delete user
|
||||
// @Description Deletes a user
|
||||
// @Tags user
|
||||
// @Summary Delete card
|
||||
// @Description Deletes a card
|
||||
// @Tags cards
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param id path int true "User ID"
|
||||
// @Param id path int true "Card ID"
|
||||
// @Success 200 {object} appresult.AppSuccess
|
||||
// @Failure 400 {object} appresult.AppError
|
||||
// @Failure 404 {object} appresult.AppError
|
||||
// @Failure 500 {object} appresult.AppError
|
||||
// @Router /users/{id} [delete]
|
||||
// @Router /cards/{id} [delete]
|
||||
func (h *handler) delete(c *gin.Context) {
|
||||
id, ok := parseID(c.Param("id"))
|
||||
if !ok {
|
||||
@@ -190,12 +191,12 @@ func (h *handler) delete(c *gin.Context) {
|
||||
c.JSON(http.StatusNotFound, appresult.ErrNotFound)
|
||||
return
|
||||
} else if err != nil {
|
||||
h.logger.Errorf("delete user failed: %v", err)
|
||||
h.logger.Errorf("delete card failed: %v", err)
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, appresult.SuccessWithData("user removed"))
|
||||
c.JSON(http.StatusOK, appresult.SuccessWithData("card removed"))
|
||||
}
|
||||
|
||||
func parseID(raw string) (int64, bool) {
|
||||
@@ -218,6 +219,18 @@ 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 raw := strings.TrimSpace(c.Query("type")); raw != "" {
|
||||
filter.Type = &raw
|
||||
}
|
||||
|
||||
if raw := c.Query("page"); raw != "" {
|
||||
page, err := strconv.Atoi(raw)
|
||||
if err != nil || page < 1 {
|
||||
@@ -234,9 +247,5 @@ func parseListFilter(c *gin.Context) (ListFilter, bool) {
|
||||
filter.Limit = limit
|
||||
}
|
||||
|
||||
if raw := strings.TrimSpace(c.Query("username")); raw != "" {
|
||||
filter.Username = raw
|
||||
}
|
||||
|
||||
return filter, true
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
package cards
|
||||
|
||||
import "context"
|
||||
|
||||
type Repository interface {
|
||||
List(ctx context.Context, filter ListFilter) (ListCardDTO, error)
|
||||
GetByID(ctx context.Context, id int64) (CardDTO, error)
|
||||
Create(ctx context.Context, dto CreateCardDTO) (CardDTO, error)
|
||||
Update(ctx context.Context, id int64, dto UpdateCardDTO) (CardDTO, error)
|
||||
Delete(ctx context.Context, id int64) error
|
||||
}
|
||||
+18
-56
@@ -7,20 +7,26 @@ import (
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"online-back/internal/admin/paymentcard"
|
||||
"online-back/internal/cards/paymentcard"
|
||||
"online-back/pkg/client/postgresql"
|
||||
"online-back/pkg/logging"
|
||||
"online-back/pkg/repository/genericrepo"
|
||||
|
||||
"github.com/jackc/pgx/v4"
|
||||
)
|
||||
|
||||
type repository struct {
|
||||
client postgresql.Client
|
||||
logger *logging.Logger
|
||||
client postgresql.Client
|
||||
generic *genericrepo.Repository[paymentcard.PaymentCardDTO]
|
||||
logger *logging.Logger
|
||||
}
|
||||
|
||||
func NewRepository(client postgresql.Client, logger *logging.Logger) paymentcard.Repository {
|
||||
return &repository{client: client, logger: logger}
|
||||
return &repository{
|
||||
client: client,
|
||||
generic: genericrepo.New(client, "card_types c", cardColumns, scanPaymentCard),
|
||||
logger: logger,
|
||||
}
|
||||
}
|
||||
|
||||
const cardColumns = `c.id, c.price, c.name, c.notes, c.active`
|
||||
@@ -28,45 +34,17 @@ const cardColumns = `c.id, c.price, c.name, c.notes, c.active`
|
||||
const cardReturningColumns = `id, price, name, notes, active`
|
||||
|
||||
func (r *repository) List(ctx context.Context, filter paymentcard.ListFilter) (paymentcard.ListPaymentCardDTO, error) {
|
||||
fromClause, whereClause, args := buildListQuery(filter)
|
||||
whereClause, args := buildListQuery(filter)
|
||||
|
||||
var count int64
|
||||
if err := r.client.QueryRow(ctx, `SELECT COUNT(*) `+fromClause+whereClause, args...).Scan(&count); err != nil {
|
||||
return paymentcard.ListPaymentCardDTO{}, err
|
||||
}
|
||||
|
||||
offset := (filter.Page - 1) * filter.Limit
|
||||
limitPlaceholder := len(args) + 1
|
||||
offsetPlaceholder := len(args) + 2
|
||||
listQuery := fmt.Sprintf(
|
||||
`SELECT %s%s%s ORDER BY c.id LIMIT $%d OFFSET $%d`,
|
||||
cardColumns, fromClause, whereClause, limitPlaceholder, offsetPlaceholder,
|
||||
)
|
||||
|
||||
rows, err := r.client.Query(ctx, listQuery, append(args, filter.Limit, offset)...)
|
||||
items, count, err := r.generic.List(ctx, whereClause, args, filter.Page, filter.Limit, "id")
|
||||
if err != nil {
|
||||
return paymentcard.ListPaymentCardDTO{}, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var items []paymentcard.PaymentCardDTO
|
||||
for rows.Next() {
|
||||
item, err := scanPaymentCard(rows)
|
||||
if err != nil {
|
||||
return paymentcard.ListPaymentCardDTO{}, err
|
||||
}
|
||||
items = append(items, item)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return paymentcard.ListPaymentCardDTO{}, err
|
||||
}
|
||||
|
||||
return paymentcard.ListPaymentCardDTO{Count: count, PaymentCards: items}, nil
|
||||
}
|
||||
|
||||
func buildListQuery(filter paymentcard.ListFilter) (fromClause, whereClause string, args []interface{}) {
|
||||
fromClause = ` FROM card_types c`
|
||||
|
||||
func buildListQuery(filter paymentcard.ListFilter) (whereClause string, args []interface{}) {
|
||||
var conditions []string
|
||||
|
||||
if filter.CardName != "" {
|
||||
@@ -83,10 +61,10 @@ func buildListQuery(filter paymentcard.ListFilter) (fromClause, whereClause stri
|
||||
}
|
||||
|
||||
if len(conditions) == 0 {
|
||||
return fromClause, "", args
|
||||
return "", args
|
||||
}
|
||||
|
||||
return fromClause, " WHERE " + strings.Join(conditions, " AND "), args
|
||||
return " WHERE " + strings.Join(conditions, " AND "), args
|
||||
}
|
||||
|
||||
func likePattern(term string) string {
|
||||
@@ -97,12 +75,7 @@ func likePattern(term string) string {
|
||||
}
|
||||
|
||||
func (r *repository) GetByID(ctx context.Context, id int64) (paymentcard.PaymentCardDTO, error) {
|
||||
query := fmt.Sprintf(`SELECT %s FROM card_types c WHERE c.id = $1`, cardColumns)
|
||||
item, err := scanPaymentCard(r.client.QueryRow(ctx, query, id))
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return paymentcard.PaymentCardDTO{}, err
|
||||
}
|
||||
return item, err
|
||||
return r.generic.GetByID(ctx, id)
|
||||
}
|
||||
|
||||
func (r *repository) Create(ctx context.Context, dto paymentcard.CreatePaymentCardDTO) (paymentcard.PaymentCardDTO, error) {
|
||||
@@ -157,25 +130,14 @@ func (r *repository) UpdateActive(ctx context.Context, id int64, active bool) (p
|
||||
}
|
||||
|
||||
func (r *repository) Delete(ctx context.Context, id int64) error {
|
||||
tag, err := r.client.Exec(ctx, `DELETE FROM card_types WHERE id = $1`, id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if tag.RowsAffected() == 0 {
|
||||
return pgx.ErrNoRows
|
||||
}
|
||||
return nil
|
||||
return r.generic.Delete(ctx, id)
|
||||
}
|
||||
|
||||
func marshalName(title paymentcard.LocalizedText) ([]byte, error) {
|
||||
return json.Marshal(title)
|
||||
}
|
||||
|
||||
type scannable interface {
|
||||
Scan(dest ...interface{}) error
|
||||
}
|
||||
|
||||
func scanPaymentCard(row scannable) (paymentcard.PaymentCardDTO, error) {
|
||||
func scanPaymentCard(row genericrepo.Scanner) (paymentcard.PaymentCardDTO, error) {
|
||||
var item paymentcard.PaymentCardDTO
|
||||
var nameJSON []byte
|
||||
|
||||
File renamed without changes.
File renamed without changes.
File renamed without changes.
+18
-56
@@ -7,20 +7,26 @@ import (
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"online-back/internal/admin/reasonscard"
|
||||
"online-back/internal/cards/reasonscard"
|
||||
"online-back/pkg/client/postgresql"
|
||||
"online-back/pkg/logging"
|
||||
"online-back/pkg/repository/genericrepo"
|
||||
|
||||
"github.com/jackc/pgx/v4"
|
||||
)
|
||||
|
||||
type repository struct {
|
||||
client postgresql.Client
|
||||
logger *logging.Logger
|
||||
client postgresql.Client
|
||||
generic *genericrepo.Repository[reasonscard.ReasonCardDTO]
|
||||
logger *logging.Logger
|
||||
}
|
||||
|
||||
func NewRepository(client postgresql.Client, logger *logging.Logger) reasonscard.Repository {
|
||||
return &repository{client: client, logger: logger}
|
||||
return &repository{
|
||||
client: client,
|
||||
generic: genericrepo.New(client, "card_states r", reasonColumns, scanReasonCard),
|
||||
logger: logger,
|
||||
}
|
||||
}
|
||||
|
||||
const reasonColumns = `r.id, r.price, r.name, r.notes, r.active, r.created_at, r.updated_at`
|
||||
@@ -28,45 +34,17 @@ const reasonColumns = `r.id, r.price, r.name, r.notes, r.active, r.created_at, r
|
||||
const reasonReturningColumns = `id, price, name, notes, active, created_at, updated_at`
|
||||
|
||||
func (r *repository) List(ctx context.Context, filter reasonscard.ListFilter) (reasonscard.ListReasonCardDTO, error) {
|
||||
fromClause, whereClause, args := buildListQuery(filter)
|
||||
whereClause, args := buildListQuery(filter)
|
||||
|
||||
var count int64
|
||||
if err := r.client.QueryRow(ctx, `SELECT COUNT(*) `+fromClause+whereClause, args...).Scan(&count); err != nil {
|
||||
return reasonscard.ListReasonCardDTO{}, err
|
||||
}
|
||||
|
||||
offset := (filter.Page - 1) * filter.Limit
|
||||
limitPlaceholder := len(args) + 1
|
||||
offsetPlaceholder := len(args) + 2
|
||||
listQuery := fmt.Sprintf(
|
||||
`SELECT %s%s%s ORDER BY r.id LIMIT $%d OFFSET $%d`,
|
||||
reasonColumns, fromClause, whereClause, limitPlaceholder, offsetPlaceholder,
|
||||
)
|
||||
|
||||
rows, err := r.client.Query(ctx, listQuery, append(args, filter.Limit, offset)...)
|
||||
items, count, err := r.generic.List(ctx, whereClause, args, filter.Page, filter.Limit, "id")
|
||||
if err != nil {
|
||||
return reasonscard.ListReasonCardDTO{}, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var items []reasonscard.ReasonCardDTO
|
||||
for rows.Next() {
|
||||
item, err := scanReasonCard(rows)
|
||||
if err != nil {
|
||||
return reasonscard.ListReasonCardDTO{}, err
|
||||
}
|
||||
items = append(items, item)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return reasonscard.ListReasonCardDTO{}, err
|
||||
}
|
||||
|
||||
return reasonscard.ListReasonCardDTO{Count: count, ReasonCards: items}, nil
|
||||
}
|
||||
|
||||
func buildListQuery(filter reasonscard.ListFilter) (fromClause, whereClause string, args []interface{}) {
|
||||
fromClause = ` FROM card_states r`
|
||||
|
||||
func buildListQuery(filter reasonscard.ListFilter) (whereClause string, args []interface{}) {
|
||||
var conditions []string
|
||||
if filter.ReasonName != "" {
|
||||
args = append(args, likePattern(filter.ReasonName))
|
||||
@@ -77,10 +55,10 @@ func buildListQuery(filter reasonscard.ListFilter) (fromClause, whereClause stri
|
||||
}
|
||||
|
||||
if len(conditions) == 0 {
|
||||
return fromClause, "", args
|
||||
return "", args
|
||||
}
|
||||
|
||||
return fromClause, " WHERE " + strings.Join(conditions, " AND "), args
|
||||
return " WHERE " + strings.Join(conditions, " AND "), args
|
||||
}
|
||||
|
||||
func likePattern(term string) string {
|
||||
@@ -91,12 +69,7 @@ func likePattern(term string) string {
|
||||
}
|
||||
|
||||
func (r *repository) GetByID(ctx context.Context, id int64) (reasonscard.ReasonCardDTO, error) {
|
||||
query := fmt.Sprintf(`SELECT %s FROM card_states r WHERE r.id = $1`, reasonColumns)
|
||||
item, err := scanReasonCard(r.client.QueryRow(ctx, query, id))
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return reasonscard.ReasonCardDTO{}, err
|
||||
}
|
||||
return item, err
|
||||
return r.generic.GetByID(ctx, id)
|
||||
}
|
||||
|
||||
func (r *repository) Create(ctx context.Context, dto reasonscard.CreateReasonCardDTO) (reasonscard.ReasonCardDTO, error) {
|
||||
@@ -139,25 +112,14 @@ func (r *repository) Update(ctx context.Context, id int64, dto reasonscard.Updat
|
||||
}
|
||||
|
||||
func (r *repository) Delete(ctx context.Context, id int64) error {
|
||||
tag, err := r.client.Exec(ctx, `DELETE FROM card_states WHERE id = $1`, id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if tag.RowsAffected() == 0 {
|
||||
return pgx.ErrNoRows
|
||||
}
|
||||
return nil
|
||||
return r.generic.Delete(ctx, id)
|
||||
}
|
||||
|
||||
func marshalName(title reasonscard.LocalizedText) ([]byte, error) {
|
||||
return json.Marshal(title)
|
||||
}
|
||||
|
||||
type scannable interface {
|
||||
Scan(dest ...interface{}) error
|
||||
}
|
||||
|
||||
func scanReasonCard(row scannable) (reasonscard.ReasonCardDTO, error) {
|
||||
func scanReasonCard(row genericrepo.Scanner) (reasonscard.ReasonCardDTO, error) {
|
||||
var item reasonscard.ReasonCardDTO
|
||||
var nameJSON []byte
|
||||
|
||||
File renamed without changes.
File renamed without changes.
File renamed without changes.
@@ -0,0 +1,39 @@
|
||||
// Package cards groups payment cards, card orders, PIN orders, and their
|
||||
// reference data (reasons, payment card types) under one bounded context,
|
||||
// replacing the flat internal/admin/* listing.
|
||||
package cards
|
||||
|
||||
import (
|
||||
"online-back/internal/cards/cardorder"
|
||||
cardorderdb "online-back/internal/cards/cardorder/db"
|
||||
"online-back/internal/cards/cardpinorders"
|
||||
cardpinordersdb "online-back/internal/cards/cardpinorders/db"
|
||||
cardentity "online-back/internal/cards/cards"
|
||||
cardentitydb "online-back/internal/cards/cards/db"
|
||||
"online-back/internal/cards/paymentcard"
|
||||
paymentcarddb "online-back/internal/cards/paymentcard/db"
|
||||
"online-back/internal/cards/reasonscard"
|
||||
reasonscarddb "online-back/internal/cards/reasonscard/db"
|
||||
"online-back/internal/handlers"
|
||||
"online-back/pkg/client/postgresql"
|
||||
"online-back/pkg/logging"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// Register wires every cards module's handler onto router.
|
||||
func Register(router *gin.RouterGroup, client postgresql.Client, logger *logging.Logger) {
|
||||
for _, h := range Handlers(client, logger) {
|
||||
h.Register(router)
|
||||
}
|
||||
}
|
||||
|
||||
func Handlers(client postgresql.Client, logger *logging.Logger) []handlers.Handler {
|
||||
return []handlers.Handler{
|
||||
cardentity.NewHandler(logger, cardentitydb.NewRepository(client, logger)),
|
||||
cardorder.NewHandler(logger, cardorderdb.NewRepository(client, logger)),
|
||||
cardpinorders.NewHandler(logger, cardpinordersdb.NewRepository(client, logger)),
|
||||
paymentcard.NewHandler(logger, paymentcarddb.NewRepository(client, logger)),
|
||||
reasonscard.NewHandler(logger, reasonscarddb.NewRepository(client, logger)),
|
||||
}
|
||||
}
|
||||
@@ -17,6 +17,7 @@ type Config struct {
|
||||
} `yaml:"listen"`
|
||||
PublicFilePath string `yaml:"public_file_path" env-required:"true"`
|
||||
Storage StorageConfig `yaml:"storage"`
|
||||
Minio MinioConfig `yaml:"minio"`
|
||||
JwtKey string `yaml:"jwt_key" env-required:"true"`
|
||||
AppVersion string `yaml:"app_version" env-required:"true"`
|
||||
}
|
||||
@@ -30,6 +31,14 @@ type StorageConfig struct {
|
||||
Password string `yaml:"password"`
|
||||
}
|
||||
|
||||
type MinioConfig struct {
|
||||
Endpoint string `yaml:"endpoint" env-required:"true"`
|
||||
AccessKey string `yaml:"access_key" env-required:"true"`
|
||||
SecretKey string `yaml:"secret_key" env-required:"true"`
|
||||
Bucket string `yaml:"bucket" env-required:"true"`
|
||||
UseSSL bool `yaml:"use_ssl" env-default:"false"`
|
||||
}
|
||||
|
||||
var (
|
||||
instance *Config
|
||||
once sync.Once
|
||||
|
||||
@@ -3,28 +3,13 @@ package handlermanager
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"online-back/internal/admin/auth"
|
||||
authdb "online-back/internal/admin/auth/db"
|
||||
"online-back/internal/admin/branches"
|
||||
branchesdb "online-back/internal/admin/branches/db"
|
||||
"online-back/internal/admin/loansdocument"
|
||||
loansdocumentdb "online-back/internal/admin/loansdocument/db"
|
||||
"online-back/internal/admin/loantype"
|
||||
loantypedb "online-back/internal/admin/loantype/db"
|
||||
"online-back/internal/admin/paymentcard"
|
||||
paymentcarddb "online-back/internal/admin/paymentcard/db"
|
||||
"online-back/internal/admin/permission"
|
||||
permissiondb "online-back/internal/admin/permission/db"
|
||||
"online-back/internal/admin/province"
|
||||
provincedb "online-back/internal/admin/province/db"
|
||||
"online-back/internal/admin/reasonscard"
|
||||
reasonscarddb "online-back/internal/admin/reasonscard/db"
|
||||
"online-back/internal/admin/role"
|
||||
roledb "online-back/internal/admin/role/db"
|
||||
"online-back/internal/admin/user"
|
||||
userdb "online-back/internal/admin/user/db"
|
||||
"online-back/internal/cards"
|
||||
"online-back/internal/config"
|
||||
"online-back/internal/handlers"
|
||||
"online-back/internal/identity"
|
||||
"online-back/internal/identity/activitylog"
|
||||
activitylogdb "online-back/internal/identity/activitylog/db"
|
||||
"online-back/internal/lending"
|
||||
"online-back/internal/org"
|
||||
"online-back/pkg/logging"
|
||||
|
||||
"github.com/gin-contrib/cors"
|
||||
@@ -58,26 +43,14 @@ func New(cfg *config.Config, client *pgxpool.Pool, logger *logging.Logger) *gin.
|
||||
}))
|
||||
|
||||
adminGroup := router.Group(adminAPIPrefix)
|
||||
for _, h := range adminHandlers(client, logger) {
|
||||
h.Register(adminGroup)
|
||||
}
|
||||
adminGroup.Use(activitylog.Record(activitylogdb.NewRepository(client, logger), logger))
|
||||
|
||||
// Each bounded context registers its own modules' handlers.
|
||||
// Add new modules inside the relevant context's router.go rather than here.
|
||||
identity.Register(adminGroup, client, logger)
|
||||
org.Register(adminGroup, client, logger)
|
||||
lending.Register(adminGroup, client, logger)
|
||||
cards.Register(adminGroup, client, logger)
|
||||
|
||||
return router
|
||||
}
|
||||
|
||||
// adminHandlers builds every handlers.Handler registered under adminAPIPrefix.
|
||||
// Add new modules here rather than inlining their wiring into New.
|
||||
func adminHandlers(client *pgxpool.Pool, logger *logging.Logger) []handlers.Handler {
|
||||
return []handlers.Handler{
|
||||
auth.NewHandler(logger, authdb.NewRepository(client, logger)),
|
||||
province.NewHandler(logger, provincedb.NewRepository(client, logger)),
|
||||
branches.NewHandler(logger, branchesdb.NewRepository(client, logger)),
|
||||
paymentcard.NewHandler(logger, paymentcarddb.NewRepository(client, logger)),
|
||||
reasonscard.NewHandler(logger, reasonscarddb.NewRepository(client, logger)),
|
||||
loantype.NewHandler(logger, loantypedb.NewRepository(client, logger)),
|
||||
loansdocument.NewHandler(logger, loansdocumentdb.NewRepository(client, logger)),
|
||||
role.NewHandler(logger, roledb.NewRepository(client, logger)),
|
||||
permission.NewHandler(logger, permissiondb.NewRepository(client, logger)),
|
||||
user.NewHandler(logger, userdb.NewRepository(client, logger)),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"online-back/internal/identity/activitylog"
|
||||
"online-back/pkg/client/postgresql"
|
||||
"online-back/pkg/logging"
|
||||
"online-back/pkg/repository/genericrepo"
|
||||
)
|
||||
|
||||
type repository struct {
|
||||
client postgresql.Client
|
||||
generic *genericrepo.Repository[activitylog.ActivityLogDTO]
|
||||
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,
|
||||
}
|
||||
}
|
||||
|
||||
var activityLogColumns = []string{
|
||||
"id", "user_id", "method", "path", "module", "action", "status_code", "request_body", "ip", "created_at",
|
||||
}
|
||||
|
||||
var activityLogColumnsSQL = strings.Join(activityLogColumns, ", ")
|
||||
|
||||
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")
|
||||
if err != nil {
|
||||
return activitylog.ListActivityLogDTO{}, err
|
||||
}
|
||||
|
||||
return activitylog.ListActivityLogDTO{Count: count, Logs: items}, nil
|
||||
}
|
||||
|
||||
func buildListQuery(filter activitylog.ListFilter) (whereClause string, args []interface{}) {
|
||||
var conditions []string
|
||||
|
||||
if filter.UserId != nil {
|
||||
args = append(args, *filter.UserId)
|
||||
conditions = append(conditions, fmt.Sprintf("user_id = $%d", len(args)))
|
||||
}
|
||||
|
||||
if filter.Module != "" {
|
||||
args = append(args, filter.Module)
|
||||
conditions = append(conditions, fmt.Sprintf("module = $%d", len(args)))
|
||||
}
|
||||
|
||||
if filter.Action != "" {
|
||||
args = append(args, filter.Action)
|
||||
conditions = append(conditions, fmt.Sprintf("action = $%d", len(args)))
|
||||
}
|
||||
|
||||
if len(conditions) == 0 {
|
||||
return "", args
|
||||
}
|
||||
|
||||
return " WHERE " + strings.Join(conditions, " AND "), args
|
||||
}
|
||||
|
||||
func (r *repository) GetByID(ctx context.Context, id int64) (activitylog.ActivityLogDTO, error) {
|
||||
return r.generic.GetByID(ctx, 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
|
||||
|
||||
row := r.client.QueryRow(ctx, query,
|
||||
dto.UserId, dto.Method, dto.Path, dto.Module, dto.Action, dto.StatusCode, dto.RequestBody, dto.Ip,
|
||||
)
|
||||
return scanActivityLog(row)
|
||||
}
|
||||
|
||||
func scanActivityLog(row genericrepo.Scanner) (activitylog.ActivityLogDTO, error) {
|
||||
var item activitylog.ActivityLogDTO
|
||||
var requestBody []byte
|
||||
|
||||
err := row.Scan(
|
||||
&item.Id, &item.UserId, &item.Method, &item.Path, &item.Module, &item.Action,
|
||||
&item.StatusCode, &requestBody, &item.Ip, &item.CreatedAt,
|
||||
)
|
||||
if err != nil {
|
||||
return activitylog.ActivityLogDTO{}, err
|
||||
}
|
||||
item.RequestBody = requestBody
|
||||
return item, nil
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
package activitylog
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"time"
|
||||
)
|
||||
|
||||
type ActivityLogDTO struct {
|
||||
Id int64 `json:"id"`
|
||||
UserId *int64 `json:"userId"`
|
||||
Method string `json:"method"`
|
||||
Path string `json:"path"`
|
||||
Module string `json:"module"`
|
||||
Action string `json:"action"`
|
||||
StatusCode int `json:"statusCode"`
|
||||
RequestBody json.RawMessage `json:"requestBody"`
|
||||
Ip string `json:"ip"`
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
}
|
||||
|
||||
// CreateActivityLogDTO is filled in by the Record middleware for every
|
||||
// mutating request made by an authenticated user.
|
||||
type CreateActivityLogDTO struct {
|
||||
UserId *int64
|
||||
Method string
|
||||
Path string
|
||||
Module string
|
||||
Action string
|
||||
StatusCode int
|
||||
RequestBody []byte
|
||||
Ip string
|
||||
}
|
||||
|
||||
type ListFilter struct {
|
||||
UserId *int64
|
||||
Module string
|
||||
Action string
|
||||
Page int
|
||||
Limit int
|
||||
}
|
||||
|
||||
type ListActivityLogDTO struct {
|
||||
Count int64 `json:"count"`
|
||||
Logs []ActivityLogDTO `json:"logs"`
|
||||
}
|
||||
@@ -0,0 +1,148 @@
|
||||
package activitylog
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
"strconv"
|
||||
|
||||
"online-back/internal/appresult"
|
||||
"online-back/internal/handlers"
|
||||
"online-back/pkg/logging"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/jackc/pgx/v4"
|
||||
)
|
||||
|
||||
const baseURL = "/activity-logs"
|
||||
|
||||
type handler struct {
|
||||
logger *logging.Logger
|
||||
repository Repository
|
||||
}
|
||||
|
||||
func NewHandler(logger *logging.Logger, repository Repository) handlers.Handler {
|
||||
return &handler{logger: logger, repository: repository}
|
||||
}
|
||||
|
||||
// Register only wires read endpoints: activity log entries are written by
|
||||
// the Record middleware, never through the API.
|
||||
func (h *handler) Register(router *gin.RouterGroup) {
|
||||
group := router.Group(baseURL, appresult.JwtTokenCheck())
|
||||
group.GET("", h.list)
|
||||
group.GET("/:id", h.getByID)
|
||||
}
|
||||
|
||||
// list godoc
|
||||
// @Summary List activity logs
|
||||
// @Description Returns a paginated audit trail of user actions (create/update/delete)
|
||||
// @Tags activity-logs
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param user_id query int false "Filter by user ID"
|
||||
// @Param module query string false "Filter by module (e.g. cards, branch-users)"
|
||||
// @Param action query string false "Filter by action (create, update, delete)"
|
||||
// @Param page query int false "Page number" default(1)
|
||||
// @Param limit query int false "Items per page" default(10)
|
||||
// @Success 200 {object} appresult.AppSuccess
|
||||
// @Failure 400 {object} appresult.AppError
|
||||
// @Failure 500 {object} appresult.AppError
|
||||
// @Router /activity-logs [get]
|
||||
func (h *handler) list(c *gin.Context) {
|
||||
filter, ok := parseListFilter(c)
|
||||
if !ok {
|
||||
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
|
||||
return
|
||||
}
|
||||
|
||||
result, err := h.repository.List(c.Request.Context(), filter)
|
||||
if err != nil {
|
||||
h.logger.Errorf("list activity logs failed: %v", err)
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, appresult.SuccessWithData(result))
|
||||
}
|
||||
|
||||
// getByID godoc
|
||||
// @Summary Get activity log by ID
|
||||
// @Description Returns a single activity log entry
|
||||
// @Tags activity-logs
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param id path int true "Activity log ID"
|
||||
// @Success 200 {object} appresult.AppSuccess
|
||||
// @Failure 400 {object} appresult.AppError
|
||||
// @Failure 404 {object} appresult.AppError
|
||||
// @Failure 500 {object} appresult.AppError
|
||||
// @Router /activity-logs/{id} [get]
|
||||
func (h *handler) getByID(c *gin.Context) {
|
||||
id, ok := parseID(c.Param("id"))
|
||||
if !ok {
|
||||
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
|
||||
return
|
||||
}
|
||||
|
||||
item, err := h.repository.GetByID(c.Request.Context(), id)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
c.JSON(http.StatusNotFound, appresult.ErrNotFound)
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
h.logger.Errorf("get activity log failed: %v", err)
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, appresult.SuccessWithData(item))
|
||||
}
|
||||
|
||||
func parseID(raw string) (int64, bool) {
|
||||
id, err := strconv.ParseInt(raw, 10, 64)
|
||||
if err != nil || id <= 0 {
|
||||
return 0, false
|
||||
}
|
||||
return id, true
|
||||
}
|
||||
|
||||
const (
|
||||
defaultPage = 1
|
||||
defaultLimit = 10
|
||||
maxLimit = 100
|
||||
)
|
||||
|
||||
func parseListFilter(c *gin.Context) (ListFilter, bool) {
|
||||
filter := ListFilter{
|
||||
Page: defaultPage,
|
||||
Limit: defaultLimit,
|
||||
}
|
||||
|
||||
if raw := c.Query("user_id"); raw != "" {
|
||||
id, ok := parseID(raw)
|
||||
if !ok {
|
||||
return ListFilter{}, false
|
||||
}
|
||||
filter.UserId = &id
|
||||
}
|
||||
|
||||
filter.Module = c.Query("module")
|
||||
filter.Action = c.Query("action")
|
||||
|
||||
if raw := c.Query("page"); raw != "" {
|
||||
page, err := strconv.Atoi(raw)
|
||||
if err != nil || page < 1 {
|
||||
return ListFilter{}, false
|
||||
}
|
||||
filter.Page = page
|
||||
}
|
||||
|
||||
if raw := c.Query("limit"); raw != "" {
|
||||
limit, err := strconv.Atoi(raw)
|
||||
if err != nil || limit < 1 || limit > maxLimit {
|
||||
return ListFilter{}, false
|
||||
}
|
||||
filter.Limit = limit
|
||||
}
|
||||
|
||||
return filter, true
|
||||
}
|
||||
@@ -0,0 +1,176 @@
|
||||
package activitylog
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"io"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"online-back/pkg/logging"
|
||||
|
||||
"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
|
||||
|
||||
// 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.
|
||||
func Record(repository Repository, logger *logging.Logger) gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
if !shouldRecord(c.Request.Method) {
|
||||
c.Next()
|
||||
return
|
||||
}
|
||||
|
||||
body := readAndRestoreBody(c)
|
||||
|
||||
c.Next()
|
||||
|
||||
userID := currentUserID(c)
|
||||
if userID == nil {
|
||||
return
|
||||
}
|
||||
|
||||
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)
|
||||
}
|
||||
}()
|
||||
}
|
||||
}
|
||||
|
||||
func shouldRecord(method string) bool {
|
||||
switch method {
|
||||
case http.MethodPost, http.MethodPut, http.MethodPatch, http.MethodDelete:
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
func readAndRestoreBody(c *gin.Context) []byte {
|
||||
if c.Request.Body == nil {
|
||||
return nil
|
||||
}
|
||||
data, err := io.ReadAll(c.Request.Body)
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
c.Request.Body = io.NopCloser(bytes.NewReader(data))
|
||||
return data
|
||||
}
|
||||
|
||||
func currentUserID(c *gin.Context) *int64 {
|
||||
raw, exists := c.Get("id")
|
||||
if !exists {
|
||||
return nil
|
||||
}
|
||||
|
||||
switch v := raw.(type) {
|
||||
case int64:
|
||||
return &v
|
||||
case int:
|
||||
id := int64(v)
|
||||
return &id
|
||||
case string:
|
||||
id, err := strconv.ParseInt(v, 10, 64)
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
return &id
|
||||
default:
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
// describeRoute derives a module (e.g. "cards", "branch-users") and an
|
||||
// action (create/update/delete) from the matched route so entries stay
|
||||
// meaningful even though logging is wired generically for every module.
|
||||
func describeRoute(c *gin.Context) (module, action string) {
|
||||
action = actionFromMethod(c.Request.Method)
|
||||
|
||||
route := c.FullPath()
|
||||
if route == "" {
|
||||
route = c.Request.URL.Path
|
||||
}
|
||||
|
||||
segments := strings.Split(strings.Trim(route, "/"), "/")
|
||||
for i, segment := range segments {
|
||||
if segment == "admin" && i+1 < len(segments) {
|
||||
return segments[i+1], action
|
||||
}
|
||||
}
|
||||
if len(segments) > 0 {
|
||||
return segments[0], action
|
||||
}
|
||||
return "", action
|
||||
}
|
||||
|
||||
func actionFromMethod(method string) string {
|
||||
switch method {
|
||||
case http.MethodPost:
|
||||
return "create"
|
||||
case http.MethodPut, http.MethodPatch:
|
||||
return "update"
|
||||
case http.MethodDelete:
|
||||
return "delete"
|
||||
default:
|
||||
return strings.ToLower(method)
|
||||
}
|
||||
}
|
||||
|
||||
// redact blanks out sensitive fields (passwords, tokens, secrets) before a
|
||||
// request body is stored. Bodies that aren't a JSON object are dropped
|
||||
// entirely rather than risk leaking something unparsed.
|
||||
func redact(body []byte) []byte {
|
||||
if len(body) == 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
var payload map[string]interface{}
|
||||
if err := json.Unmarshal(body, &payload); err != nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
for key := range payload {
|
||||
lower := strings.ToLower(key)
|
||||
for _, needle := range sensitiveFieldSubstrings {
|
||||
if strings.Contains(lower, needle) {
|
||||
payload[key] = "***"
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
redacted, err := json.Marshal(payload)
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
return redacted
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
package activitylog
|
||||
|
||||
import "context"
|
||||
|
||||
type Repository interface {
|
||||
List(ctx context.Context, filter ListFilter) (ListActivityLogDTO, error)
|
||||
GetByID(ctx context.Context, id int64) (ActivityLogDTO, error)
|
||||
Create(ctx context.Context, dto CreateActivityLogDTO) (ActivityLogDTO, error)
|
||||
}
|
||||
@@ -2,10 +2,13 @@ package db
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
|
||||
"online-back/internal/admin/auth"
|
||||
"online-back/internal/identity/auth"
|
||||
"online-back/pkg/client/postgresql"
|
||||
"online-back/pkg/logging"
|
||||
|
||||
"github.com/jackc/pgx/v4"
|
||||
)
|
||||
|
||||
type repository struct {
|
||||
@@ -23,7 +26,7 @@ func NewRepository(client postgresql.Client, logger *logging.Logger) auth.Reposi
|
||||
const (
|
||||
loginQuery = `SELECT id, password FROM users WHERE email = $1`
|
||||
userByIDQuery = `SELECT id, password FROM users WHERE id = $1`
|
||||
profileQuery = `SELECT id, fullname, phone_number, avatar, created_at
|
||||
profileQuery = `SELECT id, name, first_name, last_name, phone, avatar, created_at
|
||||
FROM users WHERE id = $1`
|
||||
)
|
||||
|
||||
@@ -43,10 +46,38 @@ func (r *repository) GetProfile(ctx context.Context, id int) (auth.UserProfileDT
|
||||
var profile auth.UserProfileDTO
|
||||
err := r.client.QueryRow(ctx, profileQuery, id).Scan(
|
||||
&profile.Id,
|
||||
&profile.FullName,
|
||||
&profile.PhoneNumber,
|
||||
&profile.Name,
|
||||
&profile.FirstName,
|
||||
&profile.LastName,
|
||||
&profile.Phone,
|
||||
&profile.Avatar,
|
||||
&profile.CreatedAt,
|
||||
)
|
||||
return profile, err
|
||||
}
|
||||
|
||||
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`
|
||||
|
||||
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,
|
||||
dto.Name, dto.FirstName, dto.LastName, dto.Phone, dto.Avatar, id,
|
||||
).Scan(
|
||||
&profile.Id,
|
||||
&profile.Name,
|
||||
&profile.FirstName,
|
||||
&profile.LastName,
|
||||
&profile.Phone,
|
||||
&profile.Avatar,
|
||||
&profile.CreatedAt,
|
||||
)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return auth.UserProfileDTO{}, err
|
||||
}
|
||||
return profile, err
|
||||
}
|
||||
Executable
+35
@@ -0,0 +1,35 @@
|
||||
package auth
|
||||
|
||||
import "time"
|
||||
|
||||
type LoginDTO struct {
|
||||
Email string `json:"email" binding:"required"`
|
||||
Password string `json:"password" binding:"required"`
|
||||
}
|
||||
|
||||
type RefreshTokenDTO struct {
|
||||
RefreshToken string `json:"refreshToken" binding:"required"`
|
||||
}
|
||||
|
||||
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"`
|
||||
}
|
||||
|
||||
type UpdateProfileDTO struct {
|
||||
Name string `json:"name" binding:"required"`
|
||||
FirstName string `json:"firstName"`
|
||||
LastName string `json:"lastName"`
|
||||
Phone string `json:"phone"`
|
||||
Avatar string `json:"avatar"`
|
||||
}
|
||||
|
||||
type UserCredentials struct {
|
||||
Id int
|
||||
Password string
|
||||
}
|
||||
@@ -1,16 +1,16 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
"strconv"
|
||||
|
||||
"online-back/internal/appresult"
|
||||
"online-back/internal/handlers"
|
||||
"online-back/pkg/logging"
|
||||
"online-back/pkg/utils"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
"github.com/jackc/pgx/v4"
|
||||
)
|
||||
|
||||
const (
|
||||
@@ -22,10 +22,11 @@ const (
|
||||
type handler struct {
|
||||
logger *logging.Logger
|
||||
repository Repository
|
||||
service *Service
|
||||
}
|
||||
|
||||
func NewHandler(logger *logging.Logger, repository Repository) handlers.Handler {
|
||||
return &handler{logger: logger, repository: repository}
|
||||
return &handler{logger: logger, repository: repository, service: NewService(repository)}
|
||||
}
|
||||
|
||||
func (h *handler) Register(router *gin.RouterGroup) {
|
||||
@@ -34,6 +35,7 @@ func (h *handler) Register(router *gin.RouterGroup) {
|
||||
|
||||
protected := router.Group("", appresult.JwtTokenCheck())
|
||||
protected.GET(profileURL, h.getProfile)
|
||||
protected.PUT(profileURL, h.updateProfile)
|
||||
}
|
||||
|
||||
// login godoc
|
||||
@@ -54,19 +56,11 @@ func (h *handler) login(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
user, err := h.repository.Login(c.Request.Context(), dto)
|
||||
if err != nil {
|
||||
h.logger.Errorf("login lookup failed: %v", err)
|
||||
tokenPair, err := h.service.Login(c.Request.Context(), dto)
|
||||
if errors.Is(err, ErrInvalidCredentials) {
|
||||
c.JSON(http.StatusUnauthorized, appresult.ErrUnauthorized)
|
||||
return
|
||||
}
|
||||
|
||||
if err := bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(dto.Password)); err != nil {
|
||||
c.JSON(http.StatusUnauthorized, appresult.ErrUnauthorized)
|
||||
return
|
||||
}
|
||||
|
||||
tokenPair, err := utils.GenerateTokenPair(user.Id)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, appresult.ErrNotAcceptable)
|
||||
return
|
||||
@@ -93,25 +87,11 @@ func (h *handler) refreshToken(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
claims, err := utils.ParseRefreshToken(dto.RefreshToken)
|
||||
if err != nil {
|
||||
tokenPair, err := h.service.RefreshToken(c.Request.Context(), dto.RefreshToken)
|
||||
if errors.Is(err, ErrInvalidCredentials) {
|
||||
c.JSON(http.StatusUnauthorized, appresult.ErrUnauthorized)
|
||||
return
|
||||
}
|
||||
|
||||
id, ok := utils.ClaimID(claims)
|
||||
if !ok {
|
||||
c.JSON(http.StatusUnauthorized, appresult.ErrUnauthorized)
|
||||
return
|
||||
}
|
||||
|
||||
user, err := h.repository.GetUserByID(c.Request.Context(), id)
|
||||
if err != nil || user.Id != id {
|
||||
c.JSON(http.StatusUnauthorized, appresult.ErrUnauthorized)
|
||||
return
|
||||
}
|
||||
|
||||
tokenPair, err := utils.GenerateTokenPair(id)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, appresult.ErrNotAcceptable)
|
||||
return
|
||||
@@ -148,6 +128,46 @@ func (h *handler) getProfile(c *gin.Context) {
|
||||
c.JSON(http.StatusOK, appresult.SuccessWithData(profile))
|
||||
}
|
||||
|
||||
// updateProfile godoc
|
||||
// @Summary Update profile
|
||||
// @Description Updates the authenticated user's profile
|
||||
// @Tags auth
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param body body UpdateProfileDTO true "Profile payload"
|
||||
// @Success 200 {object} appresult.AppSuccess
|
||||
// @Failure 400 {object} appresult.AppError
|
||||
// @Failure 401 {object} appresult.AppError
|
||||
// @Failure 404 {object} appresult.AppError
|
||||
// @Router /profile [put]
|
||||
func (h *handler) updateProfile(c *gin.Context) {
|
||||
userID, ok := currentUserID(c)
|
||||
if !ok {
|
||||
c.JSON(http.StatusUnauthorized, appresult.ErrUnauthorized)
|
||||
return
|
||||
}
|
||||
|
||||
var dto UpdateProfileDTO
|
||||
if err := c.ShouldBindJSON(&dto); err != nil {
|
||||
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
|
||||
return
|
||||
}
|
||||
|
||||
profile, err := h.repository.UpdateProfile(c.Request.Context(), userID, dto)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
c.JSON(http.StatusNotFound, appresult.ErrNotFound)
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
h.logger.Errorf("update profile failed: %v", err)
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, appresult.SuccessWithData(profile))
|
||||
}
|
||||
|
||||
func currentUserID(c *gin.Context) (int, bool) {
|
||||
rawID, exists := c.Get("id")
|
||||
if !exists {
|
||||
@@ -0,0 +1,55 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
|
||||
"online-back/pkg/utils"
|
||||
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
)
|
||||
|
||||
// ErrInvalidCredentials covers both "no such user" and "wrong password" for
|
||||
// login, and any refresh-token validation failure — callers map it to 401.
|
||||
// Any other error from these methods (token generation failure) maps to 400.
|
||||
var ErrInvalidCredentials = errors.New("invalid credentials")
|
||||
|
||||
type Service struct {
|
||||
repository Repository
|
||||
}
|
||||
|
||||
func NewService(repository Repository) *Service {
|
||||
return &Service{repository: repository}
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
|
||||
if err := bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(dto.Password)); err != nil {
|
||||
return nil, ErrInvalidCredentials
|
||||
}
|
||||
|
||||
return utils.GenerateTokenPair(user.Id)
|
||||
}
|
||||
|
||||
func (s *Service) RefreshToken(ctx context.Context, refreshToken string) (map[string]string, error) {
|
||||
claims, err := utils.ParseRefreshToken(refreshToken)
|
||||
if err != nil {
|
||||
return nil, ErrInvalidCredentials
|
||||
}
|
||||
|
||||
id, ok := utils.ClaimID(claims)
|
||||
if !ok {
|
||||
return nil, ErrInvalidCredentials
|
||||
}
|
||||
|
||||
user, err := s.repository.GetUserByID(ctx, id)
|
||||
if err != nil || user.Id != id {
|
||||
return nil, ErrInvalidCredentials
|
||||
}
|
||||
|
||||
return utils.GenerateTokenPair(id)
|
||||
}
|
||||
@@ -6,4 +6,5 @@ type Repository interface {
|
||||
Login(ctx context.Context, dto LoginDTO) (UserCredentials, error)
|
||||
GetUserByID(ctx context.Context, id int) (UserCredentials, error)
|
||||
GetProfile(ctx context.Context, id int) (UserProfileDTO, error)
|
||||
UpdateProfile(ctx context.Context, id int, dto UpdateProfileDTO) (UserProfileDTO, error)
|
||||
}
|
||||
+18
-56
@@ -6,20 +6,26 @@ import (
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"online-back/internal/admin/permission"
|
||||
"online-back/internal/identity/permission"
|
||||
"online-back/pkg/client/postgresql"
|
||||
"online-back/pkg/logging"
|
||||
"online-back/pkg/repository/genericrepo"
|
||||
|
||||
"github.com/jackc/pgx/v4"
|
||||
)
|
||||
|
||||
type repository struct {
|
||||
client postgresql.Client
|
||||
logger *logging.Logger
|
||||
client postgresql.Client
|
||||
generic *genericrepo.Repository[permission.PermissionDTO]
|
||||
logger *logging.Logger
|
||||
}
|
||||
|
||||
func NewRepository(client postgresql.Client, logger *logging.Logger) permission.Repository {
|
||||
return &repository{client: client, logger: logger}
|
||||
return &repository{
|
||||
client: client,
|
||||
generic: genericrepo.New(client, "permissions p", permissionColumns, scanPermission),
|
||||
logger: logger,
|
||||
}
|
||||
}
|
||||
|
||||
const permissionColumns = `p.id, p.code, p.name, p.guard_name, p.created_at, p.updated_at`
|
||||
@@ -27,45 +33,17 @@ const permissionColumns = `p.id, p.code, p.name, p.guard_name, p.created_at, p.u
|
||||
const permissionReturningColumns = `id, code, name, guard_name, created_at, updated_at`
|
||||
|
||||
func (r *repository) List(ctx context.Context, filter permission.ListFilter) (permission.ListPermissionDTO, error) {
|
||||
fromClause, whereClause, args := buildListQuery(filter)
|
||||
whereClause, args := buildListQuery(filter)
|
||||
|
||||
var count int64
|
||||
if err := r.client.QueryRow(ctx, `SELECT COUNT(*) `+fromClause+whereClause, args...).Scan(&count); err != nil {
|
||||
return permission.ListPermissionDTO{}, err
|
||||
}
|
||||
|
||||
offset := (filter.Page - 1) * filter.Limit
|
||||
limitPlaceholder := len(args) + 1
|
||||
offsetPlaceholder := len(args) + 2
|
||||
listQuery := fmt.Sprintf(
|
||||
`SELECT %s%s%s ORDER BY p.id LIMIT $%d OFFSET $%d`,
|
||||
permissionColumns, fromClause, whereClause, limitPlaceholder, offsetPlaceholder,
|
||||
)
|
||||
|
||||
rows, err := r.client.Query(ctx, listQuery, append(args, filter.Limit, offset)...)
|
||||
items, count, err := r.generic.List(ctx, whereClause, args, filter.Page, filter.Limit, "id")
|
||||
if err != nil {
|
||||
return permission.ListPermissionDTO{}, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var items []permission.PermissionDTO
|
||||
for rows.Next() {
|
||||
item, err := scanPermission(rows)
|
||||
if err != nil {
|
||||
return permission.ListPermissionDTO{}, err
|
||||
}
|
||||
items = append(items, item)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return permission.ListPermissionDTO{}, err
|
||||
}
|
||||
|
||||
return permission.ListPermissionDTO{Count: count, Permissions: items}, nil
|
||||
}
|
||||
|
||||
func buildListQuery(filter permission.ListFilter) (fromClause, whereClause string, args []interface{}) {
|
||||
fromClause = ` FROM permissions p`
|
||||
|
||||
func buildListQuery(filter permission.ListFilter) (whereClause string, args []interface{}) {
|
||||
var conditions []string
|
||||
if filter.PermissionName != "" {
|
||||
args = append(args, likePattern(filter.PermissionName))
|
||||
@@ -74,10 +52,10 @@ func buildListQuery(filter permission.ListFilter) (fromClause, whereClause strin
|
||||
}
|
||||
|
||||
if len(conditions) == 0 {
|
||||
return fromClause, "", args
|
||||
return "", args
|
||||
}
|
||||
|
||||
return fromClause, " WHERE " + strings.Join(conditions, " AND "), args
|
||||
return " WHERE " + strings.Join(conditions, " AND "), args
|
||||
}
|
||||
|
||||
func likePattern(term string) string {
|
||||
@@ -88,12 +66,7 @@ func likePattern(term string) string {
|
||||
}
|
||||
|
||||
func (r *repository) GetByID(ctx context.Context, id int64) (permission.PermissionDTO, error) {
|
||||
query := fmt.Sprintf(`SELECT %s FROM permissions p WHERE p.id = $1`, permissionColumns)
|
||||
item, err := scanPermission(r.client.QueryRow(ctx, query, id))
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return permission.PermissionDTO{}, err
|
||||
}
|
||||
return item, err
|
||||
return r.generic.GetByID(ctx, id)
|
||||
}
|
||||
|
||||
func (r *repository) Create(ctx context.Context, dto permission.CreatePermissionDTO) (permission.PermissionDTO, error) {
|
||||
@@ -121,21 +94,10 @@ func (r *repository) Update(ctx context.Context, id int64, dto permission.Update
|
||||
}
|
||||
|
||||
func (r *repository) Delete(ctx context.Context, id int64) error {
|
||||
tag, err := r.client.Exec(ctx, `DELETE FROM permissions WHERE id = $1`, id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if tag.RowsAffected() == 0 {
|
||||
return pgx.ErrNoRows
|
||||
}
|
||||
return nil
|
||||
return r.generic.Delete(ctx, id)
|
||||
}
|
||||
|
||||
type scannable interface {
|
||||
Scan(dest ...interface{}) error
|
||||
}
|
||||
|
||||
func scanPermission(row scannable) (permission.PermissionDTO, error) {
|
||||
func scanPermission(row genericrepo.Scanner) (permission.PermissionDTO, error) {
|
||||
var item permission.PermissionDTO
|
||||
if err := row.Scan(
|
||||
&item.Id, &item.Code, &item.Name, &item.GuardName, &item.CreatedAt, &item.UpdatedAt,
|
||||
File renamed without changes.
File renamed without changes.
File renamed without changes.
@@ -0,0 +1,132 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"online-back/internal/identity/permissionuser"
|
||||
"online-back/pkg/client/postgresql"
|
||||
"online-back/pkg/logging"
|
||||
|
||||
"github.com/jackc/pgx/v4"
|
||||
)
|
||||
|
||||
type repository struct {
|
||||
client postgresql.Client
|
||||
logger *logging.Logger
|
||||
}
|
||||
|
||||
func NewRepository(client postgresql.Client, logger *logging.Logger) permissionuser.Repository {
|
||||
return &repository{client: client, logger: logger}
|
||||
}
|
||||
|
||||
const permissionUserFromClause = ` FROM permission_user pu
|
||||
JOIN permissions p ON p.id = pu.permission_id
|
||||
JOIN users u ON u.id = pu.user_id`
|
||||
|
||||
const permissionUserSelectColumns = `pu.id, pu.permission_id, p.name, pu.user_id, u.name, pu.created_at, pu.updated_at`
|
||||
|
||||
func (r *repository) List(ctx context.Context, filter permissionuser.ListFilter) (permissionuser.ListPermissionUserDTO, error) {
|
||||
whereClause, args := buildListQuery(filter)
|
||||
|
||||
var count int64
|
||||
if err := r.client.QueryRow(ctx, `SELECT COUNT(*)`+permissionUserFromClause+whereClause, args...).Scan(&count); err != nil {
|
||||
return permissionuser.ListPermissionUserDTO{}, err
|
||||
}
|
||||
|
||||
query := `SELECT ` + permissionUserSelectColumns + permissionUserFromClause + whereClause + ` ORDER BY pu.id DESC`
|
||||
rows, err := r.client.Query(ctx, query, args...)
|
||||
if err != nil {
|
||||
return permissionuser.ListPermissionUserDTO{}, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var items []permissionuser.PermissionUserDTO
|
||||
for rows.Next() {
|
||||
item, err := scanPermissionUser(rows)
|
||||
if err != nil {
|
||||
return permissionuser.ListPermissionUserDTO{}, err
|
||||
}
|
||||
items = append(items, item)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return permissionuser.ListPermissionUserDTO{}, err
|
||||
}
|
||||
|
||||
return permissionuser.ListPermissionUserDTO{Count: count, Items: items}, nil
|
||||
}
|
||||
|
||||
func buildListQuery(filter permissionuser.ListFilter) (whereClause string, args []interface{}) {
|
||||
var conditions []string
|
||||
|
||||
if filter.UserId != nil {
|
||||
args = append(args, *filter.UserId)
|
||||
conditions = append(conditions, fmt.Sprintf("pu.user_id = $%d", len(args)))
|
||||
}
|
||||
|
||||
if filter.PermissionName != "" {
|
||||
args = append(args, likePattern(filter.PermissionName))
|
||||
conditions = append(conditions, fmt.Sprintf("p.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 permissionuser.CreatePermissionUserDTO) (permissionuser.PermissionUserDTO, error) {
|
||||
query := `
|
||||
WITH inserted AS (
|
||||
INSERT INTO permission_user (permission_id, user_id)
|
||||
VALUES ($1, $2)
|
||||
RETURNING id, permission_id, user_id, created_at, updated_at
|
||||
)
|
||||
SELECT inserted.id, inserted.permission_id, p.name, inserted.user_id, u.name, inserted.created_at, inserted.updated_at
|
||||
FROM inserted
|
||||
JOIN permissions p ON p.id = inserted.permission_id
|
||||
JOIN users u ON u.id = inserted.user_id`
|
||||
|
||||
row := r.client.QueryRow(ctx, query, dto.PermissionId, dto.UserId)
|
||||
return scanPermissionUser(row)
|
||||
}
|
||||
|
||||
func (r *repository) Delete(ctx context.Context, id int64) error {
|
||||
tag, err := r.client.Exec(ctx, `DELETE FROM permission_user WHERE id = $1`, id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if tag.RowsAffected() == 0 {
|
||||
return pgx.ErrNoRows
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
type scannable interface {
|
||||
Scan(dest ...interface{}) error
|
||||
}
|
||||
|
||||
func scanPermissionUser(row scannable) (permissionuser.PermissionUserDTO, error) {
|
||||
var item permissionuser.PermissionUserDTO
|
||||
|
||||
err := row.Scan(
|
||||
&item.Id, &item.PermissionId, &item.PermissionName, &item.UserId, &item.UserName, &item.CreatedAt, &item.UpdatedAt,
|
||||
)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return permissionuser.PermissionUserDTO{}, err
|
||||
}
|
||||
if err != nil {
|
||||
return permissionuser.PermissionUserDTO{}, err
|
||||
}
|
||||
return item, nil
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
package permissionuser
|
||||
|
||||
import "time"
|
||||
|
||||
type PermissionUserDTO struct {
|
||||
Id int64 `json:"id"`
|
||||
UserId int64 `json:"userId"`
|
||||
UserName string `json:"userName"`
|
||||
PermissionId int64 `json:"permissionId"`
|
||||
PermissionName string `json:"permissionName"`
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
UpdatedAt time.Time `json:"updatedAt"`
|
||||
}
|
||||
|
||||
type ListPermissionUserDTO struct {
|
||||
Count int64 `json:"count"`
|
||||
Items []PermissionUserDTO `json:"items"`
|
||||
}
|
||||
|
||||
type ListFilter struct {
|
||||
UserId *int64
|
||||
PermissionName string
|
||||
}
|
||||
|
||||
type CreatePermissionUserDTO struct {
|
||||
PermissionId int64 `json:"permissionId" binding:"required"`
|
||||
UserId int64 `json:"userId" binding:"required"`
|
||||
}
|
||||
@@ -0,0 +1,152 @@
|
||||
package permissionuser
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"online-back/internal/appresult"
|
||||
"online-back/internal/handlers"
|
||||
"online-back/pkg/logging"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/jackc/pgx/v4"
|
||||
)
|
||||
|
||||
const baseURL = "/permission-users"
|
||||
|
||||
type handler struct {
|
||||
logger *logging.Logger
|
||||
repository Repository
|
||||
}
|
||||
|
||||
func NewHandler(logger *logging.Logger, repository Repository) handlers.Handler {
|
||||
return &handler{logger: logger, repository: repository}
|
||||
}
|
||||
|
||||
func (h *handler) Register(router *gin.RouterGroup) {
|
||||
group := router.Group(baseURL, appresult.JwtTokenCheck())
|
||||
group.GET("", h.list)
|
||||
group.POST("", h.create)
|
||||
group.DELETE("/:id", h.delete)
|
||||
}
|
||||
|
||||
// list godoc
|
||||
// @Summary List permission users
|
||||
// @Description Returns the authenticated user's permission-user assignments with the related user and permission
|
||||
// @Tags permission-users
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param permission_name query string false "Filter by permission name"
|
||||
// @Success 200 {object} appresult.AppSuccess
|
||||
// @Failure 401 {object} appresult.AppError
|
||||
// @Failure 500 {object} appresult.AppError
|
||||
// @Router /permission-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,
|
||||
PermissionName: strings.TrimSpace(c.Query("permission_name")),
|
||||
}
|
||||
|
||||
result, err := h.repository.List(c.Request.Context(), filter)
|
||||
if err != nil {
|
||||
h.logger.Errorf("list permission users failed: %v", err)
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, appresult.SuccessWithData(result))
|
||||
}
|
||||
|
||||
// create godoc
|
||||
// @Summary Assign user to permission
|
||||
// @Description Creates a permission-user assignment
|
||||
// @Tags permission-users
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param body body CreatePermissionUserDTO true "Permission-user payload"
|
||||
// @Success 201 {object} appresult.AppSuccess
|
||||
// @Failure 400 {object} appresult.AppError
|
||||
// @Failure 500 {object} appresult.AppError
|
||||
// @Router /permission-users [post]
|
||||
func (h *handler) create(c *gin.Context) {
|
||||
var dto CreatePermissionUserDTO
|
||||
if err := c.ShouldBindJSON(&dto); err != nil {
|
||||
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
|
||||
return
|
||||
}
|
||||
|
||||
item, err := h.repository.Create(c.Request.Context(), dto)
|
||||
if err != nil {
|
||||
h.logger.Errorf("create permission user failed: %v", err)
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusCreated, appresult.SuccessWithData(item))
|
||||
}
|
||||
|
||||
// delete godoc
|
||||
// @Summary Remove user from permission
|
||||
// @Description Deletes a permission-user assignment
|
||||
// @Tags permission-users
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param id path int true "Permission-user ID"
|
||||
// @Success 200 {object} appresult.AppSuccess
|
||||
// @Failure 400 {object} appresult.AppError
|
||||
// @Failure 404 {object} appresult.AppError
|
||||
// @Failure 500 {object} appresult.AppError
|
||||
// @Router /permission-users/{id} [delete]
|
||||
func (h *handler) delete(c *gin.Context) {
|
||||
id, ok := parseID(c.Param("id"))
|
||||
if !ok {
|
||||
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
|
||||
return
|
||||
}
|
||||
|
||||
if err := h.repository.Delete(c.Request.Context(), id); errors.Is(err, pgx.ErrNoRows) {
|
||||
c.JSON(http.StatusNotFound, appresult.ErrNotFound)
|
||||
return
|
||||
} else if err != nil {
|
||||
h.logger.Errorf("delete permission user failed: %v", err)
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, appresult.SuccessWithData("permission user removed"))
|
||||
}
|
||||
|
||||
func parseID(raw string) (int64, bool) {
|
||||
id, err := strconv.ParseInt(raw, 10, 64)
|
||||
if err != nil || id <= 0 {
|
||||
return 0, false
|
||||
}
|
||||
return id, true
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
package permissionuser
|
||||
|
||||
import "context"
|
||||
|
||||
type Repository interface {
|
||||
List(ctx context.Context, filter ListFilter) (ListPermissionUserDTO, error)
|
||||
Create(ctx context.Context, dto CreatePermissionUserDTO) (PermissionUserDTO, error)
|
||||
Delete(ctx context.Context, id int64) error
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
package rbac
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strconv"
|
||||
|
||||
"online-back/internal/appresult"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// RequirePermission returns a gin middleware that 403s unless the
|
||||
// authenticated user (set by appresult.JwtTokenCheck, which must run first)
|
||||
// has been directly granted the given permission code. Not currently
|
||||
// attached to any route.
|
||||
func RequirePermission(service *Service, code string) gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
rawID, exists := c.Get("id")
|
||||
if !exists {
|
||||
c.AbortWithStatusJSON(http.StatusForbidden, appresult.ErrUnauthorized)
|
||||
return
|
||||
}
|
||||
|
||||
userID, err := strconv.ParseInt(rawID.(string), 10, 64)
|
||||
if err != nil {
|
||||
c.AbortWithStatusJSON(http.StatusForbidden, appresult.ErrUnauthorized)
|
||||
return
|
||||
}
|
||||
|
||||
granted, err := service.HasPermission(c.Request.Context(), userID, code)
|
||||
if err != nil || !granted {
|
||||
c.AbortWithStatusJSON(http.StatusForbidden, appresult.ErrUnauthorized)
|
||||
return
|
||||
}
|
||||
|
||||
c.Next()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
// Package rbac provides permission-check capability on top of the existing
|
||||
// permissions/permission_user tables. It is not wired into any route yet —
|
||||
// today every route is still gated only by appresult.JwtTokenCheck()'s
|
||||
// admin-claim check. RequirePermission is available for routes to opt into
|
||||
// once permission data is populated and specific routes are chosen.
|
||||
//
|
||||
// Note: the schema has no role_permission pivot table, so role-based
|
||||
// permission resolution isn't possible yet — HasPermission only resolves
|
||||
// permissions granted directly via permission_user.
|
||||
package rbac
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"online-back/pkg/client/postgresql"
|
||||
)
|
||||
|
||||
type Service struct {
|
||||
client postgresql.Client
|
||||
}
|
||||
|
||||
func NewService(client postgresql.Client) *Service {
|
||||
return &Service{client: client}
|
||||
}
|
||||
|
||||
// HasPermission reports whether userID has been directly granted the
|
||||
// permission identified by code (permissions.code) via permission_user.
|
||||
func (s *Service) HasPermission(ctx context.Context, userID int64, code string) (bool, error) {
|
||||
const query = `
|
||||
SELECT EXISTS (
|
||||
SELECT 1
|
||||
FROM permission_user pu
|
||||
JOIN permissions p ON p.id = pu.permission_id
|
||||
WHERE pu.user_id = $1 AND p.code = $2
|
||||
)`
|
||||
|
||||
var granted bool
|
||||
if err := s.client.QueryRow(ctx, query, userID, code).Scan(&granted); err != nil {
|
||||
return false, err
|
||||
}
|
||||
return granted, nil
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
package rbac
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
|
||||
"github.com/jackc/pgconn"
|
||||
"github.com/jackc/pgx/v4"
|
||||
)
|
||||
|
||||
type fakeClient struct {
|
||||
granted bool
|
||||
}
|
||||
|
||||
func (f *fakeClient) Exec(ctx context.Context, sql string, args ...interface{}) (pgconn.CommandTag, error) {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
func (f *fakeClient) Query(ctx context.Context, sql string, args ...interface{}) (pgx.Rows, error) {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
func (f *fakeClient) QueryRow(ctx context.Context, sql string, args ...interface{}) pgx.Row {
|
||||
return fakeRow{granted: f.granted}
|
||||
}
|
||||
|
||||
func (f *fakeClient) Begin(ctx context.Context) (pgx.Tx, error) {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
type fakeRow struct {
|
||||
granted bool
|
||||
}
|
||||
|
||||
func (r fakeRow) Scan(dest ...interface{}) error {
|
||||
*dest[0].(*bool) = r.granted
|
||||
return nil
|
||||
}
|
||||
|
||||
func TestHasPermission(t *testing.T) {
|
||||
granted, err := NewService(&fakeClient{granted: true}).HasPermission(context.Background(), 1, "province.write")
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
if !granted {
|
||||
t.Fatal("expected permission to be granted")
|
||||
}
|
||||
|
||||
granted, err = NewService(&fakeClient{granted: false}).HasPermission(context.Background(), 1, "province.write")
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
if granted {
|
||||
t.Fatal("expected permission to not be granted")
|
||||
}
|
||||
}
|
||||
@@ -6,20 +6,26 @@ import (
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"online-back/internal/admin/role"
|
||||
"online-back/internal/identity/role"
|
||||
"online-back/pkg/client/postgresql"
|
||||
"online-back/pkg/logging"
|
||||
"online-back/pkg/repository/genericrepo"
|
||||
|
||||
"github.com/jackc/pgx/v4"
|
||||
)
|
||||
|
||||
type repository struct {
|
||||
client postgresql.Client
|
||||
logger *logging.Logger
|
||||
client postgresql.Client
|
||||
generic *genericrepo.Repository[role.RoleDTO]
|
||||
logger *logging.Logger
|
||||
}
|
||||
|
||||
func NewRepository(client postgresql.Client, logger *logging.Logger) role.Repository {
|
||||
return &repository{client: client, logger: logger}
|
||||
return &repository{
|
||||
client: client,
|
||||
generic: genericrepo.New(client, "roles r", roleColumns, scanRole),
|
||||
logger: logger,
|
||||
}
|
||||
}
|
||||
|
||||
const roleColumns = `r.id, r.code, r.name, r.guard_name, r.created_at, r.updated_at`
|
||||
@@ -27,45 +33,17 @@ const roleColumns = `r.id, r.code, r.name, r.guard_name, r.created_at, r.updated
|
||||
const roleReturningColumns = `id, code, name, guard_name, created_at, updated_at`
|
||||
|
||||
func (r *repository) List(ctx context.Context, filter role.ListFilter) (role.ListRoleDTO, error) {
|
||||
fromClause, whereClause, args := buildListQuery(filter)
|
||||
whereClause, args := buildListQuery(filter)
|
||||
|
||||
var count int64
|
||||
if err := r.client.QueryRow(ctx, `SELECT COUNT(*) `+fromClause+whereClause, args...).Scan(&count); err != nil {
|
||||
return role.ListRoleDTO{}, err
|
||||
}
|
||||
|
||||
offset := (filter.Page - 1) * filter.Limit
|
||||
limitPlaceholder := len(args) + 1
|
||||
offsetPlaceholder := len(args) + 2
|
||||
listQuery := fmt.Sprintf(
|
||||
`SELECT %s%s%s ORDER BY r.id LIMIT $%d OFFSET $%d`,
|
||||
roleColumns, fromClause, whereClause, limitPlaceholder, offsetPlaceholder,
|
||||
)
|
||||
|
||||
rows, err := r.client.Query(ctx, listQuery, append(args, filter.Limit, offset)...)
|
||||
items, count, err := r.generic.List(ctx, whereClause, args, filter.Page, filter.Limit, "id")
|
||||
if err != nil {
|
||||
return role.ListRoleDTO{}, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var items []role.RoleDTO
|
||||
for rows.Next() {
|
||||
item, err := scanRole(rows)
|
||||
if err != nil {
|
||||
return role.ListRoleDTO{}, err
|
||||
}
|
||||
items = append(items, item)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return role.ListRoleDTO{}, err
|
||||
}
|
||||
|
||||
return role.ListRoleDTO{Count: count, Roles: items}, nil
|
||||
}
|
||||
|
||||
func buildListQuery(filter role.ListFilter) (fromClause, whereClause string, args []interface{}) {
|
||||
fromClause = ` FROM roles r`
|
||||
|
||||
func buildListQuery(filter role.ListFilter) (whereClause string, args []interface{}) {
|
||||
var conditions []string
|
||||
if filter.RoleName != "" {
|
||||
args = append(args, likePattern(filter.RoleName))
|
||||
@@ -74,10 +52,10 @@ func buildListQuery(filter role.ListFilter) (fromClause, whereClause string, arg
|
||||
}
|
||||
|
||||
if len(conditions) == 0 {
|
||||
return fromClause, "", args
|
||||
return "", args
|
||||
}
|
||||
|
||||
return fromClause, " WHERE " + strings.Join(conditions, " AND "), args
|
||||
return " WHERE " + strings.Join(conditions, " AND "), args
|
||||
}
|
||||
|
||||
func likePattern(term string) string {
|
||||
@@ -88,12 +66,7 @@ func likePattern(term string) string {
|
||||
}
|
||||
|
||||
func (r *repository) GetByID(ctx context.Context, id int64) (role.RoleDTO, error) {
|
||||
query := fmt.Sprintf(`SELECT %s FROM roles r WHERE r.id = $1`, roleColumns)
|
||||
item, err := scanRole(r.client.QueryRow(ctx, query, id))
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return role.RoleDTO{}, err
|
||||
}
|
||||
return item, err
|
||||
return r.generic.GetByID(ctx, id)
|
||||
}
|
||||
|
||||
func (r *repository) Create(ctx context.Context, dto role.CreateRoleDTO) (role.RoleDTO, error) {
|
||||
@@ -121,21 +94,10 @@ func (r *repository) Update(ctx context.Context, id int64, dto role.UpdateRoleDT
|
||||
}
|
||||
|
||||
func (r *repository) Delete(ctx context.Context, id int64) error {
|
||||
tag, err := r.client.Exec(ctx, `DELETE FROM roles WHERE id = $1`, id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if tag.RowsAffected() == 0 {
|
||||
return pgx.ErrNoRows
|
||||
}
|
||||
return nil
|
||||
return r.generic.Delete(ctx, id)
|
||||
}
|
||||
|
||||
type scannable interface {
|
||||
Scan(dest ...interface{}) error
|
||||
}
|
||||
|
||||
func scanRole(row scannable) (role.RoleDTO, error) {
|
||||
func scanRole(row genericrepo.Scanner) (role.RoleDTO, error) {
|
||||
var item role.RoleDTO
|
||||
if err := row.Scan(
|
||||
&item.Id, &item.Code, &item.Name, &item.GuardName, &item.CreatedAt, &item.UpdatedAt,
|
||||
File renamed without changes.
File renamed without changes.
File renamed without changes.
@@ -0,0 +1,132 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"online-back/internal/identity/roleusers"
|
||||
"online-back/pkg/client/postgresql"
|
||||
"online-back/pkg/logging"
|
||||
|
||||
"github.com/jackc/pgx/v4"
|
||||
)
|
||||
|
||||
type repository struct {
|
||||
client postgresql.Client
|
||||
logger *logging.Logger
|
||||
}
|
||||
|
||||
func NewRepository(client postgresql.Client, logger *logging.Logger) roleusers.Repository {
|
||||
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)
|
||||
RETURNING id, role_id, user_id, created_at, updated_at
|
||||
)
|
||||
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`
|
||||
|
||||
row := r.client.QueryRow(ctx, query, dto.RoleId, dto.UserId)
|
||||
return scanRoleUser(row)
|
||||
}
|
||||
|
||||
func (r *repository) Delete(ctx context.Context, id int64) error {
|
||||
tag, err := r.client.Exec(ctx, `DELETE FROM role_user WHERE id = $1`, id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if tag.RowsAffected() == 0 {
|
||||
return pgx.ErrNoRows
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
type scannable interface {
|
||||
Scan(dest ...interface{}) error
|
||||
}
|
||||
|
||||
func scanRoleUser(row scannable) (roleusers.RoleUserDTO, error) {
|
||||
var item roleusers.RoleUserDTO
|
||||
|
||||
err := row.Scan(
|
||||
&item.Id, &item.RoleId, &item.RoleName, &item.UserId, &item.UserName, &item.CreatedAt, &item.UpdatedAt,
|
||||
)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return roleusers.RoleUserDTO{}, err
|
||||
}
|
||||
if err != nil {
|
||||
return roleusers.RoleUserDTO{}, err
|
||||
}
|
||||
return item, nil
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
package roleusers
|
||||
|
||||
import "time"
|
||||
|
||||
type RoleUserDTO struct {
|
||||
Id int64 `json:"id"`
|
||||
UserId int64 `json:"userId"`
|
||||
UserName string `json:"userName"`
|
||||
RoleId int64 `json:"roleId"`
|
||||
RoleName string `json:"roleName"`
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
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"`
|
||||
}
|
||||
@@ -0,0 +1,152 @@
|
||||
package roleusers
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"online-back/internal/appresult"
|
||||
"online-back/internal/handlers"
|
||||
"online-back/pkg/logging"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/jackc/pgx/v4"
|
||||
)
|
||||
|
||||
const baseURL = "/role-users"
|
||||
|
||||
type handler struct {
|
||||
logger *logging.Logger
|
||||
repository Repository
|
||||
}
|
||||
|
||||
func NewHandler(logger *logging.Logger, repository Repository) handlers.Handler {
|
||||
return &handler{logger: logger, repository: repository}
|
||||
}
|
||||
|
||||
func (h *handler) Register(router *gin.RouterGroup) {
|
||||
group := router.Group(baseURL, appresult.JwtTokenCheck())
|
||||
group.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
|
||||
// @Tags role-users
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param body body CreateRoleUserDTO true "Role-user payload"
|
||||
// @Success 201 {object} appresult.AppSuccess
|
||||
// @Failure 400 {object} appresult.AppError
|
||||
// @Failure 500 {object} appresult.AppError
|
||||
// @Router /role-users [post]
|
||||
func (h *handler) create(c *gin.Context) {
|
||||
var dto CreateRoleUserDTO
|
||||
if err := c.ShouldBindJSON(&dto); err != nil {
|
||||
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
|
||||
return
|
||||
}
|
||||
|
||||
item, err := h.repository.Create(c.Request.Context(), dto)
|
||||
if err != nil {
|
||||
h.logger.Errorf("create role user failed: %v", err)
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusCreated, appresult.SuccessWithData(item))
|
||||
}
|
||||
|
||||
// delete godoc
|
||||
// @Summary Remove user from role
|
||||
// @Description Deletes a role-user assignment
|
||||
// @Tags role-users
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param id path int true "Role-user ID"
|
||||
// @Success 200 {object} appresult.AppSuccess
|
||||
// @Failure 400 {object} appresult.AppError
|
||||
// @Failure 404 {object} appresult.AppError
|
||||
// @Failure 500 {object} appresult.AppError
|
||||
// @Router /role-users/{id} [delete]
|
||||
func (h *handler) delete(c *gin.Context) {
|
||||
id, ok := parseID(c.Param("id"))
|
||||
if !ok {
|
||||
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
|
||||
return
|
||||
}
|
||||
|
||||
if err := h.repository.Delete(c.Request.Context(), id); errors.Is(err, pgx.ErrNoRows) {
|
||||
c.JSON(http.StatusNotFound, appresult.ErrNotFound)
|
||||
return
|
||||
} else if err != nil {
|
||||
h.logger.Errorf("delete role user failed: %v", err)
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, appresult.SuccessWithData("role user removed"))
|
||||
}
|
||||
|
||||
func parseID(raw string) (int64, bool) {
|
||||
id, err := strconv.ParseInt(raw, 10, 64)
|
||||
if err != nil || id <= 0 {
|
||||
return 0, false
|
||||
}
|
||||
return id, true
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
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
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
// Package identity groups authentication, users, and RBAC (roles,
|
||||
// permissions, and their user/branch assignments) under one bounded
|
||||
// context, replacing the flat internal/admin/* listing.
|
||||
package identity
|
||||
|
||||
import (
|
||||
"online-back/internal/handlers"
|
||||
"online-back/internal/identity/activitylog"
|
||||
activitylogdb "online-back/internal/identity/activitylog/db"
|
||||
"online-back/internal/identity/auth"
|
||||
authdb "online-back/internal/identity/auth/db"
|
||||
"online-back/internal/identity/permission"
|
||||
permissiondb "online-back/internal/identity/permission/db"
|
||||
"online-back/internal/identity/permissionuser"
|
||||
permissionuserdb "online-back/internal/identity/permissionuser/db"
|
||||
"online-back/internal/identity/role"
|
||||
roledb "online-back/internal/identity/role/db"
|
||||
"online-back/internal/identity/roleusers"
|
||||
roleusersdb "online-back/internal/identity/roleusers/db"
|
||||
"online-back/internal/identity/user"
|
||||
userdb "online-back/internal/identity/user/db"
|
||||
"online-back/internal/identity/userbranch"
|
||||
userbranchdb "online-back/internal/identity/userbranch/db"
|
||||
"online-back/pkg/client/postgresql"
|
||||
"online-back/pkg/logging"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// Register wires every identity module's handler onto router.
|
||||
func Register(router *gin.RouterGroup, client postgresql.Client, logger *logging.Logger) {
|
||||
for _, h := range Handlers(client, logger) {
|
||||
h.Register(router)
|
||||
}
|
||||
}
|
||||
|
||||
func Handlers(client postgresql.Client, logger *logging.Logger) []handlers.Handler {
|
||||
return []handlers.Handler{
|
||||
activitylog.NewHandler(logger, activitylogdb.NewRepository(client, logger)),
|
||||
auth.NewHandler(logger, authdb.NewRepository(client, logger)),
|
||||
user.NewHandler(logger, userdb.NewRepository(client, logger)),
|
||||
role.NewHandler(logger, roledb.NewRepository(client, logger)),
|
||||
permission.NewHandler(logger, permissiondb.NewRepository(client, logger)),
|
||||
roleusers.NewHandler(logger, roleusersdb.NewRepository(client, logger)),
|
||||
permissionuser.NewHandler(logger, permissionuserdb.NewRepository(client, logger)),
|
||||
userbranch.NewHandler(logger, userbranchdb.NewRepository(client, logger)),
|
||||
}
|
||||
}
|
||||
@@ -7,7 +7,7 @@ import (
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"online-back/internal/admin/user"
|
||||
"online-back/internal/identity/user"
|
||||
"online-back/pkg/client/postgresql"
|
||||
"online-back/pkg/logging"
|
||||
|
||||
@@ -24,9 +24,9 @@ func NewRepository(client postgresql.Client, logger *logging.Logger) user.Reposi
|
||||
return &repository{client: client, logger: logger}
|
||||
}
|
||||
|
||||
const userColumns = `u.id, u.email, u.fullname, u.username, u.phone_number, u.avatar, u.social_media, u.light_mode, u.role, u.active, u.created_at, u.updated_at`
|
||||
const userColumns = `u.id, u.email, u.name, u.first_name, u.last_name, u.username, u.phone, u.avatar, u.social_media, u.light_mode, u.role, u.active, u.created_at, u.updated_at`
|
||||
|
||||
const userReturningColumns = `id, email, fullname, username, phone_number, avatar, social_media, light_mode, role, active, created_at, updated_at`
|
||||
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)
|
||||
@@ -66,7 +66,11 @@ func (r *repository) List(ctx context.Context, filter user.ListFilter) (user.Lis
|
||||
}
|
||||
|
||||
func buildListQuery(filter user.ListFilter) (fromClause, whereClause string, args []interface{}) {
|
||||
fromClause = ` FROM users u`
|
||||
return buildFilteredListQuery(filter, "")
|
||||
}
|
||||
|
||||
func buildFilteredListQuery(filter user.ListFilter, role string) (fromClause, whereClause string, args []interface{}) {
|
||||
fromClause = ` FROM users u `
|
||||
|
||||
var conditions []string
|
||||
if filter.Username != "" {
|
||||
@@ -74,6 +78,11 @@ func buildListQuery(filter user.ListFilter) (fromClause, whereClause string, arg
|
||||
n := len(args)
|
||||
conditions = append(conditions, fmt.Sprintf(`u.username ILIKE $%d`, n))
|
||||
}
|
||||
if role != "" {
|
||||
args = append(args, role)
|
||||
n := len(args)
|
||||
conditions = append(conditions, fmt.Sprintf(`u.role = $%d`, n))
|
||||
}
|
||||
|
||||
if len(conditions) == 0 {
|
||||
return fromClause, "", args
|
||||
@@ -89,6 +98,43 @@ func likePattern(term string) string {
|
||||
return "%" + term + "%"
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
|
||||
func (r *repository) GetByID(ctx context.Context, id int64) (user.UserDTO, error) {
|
||||
query := fmt.Sprintf(`SELECT %s FROM users u WHERE u.id = $1`, userColumns)
|
||||
item, err := scanUser(r.client.QueryRow(ctx, query, id))
|
||||
@@ -115,12 +161,12 @@ func (r *repository) Create(ctx context.Context, dto user.CreateUserDTO) (user.U
|
||||
}
|
||||
|
||||
query := fmt.Sprintf(`
|
||||
INSERT INTO users (email, password, fullname, username, phone_number, avatar, social_media, light_mode, role, active)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)
|
||||
INSERT INTO users (email, password, name, first_name, last_name, username, phone, avatar, social_media, light_mode, role, active)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12)
|
||||
RETURNING %s`, userReturningColumns)
|
||||
|
||||
return scanUser(r.client.QueryRow(ctx, query,
|
||||
dto.Email, hashedPassword, dto.Fullname, dto.Username, dto.PhoneNumber, dto.Avatar, socialMedia, dto.LightMode, dto.Role, active,
|
||||
dto.Email, hashedPassword, dto.Name, dto.FirstName, dto.LastName, dto.Username, dto.Phone, dto.Avatar, socialMedia, dto.LightMode, dto.Role, active,
|
||||
))
|
||||
}
|
||||
|
||||
@@ -132,14 +178,14 @@ func (r *repository) Update(ctx context.Context, id int64, dto user.UpdateUserDT
|
||||
|
||||
query := fmt.Sprintf(`
|
||||
UPDATE users SET
|
||||
email = $1, fullname = $2, username = $3, phone_number = $4, avatar = $5,
|
||||
social_media = $6, light_mode = $7, role = $8, active = $9,
|
||||
email = $1, name = $2, first_name = $3, last_name = $4, username = $5, phone = $6, avatar = $7,
|
||||
social_media = $8, light_mode = $9, role = $10, active = $11,
|
||||
updated_at = (CURRENT_TIMESTAMP AT TIME ZONE 'UTC')
|
||||
WHERE id = $10
|
||||
WHERE id = $12
|
||||
RETURNING %s`, userReturningColumns)
|
||||
|
||||
item, err := scanUser(r.client.QueryRow(ctx, query,
|
||||
dto.Email, dto.Fullname, dto.Username, dto.PhoneNumber, dto.Avatar, socialMedia, dto.LightMode, dto.Role, dto.Active, id,
|
||||
dto.Email, dto.Name, dto.FirstName, dto.LastName, dto.Username, dto.Phone, dto.Avatar, socialMedia, dto.LightMode, dto.Role, dto.Active, id,
|
||||
))
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return user.UserDTO{}, err
|
||||
@@ -166,7 +212,7 @@ func scanUser(row scannable) (user.UserDTO, error) {
|
||||
var item user.UserDTO
|
||||
var socialMedia []byte
|
||||
if err := row.Scan(
|
||||
&item.Id, &item.Email, &item.Fullname, &item.Username, &item.PhoneNumber, &item.Avatar,
|
||||
&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,
|
||||
); err != nil {
|
||||
return user.UserDTO{}, err
|
||||
@@ -11,9 +11,11 @@ type SocialMedia struct {
|
||||
type UserDTO struct {
|
||||
Id int64 `json:"id"`
|
||||
Email string `json:"email"`
|
||||
Fullname string `json:"fullname"`
|
||||
Name string `json:"name"`
|
||||
FirstName string `json:"firstName"`
|
||||
LastName string `json:"lastName"`
|
||||
Username string `json:"username"`
|
||||
PhoneNumber string `json:"phoneNumber"`
|
||||
Phone string `json:"phone"`
|
||||
Avatar string `json:"avatar"`
|
||||
SocialMedia SocialMedia `json:"socialMedia"`
|
||||
LightMode int `json:"lightMode"`
|
||||
@@ -26,9 +28,11 @@ type UserDTO struct {
|
||||
type CreateUserDTO struct {
|
||||
Email string `json:"email" binding:"required"`
|
||||
Password string `json:"password" binding:"required"`
|
||||
Fullname string `json:"fullname" binding:"required"`
|
||||
Name string `json:"name" binding:"required"`
|
||||
FirstName string `json:"firstName"`
|
||||
LastName string `json:"lastName"`
|
||||
Username string `json:"username" binding:"required"`
|
||||
PhoneNumber string `json:"phoneNumber"`
|
||||
Phone string `json:"phone"`
|
||||
Avatar string `json:"avatar"`
|
||||
SocialMedia SocialMedia `json:"socialMedia"`
|
||||
LightMode int `json:"lightMode"`
|
||||
@@ -38,9 +42,11 @@ type CreateUserDTO struct {
|
||||
|
||||
type UpdateUserDTO struct {
|
||||
Email string `json:"email" binding:"required"`
|
||||
Fullname string `json:"fullname" binding:"required"`
|
||||
Name string `json:"name" binding:"required"`
|
||||
FirstName string `json:"firstName"`
|
||||
LastName string `json:"lastName"`
|
||||
Username string `json:"username" binding:"required"`
|
||||
PhoneNumber string `json:"phoneNumber"`
|
||||
Phone string `json:"phone"`
|
||||
Avatar string `json:"avatar"`
|
||||
SocialMedia SocialMedia `json:"socialMedia"`
|
||||
LightMode int `json:"lightMode"`
|
||||
@@ -0,0 +1,437 @@
|
||||
package user
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"online-back/internal/appresult"
|
||||
"online-back/internal/config"
|
||||
"online-back/internal/handlers"
|
||||
"online-back/pkg/logging"
|
||||
minioUpload "online-back/pkg/minio"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/jackc/pgx/v4"
|
||||
"github.com/minio/minio-go/v7"
|
||||
)
|
||||
|
||||
const (
|
||||
baseURL = "/users"
|
||||
fileUploadURL = "/file"
|
||||
fileURL = "/file/:id"
|
||||
)
|
||||
|
||||
type handler struct {
|
||||
logger *logging.Logger
|
||||
repository Repository
|
||||
}
|
||||
|
||||
func NewHandler(logger *logging.Logger, repository Repository) handlers.Handler {
|
||||
return &handler{logger: logger, repository: repository}
|
||||
}
|
||||
|
||||
func (h *handler) Register(router *gin.RouterGroup) {
|
||||
group := router.Group(baseURL, appresult.JwtTokenCheck())
|
||||
group.GET("", h.list)
|
||||
group.GET("/role", h.listUsersByRole)
|
||||
group.GET("/:id", h.getByID)
|
||||
group.POST("", h.create)
|
||||
group.PUT("/:id", h.update)
|
||||
group.DELETE("/:id", h.delete)
|
||||
|
||||
// Avatar/profile file storage — kept at the top-level /file path (not
|
||||
// nested under /users) to preserve the existing API contract; this used
|
||||
// to live in the auth handler purely incidentally.
|
||||
files := router.Group("", appresult.JwtTokenCheck())
|
||||
files.POST(fileUploadURL, h.fileUpload)
|
||||
files.GET(fileURL, h.getFile)
|
||||
files.DELETE(fileURL, h.deleteFile)
|
||||
}
|
||||
|
||||
// list godoc
|
||||
// @Summary List users
|
||||
// @Description Returns paginated users with optional filters
|
||||
// @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 [get]
|
||||
func (h *handler) list(c *gin.Context) {
|
||||
filter, ok := parseListFilter(c)
|
||||
if !ok {
|
||||
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
|
||||
return
|
||||
}
|
||||
|
||||
result, err := h.repository.List(c.Request.Context(), filter)
|
||||
if err != nil {
|
||||
h.logger.Errorf("list users failed: %v", err)
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, appresult.SuccessWithData(result))
|
||||
}
|
||||
|
||||
// listUsersByRole godoc
|
||||
// @Summary List users by role
|
||||
// @Description Returns paginated users filtered by role
|
||||
// @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
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
if err != nil {
|
||||
h.logger.Errorf("get user failed: %v", err)
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, appresult.SuccessWithData(item))
|
||||
}
|
||||
|
||||
// getByID godoc
|
||||
// @Summary Get user by ID
|
||||
// @Description Returns a single user
|
||||
// @Tags user
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param id path int true "User ID"
|
||||
// @Success 200 {object} appresult.AppSuccess
|
||||
// @Failure 400 {object} appresult.AppError
|
||||
// @Failure 404 {object} appresult.AppError
|
||||
// @Failure 500 {object} appresult.AppError
|
||||
// @Router /users/{id} [get]
|
||||
func (h *handler) getByID(c *gin.Context) {
|
||||
id, ok := parseID(c.Param("id"))
|
||||
if !ok {
|
||||
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
|
||||
return
|
||||
}
|
||||
|
||||
item, err := h.repository.GetByID(c.Request.Context(), id)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
c.JSON(http.StatusNotFound, appresult.ErrNotFound)
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
h.logger.Errorf("get user failed: %v", err)
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, appresult.SuccessWithData(item))
|
||||
}
|
||||
|
||||
// create godoc
|
||||
// @Summary Create user
|
||||
// @Description Creates a new user
|
||||
// @Tags user
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param body body CreateUserDTO true "User payload"
|
||||
// @Success 201 {object} appresult.AppSuccess
|
||||
// @Failure 400 {object} appresult.AppError
|
||||
// @Failure 500 {object} appresult.AppError
|
||||
// @Router /users [post]
|
||||
func (h *handler) create(c *gin.Context) {
|
||||
var dto CreateUserDTO
|
||||
if err := c.ShouldBindJSON(&dto); err != nil {
|
||||
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
|
||||
return
|
||||
}
|
||||
|
||||
item, err := h.repository.Create(c.Request.Context(), dto)
|
||||
if err != nil {
|
||||
h.logger.Errorf("create user failed: %v", err)
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusCreated, appresult.SuccessWithData(item))
|
||||
}
|
||||
|
||||
// update godoc
|
||||
// @Summary Update user
|
||||
// @Description Updates an existing user
|
||||
// @Tags user
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param id path int true "User ID"
|
||||
// @Param body body UpdateUserDTO true "User payload"
|
||||
// @Success 200 {object} appresult.AppSuccess
|
||||
// @Failure 400 {object} appresult.AppError
|
||||
// @Failure 404 {object} appresult.AppError
|
||||
// @Failure 500 {object} appresult.AppError
|
||||
// @Router /users/{id} [put]
|
||||
func (h *handler) update(c *gin.Context) {
|
||||
id, ok := parseID(c.Param("id"))
|
||||
if !ok {
|
||||
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
|
||||
return
|
||||
}
|
||||
|
||||
var dto UpdateUserDTO
|
||||
if err := c.ShouldBindJSON(&dto); err != nil {
|
||||
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
|
||||
return
|
||||
}
|
||||
|
||||
item, err := h.repository.Update(c.Request.Context(), id, dto)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
c.JSON(http.StatusNotFound, appresult.ErrNotFound)
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
h.logger.Errorf("update user failed: %v", err)
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, appresult.SuccessWithData(item))
|
||||
}
|
||||
|
||||
// delete godoc
|
||||
// @Summary Delete user
|
||||
// @Description Deletes a user
|
||||
// @Tags user
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param id path int true "User ID"
|
||||
// @Success 200 {object} appresult.AppSuccess
|
||||
// @Failure 400 {object} appresult.AppError
|
||||
// @Failure 404 {object} appresult.AppError
|
||||
// @Failure 500 {object} appresult.AppError
|
||||
// @Router /users/{id} [delete]
|
||||
func (h *handler) delete(c *gin.Context) {
|
||||
id, ok := parseID(c.Param("id"))
|
||||
if !ok {
|
||||
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
|
||||
return
|
||||
}
|
||||
|
||||
if err := h.repository.Delete(c.Request.Context(), id); errors.Is(err, pgx.ErrNoRows) {
|
||||
c.JSON(http.StatusNotFound, appresult.ErrNotFound)
|
||||
return
|
||||
} else if err != nil {
|
||||
h.logger.Errorf("delete user failed: %v", err)
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, appresult.SuccessWithData("user removed"))
|
||||
}
|
||||
|
||||
func parseID(raw string) (int64, bool) {
|
||||
id, err := strconv.ParseInt(raw, 10, 64)
|
||||
if err != nil || id <= 0 {
|
||||
return 0, false
|
||||
}
|
||||
return id, true
|
||||
}
|
||||
|
||||
const (
|
||||
defaultPage = 1
|
||||
defaultLimit = 10
|
||||
maxLimit = 100
|
||||
)
|
||||
|
||||
func parseListFilter(c *gin.Context) (ListFilter, bool) {
|
||||
filter := ListFilter{
|
||||
Page: defaultPage,
|
||||
Limit: defaultLimit,
|
||||
}
|
||||
|
||||
if raw := c.Query("page"); raw != "" {
|
||||
page, err := strconv.Atoi(raw)
|
||||
if err != nil || page < 1 {
|
||||
return ListFilter{}, false
|
||||
}
|
||||
filter.Page = page
|
||||
}
|
||||
|
||||
if raw := c.Query("limit"); raw != "" {
|
||||
limit, err := strconv.Atoi(raw)
|
||||
if err != nil || limit < 1 || limit > maxLimit {
|
||||
return ListFilter{}, false
|
||||
}
|
||||
filter.Limit = limit
|
||||
}
|
||||
|
||||
if raw := strings.TrimSpace(c.Query("username")); raw != "" {
|
||||
filter.Username = raw
|
||||
}
|
||||
|
||||
return filter, true
|
||||
}
|
||||
|
||||
// fileUpload godoc
|
||||
// @Description file upload
|
||||
// @Tags file-upload
|
||||
//
|
||||
// @Accept multipart/form-data
|
||||
// @Produce json
|
||||
// @Param file formData file true "this is a test file"
|
||||
//
|
||||
// @Security BearerAuth
|
||||
// @Success 200 {object} appresult.AppSuccess
|
||||
// @Failure 400 {object} appresult.AppError
|
||||
// @Failure 500 {object} appresult.AppError
|
||||
// @Router /file [post]
|
||||
func (h *handler) fileUpload(c *gin.Context) {
|
||||
file, header, err := c.Request.FormFile("file")
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
|
||||
return
|
||||
}
|
||||
defer file.Close()
|
||||
|
||||
minioCfg := config.GetConfig().Minio
|
||||
minioClient, ok := h.connectMinio(c, minioCfg)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
ctx := c.Request.Context()
|
||||
if err := ensureBucket(ctx, minioClient, minioCfg.Bucket); err != nil {
|
||||
h.logger.Errorf("ensure minio bucket failed: %v", err)
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
objectName := fmt.Sprintf("%d%s", time.Now().UnixNano(), filepath.Ext(header.Filename))
|
||||
contentType := header.Header.Get("Content-Type")
|
||||
|
||||
if _, err := minioClient.PutObject(ctx, minioCfg.Bucket, objectName, file, header.Size, minio.PutObjectOptions{ContentType: contentType}); err != nil {
|
||||
h.logger.Errorf("upload file to minio failed: %v", err)
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, appresult.SuccessWithData(objectName))
|
||||
}
|
||||
|
||||
// getFile godoc
|
||||
// @Description download file
|
||||
// @Tags file-upload
|
||||
// @Produce octet-stream
|
||||
// @Param id path string true "object name"
|
||||
// @Security BearerAuth
|
||||
// @Success 200 {file} binary
|
||||
// @Failure 500 {object} appresult.AppError
|
||||
// @Router /file/{id} [get]
|
||||
func (h *handler) getFile(c *gin.Context) {
|
||||
id := c.Param("id")
|
||||
|
||||
minioCfg := config.GetConfig().Minio
|
||||
minioClient, ok := h.connectMinio(c, minioCfg)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
object, err := minioClient.GetObject(c.Request.Context(), minioCfg.Bucket, id, minio.GetObjectOptions{})
|
||||
if err != nil {
|
||||
h.logger.Errorf("get object from minio failed: %v", err)
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrNotAcceptable)
|
||||
return
|
||||
}
|
||||
defer object.Close()
|
||||
|
||||
content, err := io.ReadAll(object)
|
||||
if err != nil {
|
||||
h.logger.Errorf("read object from minio failed: %v", err)
|
||||
c.JSON(http.StatusNotFound, appresult.ErrNotFound)
|
||||
return
|
||||
}
|
||||
|
||||
c.Data(http.StatusOK, http.DetectContentType(content), content)
|
||||
}
|
||||
|
||||
// deleteFile godoc
|
||||
// @Description remove file
|
||||
// @Tags file-upload
|
||||
// @Produce json
|
||||
// @Param id path string true "object name"
|
||||
// @Security BearerAuth
|
||||
// @Success 200 {object} appresult.AppSuccess
|
||||
// @Failure 500 {object} appresult.AppError
|
||||
// @Router /file/{id} [delete]
|
||||
func (h *handler) deleteFile(c *gin.Context) {
|
||||
id := c.Param("id")
|
||||
|
||||
minioCfg := config.GetConfig().Minio
|
||||
minioClient, ok := h.connectMinio(c, minioCfg)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
if err := minioClient.RemoveObject(c.Request.Context(), minioCfg.Bucket, id, minio.RemoveObjectOptions{GovernanceBypass: true}); err != nil {
|
||||
h.logger.Errorf("remove object from minio failed: %v", err)
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, appresult.SuccessWithData("file removed"))
|
||||
}
|
||||
|
||||
// connectMinio opens a MinIO client, writing an error response and returning
|
||||
// ok=false if the connection fails so callers can bail out immediately.
|
||||
func (h *handler) connectMinio(c *gin.Context, cfg config.MinioConfig) (*minio.Client, bool) {
|
||||
client, err := minioUpload.Connect(cfg.Endpoint, cfg.AccessKey, cfg.SecretKey, cfg.UseSSL)
|
||||
if err != nil {
|
||||
h.logger.Errorf("minio connection failed: %v", err)
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return nil, false
|
||||
}
|
||||
return client, true
|
||||
}
|
||||
|
||||
func ensureBucket(ctx context.Context, client *minio.Client, bucket string) error {
|
||||
exists, err := client.BucketExists(ctx, bucket)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if exists {
|
||||
return nil
|
||||
}
|
||||
return client.MakeBucket(ctx, bucket, minio.MakeBucketOptions{})
|
||||
}
|
||||
@@ -5,6 +5,7 @@ import "context"
|
||||
type Repository interface {
|
||||
List(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)
|
||||
Update(ctx context.Context, id int64, dto UpdateUserDTO) (UserDTO, error)
|
||||
Delete(ctx context.Context, id int64) error
|
||||
@@ -0,0 +1,140 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"online-back/internal/identity/userbranch"
|
||||
"online-back/pkg/client/postgresql"
|
||||
"online-back/pkg/logging"
|
||||
|
||||
"github.com/jackc/pgx/v4"
|
||||
)
|
||||
|
||||
type repository struct {
|
||||
client postgresql.Client
|
||||
logger *logging.Logger
|
||||
}
|
||||
|
||||
func NewRepository(client postgresql.Client, logger *logging.Logger) userbranch.Repository {
|
||||
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)
|
||||
RETURNING id, branch_id, user_id, created_at, updated_at
|
||||
)
|
||||
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`
|
||||
|
||||
row := r.client.QueryRow(ctx, query, dto.BranchId, dto.UserId)
|
||||
return scanUserBranch(row)
|
||||
}
|
||||
|
||||
func (r *repository) Delete(ctx context.Context, id int64) error {
|
||||
tag, err := r.client.Exec(ctx, `DELETE FROM branch_user WHERE id = $1`, id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if tag.RowsAffected() == 0 {
|
||||
return pgx.ErrNoRows
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
type scannable interface {
|
||||
Scan(dest ...interface{}) error
|
||||
}
|
||||
|
||||
func scanUserBranch(row scannable) (userbranch.UserBranchDTO, error) {
|
||||
var item userbranch.UserBranchDTO
|
||||
var branchNameJSON []byte
|
||||
|
||||
err := row.Scan(
|
||||
&item.Id, &item.BranchId, &branchNameJSON, &item.UserId, &item.UserName, &item.CreatedAt, &item.UpdatedAt,
|
||||
)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return userbranch.UserBranchDTO{}, err
|
||||
}
|
||||
if err != nil {
|
||||
return userbranch.UserBranchDTO{}, err
|
||||
}
|
||||
if err := json.Unmarshal(branchNameJSON, &item.BranchName); err != nil {
|
||||
return userbranch.UserBranchDTO{}, err
|
||||
}
|
||||
return item, nil
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
package userbranch
|
||||
|
||||
import "time"
|
||||
|
||||
type LocalizedText struct {
|
||||
En string `json:"en"`
|
||||
Ru string `json:"ru"`
|
||||
Tm string `json:"tm"`
|
||||
}
|
||||
|
||||
type UserBranchDTO struct {
|
||||
Id int64 `json:"id"`
|
||||
UserId int64 `json:"userId"`
|
||||
UserName string `json:"userName"`
|
||||
BranchId int64 `json:"branchId"`
|
||||
BranchName LocalizedText `json:"branchName"`
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
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"`
|
||||
}
|
||||
@@ -0,0 +1,152 @@
|
||||
package userbranch
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"online-back/internal/appresult"
|
||||
"online-back/internal/handlers"
|
||||
"online-back/pkg/logging"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/jackc/pgx/v4"
|
||||
)
|
||||
|
||||
const baseURL = "/branch-users"
|
||||
|
||||
type handler struct {
|
||||
logger *logging.Logger
|
||||
repository Repository
|
||||
}
|
||||
|
||||
func NewHandler(logger *logging.Logger, repository Repository) handlers.Handler {
|
||||
return &handler{logger: logger, repository: repository}
|
||||
}
|
||||
|
||||
func (h *handler) Register(router *gin.RouterGroup) {
|
||||
group := router.Group(baseURL, appresult.JwtTokenCheck())
|
||||
group.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
|
||||
// @Tags branch-users
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param body body CreateUserBranchDTO true "Branch-user payload"
|
||||
// @Success 201 {object} appresult.AppSuccess
|
||||
// @Failure 400 {object} appresult.AppError
|
||||
// @Failure 500 {object} appresult.AppError
|
||||
// @Router /branch-users [post]
|
||||
func (h *handler) create(c *gin.Context) {
|
||||
var dto CreateUserBranchDTO
|
||||
if err := c.ShouldBindJSON(&dto); err != nil {
|
||||
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
|
||||
return
|
||||
}
|
||||
|
||||
item, err := h.repository.Create(c.Request.Context(), dto)
|
||||
if err != nil {
|
||||
h.logger.Errorf("create branch user failed: %v", err)
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusCreated, appresult.SuccessWithData(item))
|
||||
}
|
||||
|
||||
// delete godoc
|
||||
// @Summary Remove user from branch
|
||||
// @Description Deletes a branch-user assignment
|
||||
// @Tags branch-users
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param id path int true "Branch-user ID"
|
||||
// @Success 200 {object} appresult.AppSuccess
|
||||
// @Failure 400 {object} appresult.AppError
|
||||
// @Failure 404 {object} appresult.AppError
|
||||
// @Failure 500 {object} appresult.AppError
|
||||
// @Router /branch-users/{id} [delete]
|
||||
func (h *handler) delete(c *gin.Context) {
|
||||
id, ok := parseID(c.Param("id"))
|
||||
if !ok {
|
||||
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
|
||||
return
|
||||
}
|
||||
|
||||
if err := h.repository.Delete(c.Request.Context(), id); errors.Is(err, pgx.ErrNoRows) {
|
||||
c.JSON(http.StatusNotFound, appresult.ErrNotFound)
|
||||
return
|
||||
} else if err != nil {
|
||||
h.logger.Errorf("delete branch user failed: %v", err)
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, appresult.SuccessWithData("branch user removed"))
|
||||
}
|
||||
|
||||
func parseID(raw string) (int64, bool) {
|
||||
id, err := strconv.ParseInt(raw, 10, 64)
|
||||
if err != nil || id <= 0 {
|
||||
return 0, false
|
||||
}
|
||||
return id, true
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
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
|
||||
}
|
||||
@@ -0,0 +1,214 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"online-back/internal/lending/loanorders"
|
||||
"online-back/pkg/client/postgresql"
|
||||
"online-back/pkg/logging"
|
||||
"online-back/pkg/repository/genericrepo"
|
||||
)
|
||||
|
||||
type repository struct {
|
||||
client postgresql.Client
|
||||
generic *genericrepo.Repository[loanorders.LoanOrderDTO]
|
||||
logger *logging.Logger
|
||||
}
|
||||
|
||||
func NewRepository(client postgresql.Client, logger *logging.Logger) loanorders.Repository {
|
||||
return &repository{
|
||||
client: client,
|
||||
generic: genericrepo.New(client, "loan_orders", loanOrderColumnsSQL, scanLoanOrder),
|
||||
logger: logger,
|
||||
}
|
||||
}
|
||||
|
||||
// loanOrderWritableColumns lists every loan_orders column except id, created_at and
|
||||
// updated_at, in the exact order CreateLoanOrderDTO/UpdateLoanOrderDTO fields are read.
|
||||
var loanOrderWritableColumns = []string{
|
||||
"unique_id", "source", "user_id", "loan_type", "region", "branch_id",
|
||||
"customer_name", "customer_surname", "customer_patronic_name",
|
||||
"passport_address", "real_address", "passport_serie", "passport_id", "passport_given_at", "passport_given_by",
|
||||
"born_place", "born_at", "email", "phone", "phone_additional", "phone_home",
|
||||
"work_region", "work_province_id", "work_company", "work_company_accountant_number", "work_started_at",
|
||||
"work_salary", "work_position", "education", "marriage_status",
|
||||
"passport_one", "passport_two", "passport_three", "passport_four",
|
||||
"loan_amount", "card_number", "card_name", "card_month", "card_year",
|
||||
"guarantor_name", "guarantor_surname", "guarantor_patronic_name", "guarantor_passport_serie", "guarantor_passport_id",
|
||||
"guarantor_card_number", "guarantor_card_name", "guarantor_card_month", "guarantor_card_year", "guarantor_note",
|
||||
"guarantor_2_name", "guarantor_2_surname", "guarantor_2_patronic_name", "guarantor_2_passport_serie", "guarantor_2_passport_id",
|
||||
"guarantor_2_card_number", "guarantor_2_card_name", "guarantor_2_card_month", "guarantor_2_card_year", "guarantor_2_note",
|
||||
"loan_card_number", "loan_card_name", "loan_card_month", "loan_card_year",
|
||||
"loan_order_required_doc_id", "status", "satisfiable", "notes",
|
||||
}
|
||||
|
||||
var loanOrderColumns = append(append([]string{"id"}, loanOrderWritableColumns...), "created_at", "updated_at")
|
||||
|
||||
var loanOrderColumnsSQL = strings.Join(loanOrderColumns, ", ")
|
||||
|
||||
var loanOrderWritableColumnsSQL = strings.Join(loanOrderWritableColumns, ", ")
|
||||
|
||||
func resolveSource(source string) string {
|
||||
source = strings.TrimSpace(source)
|
||||
if source == "" {
|
||||
return "web"
|
||||
}
|
||||
return source
|
||||
}
|
||||
|
||||
func createArgs(dto loanorders.CreateLoanOrderDTO) []interface{} {
|
||||
return []interface{}{
|
||||
dto.UniqueId, resolveSource(dto.Source), dto.UserId, dto.LoanType, dto.Region, dto.BranchId,
|
||||
dto.CustomerName, dto.CustomerSurname, dto.CustomerPatronicName,
|
||||
dto.PassportAddress, dto.RealAddress, dto.PassportSerie, dto.PassportId, dto.PassportGivenAt, dto.PassportGivenBy,
|
||||
dto.BornPlace, dto.BornAt, dto.Email, dto.Phone, dto.PhoneAdditional, dto.PhoneHome,
|
||||
dto.WorkRegion, dto.WorkProvinceId, dto.WorkCompany, dto.WorkCompanyAccountantNumber, dto.WorkStartedAt,
|
||||
dto.WorkSalary, dto.WorkPosition, dto.Education, dto.MarriageStatus,
|
||||
dto.PassportOne, dto.PassportTwo, dto.PassportThree, dto.PassportFour,
|
||||
dto.LoanAmount, dto.CardNumber, dto.CardName, dto.CardMonth, dto.CardYear,
|
||||
dto.GuarantorName, dto.GuarantorSurname, dto.GuarantorPatronicName, dto.GuarantorPassportSerie, dto.GuarantorPassportId,
|
||||
dto.GuarantorCardNumber, dto.GuarantorCardName, dto.GuarantorCardMonth, dto.GuarantorCardYear, dto.GuarantorNote,
|
||||
dto.Guarantor2Name, dto.Guarantor2Surname, dto.Guarantor2PatronicName, dto.Guarantor2PassportSerie, dto.Guarantor2PassportId,
|
||||
dto.Guarantor2CardNumber, dto.Guarantor2CardName, dto.Guarantor2CardMonth, dto.Guarantor2CardYear, dto.Guarantor2Note,
|
||||
dto.LoanCardNumber, dto.LoanCardName, dto.LoanCardMonth, dto.LoanCardYear,
|
||||
dto.LoanOrderRequiredDocId, dto.Status, dto.Satisfiable, dto.Notes,
|
||||
}
|
||||
}
|
||||
|
||||
func updateArgs(dto loanorders.UpdateLoanOrderDTO) []interface{} {
|
||||
return []interface{}{
|
||||
dto.UniqueId, resolveSource(dto.Source), dto.UserId, dto.LoanType, dto.Region, dto.BranchId,
|
||||
dto.CustomerName, dto.CustomerSurname, dto.CustomerPatronicName,
|
||||
dto.PassportAddress, dto.RealAddress, dto.PassportSerie, dto.PassportId, dto.PassportGivenAt, dto.PassportGivenBy,
|
||||
dto.BornPlace, dto.BornAt, dto.Email, dto.Phone, dto.PhoneAdditional, dto.PhoneHome,
|
||||
dto.WorkRegion, dto.WorkProvinceId, dto.WorkCompany, dto.WorkCompanyAccountantNumber, dto.WorkStartedAt,
|
||||
dto.WorkSalary, dto.WorkPosition, dto.Education, dto.MarriageStatus,
|
||||
dto.PassportOne, dto.PassportTwo, dto.PassportThree, dto.PassportFour,
|
||||
dto.LoanAmount, dto.CardNumber, dto.CardName, dto.CardMonth, dto.CardYear,
|
||||
dto.GuarantorName, dto.GuarantorSurname, dto.GuarantorPatronicName, dto.GuarantorPassportSerie, dto.GuarantorPassportId,
|
||||
dto.GuarantorCardNumber, dto.GuarantorCardName, dto.GuarantorCardMonth, dto.GuarantorCardYear, dto.GuarantorNote,
|
||||
dto.Guarantor2Name, dto.Guarantor2Surname, dto.Guarantor2PatronicName, dto.Guarantor2PassportSerie, dto.Guarantor2PassportId,
|
||||
dto.Guarantor2CardNumber, dto.Guarantor2CardName, dto.Guarantor2CardMonth, dto.Guarantor2CardYear, dto.Guarantor2Note,
|
||||
dto.LoanCardNumber, dto.LoanCardName, dto.LoanCardMonth, dto.LoanCardYear,
|
||||
dto.LoanOrderRequiredDocId, dto.Status, dto.Satisfiable, dto.Notes,
|
||||
}
|
||||
}
|
||||
|
||||
func (r *repository) List(ctx context.Context, filter loanorders.ListFilter) (loanorders.ListLoanOrderDTO, error) {
|
||||
whereClause, args := buildListQuery(filter)
|
||||
|
||||
items, count, err := r.generic.List(ctx, whereClause, args, filter.Page, filter.Limit, "id DESC")
|
||||
if err != nil {
|
||||
return loanorders.ListLoanOrderDTO{}, err
|
||||
}
|
||||
|
||||
return loanorders.ListLoanOrderDTO{Count: count, LoanOrders: items}, nil
|
||||
}
|
||||
|
||||
func buildListQuery(filter loanorders.ListFilter) (whereClause string, args []interface{}) {
|
||||
var conditions []string
|
||||
|
||||
if filter.Status != nil {
|
||||
args = append(args, *filter.Status)
|
||||
conditions = append(conditions, fmt.Sprintf("status = $%d", len(args)))
|
||||
}
|
||||
|
||||
if filter.BranchId != nil {
|
||||
args = append(args, *filter.BranchId)
|
||||
conditions = append(conditions, fmt.Sprintf("branch_id = $%d", len(args)))
|
||||
}
|
||||
|
||||
if filter.UserId != nil {
|
||||
args = append(args, *filter.UserId)
|
||||
conditions = append(conditions, fmt.Sprintf("user_id = $%d", len(args)))
|
||||
}
|
||||
|
||||
if filter.Region != "" {
|
||||
args = append(args, filter.Region)
|
||||
conditions = append(conditions, fmt.Sprintf("region = $%d", len(args)))
|
||||
}
|
||||
|
||||
if len(conditions) == 0 {
|
||||
return "", args
|
||||
}
|
||||
|
||||
return " WHERE " + strings.Join(conditions, " AND "), args
|
||||
}
|
||||
|
||||
func (r *repository) GetByID(ctx context.Context, id int64) (loanorders.LoanOrderDTO, error) {
|
||||
return r.generic.GetByID(ctx, id)
|
||||
}
|
||||
|
||||
// nextUniqueIDSQL computes unique_id as the last value stored in loan_orders plus
|
||||
// one, zero-padded to 4 digits, mirroring a serial/auto-increment column.
|
||||
const nextUniqueIDSQL = `(SELECT LPAD((COALESCE(MAX(unique_id::bigint), 0) + 1)::text, 4, '0') FROM loan_orders)`
|
||||
|
||||
func (r *repository) Create(ctx context.Context, dto loanorders.CreateLoanOrderDTO) (loanorders.LoanOrderDTO, error) {
|
||||
// unique_id is supplied positionally via nextUniqueIDSQL below, so drop it
|
||||
// from the bound args to avoid double-supplying the first column.
|
||||
args := createArgs(dto)[1:]
|
||||
|
||||
placeholders := make([]string, len(args))
|
||||
for i := range args {
|
||||
placeholders[i] = fmt.Sprintf("$%d", i+1)
|
||||
}
|
||||
|
||||
query := fmt.Sprintf(
|
||||
`INSERT INTO loan_orders (%s) VALUES (%s, %s) RETURNING %s`,
|
||||
loanOrderWritableColumnsSQL, nextUniqueIDSQL, strings.Join(placeholders, ", "), loanOrderColumnsSQL,
|
||||
)
|
||||
|
||||
return scanLoanOrder(r.client.QueryRow(ctx, query, args...))
|
||||
}
|
||||
|
||||
func (r *repository) Update(ctx context.Context, id int64, dto loanorders.UpdateLoanOrderDTO) (loanorders.LoanOrderDTO, error) {
|
||||
args := updateArgs(dto)
|
||||
|
||||
assignments := make([]string, len(loanOrderWritableColumns))
|
||||
for i, column := range loanOrderWritableColumns {
|
||||
assignments[i] = fmt.Sprintf("%s = $%d", column, i+1)
|
||||
}
|
||||
args = append(args, id)
|
||||
|
||||
query := fmt.Sprintf(
|
||||
`UPDATE loan_orders SET %s, updated_at = (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') WHERE id = $%d RETURNING %s`,
|
||||
strings.Join(assignments, ", "), len(args), loanOrderColumnsSQL,
|
||||
)
|
||||
|
||||
item, err := scanLoanOrder(r.client.QueryRow(ctx, query, args...))
|
||||
if err != nil {
|
||||
return loanorders.LoanOrderDTO{}, err
|
||||
}
|
||||
return item, nil
|
||||
}
|
||||
|
||||
func (r *repository) Delete(ctx context.Context, id int64) error {
|
||||
return r.generic.Delete(ctx, id)
|
||||
}
|
||||
|
||||
func scanLoanOrder(row genericrepo.Scanner) (loanorders.LoanOrderDTO, error) {
|
||||
var item loanorders.LoanOrderDTO
|
||||
err := row.Scan(
|
||||
&item.Id, &item.UniqueId, &item.Source, &item.UserId, &item.LoanType, &item.Region, &item.BranchId,
|
||||
&item.CustomerName, &item.CustomerSurname, &item.CustomerPatronicName,
|
||||
&item.PassportAddress, &item.RealAddress, &item.PassportSerie, &item.PassportId, &item.PassportGivenAt, &item.PassportGivenBy,
|
||||
&item.BornPlace, &item.BornAt, &item.Email, &item.Phone, &item.PhoneAdditional, &item.PhoneHome,
|
||||
&item.WorkRegion, &item.WorkProvinceId, &item.WorkCompany, &item.WorkCompanyAccountantNumber, &item.WorkStartedAt,
|
||||
&item.WorkSalary, &item.WorkPosition, &item.Education, &item.MarriageStatus,
|
||||
&item.PassportOne, &item.PassportTwo, &item.PassportThree, &item.PassportFour,
|
||||
&item.LoanAmount, &item.CardNumber, &item.CardName, &item.CardMonth, &item.CardYear,
|
||||
&item.GuarantorName, &item.GuarantorSurname, &item.GuarantorPatronicName, &item.GuarantorPassportSerie, &item.GuarantorPassportId,
|
||||
&item.GuarantorCardNumber, &item.GuarantorCardName, &item.GuarantorCardMonth, &item.GuarantorCardYear, &item.GuarantorNote,
|
||||
&item.Guarantor2Name, &item.Guarantor2Surname, &item.Guarantor2PatronicName, &item.Guarantor2PassportSerie, &item.Guarantor2PassportId,
|
||||
&item.Guarantor2CardNumber, &item.Guarantor2CardName, &item.Guarantor2CardMonth, &item.Guarantor2CardYear, &item.Guarantor2Note,
|
||||
&item.LoanCardNumber, &item.LoanCardName, &item.LoanCardMonth, &item.LoanCardYear,
|
||||
&item.LoanOrderRequiredDocId, &item.Status, &item.Satisfiable, &item.Notes,
|
||||
&item.CreatedAt, &item.UpdatedAt,
|
||||
)
|
||||
if err != nil {
|
||||
return loanorders.LoanOrderDTO{}, err
|
||||
}
|
||||
return item, nil
|
||||
}
|
||||
@@ -0,0 +1,230 @@
|
||||
package loanorders
|
||||
|
||||
import "time"
|
||||
|
||||
type LoanOrderDTO struct {
|
||||
Id int64 `json:"id"`
|
||||
UniqueId *string `json:"uniqueId"`
|
||||
Source string `json:"source"`
|
||||
UserId *int64 `json:"userId"`
|
||||
LoanType int64 `json:"loanType"`
|
||||
Region string `json:"region"`
|
||||
BranchId int64 `json:"branchId"`
|
||||
CustomerName string `json:"customerName"`
|
||||
CustomerSurname string `json:"customerSurname"`
|
||||
CustomerPatronicName *string `json:"customerPatronicName"`
|
||||
PassportAddress string `json:"passportAddress"`
|
||||
RealAddress string `json:"realAddress"`
|
||||
PassportSerie string `json:"passportSerie"`
|
||||
PassportId string `json:"passportId"`
|
||||
PassportGivenAt time.Time `json:"passportGivenAt"`
|
||||
PassportGivenBy string `json:"passportGivenBy"`
|
||||
BornPlace string `json:"bornPlace"`
|
||||
BornAt time.Time `json:"bornAt"`
|
||||
Email *string `json:"email"`
|
||||
Phone string `json:"phone"`
|
||||
PhoneAdditional *string `json:"phoneAdditional"`
|
||||
PhoneHome *string `json:"phoneHome"`
|
||||
WorkRegion *string `json:"workRegion"`
|
||||
WorkProvinceId *int64 `json:"workProvinceId"`
|
||||
WorkCompany *string `json:"workCompany"`
|
||||
WorkCompanyAccountantNumber *string `json:"workCompanyAccountantNumber"`
|
||||
WorkStartedAt *time.Time `json:"workStartedAt"`
|
||||
WorkSalary *string `json:"workSalary"`
|
||||
WorkPosition *string `json:"workPosition"`
|
||||
Education string `json:"education"`
|
||||
MarriageStatus string `json:"marriageStatus"`
|
||||
PassportOne string `json:"passportOne"`
|
||||
PassportTwo string `json:"passportTwo"`
|
||||
PassportThree string `json:"passportThree"`
|
||||
PassportFour string `json:"passportFour"`
|
||||
LoanAmount *string `json:"loanAmount"`
|
||||
CardNumber *string `json:"cardNumber"`
|
||||
CardName *string `json:"cardName"`
|
||||
CardMonth *string `json:"cardMonth"`
|
||||
CardYear *string `json:"cardYear"`
|
||||
GuarantorName *string `json:"guarantorName"`
|
||||
GuarantorSurname *string `json:"guarantorSurname"`
|
||||
GuarantorPatronicName *string `json:"guarantorPatronicName"`
|
||||
GuarantorPassportSerie *string `json:"guarantorPassportSerie"`
|
||||
GuarantorPassportId *string `json:"guarantorPassportId"`
|
||||
GuarantorCardNumber *string `json:"guarantorCardNumber"`
|
||||
GuarantorCardName *string `json:"guarantorCardName"`
|
||||
GuarantorCardMonth *string `json:"guarantorCardMonth"`
|
||||
GuarantorCardYear *string `json:"guarantorCardYear"`
|
||||
GuarantorNote *string `json:"guarantorNote"`
|
||||
Guarantor2Name *string `json:"guarantor2Name"`
|
||||
Guarantor2Surname *string `json:"guarantor2Surname"`
|
||||
Guarantor2PatronicName *string `json:"guarantor2PatronicName"`
|
||||
Guarantor2PassportSerie *string `json:"guarantor2PassportSerie"`
|
||||
Guarantor2PassportId *string `json:"guarantor2PassportId"`
|
||||
Guarantor2CardNumber *string `json:"guarantor2CardNumber"`
|
||||
Guarantor2CardName *string `json:"guarantor2CardName"`
|
||||
Guarantor2CardMonth *string `json:"guarantor2CardMonth"`
|
||||
Guarantor2CardYear *string `json:"guarantor2CardYear"`
|
||||
Guarantor2Note *string `json:"guarantor2Note"`
|
||||
LoanCardNumber *string `json:"loanCardNumber"`
|
||||
LoanCardName *string `json:"loanCardName"`
|
||||
LoanCardMonth *string `json:"loanCardMonth"`
|
||||
LoanCardYear *string `json:"loanCardYear"`
|
||||
LoanOrderRequiredDocId *int64 `json:"loanOrderRequiredDocId"`
|
||||
Status *string `json:"status"`
|
||||
Satisfiable *string `json:"satisfiable"`
|
||||
Notes *string `json:"notes"`
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
UpdatedAt time.Time `json:"updatedAt"`
|
||||
}
|
||||
|
||||
type CreateLoanOrderDTO struct {
|
||||
Source string `json:"source"`
|
||||
UserId *int64 `json:"userId"`
|
||||
UniqueId *string `json:"uniqueId"`
|
||||
LoanType int64 `json:"loanType" 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"`
|
||||
PassportAddress string `json:"passportAddress" binding:"required"`
|
||||
RealAddress string `json:"realAddress" 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"`
|
||||
BornAt time.Time `json:"bornAt" binding:"required"`
|
||||
Email *string `json:"email"`
|
||||
Phone string `json:"phone" binding:"required"`
|
||||
PhoneAdditional *string `json:"phoneAdditional"`
|
||||
PhoneHome *string `json:"phoneHome"`
|
||||
WorkRegion *string `json:"workRegion"`
|
||||
WorkProvinceId *int64 `json:"workProvinceId"`
|
||||
WorkCompany *string `json:"workCompany"`
|
||||
WorkCompanyAccountantNumber *string `json:"workCompanyAccountantNumber"`
|
||||
WorkStartedAt *time.Time `json:"workStartedAt"`
|
||||
WorkSalary *string `json:"workSalary"`
|
||||
WorkPosition *string `json:"workPosition"`
|
||||
Education string `json:"education" binding:"required"`
|
||||
MarriageStatus string `json:"marriageStatus" binding:"required"`
|
||||
PassportOne string `json:"passportOne" binding:"required"`
|
||||
PassportTwo string `json:"passportTwo" binding:"required"`
|
||||
PassportThree string `json:"passportThree" binding:"required"`
|
||||
PassportFour string `json:"passportFour" binding:"required"`
|
||||
LoanAmount *string `json:"loanAmount"`
|
||||
CardNumber *string `json:"cardNumber"`
|
||||
CardName *string `json:"cardName"`
|
||||
CardMonth *string `json:"cardMonth"`
|
||||
CardYear *string `json:"cardYear"`
|
||||
GuarantorName *string `json:"guarantorName"`
|
||||
GuarantorSurname *string `json:"guarantorSurname"`
|
||||
GuarantorPatronicName *string `json:"guarantorPatronicName"`
|
||||
GuarantorPassportSerie *string `json:"guarantorPassportSerie"`
|
||||
GuarantorPassportId *string `json:"guarantorPassportId"`
|
||||
GuarantorCardNumber *string `json:"guarantorCardNumber"`
|
||||
GuarantorCardName *string `json:"guarantorCardName"`
|
||||
GuarantorCardMonth *string `json:"guarantorCardMonth"`
|
||||
GuarantorCardYear *string `json:"guarantorCardYear"`
|
||||
GuarantorNote *string `json:"guarantorNote"`
|
||||
Guarantor2Name *string `json:"guarantor2Name"`
|
||||
Guarantor2Surname *string `json:"guarantor2Surname"`
|
||||
Guarantor2PatronicName *string `json:"guarantor2PatronicName"`
|
||||
Guarantor2PassportSerie *string `json:"guarantor2PassportSerie"`
|
||||
Guarantor2PassportId *string `json:"guarantor2PassportId"`
|
||||
Guarantor2CardNumber *string `json:"guarantor2CardNumber"`
|
||||
Guarantor2CardName *string `json:"guarantor2CardName"`
|
||||
Guarantor2CardMonth *string `json:"guarantor2CardMonth"`
|
||||
Guarantor2CardYear *string `json:"guarantor2CardYear"`
|
||||
Guarantor2Note *string `json:"guarantor2Note"`
|
||||
LoanCardNumber *string `json:"loanCardNumber"`
|
||||
LoanCardName *string `json:"loanCardName"`
|
||||
LoanCardMonth *string `json:"loanCardMonth"`
|
||||
LoanCardYear *string `json:"loanCardYear"`
|
||||
LoanOrderRequiredDocId *int64 `json:"loanOrderRequiredDocId"`
|
||||
Status *string `json:"status"`
|
||||
Satisfiable *string `json:"satisfiable"`
|
||||
Notes *string `json:"notes"`
|
||||
}
|
||||
|
||||
type UpdateLoanOrderDTO struct {
|
||||
UniqueId *string `json:"uniqueId"`
|
||||
Source string `json:"source"`
|
||||
UserId *int64 `json:"userId"`
|
||||
LoanType int64 `json:"loanType" 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"`
|
||||
PassportAddress string `json:"passportAddress" binding:"required"`
|
||||
RealAddress string `json:"realAddress" 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"`
|
||||
BornAt time.Time `json:"bornAt" binding:"required"`
|
||||
Email *string `json:"email"`
|
||||
Phone string `json:"phone" binding:"required"`
|
||||
PhoneAdditional *string `json:"phoneAdditional"`
|
||||
PhoneHome *string `json:"phoneHome"`
|
||||
WorkRegion *string `json:"workRegion"`
|
||||
WorkProvinceId *int64 `json:"workProvinceId"`
|
||||
WorkCompany *string `json:"workCompany"`
|
||||
WorkCompanyAccountantNumber *string `json:"workCompanyAccountantNumber"`
|
||||
WorkStartedAt *time.Time `json:"workStartedAt"`
|
||||
WorkSalary *string `json:"workSalary"`
|
||||
WorkPosition *string `json:"workPosition"`
|
||||
Education string `json:"education" binding:"required"`
|
||||
MarriageStatus string `json:"marriageStatus" binding:"required"`
|
||||
PassportOne string `json:"passportOne" binding:"required"`
|
||||
PassportTwo string `json:"passportTwo" binding:"required"`
|
||||
PassportThree string `json:"passportThree" binding:"required"`
|
||||
PassportFour string `json:"passportFour" binding:"required"`
|
||||
LoanAmount *string `json:"loanAmount"`
|
||||
CardNumber *string `json:"cardNumber"`
|
||||
CardName *string `json:"cardName"`
|
||||
CardMonth *string `json:"cardMonth"`
|
||||
CardYear *string `json:"cardYear"`
|
||||
GuarantorName *string `json:"guarantorName"`
|
||||
GuarantorSurname *string `json:"guarantorSurname"`
|
||||
GuarantorPatronicName *string `json:"guarantorPatronicName"`
|
||||
GuarantorPassportSerie *string `json:"guarantorPassportSerie"`
|
||||
GuarantorPassportId *string `json:"guarantorPassportId"`
|
||||
GuarantorCardNumber *string `json:"guarantorCardNumber"`
|
||||
GuarantorCardName *string `json:"guarantorCardName"`
|
||||
GuarantorCardMonth *string `json:"guarantorCardMonth"`
|
||||
GuarantorCardYear *string `json:"guarantorCardYear"`
|
||||
GuarantorNote *string `json:"guarantorNote"`
|
||||
Guarantor2Name *string `json:"guarantor2Name"`
|
||||
Guarantor2Surname *string `json:"guarantor2Surname"`
|
||||
Guarantor2PatronicName *string `json:"guarantor2PatronicName"`
|
||||
Guarantor2PassportSerie *string `json:"guarantor2PassportSerie"`
|
||||
Guarantor2PassportId *string `json:"guarantor2PassportId"`
|
||||
Guarantor2CardNumber *string `json:"guarantor2CardNumber"`
|
||||
Guarantor2CardName *string `json:"guarantor2CardName"`
|
||||
Guarantor2CardMonth *string `json:"guarantor2CardMonth"`
|
||||
Guarantor2CardYear *string `json:"guarantor2CardYear"`
|
||||
Guarantor2Note *string `json:"guarantor2Note"`
|
||||
LoanCardNumber *string `json:"loanCardNumber"`
|
||||
LoanCardName *string `json:"loanCardName"`
|
||||
LoanCardMonth *string `json:"loanCardMonth"`
|
||||
LoanCardYear *string `json:"loanCardYear"`
|
||||
LoanOrderRequiredDocId *int64 `json:"loanOrderRequiredDocId"`
|
||||
Status *string `json:"status"`
|
||||
Satisfiable *string `json:"satisfiable"`
|
||||
Notes *string `json:"notes"`
|
||||
}
|
||||
|
||||
type ListFilter struct {
|
||||
Status *string
|
||||
BranchId *int64
|
||||
UserId *int64
|
||||
Region string
|
||||
Page int
|
||||
Limit int
|
||||
}
|
||||
|
||||
type ListLoanOrderDTO struct {
|
||||
Count int64 `json:"count"`
|
||||
LoanOrders []LoanOrderDTO `json:"loanOrders"`
|
||||
}
|
||||
@@ -0,0 +1,265 @@
|
||||
package loanorders
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"online-back/internal/appresult"
|
||||
"online-back/internal/handlers"
|
||||
"online-back/pkg/logging"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/jackc/pgx/v4"
|
||||
)
|
||||
|
||||
const baseURL = "/loan-orders"
|
||||
|
||||
type handler struct {
|
||||
logger *logging.Logger
|
||||
repository Repository
|
||||
}
|
||||
|
||||
func NewHandler(logger *logging.Logger, repository Repository) handlers.Handler {
|
||||
return &handler{logger: logger, repository: repository}
|
||||
}
|
||||
|
||||
func (h *handler) Register(router *gin.RouterGroup) {
|
||||
group := router.Group(baseURL, appresult.JwtTokenCheck())
|
||||
group.GET("", h.list)
|
||||
group.GET("/:id", h.getByID)
|
||||
group.POST("", h.create)
|
||||
group.PUT("/:id", h.update)
|
||||
group.DELETE("/:id", h.delete)
|
||||
}
|
||||
|
||||
// list godoc
|
||||
// @Summary List loan orders
|
||||
// @Description Returns paginated loan orders with optional filters
|
||||
// @Tags loan-orders
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param status query string false "Filter by status"
|
||||
// @Param branch_id query int false "Filter by branch ID"
|
||||
// @Param user_id query int false "Filter by user ID"
|
||||
// @Param region query string false "Filter by region"
|
||||
// @Param page query int false "Page number" default(1)
|
||||
// @Param limit query int false "Items per page" default(10)
|
||||
// @Success 200 {object} appresult.AppSuccess
|
||||
// @Failure 400 {object} appresult.AppError
|
||||
// @Failure 500 {object} appresult.AppError
|
||||
// @Router /loan-orders [get]
|
||||
func (h *handler) list(c *gin.Context) {
|
||||
filter, ok := parseListFilter(c)
|
||||
if !ok {
|
||||
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
|
||||
return
|
||||
}
|
||||
|
||||
result, err := h.repository.List(c.Request.Context(), filter)
|
||||
if err != nil {
|
||||
h.logger.Errorf("list loan orders failed: %v", err)
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, appresult.SuccessWithData(result))
|
||||
}
|
||||
|
||||
// getByID godoc
|
||||
// @Summary Get loan order by ID
|
||||
// @Description Returns a single loan order
|
||||
// @Tags loan-orders
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param id path int true "Loan order ID"
|
||||
// @Success 200 {object} appresult.AppSuccess
|
||||
// @Failure 400 {object} appresult.AppError
|
||||
// @Failure 404 {object} appresult.AppError
|
||||
// @Failure 500 {object} appresult.AppError
|
||||
// @Router /loan-orders/{id} [get]
|
||||
func (h *handler) getByID(c *gin.Context) {
|
||||
id, ok := parseID(c.Param("id"))
|
||||
if !ok {
|
||||
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
|
||||
return
|
||||
}
|
||||
|
||||
item, err := h.repository.GetByID(c.Request.Context(), id)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
c.JSON(http.StatusNotFound, appresult.ErrNotFound)
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
h.logger.Errorf("get loan order failed: %v", err)
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, appresult.SuccessWithData(item))
|
||||
}
|
||||
|
||||
// create godoc
|
||||
// @Summary Create loan order
|
||||
// @Description Creates a new loan order
|
||||
// @Tags loan-orders
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param body body CreateLoanOrderDTO true "Loan order payload"
|
||||
// @Success 201 {object} appresult.AppSuccess
|
||||
// @Failure 400 {object} appresult.AppError
|
||||
// @Failure 500 {object} appresult.AppError
|
||||
// @Router /loan-orders [post]
|
||||
func (h *handler) create(c *gin.Context) {
|
||||
var dto CreateLoanOrderDTO
|
||||
if err := c.ShouldBindJSON(&dto); err != nil {
|
||||
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
|
||||
return
|
||||
}
|
||||
|
||||
item, err := h.repository.Create(c.Request.Context(), dto)
|
||||
if err != nil {
|
||||
h.logger.Errorf("create loan order failed: %v", err)
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusCreated, appresult.SuccessWithData(item))
|
||||
}
|
||||
|
||||
// update godoc
|
||||
// @Summary Update loan order
|
||||
// @Description Updates an existing loan order
|
||||
// @Tags loan-orders
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param id path int true "Loan order ID"
|
||||
// @Param body body UpdateLoanOrderDTO true "Loan order payload"
|
||||
// @Success 200 {object} appresult.AppSuccess
|
||||
// @Failure 400 {object} appresult.AppError
|
||||
// @Failure 404 {object} appresult.AppError
|
||||
// @Failure 500 {object} appresult.AppError
|
||||
// @Router /loan-orders/{id} [put]
|
||||
func (h *handler) update(c *gin.Context) {
|
||||
id, ok := parseID(c.Param("id"))
|
||||
if !ok {
|
||||
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
|
||||
return
|
||||
}
|
||||
|
||||
var dto UpdateLoanOrderDTO
|
||||
if err := c.ShouldBindJSON(&dto); err != nil {
|
||||
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
|
||||
return
|
||||
}
|
||||
|
||||
item, err := h.repository.Update(c.Request.Context(), id, dto)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
c.JSON(http.StatusNotFound, appresult.ErrNotFound)
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
h.logger.Errorf("update loan order failed: %v", err)
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, appresult.SuccessWithData(item))
|
||||
}
|
||||
|
||||
// delete godoc
|
||||
// @Summary Delete loan order
|
||||
// @Description Deletes a loan order
|
||||
// @Tags loan-orders
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param id path int true "Loan order ID"
|
||||
// @Success 200 {object} appresult.AppSuccess
|
||||
// @Failure 400 {object} appresult.AppError
|
||||
// @Failure 404 {object} appresult.AppError
|
||||
// @Failure 500 {object} appresult.AppError
|
||||
// @Router /loan-orders/{id} [delete]
|
||||
func (h *handler) delete(c *gin.Context) {
|
||||
id, ok := parseID(c.Param("id"))
|
||||
if !ok {
|
||||
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
|
||||
return
|
||||
}
|
||||
|
||||
if err := h.repository.Delete(c.Request.Context(), id); errors.Is(err, pgx.ErrNoRows) {
|
||||
c.JSON(http.StatusNotFound, appresult.ErrNotFound)
|
||||
return
|
||||
} else if err != nil {
|
||||
h.logger.Errorf("delete loan order failed: %v", err)
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, appresult.SuccessWithData("loan order removed"))
|
||||
}
|
||||
|
||||
func parseID(raw string) (int64, bool) {
|
||||
id, err := strconv.ParseInt(raw, 10, 64)
|
||||
if err != nil || id <= 0 {
|
||||
return 0, false
|
||||
}
|
||||
return id, true
|
||||
}
|
||||
|
||||
const (
|
||||
defaultPage = 1
|
||||
defaultLimit = 10
|
||||
maxLimit = 100
|
||||
)
|
||||
|
||||
func parseListFilter(c *gin.Context) (ListFilter, bool) {
|
||||
filter := ListFilter{
|
||||
Page: defaultPage,
|
||||
Limit: defaultLimit,
|
||||
}
|
||||
|
||||
if raw := c.Query("branch_id"); raw != "" {
|
||||
id, ok := parseID(raw)
|
||||
if !ok {
|
||||
return ListFilter{}, false
|
||||
}
|
||||
filter.BranchId = &id
|
||||
}
|
||||
|
||||
if raw := c.Query("user_id"); raw != "" {
|
||||
id, ok := parseID(raw)
|
||||
if !ok {
|
||||
return ListFilter{}, false
|
||||
}
|
||||
filter.UserId = &id
|
||||
}
|
||||
|
||||
if raw := c.Query("page"); raw != "" {
|
||||
page, err := strconv.Atoi(raw)
|
||||
if err != nil || page < 1 {
|
||||
return ListFilter{}, false
|
||||
}
|
||||
filter.Page = page
|
||||
}
|
||||
|
||||
if raw := c.Query("limit"); raw != "" {
|
||||
limit, err := strconv.Atoi(raw)
|
||||
if err != nil || limit < 1 || limit > maxLimit {
|
||||
return ListFilter{}, false
|
||||
}
|
||||
filter.Limit = limit
|
||||
}
|
||||
|
||||
if raw := strings.TrimSpace(c.Query("status")); raw != "" {
|
||||
filter.Status = &raw
|
||||
}
|
||||
|
||||
if raw := strings.TrimSpace(c.Query("region")); raw != "" {
|
||||
filter.Region = raw
|
||||
}
|
||||
|
||||
return filter, true
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
package loanorders
|
||||
|
||||
import "context"
|
||||
|
||||
type Repository interface {
|
||||
List(ctx context.Context, filter ListFilter) (ListLoanOrderDTO, error)
|
||||
GetByID(ctx context.Context, id int64) (LoanOrderDTO, error)
|
||||
Create(ctx context.Context, dto CreateLoanOrderDTO) (LoanOrderDTO, error)
|
||||
Update(ctx context.Context, id int64, dto UpdateLoanOrderDTO) (LoanOrderDTO, error)
|
||||
Delete(ctx context.Context, id int64) error
|
||||
}
|
||||
@@ -0,0 +1,171 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"online-back/internal/lending/loanpaidletter"
|
||||
"online-back/pkg/client/postgresql"
|
||||
"online-back/pkg/logging"
|
||||
"online-back/pkg/repository/genericrepo"
|
||||
)
|
||||
|
||||
type repository struct {
|
||||
client postgresql.Client
|
||||
generic *genericrepo.Repository[loanpaidletter.LoanPaidLetterDTO]
|
||||
logger *logging.Logger
|
||||
}
|
||||
|
||||
func NewRepository(client postgresql.Client, logger *logging.Logger) loanpaidletter.Repository {
|
||||
return &repository{
|
||||
client: client,
|
||||
generic: genericrepo.New(client, "loan_paid_off_letters", letterColumnsSQL, scanLoanPaidLetter),
|
||||
logger: logger,
|
||||
}
|
||||
}
|
||||
|
||||
// letterWritableColumns lists every loan_paid_off_letters column except id, created_at
|
||||
// and updated_at, in the exact order CreateLoanPaidLetterDTO/UpdateLoanPaidLetterDTO fields are read.
|
||||
var letterWritableColumns = []string{
|
||||
"unique_id", "region", "branch_id", "user_id",
|
||||
"customer_name", "customer_surname", "customer_patronic_name", "born_at",
|
||||
"phone", "passport_serie", "passport_id",
|
||||
"status", "notes", "loan_contract_number", "loan_contract_date",
|
||||
"loan_amount", "loan_reason", "loan_file",
|
||||
}
|
||||
|
||||
var letterColumns = append(append([]string{"id"}, letterWritableColumns...), "created_at", "updated_at")
|
||||
|
||||
var letterColumnsSQL = strings.Join(letterColumns, ", ")
|
||||
|
||||
var letterWritableColumnsSQL = strings.Join(letterWritableColumns, ", ")
|
||||
|
||||
func createArgs(dto loanpaidletter.CreateLoanPaidLetterDTO) []interface{} {
|
||||
return []interface{}{
|
||||
dto.UniqueId, dto.Region, dto.BranchId, dto.UserId,
|
||||
dto.CustomerName, dto.CustomerSurname, dto.CustomerPatronicName, dto.BornAt,
|
||||
dto.Phone, dto.PassportSerie, dto.PassportId,
|
||||
dto.Status, dto.Notes, dto.LoanContractNumber, dto.LoanContractDate,
|
||||
dto.LoanAmount, dto.LoanReason, dto.LoanFile,
|
||||
}
|
||||
}
|
||||
|
||||
func updateArgs(dto loanpaidletter.UpdateLoanPaidLetterDTO) []interface{} {
|
||||
return []interface{}{
|
||||
dto.UniqueId, dto.Region, dto.BranchId, dto.UserId,
|
||||
dto.CustomerName, dto.CustomerSurname, dto.CustomerPatronicName, dto.BornAt,
|
||||
dto.Phone, dto.PassportSerie, dto.PassportId,
|
||||
dto.Status, dto.Notes, dto.LoanContractNumber, dto.LoanContractDate,
|
||||
dto.LoanAmount, dto.LoanReason, dto.LoanFile,
|
||||
}
|
||||
}
|
||||
|
||||
func (r *repository) List(ctx context.Context, filter loanpaidletter.ListFilter) (loanpaidletter.ListLoanPaidLetterDTO, error) {
|
||||
whereClause, args := buildListQuery(filter)
|
||||
|
||||
items, count, err := r.generic.List(ctx, whereClause, args, filter.Page, filter.Limit, "id DESC")
|
||||
if err != nil {
|
||||
return loanpaidletter.ListLoanPaidLetterDTO{}, err
|
||||
}
|
||||
|
||||
return loanpaidletter.ListLoanPaidLetterDTO{Count: count, LoanPaidLetters: items}, nil
|
||||
}
|
||||
|
||||
func buildListQuery(filter loanpaidletter.ListFilter) (whereClause string, args []interface{}) {
|
||||
var conditions []string
|
||||
|
||||
if filter.PassportId != "" {
|
||||
args = append(args, likePattern(filter.PassportId))
|
||||
conditions = append(conditions, fmt.Sprintf("passport_id ILIKE $%d", len(args)))
|
||||
}
|
||||
|
||||
if filter.Status != nil {
|
||||
args = append(args, *filter.Status)
|
||||
conditions = append(conditions, fmt.Sprintf("status = $%d", len(args)))
|
||||
}
|
||||
|
||||
if filter.BranchId != nil {
|
||||
args = append(args, *filter.BranchId)
|
||||
conditions = append(conditions, fmt.Sprintf("branch_id = $%d", len(args)))
|
||||
}
|
||||
|
||||
if filter.Region != "" {
|
||||
args = append(args, filter.Region)
|
||||
conditions = append(conditions, fmt.Sprintf("region = $%d", len(args)))
|
||||
}
|
||||
|
||||
if len(conditions) == 0 {
|
||||
return "", args
|
||||
}
|
||||
|
||||
return " WHERE " + strings.Join(conditions, " AND "), args
|
||||
}
|
||||
|
||||
func likePattern(term string) string {
|
||||
term = strings.ReplaceAll(term, `\`, `\\`)
|
||||
term = strings.ReplaceAll(term, `%`, `\%`)
|
||||
term = strings.ReplaceAll(term, `_`, `\_`)
|
||||
return "%" + term + "%"
|
||||
}
|
||||
|
||||
func (r *repository) GetByID(ctx context.Context, id int64) (loanpaidletter.LoanPaidLetterDTO, error) {
|
||||
return r.generic.GetByID(ctx, id)
|
||||
}
|
||||
|
||||
func (r *repository) Create(ctx context.Context, dto loanpaidletter.CreateLoanPaidLetterDTO) (loanpaidletter.LoanPaidLetterDTO, error) {
|
||||
args := createArgs(dto)
|
||||
|
||||
placeholders := make([]string, len(args))
|
||||
for i := range args {
|
||||
placeholders[i] = fmt.Sprintf("$%d", i+1)
|
||||
}
|
||||
|
||||
query := fmt.Sprintf(
|
||||
`INSERT INTO loan_paid_off_letters (%s) VALUES (%s) RETURNING %s`,
|
||||
letterWritableColumnsSQL, strings.Join(placeholders, ", "), letterColumnsSQL,
|
||||
)
|
||||
|
||||
return scanLoanPaidLetter(r.client.QueryRow(ctx, query, args...))
|
||||
}
|
||||
|
||||
func (r *repository) Update(ctx context.Context, id int64, dto loanpaidletter.UpdateLoanPaidLetterDTO) (loanpaidletter.LoanPaidLetterDTO, error) {
|
||||
args := updateArgs(dto)
|
||||
|
||||
assignments := make([]string, len(letterWritableColumns))
|
||||
for i, column := range letterWritableColumns {
|
||||
assignments[i] = fmt.Sprintf("%s = $%d", column, i+1)
|
||||
}
|
||||
args = append(args, id)
|
||||
|
||||
query := fmt.Sprintf(
|
||||
`UPDATE loan_paid_off_letters SET %s, updated_at = (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') WHERE id = $%d RETURNING %s`,
|
||||
strings.Join(assignments, ", "), len(args), letterColumnsSQL,
|
||||
)
|
||||
|
||||
item, err := scanLoanPaidLetter(r.client.QueryRow(ctx, query, args...))
|
||||
if err != nil {
|
||||
return loanpaidletter.LoanPaidLetterDTO{}, err
|
||||
}
|
||||
return item, nil
|
||||
}
|
||||
|
||||
func (r *repository) Delete(ctx context.Context, id int64) error {
|
||||
return r.generic.Delete(ctx, id)
|
||||
}
|
||||
|
||||
func scanLoanPaidLetter(row genericrepo.Scanner) (loanpaidletter.LoanPaidLetterDTO, error) {
|
||||
var item loanpaidletter.LoanPaidLetterDTO
|
||||
err := row.Scan(
|
||||
&item.Id, &item.UniqueId, &item.Region, &item.BranchId, &item.UserId,
|
||||
&item.CustomerName, &item.CustomerSurname, &item.CustomerPatronicName, &item.BornAt,
|
||||
&item.Phone, &item.PassportSerie, &item.PassportId,
|
||||
&item.Status, &item.Notes, &item.LoanContractNumber, &item.LoanContractDate,
|
||||
&item.LoanAmount, &item.LoanReason, &item.LoanFile,
|
||||
&item.CreatedAt, &item.UpdatedAt,
|
||||
)
|
||||
if err != nil {
|
||||
return loanpaidletter.LoanPaidLetterDTO{}, err
|
||||
}
|
||||
return item, nil
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
package loanpaidletter
|
||||
|
||||
import "time"
|
||||
|
||||
type LoanPaidLetterDTO struct {
|
||||
Id int64 `json:"id"`
|
||||
UniqueId *string `json:"uniqueId"`
|
||||
Region string `json:"region"`
|
||||
BranchId int64 `json:"branchId"`
|
||||
UserId *int64 `json:"userId"`
|
||||
CustomerName string `json:"customerName"`
|
||||
CustomerSurname string `json:"customerSurname"`
|
||||
CustomerPatronicName *string `json:"customerPatronicName"`
|
||||
BornAt *time.Time `json:"bornAt"`
|
||||
Phone string `json:"phone"`
|
||||
PassportSerie string `json:"passportSerie"`
|
||||
PassportId string `json:"passportId"`
|
||||
Status *string `json:"status"`
|
||||
Notes *string `json:"notes"`
|
||||
LoanContractNumber *string `json:"loanContractNumber"`
|
||||
LoanContractDate *time.Time `json:"loanContractDate"`
|
||||
LoanAmount *string `json:"loanAmount"`
|
||||
LoanReason *string `json:"loanReason"`
|
||||
LoanFile *string `json:"loanFile"`
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
UpdatedAt time.Time `json:"updatedAt"`
|
||||
}
|
||||
|
||||
type CreateLoanPaidLetterDTO struct {
|
||||
UniqueId *string `json:"uniqueId"`
|
||||
Region string `json:"region" binding:"required"`
|
||||
BranchId int64 `json:"branchId" binding:"required"`
|
||||
UserId *int64 `json:"userId"`
|
||||
CustomerName string `json:"customerName" binding:"required"`
|
||||
CustomerSurname string `json:"customerSurname" binding:"required"`
|
||||
CustomerPatronicName *string `json:"customerPatronicName"`
|
||||
BornAt *time.Time `json:"bornAt"`
|
||||
Phone string `json:"phone" binding:"required"`
|
||||
PassportSerie string `json:"passportSerie" binding:"required"`
|
||||
PassportId string `json:"passportId" binding:"required"`
|
||||
Status *string `json:"status"`
|
||||
Notes *string `json:"notes"`
|
||||
LoanContractNumber *string `json:"loanContractNumber"`
|
||||
LoanContractDate *time.Time `json:"loanContractDate"`
|
||||
LoanAmount *string `json:"loanAmount"`
|
||||
LoanReason *string `json:"loanReason"`
|
||||
LoanFile *string `json:"loanFile"`
|
||||
}
|
||||
|
||||
type UpdateLoanPaidLetterDTO struct {
|
||||
UniqueId *string `json:"uniqueId"`
|
||||
Region string `json:"region" binding:"required"`
|
||||
BranchId int64 `json:"branchId" binding:"required"`
|
||||
UserId *int64 `json:"userId"`
|
||||
CustomerName string `json:"customerName" binding:"required"`
|
||||
CustomerSurname string `json:"customerSurname" binding:"required"`
|
||||
CustomerPatronicName *string `json:"customerPatronicName"`
|
||||
BornAt *time.Time `json:"bornAt"`
|
||||
Phone string `json:"phone" binding:"required"`
|
||||
PassportSerie string `json:"passportSerie" binding:"required"`
|
||||
PassportId string `json:"passportId" binding:"required"`
|
||||
Status *string `json:"status"`
|
||||
Notes *string `json:"notes"`
|
||||
LoanContractNumber *string `json:"loanContractNumber"`
|
||||
LoanContractDate *time.Time `json:"loanContractDate"`
|
||||
LoanAmount *string `json:"loanAmount"`
|
||||
LoanReason *string `json:"loanReason"`
|
||||
LoanFile *string `json:"loanFile"`
|
||||
}
|
||||
|
||||
type ListFilter struct {
|
||||
PassportId string
|
||||
Status *string
|
||||
BranchId *int64
|
||||
Region string
|
||||
Page int
|
||||
Limit int
|
||||
}
|
||||
|
||||
type ListLoanPaidLetterDTO struct {
|
||||
Count int64 `json:"count"`
|
||||
LoanPaidLetters []LoanPaidLetterDTO `json:"loanPaidLetters"`
|
||||
}
|
||||
@@ -0,0 +1,261 @@
|
||||
package loanpaidletter
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"online-back/internal/appresult"
|
||||
"online-back/internal/handlers"
|
||||
"online-back/pkg/logging"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/jackc/pgx/v4"
|
||||
)
|
||||
|
||||
const baseURL = "/loan-paid-off-letters"
|
||||
|
||||
type handler struct {
|
||||
logger *logging.Logger
|
||||
repository Repository
|
||||
}
|
||||
|
||||
func NewHandler(logger *logging.Logger, repository Repository) handlers.Handler {
|
||||
return &handler{logger: logger, repository: repository}
|
||||
}
|
||||
|
||||
func (h *handler) Register(router *gin.RouterGroup) {
|
||||
group := router.Group(baseURL, appresult.JwtTokenCheck())
|
||||
group.GET("", h.list)
|
||||
group.GET("/:id", h.getByID)
|
||||
group.POST("", h.create)
|
||||
group.PUT("/:id", h.update)
|
||||
group.DELETE("/:id", h.delete)
|
||||
}
|
||||
|
||||
// list godoc
|
||||
// @Summary List loan paid off letters
|
||||
// @Description Returns paginated loan paid off letters with optional filters
|
||||
// @Tags loan-paid-off-letters
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param passport_id query string false "Filter by passport ID"
|
||||
// @Param status query string false "Filter by status"
|
||||
// @Param branch_id query int false "Filter by branch ID"
|
||||
// @Param region query string false "Filter by region"
|
||||
// @Param page query int false "Page number" default(1)
|
||||
// @Param limit query int false "Items per page" default(10)
|
||||
// @Success 200 {object} appresult.AppSuccess
|
||||
// @Failure 400 {object} appresult.AppError
|
||||
// @Failure 500 {object} appresult.AppError
|
||||
// @Router /loan-paid-off-letters [get]
|
||||
func (h *handler) list(c *gin.Context) {
|
||||
filter, ok := parseListFilter(c)
|
||||
if !ok {
|
||||
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
|
||||
return
|
||||
}
|
||||
|
||||
result, err := h.repository.List(c.Request.Context(), filter)
|
||||
if err != nil {
|
||||
h.logger.Errorf("list loan paid off letters failed: %v", err)
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, appresult.SuccessWithData(result))
|
||||
}
|
||||
|
||||
// getByID godoc
|
||||
// @Summary Get loan paid off letter by ID
|
||||
// @Description Returns a single loan paid off letter
|
||||
// @Tags loan-paid-off-letters
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param id path int true "Loan paid off letter ID"
|
||||
// @Success 200 {object} appresult.AppSuccess
|
||||
// @Failure 400 {object} appresult.AppError
|
||||
// @Failure 404 {object} appresult.AppError
|
||||
// @Failure 500 {object} appresult.AppError
|
||||
// @Router /loan-paid-off-letters/{id} [get]
|
||||
func (h *handler) getByID(c *gin.Context) {
|
||||
id, ok := parseID(c.Param("id"))
|
||||
if !ok {
|
||||
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
|
||||
return
|
||||
}
|
||||
|
||||
item, err := h.repository.GetByID(c.Request.Context(), id)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
c.JSON(http.StatusNotFound, appresult.ErrNotFound)
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
h.logger.Errorf("get loan paid off letter failed: %v", err)
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, appresult.SuccessWithData(item))
|
||||
}
|
||||
|
||||
// create godoc
|
||||
// @Summary Create loan paid off letter
|
||||
// @Description Creates a new loan paid off letter
|
||||
// @Tags loan-paid-off-letters
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param body body CreateLoanPaidLetterDTO true "Loan paid off letter payload"
|
||||
// @Success 201 {object} appresult.AppSuccess
|
||||
// @Failure 400 {object} appresult.AppError
|
||||
// @Failure 500 {object} appresult.AppError
|
||||
// @Router /loan-paid-off-letters [post]
|
||||
func (h *handler) create(c *gin.Context) {
|
||||
var dto CreateLoanPaidLetterDTO
|
||||
if err := c.ShouldBindJSON(&dto); err != nil {
|
||||
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
|
||||
return
|
||||
}
|
||||
|
||||
item, err := h.repository.Create(c.Request.Context(), dto)
|
||||
if err != nil {
|
||||
h.logger.Errorf("create loan paid off letter failed: %v", err)
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusCreated, appresult.SuccessWithData(item))
|
||||
}
|
||||
|
||||
// update godoc
|
||||
// @Summary Update loan paid off letter
|
||||
// @Description Updates an existing loan paid off letter
|
||||
// @Tags loan-paid-off-letters
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param id path int true "Loan paid off letter ID"
|
||||
// @Param body body UpdateLoanPaidLetterDTO true "Loan paid off letter payload"
|
||||
// @Success 200 {object} appresult.AppSuccess
|
||||
// @Failure 400 {object} appresult.AppError
|
||||
// @Failure 404 {object} appresult.AppError
|
||||
// @Failure 500 {object} appresult.AppError
|
||||
// @Router /loan-paid-off-letters/{id} [put]
|
||||
func (h *handler) update(c *gin.Context) {
|
||||
id, ok := parseID(c.Param("id"))
|
||||
if !ok {
|
||||
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
|
||||
return
|
||||
}
|
||||
|
||||
var dto UpdateLoanPaidLetterDTO
|
||||
if err := c.ShouldBindJSON(&dto); err != nil {
|
||||
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
|
||||
return
|
||||
}
|
||||
|
||||
item, err := h.repository.Update(c.Request.Context(), id, dto)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
c.JSON(http.StatusNotFound, appresult.ErrNotFound)
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
h.logger.Errorf("update loan paid off letter failed: %v", err)
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, appresult.SuccessWithData(item))
|
||||
}
|
||||
|
||||
// delete godoc
|
||||
// @Summary Delete loan paid off letter
|
||||
// @Description Deletes a loan paid off letter
|
||||
// @Tags loan-paid-off-letters
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param id path int true "Loan paid off letter ID"
|
||||
// @Success 200 {object} appresult.AppSuccess
|
||||
// @Failure 400 {object} appresult.AppError
|
||||
// @Failure 404 {object} appresult.AppError
|
||||
// @Failure 500 {object} appresult.AppError
|
||||
// @Router /loan-paid-off-letters/{id} [delete]
|
||||
func (h *handler) delete(c *gin.Context) {
|
||||
id, ok := parseID(c.Param("id"))
|
||||
if !ok {
|
||||
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
|
||||
return
|
||||
}
|
||||
|
||||
if err := h.repository.Delete(c.Request.Context(), id); errors.Is(err, pgx.ErrNoRows) {
|
||||
c.JSON(http.StatusNotFound, appresult.ErrNotFound)
|
||||
return
|
||||
} else if err != nil {
|
||||
h.logger.Errorf("delete loan paid off letter failed: %v", err)
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, appresult.SuccessWithData("loan paid off letter removed"))
|
||||
}
|
||||
|
||||
func parseID(raw string) (int64, bool) {
|
||||
id, err := strconv.ParseInt(raw, 10, 64)
|
||||
if err != nil || id <= 0 {
|
||||
return 0, false
|
||||
}
|
||||
return id, true
|
||||
}
|
||||
|
||||
const (
|
||||
defaultPage = 1
|
||||
defaultLimit = 10
|
||||
maxLimit = 100
|
||||
)
|
||||
|
||||
func parseListFilter(c *gin.Context) (ListFilter, bool) {
|
||||
filter := ListFilter{
|
||||
Page: defaultPage,
|
||||
Limit: defaultLimit,
|
||||
}
|
||||
|
||||
if raw := c.Query("page"); raw != "" {
|
||||
page, err := strconv.Atoi(raw)
|
||||
if err != nil || page < 1 {
|
||||
return ListFilter{}, false
|
||||
}
|
||||
filter.Page = page
|
||||
}
|
||||
|
||||
if raw := c.Query("limit"); raw != "" {
|
||||
limit, err := strconv.Atoi(raw)
|
||||
if err != nil || limit < 1 || limit > maxLimit {
|
||||
return ListFilter{}, false
|
||||
}
|
||||
filter.Limit = limit
|
||||
}
|
||||
|
||||
if raw := strings.TrimSpace(c.Query("passport_id")); raw != "" {
|
||||
filter.PassportId = raw
|
||||
}
|
||||
|
||||
if raw := strings.TrimSpace(c.Query("status")); raw != "" {
|
||||
filter.Status = &raw
|
||||
}
|
||||
|
||||
if raw := strings.TrimSpace(c.Query("region")); raw != "" {
|
||||
filter.Region = raw
|
||||
}
|
||||
|
||||
if raw := c.Query("branch_id"); raw != "" {
|
||||
id, ok := parseID(raw)
|
||||
if !ok {
|
||||
return ListFilter{}, false
|
||||
}
|
||||
filter.BranchId = &id
|
||||
}
|
||||
|
||||
return filter, true
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
package loanpaidletter
|
||||
|
||||
import "context"
|
||||
|
||||
type Repository interface {
|
||||
List(ctx context.Context, filter ListFilter) (ListLoanPaidLetterDTO, error)
|
||||
GetByID(ctx context.Context, id int64) (LoanPaidLetterDTO, error)
|
||||
Create(ctx context.Context, dto CreateLoanPaidLetterDTO) (LoanPaidLetterDTO, error)
|
||||
Update(ctx context.Context, id int64, dto UpdateLoanPaidLetterDTO) (LoanPaidLetterDTO, error)
|
||||
Delete(ctx context.Context, id int64) error
|
||||
}
|
||||
+18
-56
@@ -6,20 +6,26 @@ import (
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"online-back/internal/admin/loansdocument"
|
||||
"online-back/internal/lending/loansdocument"
|
||||
"online-back/pkg/client/postgresql"
|
||||
"online-back/pkg/logging"
|
||||
"online-back/pkg/repository/genericrepo"
|
||||
|
||||
"github.com/jackc/pgx/v4"
|
||||
)
|
||||
|
||||
type repository struct {
|
||||
client postgresql.Client
|
||||
logger *logging.Logger
|
||||
client postgresql.Client
|
||||
generic *genericrepo.Repository[loansdocument.LoanDocumentDTO]
|
||||
logger *logging.Logger
|
||||
}
|
||||
|
||||
func NewRepository(client postgresql.Client, logger *logging.Logger) loansdocument.Repository {
|
||||
return &repository{client: client, logger: logger}
|
||||
return &repository{
|
||||
client: client,
|
||||
generic: genericrepo.New(client, "loan_order_required_docs d", documentColumns, scanLoanDocument),
|
||||
logger: logger,
|
||||
}
|
||||
}
|
||||
|
||||
const documentColumns = `d.id, d.name, d.value, d.active, d.created_at, d.updated_at`
|
||||
@@ -27,45 +33,17 @@ const documentColumns = `d.id, d.name, d.value, d.active, d.created_at, d.update
|
||||
const documentReturningColumns = `id, name, value, active, created_at, updated_at`
|
||||
|
||||
func (r *repository) List(ctx context.Context, filter loansdocument.ListFilter) (loansdocument.ListLoanDocumentDTO, error) {
|
||||
fromClause, whereClause, args := buildListQuery(filter)
|
||||
whereClause, args := buildListQuery(filter)
|
||||
|
||||
var count int64
|
||||
if err := r.client.QueryRow(ctx, `SELECT COUNT(*) `+fromClause+whereClause, args...).Scan(&count); err != nil {
|
||||
return loansdocument.ListLoanDocumentDTO{}, err
|
||||
}
|
||||
|
||||
offset := (filter.Page - 1) * filter.Limit
|
||||
limitPlaceholder := len(args) + 1
|
||||
offsetPlaceholder := len(args) + 2
|
||||
listQuery := fmt.Sprintf(
|
||||
`SELECT %s%s%s ORDER BY d.id LIMIT $%d OFFSET $%d`,
|
||||
documentColumns, fromClause, whereClause, limitPlaceholder, offsetPlaceholder,
|
||||
)
|
||||
|
||||
rows, err := r.client.Query(ctx, listQuery, append(args, filter.Limit, offset)...)
|
||||
items, count, err := r.generic.List(ctx, whereClause, args, filter.Page, filter.Limit, "id")
|
||||
if err != nil {
|
||||
return loansdocument.ListLoanDocumentDTO{}, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var items []loansdocument.LoanDocumentDTO
|
||||
for rows.Next() {
|
||||
item, err := scanLoanDocument(rows)
|
||||
if err != nil {
|
||||
return loansdocument.ListLoanDocumentDTO{}, err
|
||||
}
|
||||
items = append(items, item)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return loansdocument.ListLoanDocumentDTO{}, err
|
||||
}
|
||||
|
||||
return loansdocument.ListLoanDocumentDTO{Count: count, LoansDocuments: items}, nil
|
||||
}
|
||||
|
||||
func buildListQuery(filter loansdocument.ListFilter) (fromClause, whereClause string, args []interface{}) {
|
||||
fromClause = ` FROM loan_order_required_docs d`
|
||||
|
||||
func buildListQuery(filter loansdocument.ListFilter) (whereClause string, args []interface{}) {
|
||||
var conditions []string
|
||||
|
||||
if filter.DocumentName != "" {
|
||||
@@ -80,10 +58,10 @@ func buildListQuery(filter loansdocument.ListFilter) (fromClause, whereClause st
|
||||
}
|
||||
|
||||
if len(conditions) == 0 {
|
||||
return fromClause, "", args
|
||||
return "", args
|
||||
}
|
||||
|
||||
return fromClause, " WHERE " + strings.Join(conditions, " AND "), args
|
||||
return " WHERE " + strings.Join(conditions, " AND "), args
|
||||
}
|
||||
|
||||
func likePattern(term string) string {
|
||||
@@ -94,12 +72,7 @@ func likePattern(term string) string {
|
||||
}
|
||||
|
||||
func (r *repository) GetByID(ctx context.Context, id int64) (loansdocument.LoanDocumentDTO, error) {
|
||||
query := fmt.Sprintf(`SELECT %s FROM loan_order_required_docs d WHERE d.id = $1`, documentColumns)
|
||||
item, err := scanLoanDocument(r.client.QueryRow(ctx, query, id))
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return loansdocument.LoanDocumentDTO{}, err
|
||||
}
|
||||
return item, err
|
||||
return r.generic.GetByID(ctx, id)
|
||||
}
|
||||
|
||||
func (r *repository) Create(ctx context.Context, dto loansdocument.CreateLoanDocumentDTO) (loansdocument.LoanDocumentDTO, error) {
|
||||
@@ -147,21 +120,10 @@ func (r *repository) UpdateActive(ctx context.Context, id int64, active bool) (l
|
||||
}
|
||||
|
||||
func (r *repository) Delete(ctx context.Context, id int64) error {
|
||||
tag, err := r.client.Exec(ctx, `DELETE FROM loan_order_required_docs WHERE id = $1`, id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if tag.RowsAffected() == 0 {
|
||||
return pgx.ErrNoRows
|
||||
}
|
||||
return nil
|
||||
return r.generic.Delete(ctx, id)
|
||||
}
|
||||
|
||||
type scannable interface {
|
||||
Scan(dest ...interface{}) error
|
||||
}
|
||||
|
||||
func scanLoanDocument(row scannable) (loansdocument.LoanDocumentDTO, error) {
|
||||
func scanLoanDocument(row genericrepo.Scanner) (loansdocument.LoanDocumentDTO, error) {
|
||||
var item loansdocument.LoanDocumentDTO
|
||||
|
||||
if err := row.Scan(
|
||||
File renamed without changes.
File renamed without changes.
File renamed without changes.
@@ -0,0 +1,108 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"online-back/internal/lending/loansrepayment"
|
||||
"online-back/pkg/client/postgresql"
|
||||
"online-back/pkg/logging"
|
||||
"online-back/pkg/repository/genericrepo"
|
||||
|
||||
"github.com/jackc/pgx/v4"
|
||||
)
|
||||
|
||||
type repository struct {
|
||||
client postgresql.Client
|
||||
generic *genericrepo.Repository[loansrepayment.LoanRepaymentDTO]
|
||||
logger *logging.Logger
|
||||
}
|
||||
|
||||
func NewRepository(client postgresql.Client, logger *logging.Logger) loansrepayment.Repository {
|
||||
return &repository{
|
||||
client: client,
|
||||
generic: genericrepo.New(client, "loans l", loanColumns, scanLoanRepayment),
|
||||
logger: logger,
|
||||
}
|
||||
}
|
||||
|
||||
const loanColumns = `l.id, l.user_id, l.passport_serie, l.passport_id, l.account_number, l.created_at, l.updated_at`
|
||||
|
||||
const loanReturningColumns = `id, user_id, passport_serie, passport_id, account_number, created_at, updated_at`
|
||||
|
||||
func (r *repository) List(ctx context.Context, filter loansrepayment.ListFilter) (loansrepayment.ListLoanRepaymentDTO, error) {
|
||||
whereClause, args := buildListQuery(filter)
|
||||
|
||||
items, count, err := r.generic.List(ctx, whereClause, args, filter.Page, filter.Limit, "id")
|
||||
if err != nil {
|
||||
return loansrepayment.ListLoanRepaymentDTO{}, err
|
||||
}
|
||||
|
||||
return loansrepayment.ListLoanRepaymentDTO{Count: count, Loans: items}, nil
|
||||
}
|
||||
|
||||
func buildListQuery(filter loansrepayment.ListFilter) (whereClause string, args []interface{}) {
|
||||
var conditions []string
|
||||
if filter.PassportId != "" {
|
||||
args = append(args, likePattern(filter.PassportId))
|
||||
conditions = append(conditions, fmt.Sprintf("l.passport_id 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) GetByID(ctx context.Context, id int64) (loansrepayment.LoanRepaymentDTO, error) {
|
||||
return r.generic.GetByID(ctx, id)
|
||||
}
|
||||
|
||||
func (r *repository) Create(ctx context.Context, dto loansrepayment.CreateLoanRepaymentDTO) (loansrepayment.LoanRepaymentDTO, error) {
|
||||
query := fmt.Sprintf(`
|
||||
INSERT INTO loans (user_id, passport_serie, passport_id, account_number)
|
||||
VALUES ($1, $2, $3, $4)
|
||||
RETURNING %s`, loanReturningColumns)
|
||||
|
||||
return scanLoanRepayment(r.client.QueryRow(ctx, query, dto.UserId, dto.PassportSerie, dto.PassportId, dto.AccountNumber))
|
||||
}
|
||||
|
||||
func (r *repository) Update(ctx context.Context, id int64, dto loansrepayment.UpdateLoanRepaymentDTO) (loansrepayment.LoanRepaymentDTO, error) {
|
||||
query := fmt.Sprintf(`
|
||||
UPDATE loans SET
|
||||
user_id = $1, passport_serie = $2, passport_id = $3, account_number = $4,
|
||||
updated_at = (CURRENT_TIMESTAMP AT TIME ZONE 'UTC')
|
||||
WHERE id = $5
|
||||
RETURNING %s`, loanReturningColumns)
|
||||
|
||||
item, err := scanLoanRepayment(r.client.QueryRow(ctx, query, dto.UserId, dto.PassportSerie, dto.PassportId, dto.AccountNumber, id))
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return loansrepayment.LoanRepaymentDTO{}, err
|
||||
}
|
||||
return item, err
|
||||
}
|
||||
|
||||
func (r *repository) Delete(ctx context.Context, id int64) error {
|
||||
return r.generic.Delete(ctx, id)
|
||||
}
|
||||
|
||||
func scanLoanRepayment(row genericrepo.Scanner) (loansrepayment.LoanRepaymentDTO, error) {
|
||||
var item loansrepayment.LoanRepaymentDTO
|
||||
|
||||
if err := row.Scan(
|
||||
&item.Id, &item.UserId, &item.PassportSerie, &item.PassportId, &item.AccountNumber, &item.CreatedAt, &item.UpdatedAt,
|
||||
); err != nil {
|
||||
return loansrepayment.LoanRepaymentDTO{}, err
|
||||
}
|
||||
return item, nil
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
package loansrepayment
|
||||
|
||||
import "time"
|
||||
|
||||
type LoanRepaymentDTO struct {
|
||||
Id int64 `json:"id"`
|
||||
UserId int64 `json:"userId"`
|
||||
PassportSerie string `json:"passportSerie"`
|
||||
PassportId string `json:"passportId"`
|
||||
AccountNumber string `json:"accountNumber"`
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
UpdatedAt time.Time `json:"updatedAt"`
|
||||
}
|
||||
|
||||
type CreateLoanRepaymentDTO struct {
|
||||
UserId int64 `json:"userId" binding:"required"`
|
||||
PassportSerie string `json:"passportSerie" binding:"required"`
|
||||
PassportId string `json:"passportId" binding:"required"`
|
||||
AccountNumber string `json:"accountNumber" binding:"required"`
|
||||
}
|
||||
|
||||
type UpdateLoanRepaymentDTO struct {
|
||||
UserId int64 `json:"userId" binding:"required"`
|
||||
PassportSerie string `json:"passportSerie" binding:"required"`
|
||||
PassportId string `json:"passportId" binding:"required"`
|
||||
AccountNumber string `json:"accountNumber" binding:"required"`
|
||||
}
|
||||
|
||||
type ListFilter struct {
|
||||
PassportId string
|
||||
Page int
|
||||
Limit int
|
||||
}
|
||||
|
||||
type ListLoanRepaymentDTO struct {
|
||||
Count int64 `json:"count"`
|
||||
Loans []LoanRepaymentDTO `json:"loans"`
|
||||
}
|
||||
@@ -0,0 +1,242 @@
|
||||
package loansrepayment
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"online-back/internal/appresult"
|
||||
"online-back/internal/handlers"
|
||||
"online-back/pkg/logging"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/jackc/pgx/v4"
|
||||
)
|
||||
|
||||
const baseURL = "/loans-repayment"
|
||||
|
||||
type handler struct {
|
||||
logger *logging.Logger
|
||||
repository Repository
|
||||
}
|
||||
|
||||
func NewHandler(logger *logging.Logger, repository Repository) handlers.Handler {
|
||||
return &handler{logger: logger, repository: repository}
|
||||
}
|
||||
|
||||
func (h *handler) Register(router *gin.RouterGroup) {
|
||||
group := router.Group(baseURL, appresult.JwtTokenCheck())
|
||||
group.GET("", h.list)
|
||||
group.GET("/:id", h.getByID)
|
||||
group.POST("", h.create)
|
||||
group.PUT("/:id", h.update)
|
||||
group.DELETE("/:id", h.delete)
|
||||
}
|
||||
|
||||
// list godoc
|
||||
// @Summary List loan repayments
|
||||
// @Description Returns paginated loan repayments with optional filters
|
||||
// @Tags loans-repayment
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param passport_id query string false "Filter by passport ID"
|
||||
// @Param page query int false "Page number" default(1)
|
||||
// @Param limit query int false "Items per page" default(10)
|
||||
// @Success 200 {object} appresult.AppSuccess
|
||||
// @Failure 400 {object} appresult.AppError
|
||||
// @Failure 500 {object} appresult.AppError
|
||||
// @Router /loans-repayment [get]
|
||||
func (h *handler) list(c *gin.Context) {
|
||||
filter, ok := parseListFilter(c)
|
||||
if !ok {
|
||||
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
|
||||
return
|
||||
}
|
||||
|
||||
result, err := h.repository.List(c.Request.Context(), filter)
|
||||
if err != nil {
|
||||
h.logger.Errorf("list loan repayments failed: %v", err)
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, appresult.SuccessWithData(result))
|
||||
}
|
||||
|
||||
// getByID godoc
|
||||
// @Summary Get loan repayment by ID
|
||||
// @Description Returns a single loan repayment
|
||||
// @Tags loans-repayment
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param id path int true "Loan repayment ID"
|
||||
// @Success 200 {object} appresult.AppSuccess
|
||||
// @Failure 400 {object} appresult.AppError
|
||||
// @Failure 404 {object} appresult.AppError
|
||||
// @Failure 500 {object} appresult.AppError
|
||||
// @Router /loans-repayment/{id} [get]
|
||||
func (h *handler) getByID(c *gin.Context) {
|
||||
id, ok := parseID(c.Param("id"))
|
||||
if !ok {
|
||||
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
|
||||
return
|
||||
}
|
||||
|
||||
item, err := h.repository.GetByID(c.Request.Context(), id)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
c.JSON(http.StatusNotFound, appresult.ErrNotFound)
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
h.logger.Errorf("get loan repayment failed: %v", err)
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, appresult.SuccessWithData(item))
|
||||
}
|
||||
|
||||
// create godoc
|
||||
// @Summary Create loan repayment
|
||||
// @Description Creates a new loan repayment record
|
||||
// @Tags loans-repayment
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param body body CreateLoanRepaymentDTO true "Loan repayment payload"
|
||||
// @Success 201 {object} appresult.AppSuccess
|
||||
// @Failure 400 {object} appresult.AppError
|
||||
// @Failure 500 {object} appresult.AppError
|
||||
// @Router /loans-repayment [post]
|
||||
func (h *handler) create(c *gin.Context) {
|
||||
var dto CreateLoanRepaymentDTO
|
||||
if err := c.ShouldBindJSON(&dto); err != nil {
|
||||
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
|
||||
return
|
||||
}
|
||||
|
||||
item, err := h.repository.Create(c.Request.Context(), dto)
|
||||
if err != nil {
|
||||
h.logger.Errorf("create loan repayment failed: %v", err)
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusCreated, appresult.SuccessWithData(item))
|
||||
}
|
||||
|
||||
// update godoc
|
||||
// @Summary Update loan repayment
|
||||
// @Description Updates an existing loan repayment record
|
||||
// @Tags loans-repayment
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param id path int true "Loan repayment ID"
|
||||
// @Param body body UpdateLoanRepaymentDTO true "Loan repayment payload"
|
||||
// @Success 200 {object} appresult.AppSuccess
|
||||
// @Failure 400 {object} appresult.AppError
|
||||
// @Failure 404 {object} appresult.AppError
|
||||
// @Failure 500 {object} appresult.AppError
|
||||
// @Router /loans-repayment/{id} [put]
|
||||
func (h *handler) update(c *gin.Context) {
|
||||
id, ok := parseID(c.Param("id"))
|
||||
if !ok {
|
||||
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
|
||||
return
|
||||
}
|
||||
|
||||
var dto UpdateLoanRepaymentDTO
|
||||
if err := c.ShouldBindJSON(&dto); err != nil {
|
||||
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
|
||||
return
|
||||
}
|
||||
|
||||
item, err := h.repository.Update(c.Request.Context(), id, dto)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
c.JSON(http.StatusNotFound, appresult.ErrNotFound)
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
h.logger.Errorf("update loan repayment failed: %v", err)
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, appresult.SuccessWithData(item))
|
||||
}
|
||||
|
||||
// delete godoc
|
||||
// @Summary Delete loan repayment
|
||||
// @Description Deletes a loan repayment record
|
||||
// @Tags loans-repayment
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param id path int true "Loan repayment ID"
|
||||
// @Success 200 {object} appresult.AppSuccess
|
||||
// @Failure 400 {object} appresult.AppError
|
||||
// @Failure 404 {object} appresult.AppError
|
||||
// @Failure 500 {object} appresult.AppError
|
||||
// @Router /loans-repayment/{id} [delete]
|
||||
func (h *handler) delete(c *gin.Context) {
|
||||
id, ok := parseID(c.Param("id"))
|
||||
if !ok {
|
||||
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
|
||||
return
|
||||
}
|
||||
|
||||
if err := h.repository.Delete(c.Request.Context(), id); errors.Is(err, pgx.ErrNoRows) {
|
||||
c.JSON(http.StatusNotFound, appresult.ErrNotFound)
|
||||
return
|
||||
} else if err != nil {
|
||||
h.logger.Errorf("delete loan repayment failed: %v", err)
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, appresult.SuccessWithData("loan repayment removed"))
|
||||
}
|
||||
|
||||
func parseID(raw string) (int64, bool) {
|
||||
id, err := strconv.ParseInt(raw, 10, 64)
|
||||
if err != nil || id <= 0 {
|
||||
return 0, false
|
||||
}
|
||||
return id, true
|
||||
}
|
||||
|
||||
const (
|
||||
defaultPage = 1
|
||||
defaultLimit = 10
|
||||
maxLimit = 100
|
||||
)
|
||||
|
||||
func parseListFilter(c *gin.Context) (ListFilter, bool) {
|
||||
filter := ListFilter{
|
||||
Page: defaultPage,
|
||||
Limit: defaultLimit,
|
||||
}
|
||||
|
||||
if raw := c.Query("page"); raw != "" {
|
||||
page, err := strconv.Atoi(raw)
|
||||
if err != nil || page < 1 {
|
||||
return ListFilter{}, false
|
||||
}
|
||||
filter.Page = page
|
||||
}
|
||||
|
||||
if raw := c.Query("limit"); raw != "" {
|
||||
limit, err := strconv.Atoi(raw)
|
||||
if err != nil || limit < 1 || limit > maxLimit {
|
||||
return ListFilter{}, false
|
||||
}
|
||||
filter.Limit = limit
|
||||
}
|
||||
|
||||
if raw := strings.TrimSpace(c.Query("passport_id")); raw != "" {
|
||||
filter.PassportId = raw
|
||||
}
|
||||
|
||||
return filter, true
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
package loansrepayment
|
||||
|
||||
import "context"
|
||||
|
||||
type Repository interface {
|
||||
List(ctx context.Context, filter ListFilter) (ListLoanRepaymentDTO, error)
|
||||
GetByID(ctx context.Context, id int64) (LoanRepaymentDTO, error)
|
||||
Create(ctx context.Context, dto CreateLoanRepaymentDTO) (LoanRepaymentDTO, error)
|
||||
Update(ctx context.Context, id int64, dto UpdateLoanRepaymentDTO) (LoanRepaymentDTO, error)
|
||||
Delete(ctx context.Context, id int64) error
|
||||
}
|
||||
+18
-56
@@ -7,20 +7,26 @@ import (
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"online-back/internal/admin/loantype"
|
||||
"online-back/internal/lending/loantype"
|
||||
"online-back/pkg/client/postgresql"
|
||||
"online-back/pkg/logging"
|
||||
"online-back/pkg/repository/genericrepo"
|
||||
|
||||
"github.com/jackc/pgx/v4"
|
||||
)
|
||||
|
||||
type repository struct {
|
||||
client postgresql.Client
|
||||
logger *logging.Logger
|
||||
client postgresql.Client
|
||||
generic *genericrepo.Repository[loantype.LoanTypeDTO]
|
||||
logger *logging.Logger
|
||||
}
|
||||
|
||||
func NewRepository(client postgresql.Client, logger *logging.Logger) loantype.Repository {
|
||||
return &repository{client: client, logger: logger}
|
||||
return &repository{
|
||||
client: client,
|
||||
generic: genericrepo.New(client, "loan_types lt", loanTypeColumns, scanLoanType),
|
||||
logger: logger,
|
||||
}
|
||||
}
|
||||
|
||||
const loanTypeColumns = `lt.id, lt.name, lt.tax, lt.maturity, lt.notes, lt.active, lt.created_at, lt.updated_at`
|
||||
@@ -28,45 +34,17 @@ const loanTypeColumns = `lt.id, lt.name, lt.tax, lt.maturity, lt.notes, lt.activ
|
||||
const loanTypeReturningColumns = `id, name, tax, maturity, notes, active, created_at, updated_at`
|
||||
|
||||
func (r *repository) List(ctx context.Context, filter loantype.ListFilter) (loantype.ListLoanTypeDTO, error) {
|
||||
fromClause, whereClause, args := buildListQuery(filter)
|
||||
whereClause, args := buildListQuery(filter)
|
||||
|
||||
var count int64
|
||||
if err := r.client.QueryRow(ctx, `SELECT COUNT(*) `+fromClause+whereClause, args...).Scan(&count); err != nil {
|
||||
return loantype.ListLoanTypeDTO{}, err
|
||||
}
|
||||
|
||||
offset := (filter.Page - 1) * filter.Limit
|
||||
limitPlaceholder := len(args) + 1
|
||||
offsetPlaceholder := len(args) + 2
|
||||
listQuery := fmt.Sprintf(
|
||||
`SELECT %s%s%s ORDER BY lt.id LIMIT $%d OFFSET $%d`,
|
||||
loanTypeColumns, fromClause, whereClause, limitPlaceholder, offsetPlaceholder,
|
||||
)
|
||||
|
||||
rows, err := r.client.Query(ctx, listQuery, append(args, filter.Limit, offset)...)
|
||||
items, count, err := r.generic.List(ctx, whereClause, args, filter.Page, filter.Limit, "id")
|
||||
if err != nil {
|
||||
return loantype.ListLoanTypeDTO{}, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var items []loantype.LoanTypeDTO
|
||||
for rows.Next() {
|
||||
item, err := scanLoanType(rows)
|
||||
if err != nil {
|
||||
return loantype.ListLoanTypeDTO{}, err
|
||||
}
|
||||
items = append(items, item)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return loantype.ListLoanTypeDTO{}, err
|
||||
}
|
||||
|
||||
return loantype.ListLoanTypeDTO{Count: count, LoanTypes: items}, nil
|
||||
}
|
||||
|
||||
func buildListQuery(filter loantype.ListFilter) (fromClause, whereClause string, args []interface{}) {
|
||||
fromClause = ` FROM loan_types lt`
|
||||
|
||||
func buildListQuery(filter loantype.ListFilter) (whereClause string, args []interface{}) {
|
||||
var conditions []string
|
||||
if filter.LoanTypeName != "" {
|
||||
args = append(args, likePattern(filter.LoanTypeName))
|
||||
@@ -77,10 +55,10 @@ func buildListQuery(filter loantype.ListFilter) (fromClause, whereClause string,
|
||||
}
|
||||
|
||||
if len(conditions) == 0 {
|
||||
return fromClause, "", args
|
||||
return "", args
|
||||
}
|
||||
|
||||
return fromClause, " WHERE " + strings.Join(conditions, " AND "), args
|
||||
return " WHERE " + strings.Join(conditions, " AND "), args
|
||||
}
|
||||
|
||||
func likePattern(term string) string {
|
||||
@@ -91,12 +69,7 @@ func likePattern(term string) string {
|
||||
}
|
||||
|
||||
func (r *repository) GetByID(ctx context.Context, id int64) (loantype.LoanTypeDTO, error) {
|
||||
query := fmt.Sprintf(`SELECT %s FROM loan_types lt WHERE lt.id = $1`, loanTypeColumns)
|
||||
item, err := scanLoanType(r.client.QueryRow(ctx, query, id))
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return loantype.LoanTypeDTO{}, err
|
||||
}
|
||||
return item, err
|
||||
return r.generic.GetByID(ctx, id)
|
||||
}
|
||||
|
||||
func (r *repository) Create(ctx context.Context, dto loantype.CreateLoanTypeDTO) (loantype.LoanTypeDTO, error) {
|
||||
@@ -139,14 +112,7 @@ func (r *repository) Update(ctx context.Context, id int64, dto loantype.UpdateLo
|
||||
}
|
||||
|
||||
func (r *repository) Delete(ctx context.Context, id int64) error {
|
||||
tag, err := r.client.Exec(ctx, `DELETE FROM loan_types WHERE id = $1`, id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if tag.RowsAffected() == 0 {
|
||||
return pgx.ErrNoRows
|
||||
}
|
||||
return nil
|
||||
return r.generic.Delete(ctx, id)
|
||||
}
|
||||
|
||||
func marshalJSON(title, content loantype.LocalizedTitle) ([]byte, []byte, error) {
|
||||
@@ -161,11 +127,7 @@ func marshalJSON(title, content loantype.LocalizedTitle) ([]byte, []byte, error)
|
||||
return titleJSON, contentJSON, nil
|
||||
}
|
||||
|
||||
type scannable interface {
|
||||
Scan(dest ...interface{}) error
|
||||
}
|
||||
|
||||
func scanLoanType(row scannable) (loantype.LoanTypeDTO, error) {
|
||||
func scanLoanType(row genericrepo.Scanner) (loantype.LoanTypeDTO, error) {
|
||||
var item loantype.LoanTypeDTO
|
||||
var nameJSON, notesJSON []byte
|
||||
|
||||
File renamed without changes.
File renamed without changes.
File renamed without changes.
@@ -0,0 +1,39 @@
|
||||
// Package lending groups loan orders and their related documents,
|
||||
// repayments, types, and paid-off letters under one bounded context,
|
||||
// replacing the flat internal/admin/* listing.
|
||||
package lending
|
||||
|
||||
import (
|
||||
"online-back/internal/handlers"
|
||||
"online-back/internal/lending/loanorders"
|
||||
loanordersdb "online-back/internal/lending/loanorders/db"
|
||||
"online-back/internal/lending/loanpaidletter"
|
||||
loanpaidletterdb "online-back/internal/lending/loanpaidletter/db"
|
||||
"online-back/internal/lending/loansdocument"
|
||||
loansdocumentdb "online-back/internal/lending/loansdocument/db"
|
||||
"online-back/internal/lending/loansrepayment"
|
||||
loansrepaymentdb "online-back/internal/lending/loansrepayment/db"
|
||||
"online-back/internal/lending/loantype"
|
||||
loantypedb "online-back/internal/lending/loantype/db"
|
||||
"online-back/pkg/client/postgresql"
|
||||
"online-back/pkg/logging"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// Register wires every lending module's handler into router.
|
||||
func Register(router *gin.RouterGroup, client postgresql.Client, logger *logging.Logger) {
|
||||
for _, h := range Handlers(client, logger) {
|
||||
h.Register(router)
|
||||
}
|
||||
}
|
||||
|
||||
func Handlers(client postgresql.Client, logger *logging.Logger) []handlers.Handler {
|
||||
return []handlers.Handler{
|
||||
loantype.NewHandler(logger, loantypedb.NewRepository(client, logger)),
|
||||
loansdocument.NewHandler(logger, loansdocumentdb.NewRepository(client, logger)),
|
||||
loansrepayment.NewHandler(logger, loansrepaymentdb.NewRepository(client, logger)),
|
||||
loanorders.NewHandler(logger, loanordersdb.NewRepository(client, logger)),
|
||||
loanpaidletter.NewHandler(logger, loanpaidletterdb.NewRepository(client, logger)),
|
||||
}
|
||||
}
|
||||
Loaded 100 of 465 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user