diff --git a/app.go b/app.go index 0048134..144128a 100755 --- a/app.go +++ b/app.go @@ -39,6 +39,8 @@ import ( // @tag.description Loan required documents // @tag.name loans-repayment // @tag.description Loan repayments +// @tag.name card-orders +// @tag.description Card orders func main() { docs.SwaggerInfo.Title = "Service APIs" docs.SwaggerInfo.Version = "1.0" diff --git a/db/migrations/20260702125108_init.down.sql b/db/migrations/20260702125108_init.down.sql index 1f528fe..a5c3472 100644 --- a/db/migrations/20260702125108_init.down.sql +++ b/db/migrations/20260702125108_init.down.sql @@ -1,3 +1,6 @@ +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; diff --git a/db/migrations/20260702125108_init.up.sql b/db/migrations/20260702125108_init.up.sql index 1b64bef..126f53e 100644 --- a/db/migrations/20260702125108_init.up.sql +++ b/db/migrations/20260702125108_init.up.sql @@ -240,3 +240,90 @@ CREATE TABLE IF NOT EXISTS loan_paid_off_letters ( FOREIGN KEY ("user_id") REFERENCES users(id) ); +CREATE TABLE IF NOT EXISTS card_orders ( + id bigserial PRIMARY KEY, + unique_id character varying(255), + card_state_id bigint NOT NULL, + card_type_id bigint NOT NULL, + region character varying(2) NOT NULL, + branch_id bigint NOT NULL, + customer_name character varying(255) NOT NULL, + customer_surname character varying(255) NOT NULL, + customer_patronic_name character varying(255), + born_at date, + old_surname character varying(255), + citizenship character varying(255) NOT NULL, + passport_serie character varying(255) NOT NULL, + passport_id character varying(255) NOT NULL, + passport_given_at date NOT NULL, + passport_given_by character varying(255) NOT NULL, + born_place character varying(255) NOT NULL, + job_location character varying(255), + passport_address character varying(255), + real_address character varying(255), + phone character varying(255), + phone_additional character varying(255), + status character varying(255) DEFAULT 'pending'::character varying, + passport_one text NOT NULL, + passport_two text NOT NULL, + passport_three text NOT NULL, + passport_four text NOT NULL, + notes text, + user_id bigint, + paid boolean NOT NULL DEFAULT false, + created_at TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL, + updated_at TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL, + CONSTRAINT card_orders_card_state_id_fkey + FOREIGN KEY ("card_state_id") REFERENCES card_states(id), + CONSTRAINT card_orders_card_type_id_fkey + FOREIGN KEY ("card_type_id") REFERENCES card_types(id), + CONSTRAINT card_orders_branch_id_fkey + FOREIGN KEY ("branch_id") REFERENCES branches(id), + CONSTRAINT card_orders_user_id_fkey + FOREIGN KEY ("user_id") REFERENCES users(id) +); + +CREATE TABLE IF NOT EXISTS card_pin_orders ( + id bigserial PRIMARY KEY, + unique_id character varying(255), + user_id bigint, + card_type_id bigint NOT NULL, + card_number character varying(255), + region character varying(2) NOT NULL, + branch_id bigint NOT NULL, + customer_name character varying(255) NOT NULL, + customer_surname character varying(255) NOT NULL, + customer_patronic_name character varying(255), + born_at date, + phone character varying(255), + passport_serie character varying(255) NOT NULL, + passport_id character varying(255) NOT NULL, + passport_one text NOT NULL, + passport_two text NOT NULL, + passport_three text NOT NULL, + passport_four text NOT NULL, + status character varying(250), + notes character varying(250), + created_at TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL, + updated_at TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL, + CONSTRAINT card_pin_orders_card_type_id_fkey + FOREIGN KEY ("card_type_id") REFERENCES card_types(id), + CONSTRAINT card_pin_orders_branch_id_fkey + FOREIGN KEY ("branch_id") REFERENCES branches(id), + CONSTRAINT card_pin_orders_user_id_fkey + FOREIGN KEY ("user_id") REFERENCES users(id) +); + +CREATE TABLE IF NOT EXISTS cards ( + id bigserial PRIMARY KEY, + user_id bigint, + number character varying(250) NOT NULL, + name character varying(250) NOT NULL, + month character varying(250) NOT NULL, + year character varying(250), + type character varying(250), + created_at TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL, + updated_at TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL, + CONSTRAINT cards_user_id_fkey + FOREIGN KEY ("user_id") REFERENCES users(id) +); \ No newline at end of file diff --git a/docs/docs.go b/docs/docs.go index 3af54cc..1ddf547 100644 --- a/docs/docs.go +++ b/docs/docs.go @@ -408,6 +408,586 @@ const docTemplate = `{ } } }, + "/card-orders": { + "get": { + "security": [ + { + "BearerAuth": [] + } + ], + "description": "Returns paginated card orders with optional filters", + "produces": [ + "application/json" + ], + "tags": [ + "card-orders" + ], + "summary": "List card orders", + "parameters": [ + { + "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": "integer", + "description": "Filter by card state ID", + "name": "card_state_id", + "in": "query" + }, + { + "type": "integer", + "description": "Filter by card type ID", + "name": "card_type_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 card order", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "card-orders" + ], + "summary": "Create card order", + "parameters": [ + { + "description": "Card order payload", + "name": "body", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/cardorder.CreateCardOrderDTO" + } + } + ], + "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" + } + } + } + } + }, + "/card-orders/{id}": { + "get": { + "security": [ + { + "BearerAuth": [] + } + ], + "description": "Returns a single card order", + "produces": [ + "application/json" + ], + "tags": [ + "card-orders" + ], + "summary": "Get card order by ID", + "parameters": [ + { + "type": "integer", + "description": "Card 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 card order", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "card-orders" + ], + "summary": "Update card order", + "parameters": [ + { + "type": "integer", + "description": "Card order ID", + "name": "id", + "in": "path", + "required": true + }, + { + "description": "Card order payload", + "name": "body", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/cardorder.UpdateCardOrderDTO" + } + } + ], + "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 card order", + "produces": [ + "application/json" + ], + "tags": [ + "card-orders" + ], + "summary": "Delete card order", + "parameters": [ + { + "type": "integer", + "description": "Card 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" + } + } + } + } + }, + "/cards": { + "get": { + "security": [ + { + "BearerAuth": [] + } + ], + "description": "Returns paginated cards with optional filters", + "produces": [ + "application/json" + ], + "tags": [ + "cards" + ], + "summary": "List cards", + "parameters": [ + { + "type": "integer", + "description": "Filter by user ID", + "name": "user_id", + "in": "query" + }, + { + "type": "string", + "description": "Filter by card type", + "name": "type", + "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 card", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "cards" + ], + "summary": "Create card", + "parameters": [ + { + "description": "Card payload", + "name": "body", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/cards.CreateCardDTO" + } + } + ], + "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" + } + } + } + } + }, + "/cards/{id}": { + "get": { + "security": [ + { + "BearerAuth": [] + } + ], + "description": "Returns a single card", + "produces": [ + "application/json" + ], + "tags": [ + "cards" + ], + "summary": "Get card by ID", + "parameters": [ + { + "type": "integer", + "description": "Card 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 card", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "cards" + ], + "summary": "Update card", + "parameters": [ + { + "type": "integer", + "description": "Card ID", + "name": "id", + "in": "path", + "required": true + }, + { + "description": "Card payload", + "name": "body", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/cards.UpdateCardDTO" + } + } + ], + "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 card", + "produces": [ + "application/json" + ], + "tags": [ + "cards" + ], + "summary": "Delete card", + "parameters": [ + { + "type": "integer", + "description": "Card 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" + } + } + } + } + }, "/file": { "post": { "security": [ @@ -4015,6 +4595,282 @@ const docTemplate = `{ } } }, + "cardorder.CreateCardOrderDTO": { + "type": "object", + "required": [ + "bornPlace", + "branchId", + "cardStateId", + "cardTypeId", + "citizenship", + "customerName", + "customerSurname", + "passportFour", + "passportGivenAt", + "passportGivenBy", + "passportId", + "passportOne", + "passportSerie", + "passportThree", + "passportTwo", + "region" + ], + "properties": { + "bornAt": { + "type": "string" + }, + "bornPlace": { + "type": "string" + }, + "branchId": { + "type": "integer" + }, + "cardStateId": { + "type": "integer" + }, + "cardTypeId": { + "type": "integer" + }, + "citizenship": { + "type": "string" + }, + "customerName": { + "type": "string" + }, + "customerPatronicName": { + "type": "string" + }, + "customerSurname": { + "type": "string" + }, + "jobLocation": { + "type": "string" + }, + "notes": { + "type": "string" + }, + "oldSurname": { + "type": "string" + }, + "paid": { + "type": "boolean" + }, + "passportAddress": { + "type": "string" + }, + "passportFour": { + "type": "string" + }, + "passportGivenAt": { + "type": "string" + }, + "passportGivenBy": { + "type": "string" + }, + "passportId": { + "type": "string" + }, + "passportOne": { + "type": "string" + }, + "passportSerie": { + "type": "string" + }, + "passportThree": { + "type": "string" + }, + "passportTwo": { + "type": "string" + }, + "phone": { + "type": "string" + }, + "phoneAdditional": { + "type": "string" + }, + "realAddress": { + "type": "string" + }, + "region": { + "type": "string" + }, + "status": { + "type": "string" + }, + "uniqueId": { + "type": "string" + }, + "userId": { + "type": "integer" + } + } + }, + "cardorder.UpdateCardOrderDTO": { + "type": "object", + "required": [ + "bornPlace", + "branchId", + "cardStateId", + "cardTypeId", + "citizenship", + "customerName", + "customerSurname", + "passportFour", + "passportGivenAt", + "passportGivenBy", + "passportId", + "passportOne", + "passportSerie", + "passportThree", + "passportTwo", + "region" + ], + "properties": { + "bornAt": { + "type": "string" + }, + "bornPlace": { + "type": "string" + }, + "branchId": { + "type": "integer" + }, + "cardStateId": { + "type": "integer" + }, + "cardTypeId": { + "type": "integer" + }, + "citizenship": { + "type": "string" + }, + "customerName": { + "type": "string" + }, + "customerPatronicName": { + "type": "string" + }, + "customerSurname": { + "type": "string" + }, + "jobLocation": { + "type": "string" + }, + "notes": { + "type": "string" + }, + "oldSurname": { + "type": "string" + }, + "paid": { + "type": "boolean" + }, + "passportAddress": { + "type": "string" + }, + "passportFour": { + "type": "string" + }, + "passportGivenAt": { + "type": "string" + }, + "passportGivenBy": { + "type": "string" + }, + "passportId": { + "type": "string" + }, + "passportOne": { + "type": "string" + }, + "passportSerie": { + "type": "string" + }, + "passportThree": { + "type": "string" + }, + "passportTwo": { + "type": "string" + }, + "phone": { + "type": "string" + }, + "phoneAdditional": { + "type": "string" + }, + "realAddress": { + "type": "string" + }, + "region": { + "type": "string" + }, + "status": { + "type": "string" + }, + "uniqueId": { + "type": "string" + }, + "userId": { + "type": "integer" + } + } + }, + "cards.CreateCardDTO": { + "type": "object", + "required": [ + "month", + "name", + "number" + ], + "properties": { + "month": { + "type": "string" + }, + "name": { + "type": "string" + }, + "number": { + "type": "string" + }, + "type": { + "type": "string" + }, + "userId": { + "type": "integer" + }, + "year": { + "type": "string" + } + } + }, + "cards.UpdateCardDTO": { + "type": "object", + "required": [ + "month", + "name", + "number" + ], + "properties": { + "month": { + "type": "string" + }, + "name": { + "type": "string" + }, + "number": { + "type": "string" + }, + "type": { + "type": "string" + }, + "userId": { + "type": "integer" + }, + "year": { + "type": "string" + } + } + }, "loanorders.CreateLoanOrderDTO": { "type": "object", "required": [ diff --git a/docs/swagger.json b/docs/swagger.json index 197d15d..4d94d63 100644 --- a/docs/swagger.json +++ b/docs/swagger.json @@ -402,6 +402,586 @@ } } }, + "/card-orders": { + "get": { + "security": [ + { + "BearerAuth": [] + } + ], + "description": "Returns paginated card orders with optional filters", + "produces": [ + "application/json" + ], + "tags": [ + "card-orders" + ], + "summary": "List card orders", + "parameters": [ + { + "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": "integer", + "description": "Filter by card state ID", + "name": "card_state_id", + "in": "query" + }, + { + "type": "integer", + "description": "Filter by card type ID", + "name": "card_type_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 card order", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "card-orders" + ], + "summary": "Create card order", + "parameters": [ + { + "description": "Card order payload", + "name": "body", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/cardorder.CreateCardOrderDTO" + } + } + ], + "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" + } + } + } + } + }, + "/card-orders/{id}": { + "get": { + "security": [ + { + "BearerAuth": [] + } + ], + "description": "Returns a single card order", + "produces": [ + "application/json" + ], + "tags": [ + "card-orders" + ], + "summary": "Get card order by ID", + "parameters": [ + { + "type": "integer", + "description": "Card 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 card order", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "card-orders" + ], + "summary": "Update card order", + "parameters": [ + { + "type": "integer", + "description": "Card order ID", + "name": "id", + "in": "path", + "required": true + }, + { + "description": "Card order payload", + "name": "body", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/cardorder.UpdateCardOrderDTO" + } + } + ], + "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 card order", + "produces": [ + "application/json" + ], + "tags": [ + "card-orders" + ], + "summary": "Delete card order", + "parameters": [ + { + "type": "integer", + "description": "Card 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" + } + } + } + } + }, + "/cards": { + "get": { + "security": [ + { + "BearerAuth": [] + } + ], + "description": "Returns paginated cards with optional filters", + "produces": [ + "application/json" + ], + "tags": [ + "cards" + ], + "summary": "List cards", + "parameters": [ + { + "type": "integer", + "description": "Filter by user ID", + "name": "user_id", + "in": "query" + }, + { + "type": "string", + "description": "Filter by card type", + "name": "type", + "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 card", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "cards" + ], + "summary": "Create card", + "parameters": [ + { + "description": "Card payload", + "name": "body", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/cards.CreateCardDTO" + } + } + ], + "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" + } + } + } + } + }, + "/cards/{id}": { + "get": { + "security": [ + { + "BearerAuth": [] + } + ], + "description": "Returns a single card", + "produces": [ + "application/json" + ], + "tags": [ + "cards" + ], + "summary": "Get card by ID", + "parameters": [ + { + "type": "integer", + "description": "Card 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 card", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "cards" + ], + "summary": "Update card", + "parameters": [ + { + "type": "integer", + "description": "Card ID", + "name": "id", + "in": "path", + "required": true + }, + { + "description": "Card payload", + "name": "body", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/cards.UpdateCardDTO" + } + } + ], + "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 card", + "produces": [ + "application/json" + ], + "tags": [ + "cards" + ], + "summary": "Delete card", + "parameters": [ + { + "type": "integer", + "description": "Card 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" + } + } + } + } + }, "/file": { "post": { "security": [ @@ -4009,6 +4589,282 @@ } } }, + "cardorder.CreateCardOrderDTO": { + "type": "object", + "required": [ + "bornPlace", + "branchId", + "cardStateId", + "cardTypeId", + "citizenship", + "customerName", + "customerSurname", + "passportFour", + "passportGivenAt", + "passportGivenBy", + "passportId", + "passportOne", + "passportSerie", + "passportThree", + "passportTwo", + "region" + ], + "properties": { + "bornAt": { + "type": "string" + }, + "bornPlace": { + "type": "string" + }, + "branchId": { + "type": "integer" + }, + "cardStateId": { + "type": "integer" + }, + "cardTypeId": { + "type": "integer" + }, + "citizenship": { + "type": "string" + }, + "customerName": { + "type": "string" + }, + "customerPatronicName": { + "type": "string" + }, + "customerSurname": { + "type": "string" + }, + "jobLocation": { + "type": "string" + }, + "notes": { + "type": "string" + }, + "oldSurname": { + "type": "string" + }, + "paid": { + "type": "boolean" + }, + "passportAddress": { + "type": "string" + }, + "passportFour": { + "type": "string" + }, + "passportGivenAt": { + "type": "string" + }, + "passportGivenBy": { + "type": "string" + }, + "passportId": { + "type": "string" + }, + "passportOne": { + "type": "string" + }, + "passportSerie": { + "type": "string" + }, + "passportThree": { + "type": "string" + }, + "passportTwo": { + "type": "string" + }, + "phone": { + "type": "string" + }, + "phoneAdditional": { + "type": "string" + }, + "realAddress": { + "type": "string" + }, + "region": { + "type": "string" + }, + "status": { + "type": "string" + }, + "uniqueId": { + "type": "string" + }, + "userId": { + "type": "integer" + } + } + }, + "cardorder.UpdateCardOrderDTO": { + "type": "object", + "required": [ + "bornPlace", + "branchId", + "cardStateId", + "cardTypeId", + "citizenship", + "customerName", + "customerSurname", + "passportFour", + "passportGivenAt", + "passportGivenBy", + "passportId", + "passportOne", + "passportSerie", + "passportThree", + "passportTwo", + "region" + ], + "properties": { + "bornAt": { + "type": "string" + }, + "bornPlace": { + "type": "string" + }, + "branchId": { + "type": "integer" + }, + "cardStateId": { + "type": "integer" + }, + "cardTypeId": { + "type": "integer" + }, + "citizenship": { + "type": "string" + }, + "customerName": { + "type": "string" + }, + "customerPatronicName": { + "type": "string" + }, + "customerSurname": { + "type": "string" + }, + "jobLocation": { + "type": "string" + }, + "notes": { + "type": "string" + }, + "oldSurname": { + "type": "string" + }, + "paid": { + "type": "boolean" + }, + "passportAddress": { + "type": "string" + }, + "passportFour": { + "type": "string" + }, + "passportGivenAt": { + "type": "string" + }, + "passportGivenBy": { + "type": "string" + }, + "passportId": { + "type": "string" + }, + "passportOne": { + "type": "string" + }, + "passportSerie": { + "type": "string" + }, + "passportThree": { + "type": "string" + }, + "passportTwo": { + "type": "string" + }, + "phone": { + "type": "string" + }, + "phoneAdditional": { + "type": "string" + }, + "realAddress": { + "type": "string" + }, + "region": { + "type": "string" + }, + "status": { + "type": "string" + }, + "uniqueId": { + "type": "string" + }, + "userId": { + "type": "integer" + } + } + }, + "cards.CreateCardDTO": { + "type": "object", + "required": [ + "month", + "name", + "number" + ], + "properties": { + "month": { + "type": "string" + }, + "name": { + "type": "string" + }, + "number": { + "type": "string" + }, + "type": { + "type": "string" + }, + "userId": { + "type": "integer" + }, + "year": { + "type": "string" + } + } + }, + "cards.UpdateCardDTO": { + "type": "object", + "required": [ + "month", + "name", + "number" + ], + "properties": { + "month": { + "type": "string" + }, + "name": { + "type": "string" + }, + "number": { + "type": "string" + }, + "type": { + "type": "string" + }, + "userId": { + "type": "integer" + }, + "year": { + "type": "string" + } + } + }, "loanorders.CreateLoanOrderDTO": { "type": "object", "required": [ diff --git a/docs/swagger.yaml b/docs/swagger.yaml index b916690..ea48ae5 100644 --- a/docs/swagger.yaml +++ b/docs/swagger.yaml @@ -133,6 +133,200 @@ definitions: - name - region type: object + cardorder.CreateCardOrderDTO: + properties: + bornAt: + type: string + bornPlace: + type: string + branchId: + type: integer + cardStateId: + type: integer + cardTypeId: + type: integer + citizenship: + type: string + customerName: + type: string + customerPatronicName: + type: string + customerSurname: + type: string + jobLocation: + type: string + notes: + type: string + oldSurname: + type: string + paid: + type: boolean + passportAddress: + type: string + passportFour: + type: string + passportGivenAt: + type: string + passportGivenBy: + type: string + passportId: + type: string + passportOne: + type: string + passportSerie: + type: string + passportThree: + type: string + passportTwo: + type: string + phone: + type: string + phoneAdditional: + type: string + realAddress: + type: string + region: + type: string + status: + type: string + uniqueId: + type: string + userId: + type: integer + required: + - bornPlace + - branchId + - cardStateId + - cardTypeId + - citizenship + - customerName + - customerSurname + - passportFour + - passportGivenAt + - passportGivenBy + - passportId + - passportOne + - passportSerie + - passportThree + - passportTwo + - region + type: object + cardorder.UpdateCardOrderDTO: + properties: + bornAt: + type: string + bornPlace: + type: string + branchId: + type: integer + cardStateId: + type: integer + cardTypeId: + type: integer + citizenship: + type: string + customerName: + type: string + customerPatronicName: + type: string + customerSurname: + type: string + jobLocation: + type: string + notes: + type: string + oldSurname: + type: string + paid: + type: boolean + passportAddress: + type: string + passportFour: + type: string + passportGivenAt: + type: string + passportGivenBy: + type: string + passportId: + type: string + passportOne: + type: string + passportSerie: + type: string + passportThree: + type: string + passportTwo: + type: string + phone: + type: string + phoneAdditional: + type: string + realAddress: + type: string + region: + type: string + status: + type: string + uniqueId: + type: string + userId: + type: integer + required: + - bornPlace + - branchId + - cardStateId + - cardTypeId + - citizenship + - customerName + - customerSurname + - passportFour + - passportGivenAt + - passportGivenBy + - passportId + - passportOne + - passportSerie + - passportThree + - passportTwo + - region + type: object + cards.CreateCardDTO: + properties: + month: + type: string + name: + type: string + number: + type: string + type: + type: string + userId: + type: integer + year: + type: string + required: + - month + - name + - number + type: object + cards.UpdateCardDTO: + properties: + month: + type: string + name: + type: string + number: + type: string + type: + type: string + userId: + type: integer + year: + type: string + required: + - month + - name + - number + type: object loanorders.CreateLoanOrderDTO: properties: bornAt: @@ -1141,6 +1335,378 @@ paths: summary: Update branch tags: - branches + /card-orders: + get: + description: Returns paginated card orders with optional filters + parameters: + - 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 card state ID + in: query + name: card_state_id + type: integer + - description: Filter by card type ID + in: query + name: card_type_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 card orders + tags: + - card-orders + post: + consumes: + - application/json + description: Creates a new card order + parameters: + - description: Card order payload + in: body + name: body + required: true + schema: + $ref: '#/definitions/cardorder.CreateCardOrderDTO' + 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 card order + tags: + - card-orders + /card-orders/{id}: + delete: + description: Deletes a card order + parameters: + - description: Card 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 card order + tags: + - card-orders + get: + description: Returns a single card order + parameters: + - description: Card 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 card order by ID + tags: + - card-orders + put: + consumes: + - application/json + description: Updates an existing card order + parameters: + - description: Card order ID + in: path + name: id + required: true + type: integer + - description: Card order payload + in: body + name: body + required: true + schema: + $ref: '#/definitions/cardorder.UpdateCardOrderDTO' + 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 card order + tags: + - card-orders + /cards: + get: + description: Returns paginated cards with optional filters + parameters: + - description: Filter by user ID + in: query + name: user_id + type: integer + - description: Filter by card type + in: query + name: type + 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 cards + tags: + - cards + post: + consumes: + - application/json + description: Creates a new card + parameters: + - description: Card payload + in: body + name: body + required: true + schema: + $ref: '#/definitions/cards.CreateCardDTO' + 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 card + tags: + - cards + /cards/{id}: + delete: + description: Deletes a card + parameters: + - description: Card 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 card + tags: + - cards + get: + description: Returns a single card + parameters: + - description: Card 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 card by ID + tags: + - cards + put: + consumes: + - application/json + description: Updates an existing card + parameters: + - description: Card ID + in: path + name: id + required: true + type: integer + - description: Card payload + in: body + name: body + required: true + schema: + $ref: '#/definitions/cards.UpdateCardDTO' + 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 card + tags: + - cards /file: post: consumes: diff --git a/internal/admin/cardorder/db/postgresql.go b/internal/admin/cardorder/db/postgresql.go new file mode 100644 index 0000000..0a9fa35 --- /dev/null +++ b/internal/admin/cardorder/db/postgresql.go @@ -0,0 +1,228 @@ +package db + +import ( + "context" + "fmt" + "strings" + + "online-back/internal/admin/cardorder" + "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) cardorder.Repository { + return &repository{client: client, 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) + + var count int64 + countQuery := `SELECT COUNT(*) FROM card_orders` + whereClause + if err := r.client.QueryRow(ctx, countQuery, args...).Scan(&count); err != nil { + return cardorder.ListCardOrderDTO{}, err + } + + offset := (filter.Page - 1) * filter.Limit + limitPlaceholder := len(args) + 1 + offsetPlaceholder := len(args) + 2 + listQuery := fmt.Sprintf( + `SELECT %s FROM card_orders%s ORDER BY id DESC LIMIT $%d OFFSET $%d`, + cardOrderColumnsSQL, whereClause, limitPlaceholder, offsetPlaceholder, + ) + + rows, err := r.client.Query(ctx, listQuery, append(args, filter.Limit, offset)...) + if err != nil { + return cardorder.ListCardOrderDTO{}, err + } + defer rows.Close() + + var items []cardorder.CardOrderDTO + for rows.Next() { + item, err := scanCardOrder(rows) + if err != nil { + return cardorder.ListCardOrderDTO{}, err + } + items = append(items, item) + } + if err := rows.Err(); 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) { + query := fmt.Sprintf(`SELECT %s FROM card_orders WHERE id = $1`, cardOrderColumnsSQL) + item, err := scanCardOrder(r.client.QueryRow(ctx, query, id)) + if err != nil { + return cardorder.CardOrderDTO{}, err + } + return item, nil +} + +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 { + tag, err := r.client.Exec(ctx, `DELETE FROM card_orders 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 scanCardOrder(row scannable) (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 +} diff --git a/internal/admin/cardorder/dto.go b/internal/admin/cardorder/dto.go new file mode 100644 index 0000000..ce3d1d4 --- /dev/null +++ b/internal/admin/cardorder/dto.go @@ -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"` +} diff --git a/internal/admin/cardorder/handler.go b/internal/admin/cardorder/handler.go new file mode 100644 index 0000000..ab5d3f9 --- /dev/null +++ b/internal/admin/cardorder/handler.go @@ -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 +} diff --git a/internal/admin/cardorder/storage.go b/internal/admin/cardorder/storage.go new file mode 100644 index 0000000..0ae5e34 --- /dev/null +++ b/internal/admin/cardorder/storage.go @@ -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 +} diff --git a/internal/admin/cardpinorders/db/postgresql.go b/internal/admin/cardpinorders/db/postgresql.go new file mode 100644 index 0000000..66c591f --- /dev/null +++ b/internal/admin/cardpinorders/db/postgresql.go @@ -0,0 +1,204 @@ +package db + +import ( + "context" + "fmt" + "strings" + + "online-back/internal/admin/cardpinorders" + "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) cardpinorders.Repository { + return &repository{client: client, 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) + + var count int64 + countQuery := `SELECT COUNT(*) FROM card_pin_orders` + whereClause + if err := r.client.QueryRow(ctx, countQuery, args...).Scan(&count); err != nil { + return cardpinorders.ListCardPinOrderDTO{}, err + } + + offset := (filter.Page - 1) * filter.Limit + limitPlaceholder := len(args) + 1 + offsetPlaceholder := len(args) + 2 + listQuery := fmt.Sprintf( + `SELECT %s FROM card_pin_orders%s ORDER BY id DESC LIMIT $%d OFFSET $%d`, + cardPinOrderColumnsSQL, whereClause, limitPlaceholder, offsetPlaceholder, + ) + + rows, err := r.client.Query(ctx, listQuery, append(args, filter.Limit, offset)...) + if err != nil { + return cardpinorders.ListCardPinOrderDTO{}, err + } + defer rows.Close() + + var items []cardpinorders.CardPinOrderDTO + for rows.Next() { + item, err := scanCardPinOrder(rows) + if err != nil { + return cardpinorders.ListCardPinOrderDTO{}, err + } + items = append(items, item) + } + if err := rows.Err(); 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) { + query := fmt.Sprintf(`SELECT %s FROM card_pin_orders WHERE id = $1`, cardPinOrderColumnsSQL) + item, err := scanCardPinOrder(r.client.QueryRow(ctx, query, id)) + if err != nil { + return cardpinorders.CardPinOrderDTO{}, err + } + return item, nil +} + +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 { + tag, err := r.client.Exec(ctx, `DELETE FROM card_pin_orders 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 scanCardPinOrder(row scannable) (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 +} diff --git a/internal/admin/cardpinorders/dto.go b/internal/admin/cardpinorders/dto.go new file mode 100644 index 0000000..4f4f5ed --- /dev/null +++ b/internal/admin/cardpinorders/dto.go @@ -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"` +} diff --git a/internal/admin/cardpinorders/handler.go b/internal/admin/cardpinorders/handler.go new file mode 100644 index 0000000..9822a1d --- /dev/null +++ b/internal/admin/cardpinorders/handler.go @@ -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 +} diff --git a/internal/admin/cardpinorders/storage.go b/internal/admin/cardpinorders/storage.go new file mode 100644 index 0000000..690589a --- /dev/null +++ b/internal/admin/cardpinorders/storage.go @@ -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 +} diff --git a/internal/admin/cards/db/postgresql.go b/internal/admin/cards/db/postgresql.go new file mode 100644 index 0000000..e602798 --- /dev/null +++ b/internal/admin/cards/db/postgresql.go @@ -0,0 +1,177 @@ +package db + +import ( + "context" + "fmt" + "strings" + + "online-back/internal/admin/cards" + "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) cards.Repository { + return &repository{client: client, 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) + + var count int64 + countQuery := `SELECT COUNT(*) FROM cards` + whereClause + if err := r.client.QueryRow(ctx, countQuery, args...).Scan(&count); err != nil { + return cards.ListCardDTO{}, err + } + + offset := (filter.Page - 1) * filter.Limit + limitPlaceholder := len(args) + 1 + offsetPlaceholder := len(args) + 2 + listQuery := fmt.Sprintf( + `SELECT %s FROM cards%s ORDER BY id DESC LIMIT $%d OFFSET $%d`, + cardColumnsSQL, whereClause, limitPlaceholder, offsetPlaceholder, + ) + + rows, err := r.client.Query(ctx, listQuery, append(args, filter.Limit, offset)...) + if err != nil { + return cards.ListCardDTO{}, err + } + defer rows.Close() + + var items []cards.CardDTO + for rows.Next() { + item, err := scanCard(rows) + if err != nil { + return cards.ListCardDTO{}, err + } + items = append(items, item) + } + if err := rows.Err(); 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) { + query := fmt.Sprintf(`SELECT %s FROM cards WHERE id = $1`, cardColumnsSQL) + item, err := scanCard(r.client.QueryRow(ctx, query, id)) + if err != nil { + return cards.CardDTO{}, err + } + return item, nil +} + +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 { + tag, err := r.client.Exec(ctx, `DELETE FROM cards 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 scanCard(row scannable) (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 +} diff --git a/internal/admin/cards/dto.go b/internal/admin/cards/dto.go new file mode 100644 index 0000000..c4fa3c4 --- /dev/null +++ b/internal/admin/cards/dto.go @@ -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"` +} diff --git a/internal/admin/cards/handler.go b/internal/admin/cards/handler.go new file mode 100644 index 0000000..40379d2 --- /dev/null +++ b/internal/admin/cards/handler.go @@ -0,0 +1,251 @@ +package cards + +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 = "/cards" + +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 cards +// @Description Returns paginated cards with optional filters +// @Tags cards +// @Produce json +// @Security BearerAuth +// @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 /cards [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 cards failed: %v", err) + c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer) + return + } + + c.JSON(http.StatusOK, appresult.SuccessWithData(result)) +} + +// getByID godoc +// @Summary Get card by ID +// @Description Returns a single card +// @Tags cards +// @Produce json +// @Security BearerAuth +// @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 /cards/{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 failed: %v", err) + c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer) + return + } + + c.JSON(http.StatusOK, appresult.SuccessWithData(item)) +} + +// create godoc +// @Summary Create card +// @Description Creates a new card +// @Tags cards +// @Accept json +// @Produce json +// @Security BearerAuth +// @Param body body CreateCardDTO true "Card payload" +// @Success 201 {object} appresult.AppSuccess +// @Failure 400 {object} appresult.AppError +// @Failure 500 {object} appresult.AppError +// @Router /cards [post] +func (h *handler) create(c *gin.Context) { + var dto CreateCardDTO + 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 failed: %v", err) + c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer) + return + } + + c.JSON(http.StatusCreated, appresult.SuccessWithData(item)) +} + +// update godoc +// @Summary Update card +// @Description Updates an existing card +// @Tags cards +// @Accept json +// @Produce json +// @Security BearerAuth +// @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 /cards/{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 UpdateCardDTO + 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 failed: %v", err) + c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer) + return + } + + c.JSON(http.StatusOK, appresult.SuccessWithData(item)) +} + +// delete godoc +// @Summary Delete card +// @Description Deletes a card +// @Tags cards +// @Produce json +// @Security BearerAuth +// @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 /cards/{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 failed: %v", err) + c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer) + return + } + + c.JSON(http.StatusOK, appresult.SuccessWithData("card 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("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 { + 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 +} diff --git a/internal/admin/cards/storage.go b/internal/admin/cards/storage.go new file mode 100644 index 0000000..f2523b5 --- /dev/null +++ b/internal/admin/cards/storage.go @@ -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 +} diff --git a/internal/handlers/manager/manager.go b/internal/handlers/manager/manager.go index ccb5198..92da951 100755 --- a/internal/handlers/manager/manager.go +++ b/internal/handlers/manager/manager.go @@ -7,6 +7,12 @@ import ( authdb "online-back/internal/admin/auth/db" "online-back/internal/admin/branches" branchesdb "online-back/internal/admin/branches/db" + "online-back/internal/admin/cardorder" + cardorderdb "online-back/internal/admin/cardorder/db" + "online-back/internal/admin/cardpinorders" + cardpinordersdb "online-back/internal/admin/cardpinorders/db" + "online-back/internal/admin/cards" + cardsdb "online-back/internal/admin/cards/db" "online-back/internal/admin/loanorders" loanordersdb "online-back/internal/admin/loanorders/db" "online-back/internal/admin/loanpaidletter" @@ -78,6 +84,9 @@ func adminHandlers(client *pgxpool.Pool, logger *logging.Logger) []handlers.Hand auth.NewHandler(logger, authdb.NewRepository(client, logger)), province.NewHandler(logger, provincedb.NewRepository(client, logger)), branches.NewHandler(logger, branchesdb.NewRepository(client, logger)), + cardorder.NewHandler(logger, cardorderdb.NewRepository(client, logger)), + cardpinorders.NewHandler(logger, cardpinordersdb.NewRepository(client, logger)), + cards.NewHandler(logger, cardsdb.NewRepository(client, logger)), paymentcard.NewHandler(logger, paymentcarddb.NewRepository(client, logger)), reasonscard.NewHandler(logger, reasonscarddb.NewRepository(client, logger)), loantype.NewHandler(logger, loantypedb.NewRepository(client, logger)),