diff --git a/app.go b/app.go index a9f40ff..c83ed8e 100755 --- a/app.go +++ b/app.go @@ -48,6 +48,8 @@ import ( // @tag.description Card orders // @tag.name activity-logs // @tag.description User activity audit trail +// @tag.name visa-master-payment-orders +// @tag.description Visa/Master student-transfer payment orders func main() { cfg := config.GetConfig() logger := logging.GetLogger() diff --git a/db/migrations/20260702125108_init.down.sql b/db/migrations/20260702125108_init.down.sql index 88c8dfd..784966e 100644 --- a/db/migrations/20260702125108_init.down.sql +++ b/db/migrations/20260702125108_init.down.sql @@ -2,6 +2,7 @@ DROP INDEX IF EXISTS idx_activity_logs_created_at; DROP INDEX IF EXISTS idx_activity_logs_module; DROP INDEX IF EXISTS idx_activity_logs_user_id; DROP TABLE IF EXISTS activity_logs; +DROP TABLE IF EXISTS visa_master_payment_orders; DROP TABLE IF EXISTS loan_paid_off_letters; DROP TABLE IF EXISTS loans; DROP TABLE IF EXISTS loan_orders; diff --git a/db/migrations/20260702125108_init.up.sql b/db/migrations/20260702125108_init.up.sql index d5a06a7..a8a226f 100644 --- a/db/migrations/20260702125108_init.up.sql +++ b/db/migrations/20260702125108_init.up.sql @@ -357,7 +357,42 @@ CREATE TABLE IF NOT EXISTS loan_paid_off_letters ( FOREIGN KEY (user_id) REFERENCES users(id) ); --- 6. Logs +-- 6. Payments (Visa / Master student transfers) +CREATE TABLE IF NOT EXISTS visa_master_payment_orders ( + id bigserial PRIMARY KEY, + unique_id character varying(255), + type character varying(255), + passport_name character varying(255) NOT NULL, + passport_surname character varying(255) NOT NULL, + phone character varying(255) NOT NULL, + email character varying(255), + region character varying(255) NOT NULL, + branch_id bigint NOT NULL, + user_id bigint, + address character varying(255) NOT NULL, + sender_datas json DEFAULT '{}'::json, + payment_reciever json DEFAULT '[]'::json, + documents json DEFAULT '{}'::json, + status character varying(255) DEFAULT 'pending', + notes character varying(255), + sender_full_name character varying(255) NOT NULL, + sender_passport_serie character varying(255) NOT NULL, + sender_passport_number character varying(255) NOT NULL, + sender_deposit_account character varying(255) NOT NULL, + reciever_full_name character varying(255), + reciever_passport_serie character varying(255), + reciever_passport_number character varying(255), + reciever_deposit_account character varying(255), + paid boolean NOT NULL DEFAULT false, + created_at TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL, + updated_at TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL, + CONSTRAINT visa_master_payment_orders_branch_id_fkey + FOREIGN KEY (branch_id) REFERENCES branches(id), + CONSTRAINT visa_master_payment_orders_user_id_fkey + FOREIGN KEY (user_id) REFERENCES users(id) +); + +-- 7. Logs CREATE TABLE IF NOT EXISTS activity_logs ( id bigserial PRIMARY KEY, user_id bigint, diff --git a/db/migrations/20260820131500_visa_master_payment_orders.down.sql b/db/migrations/20260820131500_visa_master_payment_orders.down.sql new file mode 100644 index 0000000..3ce8548 --- /dev/null +++ b/db/migrations/20260820131500_visa_master_payment_orders.down.sql @@ -0,0 +1 @@ +DROP TABLE IF EXISTS visa_master_payment_orders; diff --git a/db/migrations/20260820131500_visa_master_payment_orders.up.sql b/db/migrations/20260820131500_visa_master_payment_orders.up.sql new file mode 100644 index 0000000..2f9bbad --- /dev/null +++ b/db/migrations/20260820131500_visa_master_payment_orders.up.sql @@ -0,0 +1,33 @@ +CREATE TABLE IF NOT EXISTS visa_master_payment_orders ( + id bigserial PRIMARY KEY, + unique_id character varying(255), + type character varying(255), + passport_name character varying(255) NOT NULL, + passport_surname character varying(255) NOT NULL, + phone character varying(255) NOT NULL, + email character varying(255), + region character varying(255) NOT NULL, + branch_id bigint NOT NULL, + user_id bigint, + address character varying(255) NOT NULL, + sender_datas json DEFAULT '{}'::json, + payment_reciever json DEFAULT '[]'::json, + documents json DEFAULT '{}'::json, + status character varying(255) DEFAULT 'pending', + notes character varying(255), + sender_full_name character varying(255) NOT NULL, + sender_passport_serie character varying(255) NOT NULL, + sender_passport_number character varying(255) NOT NULL, + sender_deposit_account character varying(255) NOT NULL, + reciever_full_name character varying(255), + reciever_passport_serie character varying(255), + reciever_passport_number character varying(255), + reciever_deposit_account character varying(255), + paid boolean NOT NULL DEFAULT false, + created_at TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL, + updated_at TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL, + CONSTRAINT visa_master_payment_orders_branch_id_fkey + FOREIGN KEY (branch_id) REFERENCES branches(id), + CONSTRAINT visa_master_payment_orders_user_id_fkey + FOREIGN KEY (user_id) REFERENCES users(id) +); diff --git a/db/seed.sql b/db/seed.sql index 947b6e9..84ac849 100644 --- a/db/seed.sql +++ b/db/seed.sql @@ -11,6 +11,7 @@ BEGIN; TRUNCATE TABLE activity_logs, + visa_master_payment_orders, loan_paid_off_letters, loans, loan_orders, @@ -596,6 +597,72 @@ INSERT INTO loan_paid_off_letters ( 'CTR-2025-3303', '2025-02-10', '20000', 'Requested too early', NULL ); +-- --------------------------------------------------------------------------- +-- Visa / Master payment orders (student transfers) +-- documents JSON keys match the admin upload slots (student + sender). +-- --------------------------------------------------------------------------- +INSERT INTO visa_master_payment_orders ( + unique_id, type, passport_name, passport_surname, phone, email, + region, branch_id, user_id, address, + sender_datas, payment_reciever, documents, + status, notes, + sender_full_name, sender_passport_serie, sender_passport_number, sender_deposit_account, + reciever_full_name, reciever_passport_serie, reciever_passport_number, reciever_deposit_account, + paid +) VALUES +( + 'VMP-2026-0001', 'student', 'Serdar', 'Myradow', '+993 61 92 92 48', 'serdar@bank.tm', + 'AG', 1, 5, 'Aşgabat, Parahat 7', + '{"fullName":"Myradow Serdar Orazowiç","passportSerie":"I-AG","passportNumber":"123456","depositAccount":"23202984200012345678"}'::json, + '[{"fullName":"Orazowa Gulnar Myradowna","passportSerie":"I-AG","passportNumber":"654321"}]'::json, + '{ + "student_visa_card_details":["visa-card-1.pdf"], + "student_enrollment_certificate":["enrollment-1.pdf"], + "student_ticket_copy":["ticket-1.pdf"], + "student_internal_passport":["student-internal-1.pdf"], + "student_foreign_passport":["student-foreign-1.pdf"], + "student_visa_page":["student-visa-page-1.pdf"], + "student_stamp_page":["student-stamp-1.pdf"], + "student_enrollment_clarification":[], + "sender_internal_passport":["sender-internal-1.pdf"], + "sender_foreign_passport":["sender-foreign-1.pdf"], + "sender_stamp_page":["sender-stamp-1.pdf"], + "kinship_documents":["kinship-1.pdf"], + "first_passport_series_info":[], + "police_passport_series_info":[] + }'::json, + 'pending', 'Garaşylýar', + 'Myradow Serdar Orazowiç', 'I-AG', '123456', '23202984200012345678', + 'Orazowa Gulnar Myradowna', 'I-AG', '654321', NULL, + false +), +( + 'VMP-2026-0002', 'student', 'Kerim', 'Atayew', '+993 61 92 92 48', NULL, + 'AG', 2, 9, 'Aşgabat, 10 ýyl Abadançylyk', + '{"fullName":"Atayew Kerim Begliýewiç","passportSerie":"I-AG","passportNumber":"101010","depositAccount":"23202984200010101011"}'::json, + '[{"fullName":"Gurbanowa Leyla Saparowna","passportSerie":"I-AG","passportNumber":"303030"}]'::json, + '{ + "student_visa_card_details":["visa-card-2.pdf"], + "student_enrollment_certificate":[], + "student_ticket_copy":[], + "student_internal_passport":["student-internal-2.pdf"], + "student_foreign_passport":[], + "student_visa_page":[], + "student_stamp_page":[], + "student_enrollment_clarification":[], + "sender_internal_passport":["sender-internal-2.pdf"], + "sender_foreign_passport":[], + "sender_stamp_page":["sender-stamp-2.pdf"], + "kinship_documents":[], + "first_passport_series_info":["old-passport-series-2.pdf"], + "police_passport_series_info":[] + }'::json, + 'approved', NULL, + 'Atayew Kerim Begliýewiç', 'I-AG', '101010', '23202984200010101011', + 'Gurbanowa Leyla Saparowna', 'I-AG', '303030', NULL, + true +); + -- --------------------------------------------------------------------------- -- Activity logs -- --------------------------------------------------------------------------- @@ -633,6 +700,7 @@ UNION ALL SELECT 'card_pin_orders', count(*) FROM card_pin_orders UNION ALL SELECT 'loan_orders', count(*) FROM loan_orders UNION ALL SELECT 'loans', count(*) FROM loans UNION ALL SELECT 'loan_paid_off_letters', count(*) FROM loan_paid_off_letters +UNION ALL SELECT 'visa_master_payment_orders', count(*) FROM visa_master_payment_orders UNION ALL SELECT 'registration_verifications', count(*) FROM registration_verifications UNION ALL SELECT 'activity_logs', count(*) FROM activity_logs ORDER BY 1; diff --git a/docs/docs.go b/docs/docs.go index 5d8a850..7e98296 100644 --- a/docs/docs.go +++ b/docs/docs.go @@ -5322,7 +5322,7 @@ const docTemplate = `{ "BearerAuth": [] } ], - "description": "Returns paginated users with role user, with optional filters", + "description": "Returns paginated users with role user, including roleId", "produces": [ "application/json" ], @@ -5436,7 +5436,7 @@ const docTemplate = `{ "BearerAuth": [] } ], - "description": "Returns paginated client users (role user, not assigned to any branch)", + "description": "Returns paginated client users (role user, not assigned to any branch), including roleId", "produces": [ "application/json" ], @@ -5501,7 +5501,7 @@ const docTemplate = `{ "BearerAuth": [] } ], - "description": "Returns paginated users assigned to branches (from branch_user), including each user's branches.", + "description": "Returns paginated users assigned to branches (from branch_user), including each user's branches and roleId.", "produces": [ "application/json" ], @@ -5566,7 +5566,7 @@ const docTemplate = `{ "BearerAuth": [] } ], - "description": "Returns a single user with assigned branches", + "description": "Returns a single user with assigned branches and roleId", "produces": [ "application/json" ], @@ -5722,6 +5722,355 @@ const docTemplate = `{ } } } + }, + "/visa-master-payment-orders": { + "get": { + "security": [ + { + "BearerAuth": [] + } + ], + "description": "Returns paginated visa/master payment orders with branch and user details", + "produces": [ + "application/json" + ], + "tags": [ + "visa-master-payment-orders" + ], + "summary": "List visa/master payment orders", + "parameters": [ + { + "type": "string", + "description": "Filter by passport name or surname", + "name": "name", + "in": "query" + }, + { + "type": "string", + "description": "Filter by status", + "name": "status", + "in": "query" + }, + { + "type": "integer", + "description": "Filter by branch ID", + "name": "branch_id", + "in": "query" + }, + { + "type": "integer", + "description": "Filter by user ID", + "name": "user_id", + "in": "query" + }, + { + "type": "string", + "description": "Filter by region", + "name": "region", + "in": "query" + }, + { + "type": "integer", + "default": 1, + "description": "Page number", + "name": "page", + "in": "query" + }, + { + "type": "integer", + "default": 10, + "description": "Items per page", + "name": "limit", + "in": "query" + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/appresult.AppSuccess" + } + }, + "400": { + "description": "Bad Request", + "schema": { + "$ref": "#/definitions/appresult.AppError" + } + }, + "500": { + "description": "Internal Server Error", + "schema": { + "$ref": "#/definitions/appresult.AppError" + } + } + } + }, + "post": { + "security": [ + { + "BearerAuth": [] + } + ], + "description": "Creates a new visa/master payment order", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "visa-master-payment-orders" + ], + "summary": "Create visa/master payment order", + "parameters": [ + { + "description": "Visa/master payment order payload", + "name": "body", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/visamaster.CreateVisaMasterPaymentOrderDTO" + } + } + ], + "responses": { + "201": { + "description": "Created", + "schema": { + "$ref": "#/definitions/appresult.AppSuccess" + } + }, + "400": { + "description": "Bad Request", + "schema": { + "$ref": "#/definitions/appresult.AppError" + } + }, + "500": { + "description": "Internal Server Error", + "schema": { + "$ref": "#/definitions/appresult.AppError" + } + } + } + } + }, + "/visa-master-payment-orders/branches": { + "get": { + "security": [ + { + "BearerAuth": [] + } + ], + "description": "Returns branches for the selected province for visa/master payment order forms", + "produces": [ + "application/json" + ], + "tags": [ + "visa-master-payment-orders" + ], + "summary": "List branches by province", + "parameters": [ + { + "type": "integer", + "description": "Province ID", + "name": "province_id", + "in": "query", + "required": true + }, + { + "type": "boolean", + "default": true, + "description": "Only active branches", + "name": "active", + "in": "query" + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/appresult.AppSuccess" + } + }, + "400": { + "description": "Bad Request", + "schema": { + "$ref": "#/definitions/appresult.AppError" + } + }, + "500": { + "description": "Internal Server Error", + "schema": { + "$ref": "#/definitions/appresult.AppError" + } + } + } + } + }, + "/visa-master-payment-orders/{id}": { + "get": { + "security": [ + { + "BearerAuth": [] + } + ], + "description": "Returns a single visa/master payment order with branch and user details", + "produces": [ + "application/json" + ], + "tags": [ + "visa-master-payment-orders" + ], + "summary": "Get visa/master payment order by ID", + "parameters": [ + { + "type": "integer", + "description": "Visa/master payment order ID", + "name": "id", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/appresult.AppSuccess" + } + }, + "400": { + "description": "Bad Request", + "schema": { + "$ref": "#/definitions/appresult.AppError" + } + }, + "404": { + "description": "Not Found", + "schema": { + "$ref": "#/definitions/appresult.AppError" + } + }, + "500": { + "description": "Internal Server Error", + "schema": { + "$ref": "#/definitions/appresult.AppError" + } + } + } + }, + "put": { + "security": [ + { + "BearerAuth": [] + } + ], + "description": "Updates an existing visa/master payment order", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "visa-master-payment-orders" + ], + "summary": "Update visa/master payment order", + "parameters": [ + { + "type": "integer", + "description": "Visa/master payment order ID", + "name": "id", + "in": "path", + "required": true + }, + { + "description": "Visa/master payment order payload", + "name": "body", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/visamaster.UpdateVisaMasterPaymentOrderDTO" + } + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/appresult.AppSuccess" + } + }, + "400": { + "description": "Bad Request", + "schema": { + "$ref": "#/definitions/appresult.AppError" + } + }, + "404": { + "description": "Not Found", + "schema": { + "$ref": "#/definitions/appresult.AppError" + } + }, + "500": { + "description": "Internal Server Error", + "schema": { + "$ref": "#/definitions/appresult.AppError" + } + } + } + }, + "delete": { + "security": [ + { + "BearerAuth": [] + } + ], + "description": "Deletes a visa/master payment order", + "produces": [ + "application/json" + ], + "tags": [ + "visa-master-payment-orders" + ], + "summary": "Delete visa/master payment order", + "parameters": [ + { + "type": "integer", + "description": "Visa/master payment order ID", + "name": "id", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/appresult.AppSuccess" + } + }, + "400": { + "description": "Bad Request", + "schema": { + "$ref": "#/definitions/appresult.AppError" + } + }, + "404": { + "description": "Not Found", + "schema": { + "$ref": "#/definitions/appresult.AppError" + } + }, + "500": { + "description": "Internal Server Error", + "schema": { + "$ref": "#/definitions/appresult.AppError" + } + } + } + } } }, "definitions": { @@ -7550,6 +7899,190 @@ const docTemplate = `{ "type": "integer" } } + }, + "visamaster.CreateVisaMasterPaymentOrderDTO": { + "type": "object", + "required": [ + "address", + "branchId", + "passportName", + "passportSurname", + "phone", + "region", + "senderDepositAccount", + "senderFullName", + "senderPassportNumber", + "senderPassportSerie" + ], + "properties": { + "address": { + "type": "string" + }, + "branchId": { + "type": "integer" + }, + "documents": { + "type": "object" + }, + "email": { + "type": "string" + }, + "notes": { + "type": "string" + }, + "paid": { + "type": "boolean" + }, + "passportName": { + "type": "string" + }, + "passportSurname": { + "type": "string" + }, + "paymentReciever": { + "type": "array", + "items": { + "type": "object" + } + }, + "phone": { + "type": "string" + }, + "recieverDepositAccount": { + "type": "string" + }, + "recieverFullName": { + "type": "string" + }, + "recieverPassportNumber": { + "type": "string" + }, + "recieverPassportSerie": { + "type": "string" + }, + "region": { + "type": "string" + }, + "senderDatas": { + "type": "object" + }, + "senderDepositAccount": { + "type": "string" + }, + "senderFullName": { + "type": "string" + }, + "senderPassportNumber": { + "type": "string" + }, + "senderPassportSerie": { + "type": "string" + }, + "status": { + "type": "string" + }, + "type": { + "type": "string" + }, + "uniqueId": { + "type": "string" + }, + "userId": { + "type": "integer" + } + } + }, + "visamaster.UpdateVisaMasterPaymentOrderDTO": { + "type": "object", + "required": [ + "address", + "branchId", + "passportName", + "passportSurname", + "phone", + "region", + "senderDepositAccount", + "senderFullName", + "senderPassportNumber", + "senderPassportSerie" + ], + "properties": { + "address": { + "type": "string" + }, + "branchId": { + "type": "integer" + }, + "documents": { + "type": "object" + }, + "email": { + "type": "string" + }, + "notes": { + "type": "string" + }, + "paid": { + "type": "boolean" + }, + "passportName": { + "type": "string" + }, + "passportSurname": { + "type": "string" + }, + "paymentReciever": { + "type": "array", + "items": { + "type": "object" + } + }, + "phone": { + "type": "string" + }, + "recieverDepositAccount": { + "type": "string" + }, + "recieverFullName": { + "type": "string" + }, + "recieverPassportNumber": { + "type": "string" + }, + "recieverPassportSerie": { + "type": "string" + }, + "region": { + "type": "string" + }, + "senderDatas": { + "type": "object" + }, + "senderDepositAccount": { + "type": "string" + }, + "senderFullName": { + "type": "string" + }, + "senderPassportNumber": { + "type": "string" + }, + "senderPassportSerie": { + "type": "string" + }, + "status": { + "type": "string" + }, + "type": { + "type": "string" + }, + "uniqueId": { + "type": "string" + }, + "userId": { + "type": "integer" + } + } } }, "securityDefinitions": { diff --git a/docs/swagger.json b/docs/swagger.json index e52d084..888d7a2 100644 --- a/docs/swagger.json +++ b/docs/swagger.json @@ -5316,7 +5316,7 @@ "BearerAuth": [] } ], - "description": "Returns paginated users with role user, with optional filters", + "description": "Returns paginated users with role user, including roleId", "produces": [ "application/json" ], @@ -5430,7 +5430,7 @@ "BearerAuth": [] } ], - "description": "Returns paginated client users (role user, not assigned to any branch)", + "description": "Returns paginated client users (role user, not assigned to any branch), including roleId", "produces": [ "application/json" ], @@ -5495,7 +5495,7 @@ "BearerAuth": [] } ], - "description": "Returns paginated users assigned to branches (from branch_user), including each user's branches.", + "description": "Returns paginated users assigned to branches (from branch_user), including each user's branches and roleId.", "produces": [ "application/json" ], @@ -5560,7 +5560,7 @@ "BearerAuth": [] } ], - "description": "Returns a single user with assigned branches", + "description": "Returns a single user with assigned branches and roleId", "produces": [ "application/json" ], @@ -5716,6 +5716,355 @@ } } } + }, + "/visa-master-payment-orders": { + "get": { + "security": [ + { + "BearerAuth": [] + } + ], + "description": "Returns paginated visa/master payment orders with branch and user details", + "produces": [ + "application/json" + ], + "tags": [ + "visa-master-payment-orders" + ], + "summary": "List visa/master payment orders", + "parameters": [ + { + "type": "string", + "description": "Filter by passport name or surname", + "name": "name", + "in": "query" + }, + { + "type": "string", + "description": "Filter by status", + "name": "status", + "in": "query" + }, + { + "type": "integer", + "description": "Filter by branch ID", + "name": "branch_id", + "in": "query" + }, + { + "type": "integer", + "description": "Filter by user ID", + "name": "user_id", + "in": "query" + }, + { + "type": "string", + "description": "Filter by region", + "name": "region", + "in": "query" + }, + { + "type": "integer", + "default": 1, + "description": "Page number", + "name": "page", + "in": "query" + }, + { + "type": "integer", + "default": 10, + "description": "Items per page", + "name": "limit", + "in": "query" + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/appresult.AppSuccess" + } + }, + "400": { + "description": "Bad Request", + "schema": { + "$ref": "#/definitions/appresult.AppError" + } + }, + "500": { + "description": "Internal Server Error", + "schema": { + "$ref": "#/definitions/appresult.AppError" + } + } + } + }, + "post": { + "security": [ + { + "BearerAuth": [] + } + ], + "description": "Creates a new visa/master payment order", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "visa-master-payment-orders" + ], + "summary": "Create visa/master payment order", + "parameters": [ + { + "description": "Visa/master payment order payload", + "name": "body", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/visamaster.CreateVisaMasterPaymentOrderDTO" + } + } + ], + "responses": { + "201": { + "description": "Created", + "schema": { + "$ref": "#/definitions/appresult.AppSuccess" + } + }, + "400": { + "description": "Bad Request", + "schema": { + "$ref": "#/definitions/appresult.AppError" + } + }, + "500": { + "description": "Internal Server Error", + "schema": { + "$ref": "#/definitions/appresult.AppError" + } + } + } + } + }, + "/visa-master-payment-orders/branches": { + "get": { + "security": [ + { + "BearerAuth": [] + } + ], + "description": "Returns branches for the selected province for visa/master payment order forms", + "produces": [ + "application/json" + ], + "tags": [ + "visa-master-payment-orders" + ], + "summary": "List branches by province", + "parameters": [ + { + "type": "integer", + "description": "Province ID", + "name": "province_id", + "in": "query", + "required": true + }, + { + "type": "boolean", + "default": true, + "description": "Only active branches", + "name": "active", + "in": "query" + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/appresult.AppSuccess" + } + }, + "400": { + "description": "Bad Request", + "schema": { + "$ref": "#/definitions/appresult.AppError" + } + }, + "500": { + "description": "Internal Server Error", + "schema": { + "$ref": "#/definitions/appresult.AppError" + } + } + } + } + }, + "/visa-master-payment-orders/{id}": { + "get": { + "security": [ + { + "BearerAuth": [] + } + ], + "description": "Returns a single visa/master payment order with branch and user details", + "produces": [ + "application/json" + ], + "tags": [ + "visa-master-payment-orders" + ], + "summary": "Get visa/master payment order by ID", + "parameters": [ + { + "type": "integer", + "description": "Visa/master payment order ID", + "name": "id", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/appresult.AppSuccess" + } + }, + "400": { + "description": "Bad Request", + "schema": { + "$ref": "#/definitions/appresult.AppError" + } + }, + "404": { + "description": "Not Found", + "schema": { + "$ref": "#/definitions/appresult.AppError" + } + }, + "500": { + "description": "Internal Server Error", + "schema": { + "$ref": "#/definitions/appresult.AppError" + } + } + } + }, + "put": { + "security": [ + { + "BearerAuth": [] + } + ], + "description": "Updates an existing visa/master payment order", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "visa-master-payment-orders" + ], + "summary": "Update visa/master payment order", + "parameters": [ + { + "type": "integer", + "description": "Visa/master payment order ID", + "name": "id", + "in": "path", + "required": true + }, + { + "description": "Visa/master payment order payload", + "name": "body", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/visamaster.UpdateVisaMasterPaymentOrderDTO" + } + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/appresult.AppSuccess" + } + }, + "400": { + "description": "Bad Request", + "schema": { + "$ref": "#/definitions/appresult.AppError" + } + }, + "404": { + "description": "Not Found", + "schema": { + "$ref": "#/definitions/appresult.AppError" + } + }, + "500": { + "description": "Internal Server Error", + "schema": { + "$ref": "#/definitions/appresult.AppError" + } + } + } + }, + "delete": { + "security": [ + { + "BearerAuth": [] + } + ], + "description": "Deletes a visa/master payment order", + "produces": [ + "application/json" + ], + "tags": [ + "visa-master-payment-orders" + ], + "summary": "Delete visa/master payment order", + "parameters": [ + { + "type": "integer", + "description": "Visa/master payment order ID", + "name": "id", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/appresult.AppSuccess" + } + }, + "400": { + "description": "Bad Request", + "schema": { + "$ref": "#/definitions/appresult.AppError" + } + }, + "404": { + "description": "Not Found", + "schema": { + "$ref": "#/definitions/appresult.AppError" + } + }, + "500": { + "description": "Internal Server Error", + "schema": { + "$ref": "#/definitions/appresult.AppError" + } + } + } + } } }, "definitions": { @@ -7544,6 +7893,190 @@ "type": "integer" } } + }, + "visamaster.CreateVisaMasterPaymentOrderDTO": { + "type": "object", + "required": [ + "address", + "branchId", + "passportName", + "passportSurname", + "phone", + "region", + "senderDepositAccount", + "senderFullName", + "senderPassportNumber", + "senderPassportSerie" + ], + "properties": { + "address": { + "type": "string" + }, + "branchId": { + "type": "integer" + }, + "documents": { + "type": "object" + }, + "email": { + "type": "string" + }, + "notes": { + "type": "string" + }, + "paid": { + "type": "boolean" + }, + "passportName": { + "type": "string" + }, + "passportSurname": { + "type": "string" + }, + "paymentReciever": { + "type": "array", + "items": { + "type": "object" + } + }, + "phone": { + "type": "string" + }, + "recieverDepositAccount": { + "type": "string" + }, + "recieverFullName": { + "type": "string" + }, + "recieverPassportNumber": { + "type": "string" + }, + "recieverPassportSerie": { + "type": "string" + }, + "region": { + "type": "string" + }, + "senderDatas": { + "type": "object" + }, + "senderDepositAccount": { + "type": "string" + }, + "senderFullName": { + "type": "string" + }, + "senderPassportNumber": { + "type": "string" + }, + "senderPassportSerie": { + "type": "string" + }, + "status": { + "type": "string" + }, + "type": { + "type": "string" + }, + "uniqueId": { + "type": "string" + }, + "userId": { + "type": "integer" + } + } + }, + "visamaster.UpdateVisaMasterPaymentOrderDTO": { + "type": "object", + "required": [ + "address", + "branchId", + "passportName", + "passportSurname", + "phone", + "region", + "senderDepositAccount", + "senderFullName", + "senderPassportNumber", + "senderPassportSerie" + ], + "properties": { + "address": { + "type": "string" + }, + "branchId": { + "type": "integer" + }, + "documents": { + "type": "object" + }, + "email": { + "type": "string" + }, + "notes": { + "type": "string" + }, + "paid": { + "type": "boolean" + }, + "passportName": { + "type": "string" + }, + "passportSurname": { + "type": "string" + }, + "paymentReciever": { + "type": "array", + "items": { + "type": "object" + } + }, + "phone": { + "type": "string" + }, + "recieverDepositAccount": { + "type": "string" + }, + "recieverFullName": { + "type": "string" + }, + "recieverPassportNumber": { + "type": "string" + }, + "recieverPassportSerie": { + "type": "string" + }, + "region": { + "type": "string" + }, + "senderDatas": { + "type": "object" + }, + "senderDepositAccount": { + "type": "string" + }, + "senderFullName": { + "type": "string" + }, + "senderPassportNumber": { + "type": "string" + }, + "senderPassportSerie": { + "type": "string" + }, + "status": { + "type": "string" + }, + "type": { + "type": "string" + }, + "uniqueId": { + "type": "string" + }, + "userId": { + "type": "integer" + } + } } }, "securityDefinitions": { diff --git a/docs/swagger.yaml b/docs/swagger.yaml index 6253a1a..5db9407 100644 --- a/docs/swagger.yaml +++ b/docs/swagger.yaml @@ -1253,6 +1253,134 @@ definitions: - branchId - userId type: object + visamaster.CreateVisaMasterPaymentOrderDTO: + properties: + address: + type: string + branchId: + type: integer + documents: + type: object + email: + type: string + notes: + type: string + paid: + type: boolean + passportName: + type: string + passportSurname: + type: string + paymentReciever: + items: + type: object + type: array + phone: + type: string + recieverDepositAccount: + type: string + recieverFullName: + type: string + recieverPassportNumber: + type: string + recieverPassportSerie: + type: string + region: + type: string + senderDatas: + type: object + senderDepositAccount: + type: string + senderFullName: + type: string + senderPassportNumber: + type: string + senderPassportSerie: + type: string + status: + type: string + type: + type: string + uniqueId: + type: string + userId: + type: integer + required: + - address + - branchId + - passportName + - passportSurname + - phone + - region + - senderDepositAccount + - senderFullName + - senderPassportNumber + - senderPassportSerie + type: object + visamaster.UpdateVisaMasterPaymentOrderDTO: + properties: + address: + type: string + branchId: + type: integer + documents: + type: object + email: + type: string + notes: + type: string + paid: + type: boolean + passportName: + type: string + passportSurname: + type: string + paymentReciever: + items: + type: object + type: array + phone: + type: string + recieverDepositAccount: + type: string + recieverFullName: + type: string + recieverPassportNumber: + type: string + recieverPassportSerie: + type: string + region: + type: string + senderDatas: + type: object + senderDepositAccount: + type: string + senderFullName: + type: string + senderPassportNumber: + type: string + senderPassportSerie: + type: string + status: + type: string + type: + type: string + uniqueId: + type: string + userId: + type: integer + required: + - address + - branchId + - passportName + - passportSurname + - phone + - region + - senderDepositAccount + - senderFullName + - senderPassportNumber + - senderPassportSerie + type: object host: localhost:5005 info: contact: {} @@ -4660,7 +4788,7 @@ paths: - auth /users: get: - description: Returns paginated users with role user, with optional filters + description: Returns paginated users with role user, including roleId parameters: - description: Search by username, first name, or last name in: query @@ -4765,7 +4893,7 @@ paths: tags: - user get: - description: Returns a single user with assigned branches + description: Returns a single user with assigned branches and roleId parameters: - description: User ID in: path @@ -4839,7 +4967,7 @@ paths: /users/clients: get: description: Returns paginated client users (role user, not assigned to any - branch) + branch), including roleId parameters: - description: Search by username, first name, or last name in: query @@ -4882,7 +5010,7 @@ paths: /users/staff: get: description: Returns paginated users assigned to branches (from branch_user), - including each user's branches. + including each user's branches and roleId. parameters: - description: Search by username, first name, or last name in: query @@ -4922,6 +5050,233 @@ paths: summary: List staff users tags: - user + /visa-master-payment-orders: + get: + description: Returns paginated visa/master payment orders with branch and user + details + parameters: + - description: Filter by passport name or surname + in: query + name: name + type: string + - description: Filter by status + in: query + name: status + type: string + - description: Filter by branch ID + in: query + name: branch_id + type: integer + - description: Filter by user ID + in: query + name: user_id + type: integer + - description: Filter by region + in: query + name: region + type: string + - default: 1 + description: Page number + in: query + name: page + type: integer + - default: 10 + description: Items per page + in: query + name: limit + type: integer + produces: + - application/json + responses: + "200": + description: OK + schema: + $ref: '#/definitions/appresult.AppSuccess' + "400": + description: Bad Request + schema: + $ref: '#/definitions/appresult.AppError' + "500": + description: Internal Server Error + schema: + $ref: '#/definitions/appresult.AppError' + security: + - BearerAuth: [] + summary: List visa/master payment orders + tags: + - visa-master-payment-orders + post: + consumes: + - application/json + description: Creates a new visa/master payment order + parameters: + - description: Visa/master payment order payload + in: body + name: body + required: true + schema: + $ref: '#/definitions/visamaster.CreateVisaMasterPaymentOrderDTO' + produces: + - application/json + responses: + "201": + description: Created + schema: + $ref: '#/definitions/appresult.AppSuccess' + "400": + description: Bad Request + schema: + $ref: '#/definitions/appresult.AppError' + "500": + description: Internal Server Error + schema: + $ref: '#/definitions/appresult.AppError' + security: + - BearerAuth: [] + summary: Create visa/master payment order + tags: + - visa-master-payment-orders + /visa-master-payment-orders/{id}: + delete: + description: Deletes a visa/master payment order + parameters: + - description: Visa/master payment order ID + in: path + name: id + required: true + type: integer + produces: + - application/json + responses: + "200": + description: OK + schema: + $ref: '#/definitions/appresult.AppSuccess' + "400": + description: Bad Request + schema: + $ref: '#/definitions/appresult.AppError' + "404": + description: Not Found + schema: + $ref: '#/definitions/appresult.AppError' + "500": + description: Internal Server Error + schema: + $ref: '#/definitions/appresult.AppError' + security: + - BearerAuth: [] + summary: Delete visa/master payment order + tags: + - visa-master-payment-orders + get: + description: Returns a single visa/master payment order with branch and user + details + parameters: + - description: Visa/master payment order ID + in: path + name: id + required: true + type: integer + produces: + - application/json + responses: + "200": + description: OK + schema: + $ref: '#/definitions/appresult.AppSuccess' + "400": + description: Bad Request + schema: + $ref: '#/definitions/appresult.AppError' + "404": + description: Not Found + schema: + $ref: '#/definitions/appresult.AppError' + "500": + description: Internal Server Error + schema: + $ref: '#/definitions/appresult.AppError' + security: + - BearerAuth: [] + summary: Get visa/master payment order by ID + tags: + - visa-master-payment-orders + put: + consumes: + - application/json + description: Updates an existing visa/master payment order + parameters: + - description: Visa/master payment order ID + in: path + name: id + required: true + type: integer + - description: Visa/master payment order payload + in: body + name: body + required: true + schema: + $ref: '#/definitions/visamaster.UpdateVisaMasterPaymentOrderDTO' + produces: + - application/json + responses: + "200": + description: OK + schema: + $ref: '#/definitions/appresult.AppSuccess' + "400": + description: Bad Request + schema: + $ref: '#/definitions/appresult.AppError' + "404": + description: Not Found + schema: + $ref: '#/definitions/appresult.AppError' + "500": + description: Internal Server Error + schema: + $ref: '#/definitions/appresult.AppError' + security: + - BearerAuth: [] + summary: Update visa/master payment order + tags: + - visa-master-payment-orders + /visa-master-payment-orders/branches: + get: + description: Returns branches for the selected province for visa/master payment + order forms + parameters: + - description: Province ID + in: query + name: province_id + required: true + type: integer + - default: true + description: Only active branches + in: query + name: active + type: boolean + produces: + - application/json + responses: + "200": + description: OK + schema: + $ref: '#/definitions/appresult.AppSuccess' + "400": + description: Bad Request + schema: + $ref: '#/definitions/appresult.AppError' + "500": + description: Internal Server Error + schema: + $ref: '#/definitions/appresult.AppError' + security: + - BearerAuth: [] + summary: List branches by province + tags: + - visa-master-payment-orders securityDefinitions: BearerAuth: in: header diff --git a/internal/cards/router.go b/internal/cards/router.go index e703563..560ce6b 100644 --- a/internal/cards/router.go +++ b/internal/cards/router.go @@ -1,6 +1,6 @@ -// 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 groups payment cards, card orders, PIN orders, visa/master +// payment orders, and their reference data (reasons, payment card types) +// under one bounded context, replacing the flat internal/admin/* listing. package cards import ( @@ -14,6 +14,8 @@ import ( paymentcarddb "online-back/internal/cards/paymentcard/db" "online-back/internal/cards/reasonscard" reasonscarddb "online-back/internal/cards/reasonscard/db" + "online-back/internal/cards/visamaster" + visamasterdb "online-back/internal/cards/visamaster/db" "online-back/internal/handlers" "online-back/pkg/client/postgresql" "online-back/pkg/logging" @@ -35,5 +37,6 @@ func Handlers(client postgresql.Client, logger *logging.Logger) []handlers.Handl cardpinorders.NewHandler(logger, cardpinordersdb.NewRepository(client, logger)), paymentcard.NewHandler(logger, paymentcarddb.NewRepository(client, logger)), reasonscard.NewHandler(logger, reasonscarddb.NewRepository(client, logger)), + visamaster.NewHandler(logger, visamasterdb.NewRepository(client, logger)), } } diff --git a/internal/cards/visamaster/db/postgresql.go b/internal/cards/visamaster/db/postgresql.go new file mode 100644 index 0000000..3efdfe5 --- /dev/null +++ b/internal/cards/visamaster/db/postgresql.go @@ -0,0 +1,357 @@ +package db + +import ( + "context" + "encoding/json" + "fmt" + "strings" + + "online-back/internal/cards/visamaster" + "online-back/pkg/client/postgresql" + "online-back/pkg/logging" + "online-back/pkg/repository/genericrepo" +) + +type repository struct { + client postgresql.Client + generic *genericrepo.Repository[visamaster.VisaMasterPaymentOrderDTO] + logger *logging.Logger +} + +func NewRepository(client postgresql.Client, logger *logging.Logger) visamaster.Repository { + return &repository{ + client: client, + generic: genericrepo.New(client, "visa_master_payment_orders", orderColumnsSQL, scanOrder), + logger: logger, + } +} + +const userDisplaySQL = `COALESCE(NULLIF(TRIM(CONCAT_WS(' ', u.first_name, u.last_name)), ''), NULLIF(u.name, ''), u.username, '')` + +const orderFromClause = ` FROM visa_master_payment_orders o +LEFT JOIN branches b ON b.id = o.branch_id +LEFT JOIN users u ON u.id = o.user_id +LEFT JOIN provinces p ON p.id = b.province_id` + +var orderWritableColumns = []string{ + "unique_id", "type", "passport_name", "passport_surname", "phone", "email", + "region", "branch_id", "user_id", "address", + "sender_datas", "payment_reciever", "documents", + "status", "notes", + "sender_full_name", "sender_passport_serie", "sender_passport_number", "sender_deposit_account", + "reciever_full_name", "reciever_passport_serie", "reciever_passport_number", "reciever_deposit_account", + "paid", +} + +var orderColumns = append(append([]string{"id"}, orderWritableColumns...), "created_at", "updated_at") + +var orderColumnsSQL = strings.Join(orderColumns, ", ") + +var orderWritableColumnsSQL = strings.Join(orderWritableColumns, ", ") + +var orderSelectColumns = prefixedColumns("o", orderColumns) + `, p.region, b.name, COALESCE(b.unique_code, ''), COALESCE(b.region, ''), b.province_id, p.name, ` + userDisplaySQL + `, COALESCE(u.username, ''), COALESCE(u.phone, ''), COALESCE(u.email, '')` + +func prefixedColumns(alias string, cols []string) string { + parts := make([]string, len(cols)) + for i, col := range cols { + parts[i] = alias + "." + col + } + return strings.Join(parts, ", ") +} + +func 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 jsonArg(raw json.RawMessage, fallback string) []byte { + if len(raw) == 0 { + return []byte(fallback) + } + return raw +} + +func createArgs(dto visamaster.CreateVisaMasterPaymentOrderDTO) []interface{} { + return []interface{}{ + dto.UniqueId, dto.Type, dto.PassportName, dto.PassportSurname, dto.Phone, dto.Email, + dto.Region, dto.BranchId, dto.UserId, dto.Address, + jsonArg(dto.SenderDatas, `{}`), jsonArg(dto.PaymentReciever, `[]`), jsonArg(dto.Documents, `{}`), + resolveStatus(dto.Status), dto.Notes, + dto.SenderFullName, dto.SenderPassportSerie, dto.SenderPassportNumber, dto.SenderDepositAccount, + dto.RecieverFullName, dto.RecieverPassportSerie, dto.RecieverPassportNumber, dto.RecieverDepositAccount, + resolvePaid(dto.Paid), + } +} + +func updateArgs(dto visamaster.UpdateVisaMasterPaymentOrderDTO) []interface{} { + return []interface{}{ + dto.UniqueId, dto.Type, dto.PassportName, dto.PassportSurname, dto.Phone, dto.Email, + dto.Region, dto.BranchId, dto.UserId, dto.Address, + jsonArg(dto.SenderDatas, `{}`), jsonArg(dto.PaymentReciever, `[]`), jsonArg(dto.Documents, `{}`), + resolveStatus(dto.Status), dto.Notes, + dto.SenderFullName, dto.SenderPassportSerie, dto.SenderPassportNumber, dto.SenderDepositAccount, + dto.RecieverFullName, dto.RecieverPassportSerie, dto.RecieverPassportNumber, dto.RecieverDepositAccount, + dto.Paid, + } +} + +func (r *repository) List(ctx context.Context, filter visamaster.ListFilter) (visamaster.ListVisaMasterPaymentOrderDTO, error) { + whereClause, args := buildListQuery(filter) + + var count int64 + if err := r.client.QueryRow(ctx, `SELECT COUNT(*) FROM visa_master_payment_orders o`+whereClause, args...).Scan(&count); err != nil { + return visamaster.ListVisaMasterPaymentOrderDTO{}, err + } + + offset := (filter.Page - 1) * filter.Limit + limitPlaceholder := len(args) + 1 + offsetPlaceholder := len(args) + 2 + query := fmt.Sprintf( + `SELECT %s%s%s ORDER BY o.id DESC LIMIT $%d OFFSET $%d`, + orderSelectColumns, orderFromClause, whereClause, limitPlaceholder, offsetPlaceholder, + ) + + rows, err := r.client.Query(ctx, query, append(args, filter.Limit, offset)...) + if err != nil { + return visamaster.ListVisaMasterPaymentOrderDTO{}, err + } + defer rows.Close() + + var items []visamaster.VisaMasterPaymentOrderDTO + for rows.Next() { + item, err := scanOrder(rows) + if err != nil { + return visamaster.ListVisaMasterPaymentOrderDTO{}, err + } + items = append(items, item) + } + if err := rows.Err(); err != nil { + return visamaster.ListVisaMasterPaymentOrderDTO{}, err + } + + return visamaster.ListVisaMasterPaymentOrderDTO{Count: count, VisaMasterPaymentOrders: items}, nil +} + +func buildListQuery(filter visamaster.ListFilter) (whereClause string, args []interface{}) { + var conditions []string + + if filter.Name != "" { + args = append(args, likePattern(filter.Name)) + n := len(args) + conditions = append(conditions, fmt.Sprintf(`( + o.passport_name ILIKE $%[1]d OR o.passport_surname ILIKE $%[1]d + OR o.sender_full_name ILIKE $%[1]d OR COALESCE(o.reciever_full_name, '') ILIKE $%[1]d + )`, n)) + } + + if filter.Status != nil { + args = append(args, *filter.Status) + conditions = append(conditions, fmt.Sprintf("o.status = $%d", len(args))) + } + + if filter.BranchId != nil { + args = append(args, *filter.BranchId) + conditions = append(conditions, fmt.Sprintf("o.branch_id = $%d", len(args))) + } + + if filter.UserId != nil { + args = append(args, *filter.UserId) + conditions = append(conditions, fmt.Sprintf("o.user_id = $%d", len(args))) + } + + if filter.Region != "" { + args = append(args, filter.Region) + conditions = append(conditions, fmt.Sprintf("o.region = $%d", len(args))) + } + + if len(conditions) == 0 { + return "", args + } + + return " WHERE " + strings.Join(conditions, " AND "), args +} + +func likePattern(term string) string { + term = strings.ReplaceAll(term, `\`, `\\`) + term = strings.ReplaceAll(term, `%`, `\%`) + term = strings.ReplaceAll(term, `_`, `\_`) + return "%" + term + "%" +} + +func (r *repository) ListBranchesByProvince(ctx context.Context, provinceID int64, activeOnly bool) (visamaster.ListBranchesByProvinceDTO, error) { + args := []interface{}{provinceID} + where := ` WHERE province_id = $1` + if activeOnly { + where += ` AND active = true` + } + + query := ` + SELECT id, COALESCE(unique_code, ''), name, region, province_id, active + FROM branches` + where + ` + ORDER BY name->>'tm', name->>'en', id` + + rows, err := r.client.Query(ctx, query, args...) + if err != nil { + return visamaster.ListBranchesByProvinceDTO{}, err + } + defer rows.Close() + + branches := make([]visamaster.BranchByProvinceDTO, 0) + for rows.Next() { + var item visamaster.BranchByProvinceDTO + var nameJSON []byte + if err := rows.Scan(&item.Id, &item.UniqueCode, &nameJSON, &item.Region, &item.ProvinceId, &item.Active); err != nil { + return visamaster.ListBranchesByProvinceDTO{}, err + } + if err := json.Unmarshal(nameJSON, &item.Name); err != nil { + return visamaster.ListBranchesByProvinceDTO{}, err + } + branches = append(branches, item) + } + if err := rows.Err(); err != nil { + return visamaster.ListBranchesByProvinceDTO{}, err + } + + return visamaster.ListBranchesByProvinceDTO{ + Count: int64(len(branches)), + Branches: branches, + }, nil +} + +func (r *repository) GetByID(ctx context.Context, id int64) (visamaster.VisaMasterPaymentOrderDTO, error) { + query := `SELECT ` + orderSelectColumns + orderFromClause + ` WHERE o.id = $1` + return scanOrder(r.client.QueryRow(ctx, query, id)) +} + +func (r *repository) Create(ctx context.Context, dto visamaster.CreateVisaMasterPaymentOrderDTO) (visamaster.VisaMasterPaymentOrderDTO, error) { + args := createArgs(dto) + + placeholders := make([]string, len(args)) + for i := range args { + placeholders[i] = fmt.Sprintf("$%d", i+1) + } + + query := fmt.Sprintf(` + WITH inserted AS ( + INSERT INTO visa_master_payment_orders (%s) VALUES (%s) + RETURNING %s + ) + SELECT %s + FROM inserted o + LEFT JOIN branches b ON b.id = o.branch_id + LEFT JOIN users u ON u.id = o.user_id + LEFT JOIN provinces p ON p.id = b.province_id`, + orderWritableColumnsSQL, strings.Join(placeholders, ", "), + orderColumnsSQL, orderSelectColumns, + ) + + return scanOrder(r.client.QueryRow(ctx, query, args...)) +} + +func (r *repository) Update(ctx context.Context, id int64, dto visamaster.UpdateVisaMasterPaymentOrderDTO) (visamaster.VisaMasterPaymentOrderDTO, error) { + args := updateArgs(dto) + + assignments := make([]string, len(orderWritableColumns)) + for i, column := range orderWritableColumns { + assignments[i] = fmt.Sprintf("%s = $%d", column, i+1) + } + args = append(args, id) + + query := fmt.Sprintf(` + WITH updated AS ( + UPDATE visa_master_payment_orders SET %s, updated_at = (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') + WHERE id = $%d + RETURNING %s + ) + SELECT %s + FROM updated o + LEFT JOIN branches b ON b.id = o.branch_id + LEFT JOIN users u ON u.id = o.user_id + LEFT JOIN provinces p ON p.id = b.province_id`, + strings.Join(assignments, ", "), len(args), orderColumnsSQL, orderSelectColumns, + ) + + item, err := scanOrder(r.client.QueryRow(ctx, query, args...)) + if err != nil { + return visamaster.VisaMasterPaymentOrderDTO{}, err + } + return item, nil +} + +func (r *repository) Delete(ctx context.Context, id int64) error { + return r.generic.Delete(ctx, id) +} + +func scanOrder(row genericrepo.Scanner) (visamaster.VisaMasterPaymentOrderDTO, error) { + var item visamaster.VisaMasterPaymentOrderDTO + var senderDatas, paymentReciever, documents []byte + var regionNameJSON, branchNameJSON, provinceNameJSON []byte + var branchRegion, userName, userUsername, userPhone, userEmail string + + err := row.Scan( + &item.Id, &item.UniqueId, &item.Type, &item.PassportName, &item.PassportSurname, &item.Phone, &item.Email, + &item.Region, &item.BranchId, &item.UserId, &item.Address, + &senderDatas, &paymentReciever, &documents, + &item.Status, &item.Notes, + &item.SenderFullName, &item.SenderPassportSerie, &item.SenderPassportNumber, &item.SenderDepositAccount, + &item.RecieverFullName, &item.RecieverPassportSerie, &item.RecieverPassportNumber, &item.RecieverDepositAccount, + &item.Paid, &item.CreatedAt, &item.UpdatedAt, + ®ionNameJSON, &branchNameJSON, &item.Branch.UniqueCode, &branchRegion, &item.Branch.ProvinceId, &provinceNameJSON, + &userName, &userUsername, &userPhone, &userEmail, + ) + if err != nil { + return visamaster.VisaMasterPaymentOrderDTO{}, err + } + + item.SenderDatas = jsonOrDefault(senderDatas, `{}`) + item.PaymentReciever = jsonOrDefault(paymentReciever, `[]`) + item.Documents = jsonOrDefault(documents, `{}`) + + item.Branch.Id = item.BranchId + item.Branch.Region = branchRegion + if err := unmarshalLocalized(regionNameJSON, &item.RegionName); err != nil { + return visamaster.VisaMasterPaymentOrderDTO{}, err + } + if err := unmarshalLocalized(branchNameJSON, &item.Branch.Name); err != nil { + return visamaster.VisaMasterPaymentOrderDTO{}, err + } + if err := unmarshalLocalized(provinceNameJSON, &item.Branch.ProvinceName); err != nil { + return visamaster.VisaMasterPaymentOrderDTO{}, err + } + + if item.UserId != nil { + item.User = &visamaster.UserInfo{ + Id: *item.UserId, + Name: userName, + Username: userUsername, + Phone: userPhone, + Email: userEmail, + } + } + + return item, nil +} + +func jsonOrDefault(raw []byte, fallback string) json.RawMessage { + if len(raw) == 0 { + return json.RawMessage(fallback) + } + return json.RawMessage(raw) +} + +func unmarshalLocalized(raw []byte, dest *visamaster.LocalizedText) error { + if len(raw) == 0 { + return nil + } + return json.Unmarshal(raw, dest) +} diff --git a/internal/cards/visamaster/db/postgresql_get_test.go b/internal/cards/visamaster/db/postgresql_get_test.go new file mode 100644 index 0000000..f6c171e --- /dev/null +++ b/internal/cards/visamaster/db/postgresql_get_test.go @@ -0,0 +1,86 @@ +package db + +import ( + "context" + "testing" + "time" + + "online-back/internal/cards/visamaster" + "online-back/internal/config" + "online-back/pkg/client/postgresql" + "online-back/pkg/logging" +) + +func testRepo(t *testing.T) (visamaster.Repository, func()) { + t.Helper() + ctx, cancel := context.WithTimeout(context.Background(), 8*time.Second) + t.Cleanup(cancel) + + pool, err := postgresql.NewClient(ctx, 2, config.StorageConfig{ + Host: "localhost", + Port: "5424", + Database: "bank_db", + Username: "bank_admin", + Password: "bank@#23#@_password", + PgPoolMaxConn: 4, + }) + if err != nil { + t.Skipf("postgres unavailable: %v", err) + } + + return NewRepository(pool, logging.GetLogger()), func() { pool.Close() } +} + +func TestGetByIDIncludesBranchAndUser(t *testing.T) { + repo, closeRepo := testRepo(t) + defer closeRepo() + ctx := context.Background() + + item, err := repo.GetByID(ctx, 1) + if err != nil { + t.Fatalf("GetByID: %v", err) + } + + if item.BranchId == 0 { + t.Fatal("branchId is empty") + } + if item.Branch.Id != item.BranchId { + t.Fatalf("branch.id=%d does not match branchId=%d", item.Branch.Id, item.BranchId) + } + if item.Branch.Name.Tm == "" && item.Branch.Name.En == "" { + t.Fatalf("branchId=%d but branch.name is empty: %+v", item.BranchId, item.Branch.Name) + } + if item.UserId != nil { + if item.User == nil { + t.Fatalf("userId=%d but user object is nil", *item.UserId) + } + if item.User.Name == "" && item.User.Username == "" { + t.Fatalf("userId=%d but user name/username are empty", *item.UserId) + } + } + + t.Logf("id=%d branchId=%d branch=%q userId=%v user=%v", + item.Id, item.BranchId, item.Branch.Name.Tm, item.UserId, item.User) +} + +func TestListIncludesBranchAndUser(t *testing.T) { + repo, closeRepo := testRepo(t) + defer closeRepo() + + list, err := repo.List(context.Background(), visamaster.ListFilter{Page: 1, Limit: 10}) + if err != nil { + t.Fatalf("List: %v", err) + } + if list.Count == 0 || len(list.VisaMasterPaymentOrders) == 0 { + t.Fatal("List returned no orders") + } + + for _, item := range list.VisaMasterPaymentOrders { + if item.BranchId != 0 && item.Branch.Name.Tm == "" && item.Branch.Name.En == "" { + t.Errorf("order %d branchId=%d missing branch.name", item.Id, item.BranchId) + } + if item.UserId != nil && (item.User == nil || (item.User.Name == "" && item.User.Username == "")) { + t.Errorf("order %d userId=%d missing user details", item.Id, *item.UserId) + } + } +} diff --git a/internal/cards/visamaster/dto.go b/internal/cards/visamaster/dto.go new file mode 100644 index 0000000..e32e65e --- /dev/null +++ b/internal/cards/visamaster/dto.go @@ -0,0 +1,145 @@ +package visamaster + +import ( + "encoding/json" + "time" +) + +type LocalizedText struct { + En string `json:"en"` + Ru string `json:"ru"` + Tm string `json:"tm"` +} + +type BranchInfo struct { + Id int64 `json:"id"` + UniqueCode string `json:"uniqueCode"` + Name LocalizedText `json:"name"` + Region string `json:"region"` + ProvinceId *int64 `json:"provinceId"` + ProvinceName LocalizedText `json:"provinceName"` +} + +type UserInfo struct { + Id int64 `json:"id"` + Name string `json:"name"` + Username string `json:"username"` + Phone string `json:"phone"` + Email string `json:"email"` +} + +type VisaMasterPaymentOrderDTO struct { + Id int64 `json:"id"` + UniqueId *string `json:"uniqueId"` + Type *string `json:"type"` + PassportName string `json:"passportName"` + PassportSurname string `json:"passportSurname"` + Phone string `json:"phone"` + Email *string `json:"email"` + Region string `json:"region"` + RegionName LocalizedText `json:"regionName"` + BranchId int64 `json:"branchId"` + Branch BranchInfo `json:"branch"` + UserId *int64 `json:"userId"` + User *UserInfo `json:"user"` + Address string `json:"address"` + SenderDatas json.RawMessage `json:"senderDatas" swaggertype:"object"` + PaymentReciever json.RawMessage `json:"paymentReciever" swaggertype:"array,object"` + Documents json.RawMessage `json:"documents" swaggertype:"object"` + Status *string `json:"status"` + Notes *string `json:"notes"` + SenderFullName string `json:"senderFullName"` + SenderPassportSerie string `json:"senderPassportSerie"` + SenderPassportNumber string `json:"senderPassportNumber"` + SenderDepositAccount string `json:"senderDepositAccount"` + RecieverFullName *string `json:"recieverFullName"` + RecieverPassportSerie *string `json:"recieverPassportSerie"` + RecieverPassportNumber *string `json:"recieverPassportNumber"` + RecieverDepositAccount *string `json:"recieverDepositAccount"` + Paid bool `json:"paid"` + CreatedAt time.Time `json:"createdAt"` + UpdatedAt time.Time `json:"updatedAt"` +} + +type CreateVisaMasterPaymentOrderDTO struct { + UniqueId *string `json:"uniqueId"` + Type *string `json:"type"` + PassportName string `json:"passportName" binding:"required"` + PassportSurname string `json:"passportSurname" binding:"required"` + Phone string `json:"phone" binding:"required"` + Email *string `json:"email"` + Region string `json:"region" binding:"required"` + BranchId int64 `json:"branchId" binding:"required"` + UserId *int64 `json:"userId"` + Address string `json:"address" binding:"required"` + SenderDatas json.RawMessage `json:"senderDatas" swaggertype:"object"` + PaymentReciever json.RawMessage `json:"paymentReciever" swaggertype:"array,object"` + Documents json.RawMessage `json:"documents" swaggertype:"object"` + Status *string `json:"status"` + Notes *string `json:"notes"` + SenderFullName string `json:"senderFullName" binding:"required"` + SenderPassportSerie string `json:"senderPassportSerie" binding:"required"` + SenderPassportNumber string `json:"senderPassportNumber" binding:"required"` + SenderDepositAccount string `json:"senderDepositAccount" binding:"required"` + RecieverFullName *string `json:"recieverFullName"` + RecieverPassportSerie *string `json:"recieverPassportSerie"` + RecieverPassportNumber *string `json:"recieverPassportNumber"` + RecieverDepositAccount *string `json:"recieverDepositAccount"` + Paid *bool `json:"paid"` +} + +type UpdateVisaMasterPaymentOrderDTO struct { + UniqueId *string `json:"uniqueId"` + Type *string `json:"type"` + PassportName string `json:"passportName" binding:"required"` + PassportSurname string `json:"passportSurname" binding:"required"` + Phone string `json:"phone" binding:"required"` + Email *string `json:"email"` + Region string `json:"region" binding:"required"` + BranchId int64 `json:"branchId" binding:"required"` + UserId *int64 `json:"userId"` + Address string `json:"address" binding:"required"` + SenderDatas json.RawMessage `json:"senderDatas" swaggertype:"object"` + PaymentReciever json.RawMessage `json:"paymentReciever" swaggertype:"array,object"` + Documents json.RawMessage `json:"documents" swaggertype:"object"` + Status *string `json:"status"` + Notes *string `json:"notes"` + SenderFullName string `json:"senderFullName" binding:"required"` + SenderPassportSerie string `json:"senderPassportSerie" binding:"required"` + SenderPassportNumber string `json:"senderPassportNumber" binding:"required"` + SenderDepositAccount string `json:"senderDepositAccount" binding:"required"` + RecieverFullName *string `json:"recieverFullName"` + RecieverPassportSerie *string `json:"recieverPassportSerie"` + RecieverPassportNumber *string `json:"recieverPassportNumber"` + RecieverDepositAccount *string `json:"recieverDepositAccount"` + Paid bool `json:"paid"` +} + +type ListFilter struct { + Name string + Status *string + BranchId *int64 + UserId *int64 + Region string + Page int + Limit int +} + +type ListVisaMasterPaymentOrderDTO struct { + Count int64 `json:"count"` + VisaMasterPaymentOrders []VisaMasterPaymentOrderDTO `json:"visaMasterPaymentOrders"` +} + +type BranchByProvinceDTO struct { + Id int64 `json:"id"` + UniqueCode string `json:"uniqueCode"` + Name LocalizedText `json:"name"` + Region string `json:"region"` + ProvinceId *int64 `json:"provinceId"` + Active bool `json:"active"` +} + +type ListBranchesByProvinceDTO struct { + Count int64 `json:"count"` + Branches []BranchByProvinceDTO `json:"branches"` +} diff --git a/internal/cards/visamaster/handler.go b/internal/cards/visamaster/handler.go new file mode 100644 index 0000000..1a95a98 --- /dev/null +++ b/internal/cards/visamaster/handler.go @@ -0,0 +1,310 @@ +package visamaster + +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 = "/visa-master-payment-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("/branches", h.listBranchesByProvince) + group.GET("/:id", h.getByID) + group.POST("", h.create) + group.PUT("/:id", h.update) + group.DELETE("/:id", h.delete) +} + +// list godoc +// @Summary List visa/master payment orders +// @Description Returns paginated visa/master payment orders with branch and user details +// @Tags visa-master-payment-orders +// @Produce json +// @Security BearerAuth +// @Param name query string false "Filter by passport name or surname" +// @Param status query string false "Filter by status" +// @Param branch_id query int false "Filter by branch ID" +// @Param user_id query int false "Filter by user ID" +// @Param region query string false "Filter by region" +// @Param page query int false "Page number" default(1) +// @Param limit query int false "Items per page" default(10) +// @Success 200 {object} appresult.AppSuccess +// @Failure 400 {object} appresult.AppError +// @Failure 500 {object} appresult.AppError +// @Router /visa-master-payment-orders [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 visa master payment orders failed: %v", err) + c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer) + return + } + + c.JSON(http.StatusOK, appresult.SuccessWithData(result)) +} + +// listBranchesByProvince godoc +// @Summary List branches by province +// @Description Returns branches for the selected province for visa/master payment order forms +// @Tags visa-master-payment-orders +// @Produce json +// @Security BearerAuth +// @Param province_id query int true "Province ID" +// @Param active query bool false "Only active branches" default(true) +// @Success 200 {object} appresult.AppSuccess +// @Failure 400 {object} appresult.AppError +// @Failure 500 {object} appresult.AppError +// @Router /visa-master-payment-orders/branches [get] +func (h *handler) listBranchesByProvince(c *gin.Context) { + provinceID, ok := parseID(c.Query("province_id")) + if !ok { + c.JSON(http.StatusBadRequest, appresult.ErrMissingParam) + return + } + + activeOnly := true + if raw := c.Query("active"); raw != "" { + active, err := strconv.ParseBool(raw) + if err != nil { + c.JSON(http.StatusBadRequest, appresult.ErrMissingParam) + return + } + activeOnly = active + } + + result, err := h.repository.ListBranchesByProvince(c.Request.Context(), provinceID, activeOnly) + if err != nil { + h.logger.Errorf("list branches by province failed: %v", err) + c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer) + return + } + + c.JSON(http.StatusOK, appresult.SuccessWithData(result)) +} + +// getByID godoc +// @Summary Get visa/master payment order by ID +// @Description Returns a single visa/master payment order with branch and user details +// @Tags visa-master-payment-orders +// @Produce json +// @Security BearerAuth +// @Param id path int true "Visa/master payment order ID" +// @Success 200 {object} appresult.AppSuccess +// @Failure 400 {object} appresult.AppError +// @Failure 404 {object} appresult.AppError +// @Failure 500 {object} appresult.AppError +// @Router /visa-master-payment-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 visa master payment order failed: %v", err) + c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer) + return + } + + c.JSON(http.StatusOK, appresult.SuccessWithData(item)) +} + +// create godoc +// @Summary Create visa/master payment order +// @Description Creates a new visa/master payment order +// @Tags visa-master-payment-orders +// @Accept json +// @Produce json +// @Security BearerAuth +// @Param body body CreateVisaMasterPaymentOrderDTO true "Visa/master payment order payload" +// @Success 201 {object} appresult.AppSuccess +// @Failure 400 {object} appresult.AppError +// @Failure 500 {object} appresult.AppError +// @Router /visa-master-payment-orders [post] +func (h *handler) create(c *gin.Context) { + var dto CreateVisaMasterPaymentOrderDTO + 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 visa master payment order failed: %v", err) + c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer) + return + } + + c.JSON(http.StatusCreated, appresult.SuccessWithData(item)) +} + +// update godoc +// @Summary Update visa/master payment order +// @Description Updates an existing visa/master payment order +// @Tags visa-master-payment-orders +// @Accept json +// @Produce json +// @Security BearerAuth +// @Param id path int true "Visa/master payment order ID" +// @Param body body UpdateVisaMasterPaymentOrderDTO true "Visa/master payment order payload" +// @Success 200 {object} appresult.AppSuccess +// @Failure 400 {object} appresult.AppError +// @Failure 404 {object} appresult.AppError +// @Failure 500 {object} appresult.AppError +// @Router /visa-master-payment-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 UpdateVisaMasterPaymentOrderDTO + 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 visa master payment order failed: %v", err) + c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer) + return + } + + c.JSON(http.StatusOK, appresult.SuccessWithData(item)) +} + +// delete godoc +// @Summary Delete visa/master payment order +// @Description Deletes a visa/master payment order +// @Tags visa-master-payment-orders +// @Produce json +// @Security BearerAuth +// @Param id path int true "Visa/master payment order ID" +// @Success 200 {object} appresult.AppSuccess +// @Failure 400 {object} appresult.AppError +// @Failure 404 {object} appresult.AppError +// @Failure 500 {object} appresult.AppError +// @Router /visa-master-payment-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 visa master payment order failed: %v", err) + c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer) + return + } + + c.JSON(http.StatusOK, appresult.SuccessWithData("visa master payment 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("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("name")); raw != "" { + filter.Name = 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 + } + + if raw := c.Query("user_id"); raw != "" { + id, ok := parseID(raw) + if !ok { + return ListFilter{}, false + } + filter.UserId = &id + } + + return filter, true +} diff --git a/internal/cards/visamaster/storage.go b/internal/cards/visamaster/storage.go new file mode 100644 index 0000000..a8c3537 --- /dev/null +++ b/internal/cards/visamaster/storage.go @@ -0,0 +1,12 @@ +package visamaster + +import "context" + +type Repository interface { + List(ctx context.Context, filter ListFilter) (ListVisaMasterPaymentOrderDTO, error) + ListBranchesByProvince(ctx context.Context, provinceID int64, activeOnly bool) (ListBranchesByProvinceDTO, error) + GetByID(ctx context.Context, id int64) (VisaMasterPaymentOrderDTO, error) + Create(ctx context.Context, dto CreateVisaMasterPaymentOrderDTO) (VisaMasterPaymentOrderDTO, error) + Update(ctx context.Context, id int64, dto UpdateVisaMasterPaymentOrderDTO) (VisaMasterPaymentOrderDTO, error) + Delete(ctx context.Context, id int64) error +} diff --git a/internal/lending/loanpaidletter/db/postgresql.go b/internal/lending/loanpaidletter/db/postgresql.go index f13540e..151089c 100644 --- a/internal/lending/loanpaidletter/db/postgresql.go +++ b/internal/lending/loanpaidletter/db/postgresql.go @@ -30,7 +30,8 @@ const userDisplaySQL = `COALESCE(NULLIF(TRIM(CONCAT_WS(' ', u.first_name, u.last const letterFromClause = ` FROM loan_paid_off_letters l LEFT JOIN branches b ON b.id = l.branch_id -LEFT JOIN users u ON u.id = l.user_id` +LEFT JOIN users u ON u.id = l.user_id +LEFT JOIN provinces p ON p.id = b.province_id` // letterWritableColumns lists every loan_paid_off_letters column except id, created_at // and updated_at, in the exact order CreateLoanPaidLetterDTO/UpdateLoanPaidLetterDTO fields are read. @@ -48,7 +49,7 @@ var letterColumnsSQL = strings.Join(letterColumns, ", ") var letterWritableColumnsSQL = strings.Join(letterWritableColumns, ", ") -var letterSelectColumns = prefixedColumns("l", letterColumns) + `, b.name, ` + userDisplaySQL +var letterSelectColumns = prefixedColumns("l", letterColumns) + `, p.region, b.name, COALESCE(b.unique_code, ''), b.province_id, p.name, ` + userDisplaySQL + `, COALESCE(u.username, '')` func prefixedColumns(alias string, cols []string) string { parts := make([]string, len(cols)) @@ -221,7 +222,8 @@ func (r *repository) Create(ctx context.Context, dto loanpaidletter.CreateLoanPa SELECT %s FROM inserted l LEFT JOIN branches b ON b.id = l.branch_id - LEFT JOIN users u ON u.id = l.user_id`, + LEFT JOIN users u ON u.id = l.user_id + LEFT JOIN provinces p ON p.id = b.province_id`, letterWritableColumnsSQL, strings.Join(placeholders, ", "), letterColumnsSQL, letterSelectColumns, ) @@ -247,7 +249,8 @@ func (r *repository) Update(ctx context.Context, id int64, dto loanpaidletter.Up SELECT %s FROM updated l LEFT JOIN branches b ON b.id = l.branch_id - LEFT JOIN users u ON u.id = l.user_id`, + LEFT JOIN users u ON u.id = l.user_id + LEFT JOIN provinces p ON p.id = b.province_id`, strings.Join(assignments, ", "), len(args), letterColumnsSQL, letterSelectColumns, ) @@ -264,7 +267,7 @@ func (r *repository) Delete(ctx context.Context, id int64) error { func scanLoanPaidLetter(row genericrepo.Scanner) (loanpaidletter.LoanPaidLetterDTO, error) { var item loanpaidletter.LoanPaidLetterDTO - var branchNameJSON []byte + var regionNameJSON, branchNameJSON, provinceNameJSON []byte err := row.Scan( &item.Id, &item.UniqueId, &item.Region, &item.BranchId, &item.UserId, @@ -273,15 +276,27 @@ func scanLoanPaidLetter(row genericrepo.Scanner) (loanpaidletter.LoanPaidLetterD &item.Status, &item.Notes, &item.LoanContractNumber, &item.LoanContractDate, &item.LoanAmount, &item.LoanReason, &item.LoanFile, &item.CreatedAt, &item.UpdatedAt, - &branchNameJSON, &item.UserName, + ®ionNameJSON, &branchNameJSON, &item.BranchUniqueCode, &item.ProvinceId, &provinceNameJSON, + &item.UserName, &item.UserUsername, ) if err != nil { return loanpaidletter.LoanPaidLetterDTO{}, err } - if len(branchNameJSON) > 0 { - if err := json.Unmarshal(branchNameJSON, &item.BranchName); err != nil { - return loanpaidletter.LoanPaidLetterDTO{}, err - } + if err := unmarshalLocalized(regionNameJSON, &item.RegionName); err != nil { + return loanpaidletter.LoanPaidLetterDTO{}, err + } + if err := unmarshalLocalized(branchNameJSON, &item.BranchName); err != nil { + return loanpaidletter.LoanPaidLetterDTO{}, err + } + if err := unmarshalLocalized(provinceNameJSON, &item.ProvinceName); err != nil { + return loanpaidletter.LoanPaidLetterDTO{}, err } return item, nil } + +func unmarshalLocalized(raw []byte, dest *loanpaidletter.LocalizedText) error { + if len(raw) == 0 { + return nil + } + return json.Unmarshal(raw, dest) +} diff --git a/internal/lending/loanpaidletter/db/postgresql_get_test.go b/internal/lending/loanpaidletter/db/postgresql_get_test.go new file mode 100644 index 0000000..24a8af6 --- /dev/null +++ b/internal/lending/loanpaidletter/db/postgresql_get_test.go @@ -0,0 +1,93 @@ +package db + +import ( + "context" + "testing" + "time" + + "online-back/internal/config" + "online-back/internal/lending/loanpaidletter" + "online-back/pkg/client/postgresql" + "online-back/pkg/logging" +) + +func testRepo(t *testing.T) (loanpaidletter.Repository, func()) { + t.Helper() + ctx, cancel := context.WithTimeout(context.Background(), 8*time.Second) + t.Cleanup(cancel) + + pool, err := postgresql.NewClient(ctx, 2, config.StorageConfig{ + Host: "localhost", + Port: "5424", + Database: "bank_db", + Username: "bank_admin", + Password: "bank@#23#@_password", + PgPoolMaxConn: 4, + }) + if err != nil { + t.Skipf("postgres unavailable: %v", err) + } + + return NewRepository(pool, logging.GetLogger()), func() { pool.Close() } +} + +func TestGetByIDIncludesNamesNextToIDs(t *testing.T) { + repo, closeRepo := testRepo(t) + defer closeRepo() + ctx := context.Background() + + item, err := repo.GetByID(ctx, 1) + if err != nil { + t.Fatalf("GetByID: %v", err) + } + + if item.BranchId == 0 { + t.Fatal("branchId is empty") + } + if item.BranchName.Tm == "" && item.BranchName.En == "" { + t.Fatalf("branchId=%d but branchName is empty: %+v", item.BranchId, item.BranchName) + } + if item.BranchUniqueCode == "" { + t.Fatalf("branchId=%d but branchUniqueCode is empty", item.BranchId) + } + if item.ProvinceId == nil || *item.ProvinceId == 0 { + t.Fatal("provinceId is empty") + } + if item.ProvinceName.Tm == "" && item.ProvinceName.En == "" { + t.Fatalf("provinceId=%d but provinceName is empty: %+v", *item.ProvinceId, item.ProvinceName) + } + if item.RegionName.Tm == "" && item.RegionName.En == "" { + t.Fatalf("region=%q but regionName is empty: %+v", item.Region, item.RegionName) + } + if item.UserId != nil { + if item.UserName == "" && item.UserUsername == "" { + t.Fatalf("userId=%d but userName and userUsername are empty", *item.UserId) + } + } + + t.Logf("id=%d branchId=%d branch=%q/%s provinceId=%d province=%q userId=%v user=%q", + item.Id, item.BranchId, item.BranchName.Tm, item.BranchUniqueCode, + *item.ProvinceId, item.ProvinceName.Tm, item.UserId, item.UserName) +} + +func TestListIncludesNamesNextToIDs(t *testing.T) { + repo, closeRepo := testRepo(t) + defer closeRepo() + + list, err := repo.List(context.Background(), loanpaidletter.ListFilter{Page: 1, Limit: 10}) + if err != nil { + t.Fatalf("List: %v", err) + } + if list.Count == 0 || len(list.LoanPaidLetters) == 0 { + t.Fatal("List returned no letters") + } + + for _, item := range list.LoanPaidLetters { + if item.BranchId != 0 && item.BranchName.Tm == "" && item.BranchName.En == "" { + t.Errorf("letter %d branchId=%d missing branchName", item.Id, item.BranchId) + } + if item.UserId != nil && item.UserName == "" && item.UserUsername == "" { + t.Errorf("letter %d userId=%d missing userName", item.Id, *item.UserId) + } + } +} diff --git a/internal/lending/loanpaidletter/dto.go b/internal/lending/loanpaidletter/dto.go index ee41809..317db8b 100644 --- a/internal/lending/loanpaidletter/dto.go +++ b/internal/lending/loanpaidletter/dto.go @@ -6,10 +6,15 @@ type LoanPaidLetterDTO struct { Id int64 `json:"id"` UniqueId *string `json:"uniqueId"` Region string `json:"region"` + RegionName LocalizedText `json:"regionName"` BranchId int64 `json:"branchId"` BranchName LocalizedText `json:"branchName"` + BranchUniqueCode string `json:"branchUniqueCode"` + ProvinceId *int64 `json:"provinceId"` + ProvinceName LocalizedText `json:"provinceName"` UserId *int64 `json:"userId"` UserName string `json:"userName"` + UserUsername string `json:"userUsername"` CustomerName string `json:"customerName"` CustomerSurname string `json:"customerSurname"` CustomerPatronicName *string `json:"customerPatronicName"`