diff --git a/db/migrations/20260702125108_init.up.sql b/db/migrations/20260702125108_init.up.sql index 126f53e..ff9f11b 100644 --- a/db/migrations/20260702125108_init.up.sql +++ b/db/migrations/20260702125108_init.up.sql @@ -7,6 +7,22 @@ CREATE TABLE IF NOT EXISTS roles ( updated_at TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL ); +CREATE TABLE IF NOT EXISTS role_user ( + id bigserial PRIMARY KEY, + role_id bigint REFERENCES roles(id), + user_id bigint REFERENCES users(id), + created_at TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL, + updated_at TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL +); + +CREATE TABLE IF NOT EXISTS permission_user ( + id bigserial PRIMARY KEY, + permission_id bigint REFERENCES permissions(id), + user_id bigint REFERENCES users(id), + created_at TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL, + updated_at TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL +); + CREATE TABLE IF NOT EXISTS users ( "id" bigserial primary key, "email" character varying(250) NOT NULL DEFAULT '', @@ -49,9 +65,9 @@ CREATE TABLE IF NOT EXISTS branches ( unique_code character varying(255) UNIQUE, name json NOT NULL DEFAULT '{}'::json, address json NOT NULL DEFAULT '{}'::json, - region character varying(2) NOT NULL DEFAULT '', + region character varying(20) NOT NULL DEFAULT '', province_id bigint, - phone_numbers json NOT NULL DEFAULT '[]'::json, + phone_numbers character varying(255) NOT NULL DEFAULT '', billing_username character varying(255) NOT NULL DEFAULT '', billing_password character varying(255) NOT NULL DEFAULT '', billing_swift_username character varying(255) NOT NULL DEFAULT '', @@ -326,4 +342,5 @@ CREATE TABLE IF NOT EXISTS cards ( 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 1ddf547..31acccd 100644 --- a/docs/docs.go +++ b/docs/docs.go @@ -16,6 +16,49 @@ const docTemplate = `{ "basePath": "{{.BasePath}}", "paths": { "/branch-users": { + "get": { + "security": [ + { + "BearerAuth": [] + } + ], + "description": "Returns the authenticated user's branch-user assignments with the related user and branch", + "produces": [ + "application/json" + ], + "tags": [ + "branch-users" + ], + "summary": "List branch users", + "parameters": [ + { + "type": "string", + "description": "Filter by branch name (en, ru, tm)", + "name": "branch_name", + "in": "query" + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/appresult.AppSuccess" + } + }, + "401": { + "description": "Unauthorized", + "schema": { + "$ref": "#/definitions/appresult.AppError" + } + }, + "500": { + "description": "Internal Server Error", + "schema": { + "$ref": "#/definitions/appresult.AppError" + } + } + } + }, "post": { "security": [ { @@ -30,7 +73,7 @@ const docTemplate = `{ "application/json" ], "tags": [ - "auth" + "branch-users" ], "summary": "Assign user to branch", "parameters": [ @@ -40,7 +83,7 @@ const docTemplate = `{ "in": "body", "required": true, "schema": { - "$ref": "#/definitions/auth.CreateBranchUserDTO" + "$ref": "#/definitions/userbranch.CreateUserBranchDTO" } } ], @@ -78,7 +121,7 @@ const docTemplate = `{ "application/json" ], "tags": [ - "auth" + "branch-users" ], "summary": "Remove user from branch", "parameters": [ @@ -710,6 +753,302 @@ const docTemplate = `{ } } }, + "/card-pin-orders": { + "get": { + "security": [ + { + "BearerAuth": [] + } + ], + "description": "Returns paginated card pin orders with optional filters", + "produces": [ + "application/json" + ], + "tags": [ + "card-pin-orders" + ], + "summary": "List card pin 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 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 pin order", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "card-pin-orders" + ], + "summary": "Create card pin order", + "parameters": [ + { + "description": "Card pin order payload", + "name": "body", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/cardpinorders.CreateCardPinOrderDTO" + } + } + ], + "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-pin-orders/{id}": { + "get": { + "security": [ + { + "BearerAuth": [] + } + ], + "description": "Returns a single card pin order", + "produces": [ + "application/json" + ], + "tags": [ + "card-pin-orders" + ], + "summary": "Get card pin order by ID", + "parameters": [ + { + "type": "integer", + "description": "Card pin 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 pin order", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "card-pin-orders" + ], + "summary": "Update card pin order", + "parameters": [ + { + "type": "integer", + "description": "Card pin order ID", + "name": "id", + "in": "path", + "required": true + }, + { + "description": "Card pin order payload", + "name": "body", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/cardpinorders.UpdateCardPinOrderDTO" + } + } + ], + "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 pin order", + "produces": [ + "application/json" + ], + "tags": [ + "card-pin-orders" + ], + "summary": "Delete card pin order", + "parameters": [ + { + "type": "integer", + "description": "Card pin 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": [ @@ -2966,6 +3305,152 @@ const docTemplate = `{ } } }, + "/permission-users": { + "get": { + "security": [ + { + "BearerAuth": [] + } + ], + "description": "Returns the authenticated user's permission-user assignments with the related user and permission", + "produces": [ + "application/json" + ], + "tags": [ + "permission-users" + ], + "summary": "List permission users", + "parameters": [ + { + "type": "string", + "description": "Filter by permission name", + "name": "permission_name", + "in": "query" + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/appresult.AppSuccess" + } + }, + "401": { + "description": "Unauthorized", + "schema": { + "$ref": "#/definitions/appresult.AppError" + } + }, + "500": { + "description": "Internal Server Error", + "schema": { + "$ref": "#/definitions/appresult.AppError" + } + } + } + }, + "post": { + "security": [ + { + "BearerAuth": [] + } + ], + "description": "Creates a permission-user assignment", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "permission-users" + ], + "summary": "Assign user to permission", + "parameters": [ + { + "description": "Permission-user payload", + "name": "body", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/permissionuser.CreatePermissionUserDTO" + } + } + ], + "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" + } + } + } + } + }, + "/permission-users/{id}": { + "delete": { + "security": [ + { + "BearerAuth": [] + } + ], + "description": "Deletes a permission-user assignment", + "produces": [ + "application/json" + ], + "tags": [ + "permission-users" + ], + "summary": "Remove user from permission", + "parameters": [ + { + "type": "integer", + "description": "Permission-user 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" + } + } + } + } + }, "/permissions": { "get": { "security": [ @@ -3279,6 +3764,61 @@ const docTemplate = `{ } } } + }, + "put": { + "security": [ + { + "BearerAuth": [] + } + ], + "description": "Updates the authenticated user's profile", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "auth" + ], + "summary": "Update profile", + "parameters": [ + { + "description": "Profile payload", + "name": "body", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/auth.UpdateProfileDTO" + } + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/appresult.AppSuccess" + } + }, + "400": { + "description": "Bad Request", + "schema": { + "$ref": "#/definitions/appresult.AppError" + } + }, + "401": { + "description": "Unauthorized", + "schema": { + "$ref": "#/definitions/appresult.AppError" + } + }, + "404": { + "description": "Not Found", + "schema": { + "$ref": "#/definitions/appresult.AppError" + } + } + } } }, "/provinces": { @@ -3288,7 +3828,7 @@ const docTemplate = `{ "BearerAuth": [] } ], - "description": "Returns all provinces", + "description": "Returns paginated provinces with optional filters", "produces": [ "application/json" ], @@ -3296,6 +3836,40 @@ const docTemplate = `{ "province" ], "summary": "List provinces", + "parameters": [ + { + "type": "string", + "description": "Filter by province name (en, ru, tm)", + "name": "name", + "in": "query" + }, + { + "type": "string", + "description": "Filter by region (en, ru, tm)", + "name": "region", + "in": "query" + }, + { + "type": "boolean", + "description": "Filter by active status", + "name": "active", + "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", @@ -3803,6 +4377,152 @@ const docTemplate = `{ } } }, + "/role-users": { + "get": { + "security": [ + { + "BearerAuth": [] + } + ], + "description": "Returns the authenticated user's role-user assignments with the related user and role", + "produces": [ + "application/json" + ], + "tags": [ + "role-users" + ], + "summary": "List role users", + "parameters": [ + { + "type": "string", + "description": "Filter by role name", + "name": "role_name", + "in": "query" + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/appresult.AppSuccess" + } + }, + "401": { + "description": "Unauthorized", + "schema": { + "$ref": "#/definitions/appresult.AppError" + } + }, + "500": { + "description": "Internal Server Error", + "schema": { + "$ref": "#/definitions/appresult.AppError" + } + } + } + }, + "post": { + "security": [ + { + "BearerAuth": [] + } + ], + "description": "Creates a role-user assignment", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "role-users" + ], + "summary": "Assign user to role", + "parameters": [ + { + "description": "Role-user payload", + "name": "body", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/roleusers.CreateRoleUserDTO" + } + } + ], + "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" + } + } + } + } + }, + "/role-users/{id}": { + "delete": { + "security": [ + { + "BearerAuth": [] + } + ], + "description": "Deletes a role-user assignment", + "produces": [ + "application/json" + ], + "tags": [ + "role-users" + ], + "summary": "Remove user from role", + "parameters": [ + { + "type": "integer", + "description": "Role-user 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" + } + } + } + } + }, "/roles": { "get": { "security": [ @@ -4229,6 +4949,78 @@ const docTemplate = `{ } } }, + "/users/role": { + "get": { + "security": [ + { + "BearerAuth": [] + } + ], + "description": "Returns paginated users filtered by role", + "produces": [ + "application/json" + ], + "tags": [ + "user" + ], + "summary": "List users by role", + "parameters": [ + { + "type": "string", + "description": "user role", + "name": "role", + "in": "query", + "required": true + }, + { + "type": "string", + "description": "Filter by username", + "name": "username", + "in": "query" + }, + { + "type": "integer", + "default": 1, + "description": "Page number", + "name": "page", + "in": "query" + }, + { + "type": "integer", + "default": 10, + "description": "Items per page", + "name": "limit", + "in": "query" + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/appresult.AppSuccess" + } + }, + "400": { + "description": "Bad Request", + "schema": { + "$ref": "#/definitions/appresult.AppError" + } + }, + "404": { + "description": "Not Found", + "schema": { + "$ref": "#/definitions/appresult.AppError" + } + }, + "500": { + "description": "Internal Server Error", + "schema": { + "$ref": "#/definitions/appresult.AppError" + } + } + } + } + }, "/users/{id}": { "get": { "security": [ @@ -4424,21 +5216,6 @@ const docTemplate = `{ } } }, - "auth.CreateBranchUserDTO": { - "type": "object", - "required": [ - "branchId", - "userId" - ], - "properties": { - "branchId": { - "type": "integer" - }, - "userId": { - "type": "integer" - } - } - }, "auth.LoginDTO": { "type": "object", "required": [ @@ -4465,6 +5242,29 @@ const docTemplate = `{ } } }, + "auth.UpdateProfileDTO": { + "type": "object", + "required": [ + "name" + ], + "properties": { + "avatar": { + "type": "string" + }, + "firstName": { + "type": "string" + }, + "lastName": { + "type": "string" + }, + "name": { + "type": "string" + }, + "phone": { + "type": "string" + } + } + }, "branches.CreateBranchDTO": { "type": "object", "required": [ @@ -4507,10 +5307,7 @@ const docTemplate = `{ "$ref": "#/definitions/branches.LocalizedText" }, "phoneNumbers": { - "type": "array", - "items": { - "type": "string" - } + "type": "string" }, "provinceId": { "type": "integer" @@ -4579,10 +5376,7 @@ const docTemplate = `{ "$ref": "#/definitions/branches.LocalizedText" }, "phoneNumbers": { - "type": "array", - "items": { - "type": "string" - } + "type": "string" }, "provinceId": { "type": "integer" @@ -4815,6 +5609,156 @@ const docTemplate = `{ } } }, + "cardpinorders.CreateCardPinOrderDTO": { + "type": "object", + "required": [ + "branchId", + "cardTypeId", + "customerName", + "customerSurname", + "passportFour", + "passportId", + "passportOne", + "passportSerie", + "passportThree", + "passportTwo", + "region" + ], + "properties": { + "bornAt": { + "type": "string" + }, + "branchId": { + "type": "integer" + }, + "cardNumber": { + "type": "string" + }, + "cardTypeId": { + "type": "integer" + }, + "customerName": { + "type": "string" + }, + "customerPatronicName": { + "type": "string" + }, + "customerSurname": { + "type": "string" + }, + "notes": { + "type": "string" + }, + "passportFour": { + "type": "string" + }, + "passportId": { + "type": "string" + }, + "passportOne": { + "type": "string" + }, + "passportSerie": { + "type": "string" + }, + "passportThree": { + "type": "string" + }, + "passportTwo": { + "type": "string" + }, + "phone": { + "type": "string" + }, + "region": { + "type": "string" + }, + "status": { + "type": "string" + }, + "uniqueId": { + "type": "string" + }, + "userId": { + "type": "integer" + } + } + }, + "cardpinorders.UpdateCardPinOrderDTO": { + "type": "object", + "required": [ + "branchId", + "cardTypeId", + "customerName", + "customerSurname", + "passportFour", + "passportId", + "passportOne", + "passportSerie", + "passportThree", + "passportTwo", + "region" + ], + "properties": { + "bornAt": { + "type": "string" + }, + "branchId": { + "type": "integer" + }, + "cardNumber": { + "type": "string" + }, + "cardTypeId": { + "type": "integer" + }, + "customerName": { + "type": "string" + }, + "customerPatronicName": { + "type": "string" + }, + "customerSurname": { + "type": "string" + }, + "notes": { + "type": "string" + }, + "passportFour": { + "type": "string" + }, + "passportId": { + "type": "string" + }, + "passportOne": { + "type": "string" + }, + "passportSerie": { + "type": "string" + }, + "passportThree": { + "type": "string" + }, + "passportTwo": { + "type": "string" + }, + "phone": { + "type": "string" + }, + "region": { + "type": "string" + }, + "status": { + "type": "string" + }, + "uniqueId": { + "type": "string" + }, + "userId": { + "type": "integer" + } + } + }, "cards.CreateCardDTO": { "type": "object", "required": [ @@ -5721,6 +6665,21 @@ const docTemplate = `{ } } }, + "permissionuser.CreatePermissionUserDTO": { + "type": "object", + "required": [ + "permissionId", + "userId" + ], + "properties": { + "permissionId": { + "type": "integer" + }, + "userId": { + "type": "integer" + } + } + }, "province.CreateProvinceDTO": { "type": "object", "required": [ @@ -5865,6 +6824,21 @@ const docTemplate = `{ } } }, + "roleusers.CreateRoleUserDTO": { + "type": "object", + "required": [ + "roleId", + "userId" + ], + "properties": { + "roleId": { + "type": "integer" + }, + "userId": { + "type": "integer" + } + } + }, "user.CreateUserDTO": { "type": "object", "required": [ @@ -5968,6 +6942,21 @@ const docTemplate = `{ "type": "string" } } + }, + "userbranch.CreateUserBranchDTO": { + "type": "object", + "required": [ + "branchId", + "userId" + ], + "properties": { + "branchId": { + "type": "integer" + }, + "userId": { + "type": "integer" + } + } } }, "securityDefinitions": { diff --git a/docs/swagger.json b/docs/swagger.json index 4d94d63..f3fc748 100644 --- a/docs/swagger.json +++ b/docs/swagger.json @@ -10,6 +10,49 @@ "basePath": "/api/admin", "paths": { "/branch-users": { + "get": { + "security": [ + { + "BearerAuth": [] + } + ], + "description": "Returns the authenticated user's branch-user assignments with the related user and branch", + "produces": [ + "application/json" + ], + "tags": [ + "branch-users" + ], + "summary": "List branch users", + "parameters": [ + { + "type": "string", + "description": "Filter by branch name (en, ru, tm)", + "name": "branch_name", + "in": "query" + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/appresult.AppSuccess" + } + }, + "401": { + "description": "Unauthorized", + "schema": { + "$ref": "#/definitions/appresult.AppError" + } + }, + "500": { + "description": "Internal Server Error", + "schema": { + "$ref": "#/definitions/appresult.AppError" + } + } + } + }, "post": { "security": [ { @@ -24,7 +67,7 @@ "application/json" ], "tags": [ - "auth" + "branch-users" ], "summary": "Assign user to branch", "parameters": [ @@ -34,7 +77,7 @@ "in": "body", "required": true, "schema": { - "$ref": "#/definitions/auth.CreateBranchUserDTO" + "$ref": "#/definitions/userbranch.CreateUserBranchDTO" } } ], @@ -72,7 +115,7 @@ "application/json" ], "tags": [ - "auth" + "branch-users" ], "summary": "Remove user from branch", "parameters": [ @@ -704,6 +747,302 @@ } } }, + "/card-pin-orders": { + "get": { + "security": [ + { + "BearerAuth": [] + } + ], + "description": "Returns paginated card pin orders with optional filters", + "produces": [ + "application/json" + ], + "tags": [ + "card-pin-orders" + ], + "summary": "List card pin 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 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 pin order", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "card-pin-orders" + ], + "summary": "Create card pin order", + "parameters": [ + { + "description": "Card pin order payload", + "name": "body", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/cardpinorders.CreateCardPinOrderDTO" + } + } + ], + "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-pin-orders/{id}": { + "get": { + "security": [ + { + "BearerAuth": [] + } + ], + "description": "Returns a single card pin order", + "produces": [ + "application/json" + ], + "tags": [ + "card-pin-orders" + ], + "summary": "Get card pin order by ID", + "parameters": [ + { + "type": "integer", + "description": "Card pin 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 pin order", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "card-pin-orders" + ], + "summary": "Update card pin order", + "parameters": [ + { + "type": "integer", + "description": "Card pin order ID", + "name": "id", + "in": "path", + "required": true + }, + { + "description": "Card pin order payload", + "name": "body", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/cardpinorders.UpdateCardPinOrderDTO" + } + } + ], + "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 pin order", + "produces": [ + "application/json" + ], + "tags": [ + "card-pin-orders" + ], + "summary": "Delete card pin order", + "parameters": [ + { + "type": "integer", + "description": "Card pin 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": [ @@ -2960,6 +3299,152 @@ } } }, + "/permission-users": { + "get": { + "security": [ + { + "BearerAuth": [] + } + ], + "description": "Returns the authenticated user's permission-user assignments with the related user and permission", + "produces": [ + "application/json" + ], + "tags": [ + "permission-users" + ], + "summary": "List permission users", + "parameters": [ + { + "type": "string", + "description": "Filter by permission name", + "name": "permission_name", + "in": "query" + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/appresult.AppSuccess" + } + }, + "401": { + "description": "Unauthorized", + "schema": { + "$ref": "#/definitions/appresult.AppError" + } + }, + "500": { + "description": "Internal Server Error", + "schema": { + "$ref": "#/definitions/appresult.AppError" + } + } + } + }, + "post": { + "security": [ + { + "BearerAuth": [] + } + ], + "description": "Creates a permission-user assignment", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "permission-users" + ], + "summary": "Assign user to permission", + "parameters": [ + { + "description": "Permission-user payload", + "name": "body", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/permissionuser.CreatePermissionUserDTO" + } + } + ], + "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" + } + } + } + } + }, + "/permission-users/{id}": { + "delete": { + "security": [ + { + "BearerAuth": [] + } + ], + "description": "Deletes a permission-user assignment", + "produces": [ + "application/json" + ], + "tags": [ + "permission-users" + ], + "summary": "Remove user from permission", + "parameters": [ + { + "type": "integer", + "description": "Permission-user 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" + } + } + } + } + }, "/permissions": { "get": { "security": [ @@ -3273,6 +3758,61 @@ } } } + }, + "put": { + "security": [ + { + "BearerAuth": [] + } + ], + "description": "Updates the authenticated user's profile", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "auth" + ], + "summary": "Update profile", + "parameters": [ + { + "description": "Profile payload", + "name": "body", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/auth.UpdateProfileDTO" + } + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/appresult.AppSuccess" + } + }, + "400": { + "description": "Bad Request", + "schema": { + "$ref": "#/definitions/appresult.AppError" + } + }, + "401": { + "description": "Unauthorized", + "schema": { + "$ref": "#/definitions/appresult.AppError" + } + }, + "404": { + "description": "Not Found", + "schema": { + "$ref": "#/definitions/appresult.AppError" + } + } + } } }, "/provinces": { @@ -3282,7 +3822,7 @@ "BearerAuth": [] } ], - "description": "Returns all provinces", + "description": "Returns paginated provinces with optional filters", "produces": [ "application/json" ], @@ -3290,6 +3830,40 @@ "province" ], "summary": "List provinces", + "parameters": [ + { + "type": "string", + "description": "Filter by province name (en, ru, tm)", + "name": "name", + "in": "query" + }, + { + "type": "string", + "description": "Filter by region (en, ru, tm)", + "name": "region", + "in": "query" + }, + { + "type": "boolean", + "description": "Filter by active status", + "name": "active", + "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", @@ -3797,6 +4371,152 @@ } } }, + "/role-users": { + "get": { + "security": [ + { + "BearerAuth": [] + } + ], + "description": "Returns the authenticated user's role-user assignments with the related user and role", + "produces": [ + "application/json" + ], + "tags": [ + "role-users" + ], + "summary": "List role users", + "parameters": [ + { + "type": "string", + "description": "Filter by role name", + "name": "role_name", + "in": "query" + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/appresult.AppSuccess" + } + }, + "401": { + "description": "Unauthorized", + "schema": { + "$ref": "#/definitions/appresult.AppError" + } + }, + "500": { + "description": "Internal Server Error", + "schema": { + "$ref": "#/definitions/appresult.AppError" + } + } + } + }, + "post": { + "security": [ + { + "BearerAuth": [] + } + ], + "description": "Creates a role-user assignment", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "role-users" + ], + "summary": "Assign user to role", + "parameters": [ + { + "description": "Role-user payload", + "name": "body", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/roleusers.CreateRoleUserDTO" + } + } + ], + "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" + } + } + } + } + }, + "/role-users/{id}": { + "delete": { + "security": [ + { + "BearerAuth": [] + } + ], + "description": "Deletes a role-user assignment", + "produces": [ + "application/json" + ], + "tags": [ + "role-users" + ], + "summary": "Remove user from role", + "parameters": [ + { + "type": "integer", + "description": "Role-user 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" + } + } + } + } + }, "/roles": { "get": { "security": [ @@ -4223,6 +4943,78 @@ } } }, + "/users/role": { + "get": { + "security": [ + { + "BearerAuth": [] + } + ], + "description": "Returns paginated users filtered by role", + "produces": [ + "application/json" + ], + "tags": [ + "user" + ], + "summary": "List users by role", + "parameters": [ + { + "type": "string", + "description": "user role", + "name": "role", + "in": "query", + "required": true + }, + { + "type": "string", + "description": "Filter by username", + "name": "username", + "in": "query" + }, + { + "type": "integer", + "default": 1, + "description": "Page number", + "name": "page", + "in": "query" + }, + { + "type": "integer", + "default": 10, + "description": "Items per page", + "name": "limit", + "in": "query" + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/appresult.AppSuccess" + } + }, + "400": { + "description": "Bad Request", + "schema": { + "$ref": "#/definitions/appresult.AppError" + } + }, + "404": { + "description": "Not Found", + "schema": { + "$ref": "#/definitions/appresult.AppError" + } + }, + "500": { + "description": "Internal Server Error", + "schema": { + "$ref": "#/definitions/appresult.AppError" + } + } + } + } + }, "/users/{id}": { "get": { "security": [ @@ -4418,21 +5210,6 @@ } } }, - "auth.CreateBranchUserDTO": { - "type": "object", - "required": [ - "branchId", - "userId" - ], - "properties": { - "branchId": { - "type": "integer" - }, - "userId": { - "type": "integer" - } - } - }, "auth.LoginDTO": { "type": "object", "required": [ @@ -4459,6 +5236,29 @@ } } }, + "auth.UpdateProfileDTO": { + "type": "object", + "required": [ + "name" + ], + "properties": { + "avatar": { + "type": "string" + }, + "firstName": { + "type": "string" + }, + "lastName": { + "type": "string" + }, + "name": { + "type": "string" + }, + "phone": { + "type": "string" + } + } + }, "branches.CreateBranchDTO": { "type": "object", "required": [ @@ -4501,10 +5301,7 @@ "$ref": "#/definitions/branches.LocalizedText" }, "phoneNumbers": { - "type": "array", - "items": { - "type": "string" - } + "type": "string" }, "provinceId": { "type": "integer" @@ -4573,10 +5370,7 @@ "$ref": "#/definitions/branches.LocalizedText" }, "phoneNumbers": { - "type": "array", - "items": { - "type": "string" - } + "type": "string" }, "provinceId": { "type": "integer" @@ -4809,6 +5603,156 @@ } } }, + "cardpinorders.CreateCardPinOrderDTO": { + "type": "object", + "required": [ + "branchId", + "cardTypeId", + "customerName", + "customerSurname", + "passportFour", + "passportId", + "passportOne", + "passportSerie", + "passportThree", + "passportTwo", + "region" + ], + "properties": { + "bornAt": { + "type": "string" + }, + "branchId": { + "type": "integer" + }, + "cardNumber": { + "type": "string" + }, + "cardTypeId": { + "type": "integer" + }, + "customerName": { + "type": "string" + }, + "customerPatronicName": { + "type": "string" + }, + "customerSurname": { + "type": "string" + }, + "notes": { + "type": "string" + }, + "passportFour": { + "type": "string" + }, + "passportId": { + "type": "string" + }, + "passportOne": { + "type": "string" + }, + "passportSerie": { + "type": "string" + }, + "passportThree": { + "type": "string" + }, + "passportTwo": { + "type": "string" + }, + "phone": { + "type": "string" + }, + "region": { + "type": "string" + }, + "status": { + "type": "string" + }, + "uniqueId": { + "type": "string" + }, + "userId": { + "type": "integer" + } + } + }, + "cardpinorders.UpdateCardPinOrderDTO": { + "type": "object", + "required": [ + "branchId", + "cardTypeId", + "customerName", + "customerSurname", + "passportFour", + "passportId", + "passportOne", + "passportSerie", + "passportThree", + "passportTwo", + "region" + ], + "properties": { + "bornAt": { + "type": "string" + }, + "branchId": { + "type": "integer" + }, + "cardNumber": { + "type": "string" + }, + "cardTypeId": { + "type": "integer" + }, + "customerName": { + "type": "string" + }, + "customerPatronicName": { + "type": "string" + }, + "customerSurname": { + "type": "string" + }, + "notes": { + "type": "string" + }, + "passportFour": { + "type": "string" + }, + "passportId": { + "type": "string" + }, + "passportOne": { + "type": "string" + }, + "passportSerie": { + "type": "string" + }, + "passportThree": { + "type": "string" + }, + "passportTwo": { + "type": "string" + }, + "phone": { + "type": "string" + }, + "region": { + "type": "string" + }, + "status": { + "type": "string" + }, + "uniqueId": { + "type": "string" + }, + "userId": { + "type": "integer" + } + } + }, "cards.CreateCardDTO": { "type": "object", "required": [ @@ -5715,6 +6659,21 @@ } } }, + "permissionuser.CreatePermissionUserDTO": { + "type": "object", + "required": [ + "permissionId", + "userId" + ], + "properties": { + "permissionId": { + "type": "integer" + }, + "userId": { + "type": "integer" + } + } + }, "province.CreateProvinceDTO": { "type": "object", "required": [ @@ -5859,6 +6818,21 @@ } } }, + "roleusers.CreateRoleUserDTO": { + "type": "object", + "required": [ + "roleId", + "userId" + ], + "properties": { + "roleId": { + "type": "integer" + }, + "userId": { + "type": "integer" + } + } + }, "user.CreateUserDTO": { "type": "object", "required": [ @@ -5962,6 +6936,21 @@ "type": "string" } } + }, + "userbranch.CreateUserBranchDTO": { + "type": "object", + "required": [ + "branchId", + "userId" + ], + "properties": { + "branchId": { + "type": "integer" + }, + "userId": { + "type": "integer" + } + } } }, "securityDefinitions": { diff --git a/docs/swagger.yaml b/docs/swagger.yaml index ea48ae5..d7e9b9d 100644 --- a/docs/swagger.yaml +++ b/docs/swagger.yaml @@ -19,16 +19,6 @@ definitions: status: type: boolean type: object - auth.CreateBranchUserDTO: - properties: - branchId: - type: integer - userId: - type: integer - required: - - branchId - - userId - type: object auth.LoginDTO: properties: email: @@ -46,6 +36,21 @@ definitions: required: - refreshToken type: object + auth.UpdateProfileDTO: + properties: + avatar: + type: string + firstName: + type: string + lastName: + type: string + name: + type: string + phone: + type: string + required: + - name + type: object branches.CreateBranchDTO: properties: active: @@ -71,9 +76,7 @@ definitions: name: $ref: '#/definitions/branches.LocalizedText' phoneNumbers: - items: - type: string - type: array + type: string provinceId: type: integer region: @@ -119,9 +122,7 @@ definitions: name: $ref: '#/definitions/branches.LocalizedText' phoneNumbers: - items: - type: string - type: array + type: string provinceId: type: integer region: @@ -289,6 +290,112 @@ definitions: - passportTwo - region type: object + cardpinorders.CreateCardPinOrderDTO: + properties: + bornAt: + type: string + branchId: + type: integer + cardNumber: + type: string + cardTypeId: + type: integer + customerName: + type: string + customerPatronicName: + type: string + customerSurname: + type: string + notes: + type: string + passportFour: + type: string + passportId: + type: string + passportOne: + type: string + passportSerie: + type: string + passportThree: + type: string + passportTwo: + type: string + phone: + type: string + region: + type: string + status: + type: string + uniqueId: + type: string + userId: + type: integer + required: + - branchId + - cardTypeId + - customerName + - customerSurname + - passportFour + - passportId + - passportOne + - passportSerie + - passportThree + - passportTwo + - region + type: object + cardpinorders.UpdateCardPinOrderDTO: + properties: + bornAt: + type: string + branchId: + type: integer + cardNumber: + type: string + cardTypeId: + type: integer + customerName: + type: string + customerPatronicName: + type: string + customerSurname: + type: string + notes: + type: string + passportFour: + type: string + passportId: + type: string + passportOne: + type: string + passportSerie: + type: string + passportThree: + type: string + passportTwo: + type: string + phone: + type: string + region: + type: string + status: + type: string + uniqueId: + type: string + userId: + type: integer + required: + - branchId + - cardTypeId + - customerName + - customerSurname + - passportFour + - passportId + - passportOne + - passportSerie + - passportThree + - passportTwo + - region + type: object cards.CreateCardDTO: properties: month: @@ -911,6 +1018,16 @@ definitions: - guardName - name type: object + permissionuser.CreatePermissionUserDTO: + properties: + permissionId: + type: integer + userId: + type: integer + required: + - permissionId + - userId + type: object province.CreateProvinceDTO: properties: active: @@ -1007,6 +1124,16 @@ definitions: - guardName - name type: object + roleusers.CreateRoleUserDTO: + properties: + roleId: + type: integer + userId: + type: integer + required: + - roleId + - userId + type: object user.CreateUserDTO: properties: active: @@ -1077,6 +1204,16 @@ definitions: - name - username type: object + userbranch.CreateUserBranchDTO: + properties: + branchId: + type: integer + userId: + type: integer + required: + - branchId + - userId + type: object host: localhost:5050 info: contact: {} @@ -1085,6 +1222,34 @@ info: version: "1.0" paths: /branch-users: + get: + description: Returns the authenticated user's branch-user assignments with the + related user and branch + parameters: + - description: Filter by branch name (en, ru, tm) + in: query + name: branch_name + type: string + produces: + - application/json + responses: + "200": + description: OK + schema: + $ref: '#/definitions/appresult.AppSuccess' + "401": + description: Unauthorized + schema: + $ref: '#/definitions/appresult.AppError' + "500": + description: Internal Server Error + schema: + $ref: '#/definitions/appresult.AppError' + security: + - BearerAuth: [] + summary: List branch users + tags: + - branch-users post: consumes: - application/json @@ -1095,7 +1260,7 @@ paths: name: body required: true schema: - $ref: '#/definitions/auth.CreateBranchUserDTO' + $ref: '#/definitions/userbranch.CreateUserBranchDTO' produces: - application/json responses: @@ -1115,7 +1280,7 @@ paths: - BearerAuth: [] summary: Assign user to branch tags: - - auth + - branch-users /branch-users/{id}: delete: description: Deletes a branch-user assignment @@ -1148,7 +1313,7 @@ paths: - BearerAuth: [] summary: Remove user from branch tags: - - auth + - branch-users /branches: get: description: Returns paginated branches with optional filters @@ -1529,6 +1694,196 @@ paths: summary: Update card order tags: - card-orders + /card-pin-orders: + get: + description: Returns paginated card pin 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 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 pin orders + tags: + - card-pin-orders + post: + consumes: + - application/json + description: Creates a new card pin order + parameters: + - description: Card pin order payload + in: body + name: body + required: true + schema: + $ref: '#/definitions/cardpinorders.CreateCardPinOrderDTO' + 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 pin order + tags: + - card-pin-orders + /card-pin-orders/{id}: + delete: + description: Deletes a card pin order + parameters: + - description: Card pin 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 pin order + tags: + - card-pin-orders + get: + description: Returns a single card pin order + parameters: + - description: Card pin 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 pin order by ID + tags: + - card-pin-orders + put: + consumes: + - application/json + description: Updates an existing card pin order + parameters: + - description: Card pin order ID + in: path + name: id + required: true + type: integer + - description: Card pin order payload + in: body + name: body + required: true + schema: + $ref: '#/definitions/cardpinorders.UpdateCardPinOrderDTO' + 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 pin order + tags: + - card-pin-orders /cards: get: description: Returns paginated cards with optional filters @@ -2972,6 +3327,99 @@ paths: summary: Update payment card active tags: - payment-card + /permission-users: + get: + description: Returns the authenticated user's permission-user assignments with + the related user and permission + parameters: + - description: Filter by permission name + in: query + name: permission_name + type: string + produces: + - application/json + responses: + "200": + description: OK + schema: + $ref: '#/definitions/appresult.AppSuccess' + "401": + description: Unauthorized + schema: + $ref: '#/definitions/appresult.AppError' + "500": + description: Internal Server Error + schema: + $ref: '#/definitions/appresult.AppError' + security: + - BearerAuth: [] + summary: List permission users + tags: + - permission-users + post: + consumes: + - application/json + description: Creates a permission-user assignment + parameters: + - description: Permission-user payload + in: body + name: body + required: true + schema: + $ref: '#/definitions/permissionuser.CreatePermissionUserDTO' + 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: Assign user to permission + tags: + - permission-users + /permission-users/{id}: + delete: + description: Deletes a permission-user assignment + parameters: + - description: Permission-user 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: Remove user from permission + tags: + - permission-users /permissions: get: description: Returns paginated permissions with optional filters @@ -3173,9 +3621,67 @@ paths: summary: Get profile tags: - auth + put: + consumes: + - application/json + description: Updates the authenticated user's profile + parameters: + - description: Profile payload + in: body + name: body + required: true + schema: + $ref: '#/definitions/auth.UpdateProfileDTO' + produces: + - application/json + responses: + "200": + description: OK + schema: + $ref: '#/definitions/appresult.AppSuccess' + "400": + description: Bad Request + schema: + $ref: '#/definitions/appresult.AppError' + "401": + description: Unauthorized + schema: + $ref: '#/definitions/appresult.AppError' + "404": + description: Not Found + schema: + $ref: '#/definitions/appresult.AppError' + security: + - BearerAuth: [] + summary: Update profile + tags: + - auth /provinces: get: - description: Returns all provinces + description: Returns paginated provinces with optional filters + parameters: + - description: Filter by province name (en, ru, tm) + in: query + name: name + type: string + - description: Filter by region (en, ru, tm) + in: query + name: region + type: string + - description: Filter by active status + in: query + name: active + type: boolean + - 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: @@ -3506,6 +4012,99 @@ paths: summary: Update reason card tags: - reason-card + /role-users: + get: + description: Returns the authenticated user's role-user assignments with the + related user and role + parameters: + - description: Filter by role name + in: query + name: role_name + type: string + produces: + - application/json + responses: + "200": + description: OK + schema: + $ref: '#/definitions/appresult.AppSuccess' + "401": + description: Unauthorized + schema: + $ref: '#/definitions/appresult.AppError' + "500": + description: Internal Server Error + schema: + $ref: '#/definitions/appresult.AppError' + security: + - BearerAuth: [] + summary: List role users + tags: + - role-users + post: + consumes: + - application/json + description: Creates a role-user assignment + parameters: + - description: Role-user payload + in: body + name: body + required: true + schema: + $ref: '#/definitions/roleusers.CreateRoleUserDTO' + 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: Assign user to role + tags: + - role-users + /role-users/{id}: + delete: + description: Deletes a role-user assignment + parameters: + - description: Role-user 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: Remove user from role + tags: + - role-users /roles: get: description: Returns paginated roles with optional filters @@ -3884,6 +4483,53 @@ paths: summary: Update user tags: - user + /users/role: + get: + description: Returns paginated users filtered by role + parameters: + - description: user role + in: query + name: role + required: true + type: string + - description: Filter by username + in: query + name: username + type: string + - default: 1 + description: Page number + in: query + name: page + type: integer + - default: 10 + description: Items per page + in: query + name: limit + type: integer + produces: + - application/json + responses: + "200": + description: OK + schema: + $ref: '#/definitions/appresult.AppSuccess' + "400": + description: Bad Request + schema: + $ref: '#/definitions/appresult.AppError' + "404": + description: Not Found + schema: + $ref: '#/definitions/appresult.AppError' + "500": + description: Internal Server Error + schema: + $ref: '#/definitions/appresult.AppError' + security: + - BearerAuth: [] + summary: List users by role + tags: + - user securityDefinitions: BearerAuth: in: header diff --git a/docs/tag_order.go b/docs/tag_order.go index e164b49..a3fda2e 100644 --- a/docs/tag_order.go +++ b/docs/tag_order.go @@ -10,11 +10,27 @@ var swaggerTagOrder = []struct { {Name: "auth", Description: "Authentication"}, {Name: "province", Description: "Provinces"}, {Name: "branches", Description: "Branches"}, + {Name: "branch-users", Description: "Branch users"}, + {Name: "user", Description: "Users"}, + {Name: "role", Description: "Roles"}, + {Name: "role-users", Description: "Role users"}, + {Name: "permission", Description: "Permissions"}, + {Name: "permission-users", Description: "Permission users"}, {Name: "payment-card", Description: "Payment cards"}, {Name: "reason-card", Description: "Reason cards"}, + {Name: "cards", Description: "Cards"}, + {Name: "card-orders", Description: "Card orders"}, + {Name: "card-pin-orders", Description: "Card pin orders"}, {Name: "loan-type", Description: "Loan types"}, {Name: "loan-document", Description: "Loan required documents"}, + {Name: "loan-orders", Description: "Loan orders"}, {Name: "loans-repayment", Description: "Loan repayments"}, + {Name: "loan-paid-off-letters", Description: "Loan paid-off letters"}, + {Name: "file-upload", Description: "File upload"}, +} + +func init() { + applySwaggerTagOrder() } func applySwaggerTagOrder() { diff --git a/internal/admin/.DS_Store b/internal/admin/.DS_Store deleted file mode 100644 index 2c51ae6..0000000 Binary files a/internal/admin/.DS_Store and /dev/null differ diff --git a/internal/admin/user/handler.go b/internal/admin/user/handler.go deleted file mode 100644 index f8687ec..0000000 --- a/internal/admin/user/handler.go +++ /dev/null @@ -1,242 +0,0 @@ -package user - -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 = "/users" - -type handler struct { - logger *logging.Logger - repository Repository -} - -func NewHandler(logger *logging.Logger, repository Repository) handlers.Handler { - return &handler{logger: logger, repository: repository} -} - -func (h *handler) Register(router *gin.RouterGroup) { - group := router.Group(baseURL, appresult.JwtTokenCheck()) - group.GET("", h.list) - group.GET("/:id", h.getByID) - group.POST("", h.create) - group.PUT("/:id", h.update) - group.DELETE("/:id", h.delete) -} - -// list godoc -// @Summary List users -// @Description Returns paginated users with optional filters -// @Tags user -// @Produce json -// @Security BearerAuth -// @Param username query string false "Filter by username" -// @Param page query int false "Page number" default(1) -// @Param limit query int false "Items per page" default(10) -// @Success 200 {object} appresult.AppSuccess -// @Failure 400 {object} appresult.AppError -// @Failure 500 {object} appresult.AppError -// @Router /users [get] -func (h *handler) list(c *gin.Context) { - filter, ok := parseListFilter(c) - if !ok { - c.JSON(http.StatusBadRequest, appresult.ErrMissingParam) - return - } - - result, err := h.repository.List(c.Request.Context(), filter) - if err != nil { - h.logger.Errorf("list users failed: %v", err) - c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer) - return - } - - c.JSON(http.StatusOK, appresult.SuccessWithData(result)) -} - -// getByID godoc -// @Summary Get user by ID -// @Description Returns a single user -// @Tags user -// @Produce json -// @Security BearerAuth -// @Param id path int true "User ID" -// @Success 200 {object} appresult.AppSuccess -// @Failure 400 {object} appresult.AppError -// @Failure 404 {object} appresult.AppError -// @Failure 500 {object} appresult.AppError -// @Router /users/{id} [get] -func (h *handler) getByID(c *gin.Context) { - id, ok := parseID(c.Param("id")) - if !ok { - c.JSON(http.StatusBadRequest, appresult.ErrMissingParam) - return - } - - item, err := h.repository.GetByID(c.Request.Context(), id) - if errors.Is(err, pgx.ErrNoRows) { - c.JSON(http.StatusNotFound, appresult.ErrNotFound) - return - } - if err != nil { - h.logger.Errorf("get user failed: %v", err) - c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer) - return - } - - c.JSON(http.StatusOK, appresult.SuccessWithData(item)) -} - -// create godoc -// @Summary Create user -// @Description Creates a new user -// @Tags user -// @Accept json -// @Produce json -// @Security BearerAuth -// @Param body body CreateUserDTO true "User payload" -// @Success 201 {object} appresult.AppSuccess -// @Failure 400 {object} appresult.AppError -// @Failure 500 {object} appresult.AppError -// @Router /users [post] -func (h *handler) create(c *gin.Context) { - var dto CreateUserDTO - if err := c.ShouldBindJSON(&dto); err != nil { - c.JSON(http.StatusBadRequest, appresult.ErrMissingParam) - return - } - - item, err := h.repository.Create(c.Request.Context(), dto) - if err != nil { - h.logger.Errorf("create user failed: %v", err) - c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer) - return - } - - c.JSON(http.StatusCreated, appresult.SuccessWithData(item)) -} - -// update godoc -// @Summary Update user -// @Description Updates an existing user -// @Tags user -// @Accept json -// @Produce json -// @Security BearerAuth -// @Param id path int true "User ID" -// @Param body body UpdateUserDTO true "User payload" -// @Success 200 {object} appresult.AppSuccess -// @Failure 400 {object} appresult.AppError -// @Failure 404 {object} appresult.AppError -// @Failure 500 {object} appresult.AppError -// @Router /users/{id} [put] -func (h *handler) update(c *gin.Context) { - id, ok := parseID(c.Param("id")) - if !ok { - c.JSON(http.StatusBadRequest, appresult.ErrMissingParam) - return - } - - var dto UpdateUserDTO - if err := c.ShouldBindJSON(&dto); err != nil { - c.JSON(http.StatusBadRequest, appresult.ErrMissingParam) - return - } - - item, err := h.repository.Update(c.Request.Context(), id, dto) - if errors.Is(err, pgx.ErrNoRows) { - c.JSON(http.StatusNotFound, appresult.ErrNotFound) - return - } - if err != nil { - h.logger.Errorf("update user failed: %v", err) - c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer) - return - } - - c.JSON(http.StatusOK, appresult.SuccessWithData(item)) -} - -// delete godoc -// @Summary Delete user -// @Description Deletes a user -// @Tags user -// @Produce json -// @Security BearerAuth -// @Param id path int true "User ID" -// @Success 200 {object} appresult.AppSuccess -// @Failure 400 {object} appresult.AppError -// @Failure 404 {object} appresult.AppError -// @Failure 500 {object} appresult.AppError -// @Router /users/{id} [delete] -func (h *handler) delete(c *gin.Context) { - id, ok := parseID(c.Param("id")) - if !ok { - c.JSON(http.StatusBadRequest, appresult.ErrMissingParam) - return - } - - if err := h.repository.Delete(c.Request.Context(), id); errors.Is(err, pgx.ErrNoRows) { - c.JSON(http.StatusNotFound, appresult.ErrNotFound) - return - } else if err != nil { - h.logger.Errorf("delete user failed: %v", err) - c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer) - return - } - - c.JSON(http.StatusOK, appresult.SuccessWithData("user removed")) -} - -func parseID(raw string) (int64, bool) { - id, err := strconv.ParseInt(raw, 10, 64) - if err != nil || id <= 0 { - return 0, false - } - return id, true -} - -const ( - defaultPage = 1 - defaultLimit = 10 - maxLimit = 100 -) - -func parseListFilter(c *gin.Context) (ListFilter, bool) { - filter := ListFilter{ - Page: defaultPage, - Limit: defaultLimit, - } - - if raw := c.Query("page"); raw != "" { - page, err := strconv.Atoi(raw) - if err != nil || page < 1 { - return ListFilter{}, false - } - filter.Page = page - } - - if raw := c.Query("limit"); raw != "" { - limit, err := strconv.Atoi(raw) - if err != nil || limit < 1 || limit > maxLimit { - return ListFilter{}, false - } - filter.Limit = limit - } - - if raw := strings.TrimSpace(c.Query("username")); raw != "" { - filter.Username = raw - } - - return filter, true -} diff --git a/internal/admin/cardorder/db/postgresql.go b/internal/cards/cardorder/db/postgresql.go similarity index 79% rename from internal/admin/cardorder/db/postgresql.go rename to internal/cards/cardorder/db/postgresql.go index 0a9fa35..6c4f2d3 100644 --- a/internal/admin/cardorder/db/postgresql.go +++ b/internal/cards/cardorder/db/postgresql.go @@ -5,20 +5,24 @@ import ( "fmt" "strings" - "online-back/internal/admin/cardorder" + "online-back/internal/cards/cardorder" "online-back/pkg/client/postgresql" "online-back/pkg/logging" - - "github.com/jackc/pgx/v4" + "online-back/pkg/repository/genericrepo" ) type repository struct { - client postgresql.Client - logger *logging.Logger + client postgresql.Client + generic *genericrepo.Repository[cardorder.CardOrderDTO] + logger *logging.Logger } func NewRepository(client postgresql.Client, logger *logging.Logger) cardorder.Repository { - return &repository{client: client, logger: logger} + return &repository{ + client: client, + generic: genericrepo.New(client, "card_orders", cardOrderColumnsSQL, scanCardOrder), + logger: logger, + } } // cardOrderWritableColumns lists every card_orders column except id, created_at and @@ -75,37 +79,10 @@ func updateArgs(dto cardorder.UpdateCardOrderDTO) []interface{} { 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)...) + items, count, err := r.generic.List(ctx, whereClause, args, filter.Page, filter.Limit, "id") 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 } @@ -151,12 +128,7 @@ func buildListQuery(filter cardorder.ListFilter) (whereClause string, args []int } 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 + return r.generic.GetByID(ctx, id) } func (r *repository) Create(ctx context.Context, dto cardorder.CreateCardOrderDTO) (cardorder.CardOrderDTO, error) { @@ -197,21 +169,10 @@ func (r *repository) Update(ctx context.Context, id int64, dto cardorder.UpdateC } 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 + return r.generic.Delete(ctx, id) } -type scannable interface { - Scan(dest ...interface{}) error -} - -func scanCardOrder(row scannable) (cardorder.CardOrderDTO, error) { +func scanCardOrder(row genericrepo.Scanner) (cardorder.CardOrderDTO, error) { var item cardorder.CardOrderDTO err := row.Scan( &item.Id, &item.UniqueId, &item.CardStateId, &item.CardTypeId, &item.Region, &item.BranchId, diff --git a/internal/admin/cardorder/dto.go b/internal/cards/cardorder/dto.go similarity index 100% rename from internal/admin/cardorder/dto.go rename to internal/cards/cardorder/dto.go diff --git a/internal/admin/cardorder/handler.go b/internal/cards/cardorder/handler.go similarity index 100% rename from internal/admin/cardorder/handler.go rename to internal/cards/cardorder/handler.go diff --git a/internal/admin/cardorder/storage.go b/internal/cards/cardorder/storage.go similarity index 100% rename from internal/admin/cardorder/storage.go rename to internal/cards/cardorder/storage.go diff --git a/internal/admin/cardpinorders/db/postgresql.go b/internal/cards/cardpinorders/db/postgresql.go similarity index 75% rename from internal/admin/cardpinorders/db/postgresql.go rename to internal/cards/cardpinorders/db/postgresql.go index 66c591f..c983dfb 100644 --- a/internal/admin/cardpinorders/db/postgresql.go +++ b/internal/cards/cardpinorders/db/postgresql.go @@ -5,20 +5,24 @@ import ( "fmt" "strings" - "online-back/internal/admin/cardpinorders" + "online-back/internal/cards/cardpinorders" "online-back/pkg/client/postgresql" "online-back/pkg/logging" - - "github.com/jackc/pgx/v4" + "online-back/pkg/repository/genericrepo" ) type repository struct { - client postgresql.Client - logger *logging.Logger + client postgresql.Client + generic *genericrepo.Repository[cardpinorders.CardPinOrderDTO] + logger *logging.Logger } func NewRepository(client postgresql.Client, logger *logging.Logger) cardpinorders.Repository { - return &repository{client: client, logger: logger} + return &repository{ + client: client, + generic: genericrepo.New(client, "card_pin_orders", cardPinOrderColumnsSQL, scanCardPinOrder), + logger: logger, + } } // cardPinOrderWritableColumns lists every card_pin_orders column except id, created_at and @@ -57,37 +61,10 @@ func updateArgs(dto cardpinorders.UpdateCardPinOrderDTO) []interface{} { 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)...) + items, count, err := r.generic.List(ctx, whereClause, args, filter.Page, filter.Limit, "id") 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 } @@ -128,12 +105,7 @@ func buildListQuery(filter cardpinorders.ListFilter) (whereClause string, 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 + return r.generic.GetByID(ctx, id) } func (r *repository) Create(ctx context.Context, dto cardpinorders.CreateCardPinOrderDTO) (cardpinorders.CardPinOrderDTO, error) { @@ -174,21 +146,10 @@ func (r *repository) Update(ctx context.Context, id int64, dto cardpinorders.Upd } 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 + return r.generic.Delete(ctx, id) } -type scannable interface { - Scan(dest ...interface{}) error -} - -func scanCardPinOrder(row scannable) (cardpinorders.CardPinOrderDTO, error) { +func scanCardPinOrder(row genericrepo.Scanner) (cardpinorders.CardPinOrderDTO, error) { var item cardpinorders.CardPinOrderDTO err := row.Scan( &item.Id, &item.UniqueId, &item.UserId, &item.CardTypeId, &item.CardNumber, &item.Region, &item.BranchId, diff --git a/internal/admin/cardpinorders/dto.go b/internal/cards/cardpinorders/dto.go similarity index 100% rename from internal/admin/cardpinorders/dto.go rename to internal/cards/cardpinorders/dto.go diff --git a/internal/admin/cardpinorders/handler.go b/internal/cards/cardpinorders/handler.go similarity index 100% rename from internal/admin/cardpinorders/handler.go rename to internal/cards/cardpinorders/handler.go diff --git a/internal/admin/cardpinorders/storage.go b/internal/cards/cardpinorders/storage.go similarity index 100% rename from internal/admin/cardpinorders/storage.go rename to internal/cards/cardpinorders/storage.go diff --git a/internal/admin/cards/db/postgresql.go b/internal/cards/cards/db/postgresql.go similarity index 69% rename from internal/admin/cards/db/postgresql.go rename to internal/cards/cards/db/postgresql.go index e602798..a28f4c6 100644 --- a/internal/admin/cards/db/postgresql.go +++ b/internal/cards/cards/db/postgresql.go @@ -5,20 +5,24 @@ import ( "fmt" "strings" - "online-back/internal/admin/cards" + "online-back/internal/cards/cards" "online-back/pkg/client/postgresql" "online-back/pkg/logging" - - "github.com/jackc/pgx/v4" + "online-back/pkg/repository/genericrepo" ) type repository struct { - client postgresql.Client - logger *logging.Logger + client postgresql.Client + generic *genericrepo.Repository[cards.CardDTO] + logger *logging.Logger } func NewRepository(client postgresql.Client, logger *logging.Logger) cards.Repository { - return &repository{client: client, logger: logger} + return &repository{ + client: client, + generic: genericrepo.New(client, "cards", cardColumnsSQL, scanCard), + logger: logger, + } } // cardWritableColumns lists every cards column except id, created_at and @@ -48,37 +52,10 @@ func updateArgs(dto cards.UpdateCardDTO) []interface{} { 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)...) + items, count, err := r.generic.List(ctx, whereClause, args, filter.Page, filter.Limit, "id") 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 } @@ -104,12 +81,7 @@ func buildListQuery(filter cards.ListFilter) (whereClause string, args []interfa } 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 + return r.generic.GetByID(ctx, id) } func (r *repository) Create(ctx context.Context, dto cards.CreateCardDTO) (cards.CardDTO, error) { @@ -150,21 +122,10 @@ func (r *repository) Update(ctx context.Context, id int64, dto cards.UpdateCardD } 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 + return r.generic.Delete(ctx, id) } -type scannable interface { - Scan(dest ...interface{}) error -} - -func scanCard(row scannable) (cards.CardDTO, error) { +func scanCard(row genericrepo.Scanner) (cards.CardDTO, error) { var item cards.CardDTO err := row.Scan( &item.Id, &item.UserId, &item.Number, &item.Name, &item.Month, &item.Year, &item.Type, diff --git a/internal/admin/cards/dto.go b/internal/cards/cards/dto.go similarity index 100% rename from internal/admin/cards/dto.go rename to internal/cards/cards/dto.go diff --git a/internal/admin/cards/handler.go b/internal/cards/cards/handler.go similarity index 100% rename from internal/admin/cards/handler.go rename to internal/cards/cards/handler.go diff --git a/internal/admin/cards/storage.go b/internal/cards/cards/storage.go similarity index 100% rename from internal/admin/cards/storage.go rename to internal/cards/cards/storage.go diff --git a/internal/admin/paymentcard/db/postgresql.go b/internal/cards/paymentcard/db/postgresql.go similarity index 65% rename from internal/admin/paymentcard/db/postgresql.go rename to internal/cards/paymentcard/db/postgresql.go index 482c098..7771152 100644 --- a/internal/admin/paymentcard/db/postgresql.go +++ b/internal/cards/paymentcard/db/postgresql.go @@ -7,20 +7,26 @@ import ( "fmt" "strings" - "online-back/internal/admin/paymentcard" + "online-back/internal/cards/paymentcard" "online-back/pkg/client/postgresql" "online-back/pkg/logging" + "online-back/pkg/repository/genericrepo" "github.com/jackc/pgx/v4" ) type repository struct { - client postgresql.Client - logger *logging.Logger + client postgresql.Client + generic *genericrepo.Repository[paymentcard.PaymentCardDTO] + logger *logging.Logger } func NewRepository(client postgresql.Client, logger *logging.Logger) paymentcard.Repository { - return &repository{client: client, logger: logger} + return &repository{ + client: client, + generic: genericrepo.New(client, "card_types c", cardColumns, scanPaymentCard), + logger: logger, + } } const cardColumns = `c.id, c.price, c.name, c.notes, c.active` @@ -28,45 +34,17 @@ const cardColumns = `c.id, c.price, c.name, c.notes, c.active` const cardReturningColumns = `id, price, name, notes, active` func (r *repository) List(ctx context.Context, filter paymentcard.ListFilter) (paymentcard.ListPaymentCardDTO, error) { - fromClause, whereClause, args := buildListQuery(filter) + whereClause, args := buildListQuery(filter) - var count int64 - if err := r.client.QueryRow(ctx, `SELECT COUNT(*) `+fromClause+whereClause, args...).Scan(&count); err != nil { - return paymentcard.ListPaymentCardDTO{}, err - } - - offset := (filter.Page - 1) * filter.Limit - limitPlaceholder := len(args) + 1 - offsetPlaceholder := len(args) + 2 - listQuery := fmt.Sprintf( - `SELECT %s%s%s ORDER BY c.id LIMIT $%d OFFSET $%d`, - cardColumns, fromClause, whereClause, limitPlaceholder, offsetPlaceholder, - ) - - rows, err := r.client.Query(ctx, listQuery, append(args, filter.Limit, offset)...) + items, count, err := r.generic.List(ctx, whereClause, args, filter.Page, filter.Limit, "id") if err != nil { return paymentcard.ListPaymentCardDTO{}, err } - defer rows.Close() - - var items []paymentcard.PaymentCardDTO - for rows.Next() { - item, err := scanPaymentCard(rows) - if err != nil { - return paymentcard.ListPaymentCardDTO{}, err - } - items = append(items, item) - } - if err := rows.Err(); err != nil { - return paymentcard.ListPaymentCardDTO{}, err - } return paymentcard.ListPaymentCardDTO{Count: count, PaymentCards: items}, nil } -func buildListQuery(filter paymentcard.ListFilter) (fromClause, whereClause string, args []interface{}) { - fromClause = ` FROM card_types c` - +func buildListQuery(filter paymentcard.ListFilter) (whereClause string, args []interface{}) { var conditions []string if filter.CardName != "" { @@ -83,10 +61,10 @@ func buildListQuery(filter paymentcard.ListFilter) (fromClause, whereClause stri } if len(conditions) == 0 { - return fromClause, "", args + return "", args } - return fromClause, " WHERE " + strings.Join(conditions, " AND "), args + return " WHERE " + strings.Join(conditions, " AND "), args } func likePattern(term string) string { @@ -97,12 +75,7 @@ func likePattern(term string) string { } func (r *repository) GetByID(ctx context.Context, id int64) (paymentcard.PaymentCardDTO, error) { - query := fmt.Sprintf(`SELECT %s FROM card_types c WHERE c.id = $1`, cardColumns) - item, err := scanPaymentCard(r.client.QueryRow(ctx, query, id)) - if errors.Is(err, pgx.ErrNoRows) { - return paymentcard.PaymentCardDTO{}, err - } - return item, err + return r.generic.GetByID(ctx, id) } func (r *repository) Create(ctx context.Context, dto paymentcard.CreatePaymentCardDTO) (paymentcard.PaymentCardDTO, error) { @@ -157,25 +130,14 @@ func (r *repository) UpdateActive(ctx context.Context, id int64, active bool) (p } func (r *repository) Delete(ctx context.Context, id int64) error { - tag, err := r.client.Exec(ctx, `DELETE FROM card_types WHERE id = $1`, id) - if err != nil { - return err - } - if tag.RowsAffected() == 0 { - return pgx.ErrNoRows - } - return nil + return r.generic.Delete(ctx, id) } func marshalName(title paymentcard.LocalizedText) ([]byte, error) { return json.Marshal(title) } -type scannable interface { - Scan(dest ...interface{}) error -} - -func scanPaymentCard(row scannable) (paymentcard.PaymentCardDTO, error) { +func scanPaymentCard(row genericrepo.Scanner) (paymentcard.PaymentCardDTO, error) { var item paymentcard.PaymentCardDTO var nameJSON []byte diff --git a/internal/admin/paymentcard/dto.go b/internal/cards/paymentcard/dto.go similarity index 100% rename from internal/admin/paymentcard/dto.go rename to internal/cards/paymentcard/dto.go diff --git a/internal/admin/paymentcard/handler.go b/internal/cards/paymentcard/handler.go similarity index 100% rename from internal/admin/paymentcard/handler.go rename to internal/cards/paymentcard/handler.go diff --git a/internal/admin/paymentcard/storage.go b/internal/cards/paymentcard/storage.go similarity index 100% rename from internal/admin/paymentcard/storage.go rename to internal/cards/paymentcard/storage.go diff --git a/internal/admin/reasonscard/db/postgresql.go b/internal/cards/reasonscard/db/postgresql.go similarity index 63% rename from internal/admin/reasonscard/db/postgresql.go rename to internal/cards/reasonscard/db/postgresql.go index f4b962a..a7b7afa 100644 --- a/internal/admin/reasonscard/db/postgresql.go +++ b/internal/cards/reasonscard/db/postgresql.go @@ -7,20 +7,26 @@ import ( "fmt" "strings" - "online-back/internal/admin/reasonscard" + "online-back/internal/cards/reasonscard" "online-back/pkg/client/postgresql" "online-back/pkg/logging" + "online-back/pkg/repository/genericrepo" "github.com/jackc/pgx/v4" ) type repository struct { - client postgresql.Client - logger *logging.Logger + client postgresql.Client + generic *genericrepo.Repository[reasonscard.ReasonCardDTO] + logger *logging.Logger } func NewRepository(client postgresql.Client, logger *logging.Logger) reasonscard.Repository { - return &repository{client: client, logger: logger} + return &repository{ + client: client, + generic: genericrepo.New(client, "card_states r", reasonColumns, scanReasonCard), + logger: logger, + } } const reasonColumns = `r.id, r.price, r.name, r.notes, r.active, r.created_at, r.updated_at` @@ -28,45 +34,17 @@ const reasonColumns = `r.id, r.price, r.name, r.notes, r.active, r.created_at, r const reasonReturningColumns = `id, price, name, notes, active, created_at, updated_at` func (r *repository) List(ctx context.Context, filter reasonscard.ListFilter) (reasonscard.ListReasonCardDTO, error) { - fromClause, whereClause, args := buildListQuery(filter) + whereClause, args := buildListQuery(filter) - var count int64 - if err := r.client.QueryRow(ctx, `SELECT COUNT(*) `+fromClause+whereClause, args...).Scan(&count); err != nil { - return reasonscard.ListReasonCardDTO{}, err - } - - offset := (filter.Page - 1) * filter.Limit - limitPlaceholder := len(args) + 1 - offsetPlaceholder := len(args) + 2 - listQuery := fmt.Sprintf( - `SELECT %s%s%s ORDER BY r.id LIMIT $%d OFFSET $%d`, - reasonColumns, fromClause, whereClause, limitPlaceholder, offsetPlaceholder, - ) - - rows, err := r.client.Query(ctx, listQuery, append(args, filter.Limit, offset)...) + items, count, err := r.generic.List(ctx, whereClause, args, filter.Page, filter.Limit, "id") if err != nil { return reasonscard.ListReasonCardDTO{}, err } - defer rows.Close() - - var items []reasonscard.ReasonCardDTO - for rows.Next() { - item, err := scanReasonCard(rows) - if err != nil { - return reasonscard.ListReasonCardDTO{}, err - } - items = append(items, item) - } - if err := rows.Err(); err != nil { - return reasonscard.ListReasonCardDTO{}, err - } return reasonscard.ListReasonCardDTO{Count: count, ReasonCards: items}, nil } -func buildListQuery(filter reasonscard.ListFilter) (fromClause, whereClause string, args []interface{}) { - fromClause = ` FROM card_states r` - +func buildListQuery(filter reasonscard.ListFilter) (whereClause string, args []interface{}) { var conditions []string if filter.ReasonName != "" { args = append(args, likePattern(filter.ReasonName)) @@ -77,10 +55,10 @@ func buildListQuery(filter reasonscard.ListFilter) (fromClause, whereClause stri } if len(conditions) == 0 { - return fromClause, "", args + return "", args } - return fromClause, " WHERE " + strings.Join(conditions, " AND "), args + return " WHERE " + strings.Join(conditions, " AND "), args } func likePattern(term string) string { @@ -91,12 +69,7 @@ func likePattern(term string) string { } func (r *repository) GetByID(ctx context.Context, id int64) (reasonscard.ReasonCardDTO, error) { - query := fmt.Sprintf(`SELECT %s FROM card_states r WHERE r.id = $1`, reasonColumns) - item, err := scanReasonCard(r.client.QueryRow(ctx, query, id)) - if errors.Is(err, pgx.ErrNoRows) { - return reasonscard.ReasonCardDTO{}, err - } - return item, err + return r.generic.GetByID(ctx, id) } func (r *repository) Create(ctx context.Context, dto reasonscard.CreateReasonCardDTO) (reasonscard.ReasonCardDTO, error) { @@ -139,25 +112,14 @@ func (r *repository) Update(ctx context.Context, id int64, dto reasonscard.Updat } func (r *repository) Delete(ctx context.Context, id int64) error { - tag, err := r.client.Exec(ctx, `DELETE FROM card_states WHERE id = $1`, id) - if err != nil { - return err - } - if tag.RowsAffected() == 0 { - return pgx.ErrNoRows - } - return nil + return r.generic.Delete(ctx, id) } func marshalName(title reasonscard.LocalizedText) ([]byte, error) { return json.Marshal(title) } -type scannable interface { - Scan(dest ...interface{}) error -} - -func scanReasonCard(row scannable) (reasonscard.ReasonCardDTO, error) { +func scanReasonCard(row genericrepo.Scanner) (reasonscard.ReasonCardDTO, error) { var item reasonscard.ReasonCardDTO var nameJSON []byte diff --git a/internal/admin/reasonscard/dto.go b/internal/cards/reasonscard/dto.go similarity index 100% rename from internal/admin/reasonscard/dto.go rename to internal/cards/reasonscard/dto.go diff --git a/internal/admin/reasonscard/handler.go b/internal/cards/reasonscard/handler.go similarity index 100% rename from internal/admin/reasonscard/handler.go rename to internal/cards/reasonscard/handler.go diff --git a/internal/admin/reasonscard/storage.go b/internal/cards/reasonscard/storage.go similarity index 100% rename from internal/admin/reasonscard/storage.go rename to internal/cards/reasonscard/storage.go diff --git a/internal/cards/router.go b/internal/cards/router.go new file mode 100644 index 0000000..e703563 --- /dev/null +++ b/internal/cards/router.go @@ -0,0 +1,39 @@ +// Package cards groups payment cards, card orders, PIN orders, and their +// reference data (reasons, payment card types) under one bounded context, +// replacing the flat internal/admin/* listing. +package cards + +import ( + "online-back/internal/cards/cardorder" + cardorderdb "online-back/internal/cards/cardorder/db" + "online-back/internal/cards/cardpinorders" + cardpinordersdb "online-back/internal/cards/cardpinorders/db" + cardentity "online-back/internal/cards/cards" + cardentitydb "online-back/internal/cards/cards/db" + "online-back/internal/cards/paymentcard" + paymentcarddb "online-back/internal/cards/paymentcard/db" + "online-back/internal/cards/reasonscard" + reasonscarddb "online-back/internal/cards/reasonscard/db" + "online-back/internal/handlers" + "online-back/pkg/client/postgresql" + "online-back/pkg/logging" + + "github.com/gin-gonic/gin" +) + +// Register wires every cards module's handler onto router. +func Register(router *gin.RouterGroup, client postgresql.Client, logger *logging.Logger) { + for _, h := range Handlers(client, logger) { + h.Register(router) + } +} + +func Handlers(client postgresql.Client, logger *logging.Logger) []handlers.Handler { + return []handlers.Handler{ + cardentity.NewHandler(logger, cardentitydb.NewRepository(client, logger)), + cardorder.NewHandler(logger, cardorderdb.NewRepository(client, logger)), + cardpinorders.NewHandler(logger, cardpinordersdb.NewRepository(client, logger)), + paymentcard.NewHandler(logger, paymentcarddb.NewRepository(client, logger)), + reasonscard.NewHandler(logger, reasonscarddb.NewRepository(client, logger)), + } +} diff --git a/internal/handlers/manager/manager.go b/internal/handlers/manager/manager.go index 92da951..bb0df79 100755 --- a/internal/handlers/manager/manager.go +++ b/internal/handlers/manager/manager.go @@ -3,40 +3,11 @@ package handlermanager import ( "net/http" - "online-back/internal/admin/auth" - authdb "online-back/internal/admin/auth/db" - "online-back/internal/admin/branches" - branchesdb "online-back/internal/admin/branches/db" - "online-back/internal/admin/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" - loanpaidletterdb "online-back/internal/admin/loanpaidletter/db" - "online-back/internal/admin/loansdocument" - loansdocumentdb "online-back/internal/admin/loansdocument/db" - "online-back/internal/admin/loansrepayment" - loansrepaymentdb "online-back/internal/admin/loansrepayment/db" - "online-back/internal/admin/loantype" - loantypedb "online-back/internal/admin/loantype/db" - "online-back/internal/admin/paymentcard" - paymentcarddb "online-back/internal/admin/paymentcard/db" - "online-back/internal/admin/permission" - permissiondb "online-back/internal/admin/permission/db" - "online-back/internal/admin/province" - provincedb "online-back/internal/admin/province/db" - "online-back/internal/admin/reasonscard" - reasonscarddb "online-back/internal/admin/reasonscard/db" - "online-back/internal/admin/role" - roledb "online-back/internal/admin/role/db" - "online-back/internal/admin/user" - userdb "online-back/internal/admin/user/db" + "online-back/internal/cards" "online-back/internal/config" - "online-back/internal/handlers" + "online-back/internal/identity" + "online-back/internal/lending" + "online-back/internal/org" "online-back/pkg/logging" "github.com/gin-contrib/cors" @@ -70,32 +41,13 @@ func New(cfg *config.Config, client *pgxpool.Pool, logger *logging.Logger) *gin. })) adminGroup := router.Group(adminAPIPrefix) - for _, h := range adminHandlers(client, logger) { - h.Register(adminGroup) - } + + // Each bounded context registers its own modules' handlers. + // Add new modules inside the relevant context's router.go rather than here. + identity.Register(adminGroup, client, logger) + org.Register(adminGroup, client, logger) + lending.Register(adminGroup, client, logger) + cards.Register(adminGroup, client, logger) return router } - -// adminHandlers builds every handlers.Handler registered under adminAPIPrefix. -// Add new modules here rather than inlining their wiring into New. -func adminHandlers(client *pgxpool.Pool, logger *logging.Logger) []handlers.Handler { - return []handlers.Handler{ - auth.NewHandler(logger, authdb.NewRepository(client, logger)), - province.NewHandler(logger, provincedb.NewRepository(client, logger)), - branches.NewHandler(logger, branchesdb.NewRepository(client, logger)), - 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)), - loansdocument.NewHandler(logger, loansdocumentdb.NewRepository(client, logger)), - loansrepayment.NewHandler(logger, loansrepaymentdb.NewRepository(client, logger)), - loanorders.NewHandler(logger, loanordersdb.NewRepository(client, logger)), - loanpaidletter.NewHandler(logger, loanpaidletterdb.NewRepository(client, logger)), - role.NewHandler(logger, roledb.NewRepository(client, logger)), - permission.NewHandler(logger, permissiondb.NewRepository(client, logger)), - user.NewHandler(logger, userdb.NewRepository(client, logger)), - } -} diff --git a/internal/admin/auth/db/postgresql.go b/internal/identity/auth/db/postgresql.go similarity index 53% rename from internal/admin/auth/db/postgresql.go rename to internal/identity/auth/db/postgresql.go index d3b6a56..7da9fd0 100755 --- a/internal/admin/auth/db/postgresql.go +++ b/internal/identity/auth/db/postgresql.go @@ -2,9 +2,9 @@ package db import ( "context" - "encoding/json" + "errors" - "online-back/internal/admin/auth" + "online-back/internal/identity/auth" "online-back/pkg/client/postgresql" "online-back/pkg/logging" @@ -56,41 +56,28 @@ func (r *repository) GetProfile(ctx context.Context, id int) (auth.UserProfileDT return profile, err } -const ( - createBranchUserQuery = ` - WITH inserted AS ( - INSERT INTO branch_user (branch_id, user_id) - VALUES ($1, $2) - RETURNING id, branch_id, user_id, created_at, updated_at - ) - SELECT inserted.id, inserted.branch_id, b.name, inserted.user_id, inserted.created_at, inserted.updated_at - FROM inserted - JOIN branches b ON b.id = inserted.branch_id` - deleteBranchUserQuery = `DELETE FROM branch_user WHERE id = $1` -) +const updateProfileQuery = ` + UPDATE users SET + name = $1, first_name = $2, last_name = $3, phone = $4, avatar = $5, + updated_at = (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') + WHERE id = $6 + RETURNING id, name, first_name, last_name, phone, avatar, created_at` -func (r *repository) CreateBranchUser(ctx context.Context, dto auth.CreateBranchUserDTO) (auth.BranchUserDTO, error) { - var item auth.BranchUserDTO - var branchNameJSON []byte - err := r.client.QueryRow(ctx, createBranchUserQuery, dto.BranchId, dto.UserId).Scan( - &item.Id, &item.BranchId, &branchNameJSON, &item.UserId, &item.CreatedAt, &item.UpdatedAt, +func (r *repository) UpdateProfile(ctx context.Context, id int, dto auth.UpdateProfileDTO) (auth.UserProfileDTO, error) { + var profile auth.UserProfileDTO + err := r.client.QueryRow(ctx, updateProfileQuery, + dto.Name, dto.FirstName, dto.LastName, dto.Phone, dto.Avatar, id, + ).Scan( + &profile.Id, + &profile.Name, + &profile.FirstName, + &profile.LastName, + &profile.Phone, + &profile.Avatar, + &profile.CreatedAt, ) - if err != nil { - return auth.BranchUserDTO{}, err + if errors.Is(err, pgx.ErrNoRows) { + return auth.UserProfileDTO{}, err } - if err := json.Unmarshal(branchNameJSON, &item.BranchName); err != nil { - return auth.BranchUserDTO{}, err - } - return item, nil -} - -func (r *repository) DeleteBranchUser(ctx context.Context, id int64) error { - tag, err := r.client.Exec(ctx, deleteBranchUserQuery, id) - if err != nil { - return err - } - if tag.RowsAffected() == 0 { - return pgx.ErrNoRows - } - return nil + return profile, err } diff --git a/internal/admin/auth/dto.go b/internal/identity/auth/dto.go similarity index 53% rename from internal/admin/auth/dto.go rename to internal/identity/auth/dto.go index df6f31c..886284b 100755 --- a/internal/admin/auth/dto.go +++ b/internal/identity/auth/dto.go @@ -21,27 +21,15 @@ type UserProfileDTO struct { CreatedAt time.Time `json:"createdAt"` } +type UpdateProfileDTO struct { + Name string `json:"name" binding:"required"` + FirstName string `json:"firstName"` + LastName string `json:"lastName"` + Phone string `json:"phone"` + Avatar string `json:"avatar"` +} + type UserCredentials struct { Id int Password string } - -type LocalizedText struct { - En string `json:"en"` - Ru string `json:"ru"` - Tm string `json:"tm"` -} - -type BranchUserDTO struct { - Id int64 `json:"id"` - BranchId int64 `json:"branchId"` - BranchName LocalizedText `json:"branchName"` - UserId int64 `json:"userId"` - CreatedAt time.Time `json:"createdAt"` - UpdatedAt time.Time `json:"updatedAt"` -} - -type CreateBranchUserDTO struct { - BranchId int64 `json:"branchId" binding:"required"` - UserId int64 `json:"userId" binding:"required"` -} diff --git a/internal/identity/auth/handler.go b/internal/identity/auth/handler.go new file mode 100755 index 0000000..ddc3b79 --- /dev/null +++ b/internal/identity/auth/handler.go @@ -0,0 +1,186 @@ +package auth + +import ( + "errors" + "net/http" + "strconv" + + "online-back/internal/appresult" + "online-back/internal/handlers" + "online-back/pkg/logging" + + "github.com/gin-gonic/gin" + "github.com/jackc/pgx/v4" +) + +const ( + loginURL = "/login" + tokenURL = "/token" + profileURL = "/profile" +) + +type handler struct { + logger *logging.Logger + repository Repository + service *Service +} + +func NewHandler(logger *logging.Logger, repository Repository) handlers.Handler { + return &handler{logger: logger, repository: repository, service: NewService(repository)} +} + +func (h *handler) Register(router *gin.RouterGroup) { + router.POST(loginURL, h.login) + router.POST(tokenURL, h.refreshToken) + + protected := router.Group("", appresult.JwtTokenCheck()) + protected.GET(profileURL, h.getProfile) + protected.PUT(profileURL, h.updateProfile) +} + +// login godoc +// @Summary Login +// @Description Authenticates a user by email and password +// @Tags auth +// @Accept json +// @Produce json +// @Param body body LoginDTO true "Login payload" +// @Success 200 {object} appresult.AppSuccess +// @Failure 400 {object} appresult.AppError +// @Failure 401 {object} appresult.AppError +// @Router /login [post] +func (h *handler) login(c *gin.Context) { + var dto LoginDTO + if err := c.ShouldBindJSON(&dto); err != nil { + c.JSON(http.StatusBadRequest, appresult.ErrMissingParam) + return + } + + tokenPair, err := h.service.Login(c.Request.Context(), dto) + if errors.Is(err, ErrInvalidCredentials) { + c.JSON(http.StatusUnauthorized, appresult.ErrUnauthorized) + return + } + if err != nil { + c.JSON(http.StatusBadRequest, appresult.ErrNotAcceptable) + return + } + + c.JSON(http.StatusOK, appresult.SuccessWithData(tokenPair)) +} + +// refreshToken godoc +// @Summary Refresh tokens +// @Description Issues a new access and refresh token pair +// @Tags auth +// @Accept json +// @Produce json +// @Param body body RefreshTokenDTO true "Refresh token payload" +// @Success 200 {object} appresult.AppSuccess +// @Failure 400 {object} appresult.AppError +// @Failure 401 {object} appresult.AppError +// @Router /token [post] +func (h *handler) refreshToken(c *gin.Context) { + var dto RefreshTokenDTO + if err := c.ShouldBindJSON(&dto); err != nil { + c.JSON(http.StatusBadRequest, appresult.ErrMissingParam) + return + } + + tokenPair, err := h.service.RefreshToken(c.Request.Context(), dto.RefreshToken) + if errors.Is(err, ErrInvalidCredentials) { + c.JSON(http.StatusUnauthorized, appresult.ErrUnauthorized) + return + } + if err != nil { + c.JSON(http.StatusBadRequest, appresult.ErrNotAcceptable) + return + } + + c.JSON(http.StatusOK, appresult.SuccessWithData(tokenPair)) +} + +// getProfile godoc +// @Summary Get profile +// @Description Returns the authenticated user's profile +// @Tags auth +// @Produce json +// @Security BearerAuth +// @Success 200 {object} appresult.AppSuccess +// @Failure 400 {object} appresult.AppError +// @Failure 401 {object} appresult.AppError +// @Failure 404 {object} appresult.AppError +// @Router /profile [get] +func (h *handler) getProfile(c *gin.Context) { + userID, ok := currentUserID(c) + if !ok { + c.JSON(http.StatusUnauthorized, appresult.ErrUnauthorized) + return + } + + profile, err := h.repository.GetProfile(c.Request.Context(), userID) + if err != nil { + h.logger.Errorf("get profile failed: %v", err) + c.JSON(http.StatusNotFound, appresult.ErrNotFound) + return + } + + c.JSON(http.StatusOK, appresult.SuccessWithData(profile)) +} + +// updateProfile godoc +// @Summary Update profile +// @Description Updates the authenticated user's profile +// @Tags auth +// @Accept json +// @Produce json +// @Security BearerAuth +// @Param body body UpdateProfileDTO true "Profile payload" +// @Success 200 {object} appresult.AppSuccess +// @Failure 400 {object} appresult.AppError +// @Failure 401 {object} appresult.AppError +// @Failure 404 {object} appresult.AppError +// @Router /profile [put] +func (h *handler) updateProfile(c *gin.Context) { + userID, ok := currentUserID(c) + if !ok { + c.JSON(http.StatusUnauthorized, appresult.ErrUnauthorized) + return + } + + var dto UpdateProfileDTO + if err := c.ShouldBindJSON(&dto); err != nil { + c.JSON(http.StatusBadRequest, appresult.ErrMissingParam) + return + } + + profile, err := h.repository.UpdateProfile(c.Request.Context(), userID, dto) + if errors.Is(err, pgx.ErrNoRows) { + c.JSON(http.StatusNotFound, appresult.ErrNotFound) + return + } + if err != nil { + h.logger.Errorf("update profile failed: %v", err) + c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer) + return + } + + c.JSON(http.StatusOK, appresult.SuccessWithData(profile)) +} + +func currentUserID(c *gin.Context) (int, bool) { + rawID, exists := c.Get("id") + if !exists { + return 0, false + } + + switch id := rawID.(type) { + case int: + return id, id > 0 + case string: + parsed, err := strconv.Atoi(id) + return parsed, err == nil && parsed > 0 + default: + return 0, false + } +} diff --git a/internal/identity/auth/service.go b/internal/identity/auth/service.go new file mode 100644 index 0000000..7d516c0 --- /dev/null +++ b/internal/identity/auth/service.go @@ -0,0 +1,55 @@ +package auth + +import ( + "context" + "errors" + + "online-back/pkg/utils" + + "golang.org/x/crypto/bcrypt" +) + +// ErrInvalidCredentials covers both "no such user" and "wrong password" for +// login, and any refresh-token validation failure — callers map it to 401. +// Any other error from these methods (token generation failure) maps to 400. +var ErrInvalidCredentials = errors.New("invalid credentials") + +type Service struct { + repository Repository +} + +func NewService(repository Repository) *Service { + return &Service{repository: repository} +} + +func (s *Service) Login(ctx context.Context, dto LoginDTO) (map[string]string, error) { + user, err := s.repository.Login(ctx, dto) + if err != nil { + return nil, ErrInvalidCredentials + } + + if err := bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(dto.Password)); err != nil { + return nil, ErrInvalidCredentials + } + + return utils.GenerateTokenPair(user.Id) +} + +func (s *Service) RefreshToken(ctx context.Context, refreshToken string) (map[string]string, error) { + claims, err := utils.ParseRefreshToken(refreshToken) + if err != nil { + return nil, ErrInvalidCredentials + } + + id, ok := utils.ClaimID(claims) + if !ok { + return nil, ErrInvalidCredentials + } + + user, err := s.repository.GetUserByID(ctx, id) + if err != nil || user.Id != id { + return nil, ErrInvalidCredentials + } + + return utils.GenerateTokenPair(id) +} diff --git a/internal/admin/auth/storage.go b/internal/identity/auth/storage.go similarity index 64% rename from internal/admin/auth/storage.go rename to internal/identity/auth/storage.go index 412a66c..5049f5d 100755 --- a/internal/admin/auth/storage.go +++ b/internal/identity/auth/storage.go @@ -6,6 +6,5 @@ type Repository interface { Login(ctx context.Context, dto LoginDTO) (UserCredentials, error) GetUserByID(ctx context.Context, id int) (UserCredentials, error) GetProfile(ctx context.Context, id int) (UserProfileDTO, error) - CreateBranchUser(ctx context.Context, dto CreateBranchUserDTO) (BranchUserDTO, error) - DeleteBranchUser(ctx context.Context, id int64) error + UpdateProfile(ctx context.Context, id int, dto UpdateProfileDTO) (UserProfileDTO, error) } diff --git a/internal/admin/permission/db/postgresql.go b/internal/identity/permission/db/postgresql.go similarity index 57% rename from internal/admin/permission/db/postgresql.go rename to internal/identity/permission/db/postgresql.go index 52dc246..0064e90 100644 --- a/internal/admin/permission/db/postgresql.go +++ b/internal/identity/permission/db/postgresql.go @@ -6,20 +6,26 @@ import ( "fmt" "strings" - "online-back/internal/admin/permission" + "online-back/internal/identity/permission" "online-back/pkg/client/postgresql" "online-back/pkg/logging" + "online-back/pkg/repository/genericrepo" "github.com/jackc/pgx/v4" ) type repository struct { - client postgresql.Client - logger *logging.Logger + client postgresql.Client + generic *genericrepo.Repository[permission.PermissionDTO] + logger *logging.Logger } func NewRepository(client postgresql.Client, logger *logging.Logger) permission.Repository { - return &repository{client: client, logger: logger} + return &repository{ + client: client, + generic: genericrepo.New(client, "permissions p", permissionColumns, scanPermission), + logger: logger, + } } const permissionColumns = `p.id, p.code, p.name, p.guard_name, p.created_at, p.updated_at` @@ -27,45 +33,17 @@ const permissionColumns = `p.id, p.code, p.name, p.guard_name, p.created_at, p.u const permissionReturningColumns = `id, code, name, guard_name, created_at, updated_at` func (r *repository) List(ctx context.Context, filter permission.ListFilter) (permission.ListPermissionDTO, error) { - fromClause, whereClause, args := buildListQuery(filter) + whereClause, args := buildListQuery(filter) - var count int64 - if err := r.client.QueryRow(ctx, `SELECT COUNT(*) `+fromClause+whereClause, args...).Scan(&count); err != nil { - return permission.ListPermissionDTO{}, err - } - - offset := (filter.Page - 1) * filter.Limit - limitPlaceholder := len(args) + 1 - offsetPlaceholder := len(args) + 2 - listQuery := fmt.Sprintf( - `SELECT %s%s%s ORDER BY p.id LIMIT $%d OFFSET $%d`, - permissionColumns, fromClause, whereClause, limitPlaceholder, offsetPlaceholder, - ) - - rows, err := r.client.Query(ctx, listQuery, append(args, filter.Limit, offset)...) + items, count, err := r.generic.List(ctx, whereClause, args, filter.Page, filter.Limit, "id") if err != nil { return permission.ListPermissionDTO{}, err } - defer rows.Close() - - var items []permission.PermissionDTO - for rows.Next() { - item, err := scanPermission(rows) - if err != nil { - return permission.ListPermissionDTO{}, err - } - items = append(items, item) - } - if err := rows.Err(); err != nil { - return permission.ListPermissionDTO{}, err - } return permission.ListPermissionDTO{Count: count, Permissions: items}, nil } -func buildListQuery(filter permission.ListFilter) (fromClause, whereClause string, args []interface{}) { - fromClause = ` FROM permissions p` - +func buildListQuery(filter permission.ListFilter) (whereClause string, args []interface{}) { var conditions []string if filter.PermissionName != "" { args = append(args, likePattern(filter.PermissionName)) @@ -74,10 +52,10 @@ func buildListQuery(filter permission.ListFilter) (fromClause, whereClause strin } if len(conditions) == 0 { - return fromClause, "", args + return "", args } - return fromClause, " WHERE " + strings.Join(conditions, " AND "), args + return " WHERE " + strings.Join(conditions, " AND "), args } func likePattern(term string) string { @@ -88,12 +66,7 @@ func likePattern(term string) string { } func (r *repository) GetByID(ctx context.Context, id int64) (permission.PermissionDTO, error) { - query := fmt.Sprintf(`SELECT %s FROM permissions p WHERE p.id = $1`, permissionColumns) - item, err := scanPermission(r.client.QueryRow(ctx, query, id)) - if errors.Is(err, pgx.ErrNoRows) { - return permission.PermissionDTO{}, err - } - return item, err + return r.generic.GetByID(ctx, id) } func (r *repository) Create(ctx context.Context, dto permission.CreatePermissionDTO) (permission.PermissionDTO, error) { @@ -121,21 +94,10 @@ func (r *repository) Update(ctx context.Context, id int64, dto permission.Update } func (r *repository) Delete(ctx context.Context, id int64) error { - tag, err := r.client.Exec(ctx, `DELETE FROM permissions WHERE id = $1`, id) - if err != nil { - return err - } - if tag.RowsAffected() == 0 { - return pgx.ErrNoRows - } - return nil + return r.generic.Delete(ctx, id) } -type scannable interface { - Scan(dest ...interface{}) error -} - -func scanPermission(row scannable) (permission.PermissionDTO, error) { +func scanPermission(row genericrepo.Scanner) (permission.PermissionDTO, error) { var item permission.PermissionDTO if err := row.Scan( &item.Id, &item.Code, &item.Name, &item.GuardName, &item.CreatedAt, &item.UpdatedAt, diff --git a/internal/admin/permission/dto.go b/internal/identity/permission/dto.go similarity index 100% rename from internal/admin/permission/dto.go rename to internal/identity/permission/dto.go diff --git a/internal/admin/permission/handler.go b/internal/identity/permission/handler.go similarity index 100% rename from internal/admin/permission/handler.go rename to internal/identity/permission/handler.go diff --git a/internal/admin/permission/storage.go b/internal/identity/permission/storage.go similarity index 100% rename from internal/admin/permission/storage.go rename to internal/identity/permission/storage.go diff --git a/internal/identity/permissionuser/db/postgresql.go b/internal/identity/permissionuser/db/postgresql.go new file mode 100644 index 0000000..545e8a1 --- /dev/null +++ b/internal/identity/permissionuser/db/postgresql.go @@ -0,0 +1,132 @@ +package db + +import ( + "context" + "errors" + "fmt" + "strings" + + "online-back/internal/identity/permissionuser" + "online-back/pkg/client/postgresql" + "online-back/pkg/logging" + + "github.com/jackc/pgx/v4" +) + +type repository struct { + client postgresql.Client + logger *logging.Logger +} + +func NewRepository(client postgresql.Client, logger *logging.Logger) permissionuser.Repository { + return &repository{client: client, logger: logger} +} + +const permissionUserFromClause = ` FROM permission_user pu + JOIN permissions p ON p.id = pu.permission_id + JOIN users u ON u.id = pu.user_id` + +const permissionUserSelectColumns = `pu.id, pu.permission_id, p.name, pu.user_id, u.name, pu.created_at, pu.updated_at` + +func (r *repository) List(ctx context.Context, filter permissionuser.ListFilter) (permissionuser.ListPermissionUserDTO, error) { + whereClause, args := buildListQuery(filter) + + var count int64 + if err := r.client.QueryRow(ctx, `SELECT COUNT(*)`+permissionUserFromClause+whereClause, args...).Scan(&count); err != nil { + return permissionuser.ListPermissionUserDTO{}, err + } + + query := `SELECT ` + permissionUserSelectColumns + permissionUserFromClause + whereClause + ` ORDER BY pu.id DESC` + rows, err := r.client.Query(ctx, query, args...) + if err != nil { + return permissionuser.ListPermissionUserDTO{}, err + } + defer rows.Close() + + var items []permissionuser.PermissionUserDTO + for rows.Next() { + item, err := scanPermissionUser(rows) + if err != nil { + return permissionuser.ListPermissionUserDTO{}, err + } + items = append(items, item) + } + if err := rows.Err(); err != nil { + return permissionuser.ListPermissionUserDTO{}, err + } + + return permissionuser.ListPermissionUserDTO{Count: count, Items: items}, nil +} + +func buildListQuery(filter permissionuser.ListFilter) (whereClause string, args []interface{}) { + var conditions []string + + if filter.UserId != nil { + args = append(args, *filter.UserId) + conditions = append(conditions, fmt.Sprintf("pu.user_id = $%d", len(args))) + } + + if filter.PermissionName != "" { + args = append(args, likePattern(filter.PermissionName)) + conditions = append(conditions, fmt.Sprintf("p.name ILIKE $%d", len(args))) + } + + if len(conditions) == 0 { + return "", args + } + + return " WHERE " + strings.Join(conditions, " AND "), args +} + +func likePattern(term string) string { + term = strings.ReplaceAll(term, `\`, `\\`) + term = strings.ReplaceAll(term, `%`, `\%`) + term = strings.ReplaceAll(term, `_`, `\_`) + return "%" + term + "%" +} + +func (r *repository) Create(ctx context.Context, dto permissionuser.CreatePermissionUserDTO) (permissionuser.PermissionUserDTO, error) { + query := ` + WITH inserted AS ( + INSERT INTO permission_user (permission_id, user_id) + VALUES ($1, $2) + RETURNING id, permission_id, user_id, created_at, updated_at + ) + SELECT inserted.id, inserted.permission_id, p.name, inserted.user_id, u.name, inserted.created_at, inserted.updated_at + FROM inserted + JOIN permissions p ON p.id = inserted.permission_id + JOIN users u ON u.id = inserted.user_id` + + row := r.client.QueryRow(ctx, query, dto.PermissionId, dto.UserId) + return scanPermissionUser(row) +} + +func (r *repository) Delete(ctx context.Context, id int64) error { + tag, err := r.client.Exec(ctx, `DELETE FROM permission_user WHERE id = $1`, id) + if err != nil { + return err + } + if tag.RowsAffected() == 0 { + return pgx.ErrNoRows + } + return nil +} + +type scannable interface { + Scan(dest ...interface{}) error +} + +func scanPermissionUser(row scannable) (permissionuser.PermissionUserDTO, error) { + var item permissionuser.PermissionUserDTO + + err := row.Scan( + &item.Id, &item.PermissionId, &item.PermissionName, &item.UserId, &item.UserName, &item.CreatedAt, &item.UpdatedAt, + ) + if errors.Is(err, pgx.ErrNoRows) { + return permissionuser.PermissionUserDTO{}, err + } + if err != nil { + return permissionuser.PermissionUserDTO{}, err + } + return item, nil +} diff --git a/internal/identity/permissionuser/dto.go b/internal/identity/permissionuser/dto.go new file mode 100644 index 0000000..3134645 --- /dev/null +++ b/internal/identity/permissionuser/dto.go @@ -0,0 +1,28 @@ +package permissionuser + +import "time" + +type PermissionUserDTO struct { + Id int64 `json:"id"` + UserId int64 `json:"userId"` + UserName string `json:"userName"` + PermissionId int64 `json:"permissionId"` + PermissionName string `json:"permissionName"` + CreatedAt time.Time `json:"createdAt"` + UpdatedAt time.Time `json:"updatedAt"` +} + +type ListPermissionUserDTO struct { + Count int64 `json:"count"` + Items []PermissionUserDTO `json:"items"` +} + +type ListFilter struct { + UserId *int64 + PermissionName string +} + +type CreatePermissionUserDTO struct { + PermissionId int64 `json:"permissionId" binding:"required"` + UserId int64 `json:"userId" binding:"required"` +} diff --git a/internal/identity/permissionuser/handler.go b/internal/identity/permissionuser/handler.go new file mode 100644 index 0000000..7430a76 --- /dev/null +++ b/internal/identity/permissionuser/handler.go @@ -0,0 +1,152 @@ +package permissionuser + +import ( + "errors" + "net/http" + "strconv" + "strings" + + "online-back/internal/appresult" + "online-back/internal/handlers" + "online-back/pkg/logging" + + "github.com/gin-gonic/gin" + "github.com/jackc/pgx/v4" +) + +const baseURL = "/permission-users" + +type handler struct { + logger *logging.Logger + repository Repository +} + +func NewHandler(logger *logging.Logger, repository Repository) handlers.Handler { + return &handler{logger: logger, repository: repository} +} + +func (h *handler) Register(router *gin.RouterGroup) { + group := router.Group(baseURL, appresult.JwtTokenCheck()) + group.GET("", h.list) + group.POST("", h.create) + group.DELETE("/:id", h.delete) +} + +// list godoc +// @Summary List permission users +// @Description Returns the authenticated user's permission-user assignments with the related user and permission +// @Tags permission-users +// @Produce json +// @Security BearerAuth +// @Param permission_name query string false "Filter by permission name" +// @Success 200 {object} appresult.AppSuccess +// @Failure 401 {object} appresult.AppError +// @Failure 500 {object} appresult.AppError +// @Router /permission-users [get] +func (h *handler) list(c *gin.Context) { + userID, ok := currentUserID(c) + if !ok { + c.JSON(http.StatusUnauthorized, appresult.ErrUnauthorized) + return + } + + filter := ListFilter{ + UserId: &userID, + PermissionName: strings.TrimSpace(c.Query("permission_name")), + } + + result, err := h.repository.List(c.Request.Context(), filter) + if err != nil { + h.logger.Errorf("list permission users failed: %v", err) + c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer) + return + } + + c.JSON(http.StatusOK, appresult.SuccessWithData(result)) +} + +// create godoc +// @Summary Assign user to permission +// @Description Creates a permission-user assignment +// @Tags permission-users +// @Accept json +// @Produce json +// @Security BearerAuth +// @Param body body CreatePermissionUserDTO true "Permission-user payload" +// @Success 201 {object} appresult.AppSuccess +// @Failure 400 {object} appresult.AppError +// @Failure 500 {object} appresult.AppError +// @Router /permission-users [post] +func (h *handler) create(c *gin.Context) { + var dto CreatePermissionUserDTO + if err := c.ShouldBindJSON(&dto); err != nil { + c.JSON(http.StatusBadRequest, appresult.ErrMissingParam) + return + } + + item, err := h.repository.Create(c.Request.Context(), dto) + if err != nil { + h.logger.Errorf("create permission user failed: %v", err) + c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer) + return + } + + c.JSON(http.StatusCreated, appresult.SuccessWithData(item)) +} + +// delete godoc +// @Summary Remove user from permission +// @Description Deletes a permission-user assignment +// @Tags permission-users +// @Produce json +// @Security BearerAuth +// @Param id path int true "Permission-user ID" +// @Success 200 {object} appresult.AppSuccess +// @Failure 400 {object} appresult.AppError +// @Failure 404 {object} appresult.AppError +// @Failure 500 {object} appresult.AppError +// @Router /permission-users/{id} [delete] +func (h *handler) delete(c *gin.Context) { + id, ok := parseID(c.Param("id")) + if !ok { + c.JSON(http.StatusBadRequest, appresult.ErrMissingParam) + return + } + + if err := h.repository.Delete(c.Request.Context(), id); errors.Is(err, pgx.ErrNoRows) { + c.JSON(http.StatusNotFound, appresult.ErrNotFound) + return + } else if err != nil { + h.logger.Errorf("delete permission user failed: %v", err) + c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer) + return + } + + c.JSON(http.StatusOK, appresult.SuccessWithData("permission user removed")) +} + +func parseID(raw string) (int64, bool) { + id, err := strconv.ParseInt(raw, 10, 64) + if err != nil || id <= 0 { + return 0, false + } + return id, true +} + +func currentUserID(c *gin.Context) (int64, bool) { + rawID, exists := c.Get("id") + if !exists { + return 0, false + } + + switch id := rawID.(type) { + case int64: + return id, id > 0 + case int: + return int64(id), id > 0 + case string: + return parseID(id) + default: + return 0, false + } +} diff --git a/internal/identity/permissionuser/storage.go b/internal/identity/permissionuser/storage.go new file mode 100644 index 0000000..ea26ea0 --- /dev/null +++ b/internal/identity/permissionuser/storage.go @@ -0,0 +1,9 @@ +package permissionuser + +import "context" + +type Repository interface { + List(ctx context.Context, filter ListFilter) (ListPermissionUserDTO, error) + Create(ctx context.Context, dto CreatePermissionUserDTO) (PermissionUserDTO, error) + Delete(ctx context.Context, id int64) error +} diff --git a/internal/identity/rbac/middleware.go b/internal/identity/rbac/middleware.go new file mode 100644 index 0000000..d038f6c --- /dev/null +++ b/internal/identity/rbac/middleware.go @@ -0,0 +1,38 @@ +package rbac + +import ( + "net/http" + "strconv" + + "online-back/internal/appresult" + + "github.com/gin-gonic/gin" +) + +// RequirePermission returns a gin middleware that 403s unless the +// authenticated user (set by appresult.JwtTokenCheck, which must run first) +// has been directly granted the given permission code. Not currently +// attached to any route. +func RequirePermission(service *Service, code string) gin.HandlerFunc { + return func(c *gin.Context) { + rawID, exists := c.Get("id") + if !exists { + c.AbortWithStatusJSON(http.StatusForbidden, appresult.ErrUnauthorized) + return + } + + userID, err := strconv.ParseInt(rawID.(string), 10, 64) + if err != nil { + c.AbortWithStatusJSON(http.StatusForbidden, appresult.ErrUnauthorized) + return + } + + granted, err := service.HasPermission(c.Request.Context(), userID, code) + if err != nil || !granted { + c.AbortWithStatusJSON(http.StatusForbidden, appresult.ErrUnauthorized) + return + } + + c.Next() + } +} diff --git a/internal/identity/rbac/service.go b/internal/identity/rbac/service.go new file mode 100644 index 0000000..021228f --- /dev/null +++ b/internal/identity/rbac/service.go @@ -0,0 +1,42 @@ +// Package rbac provides permission-check capability on top of the existing +// permissions/permission_user tables. It is not wired into any route yet — +// today every route is still gated only by appresult.JwtTokenCheck()'s +// admin-claim check. RequirePermission is available for routes to opt into +// once permission data is populated and specific routes are chosen. +// +// Note: the schema has no role_permission pivot table, so role-based +// permission resolution isn't possible yet — HasPermission only resolves +// permissions granted directly via permission_user. +package rbac + +import ( + "context" + + "online-back/pkg/client/postgresql" +) + +type Service struct { + client postgresql.Client +} + +func NewService(client postgresql.Client) *Service { + return &Service{client: client} +} + +// HasPermission reports whether userID has been directly granted the +// permission identified by code (permissions.code) via permission_user. +func (s *Service) HasPermission(ctx context.Context, userID int64, code string) (bool, error) { + const query = ` + SELECT EXISTS ( + SELECT 1 + FROM permission_user pu + JOIN permissions p ON p.id = pu.permission_id + WHERE pu.user_id = $1 AND p.code = $2 + )` + + var granted bool + if err := s.client.QueryRow(ctx, query, userID, code).Scan(&granted); err != nil { + return false, err + } + return granted, nil +} diff --git a/internal/identity/rbac/service_test.go b/internal/identity/rbac/service_test.go new file mode 100644 index 0000000..faef505 --- /dev/null +++ b/internal/identity/rbac/service_test.go @@ -0,0 +1,56 @@ +package rbac + +import ( + "context" + "testing" + + "github.com/jackc/pgconn" + "github.com/jackc/pgx/v4" +) + +type fakeClient struct { + granted bool +} + +func (f *fakeClient) Exec(ctx context.Context, sql string, args ...interface{}) (pgconn.CommandTag, error) { + return nil, nil +} + +func (f *fakeClient) Query(ctx context.Context, sql string, args ...interface{}) (pgx.Rows, error) { + return nil, nil +} + +func (f *fakeClient) QueryRow(ctx context.Context, sql string, args ...interface{}) pgx.Row { + return fakeRow{granted: f.granted} +} + +func (f *fakeClient) Begin(ctx context.Context) (pgx.Tx, error) { + return nil, nil +} + +type fakeRow struct { + granted bool +} + +func (r fakeRow) Scan(dest ...interface{}) error { + *dest[0].(*bool) = r.granted + return nil +} + +func TestHasPermission(t *testing.T) { + granted, err := NewService(&fakeClient{granted: true}).HasPermission(context.Background(), 1, "province.write") + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + if !granted { + t.Fatal("expected permission to be granted") + } + + granted, err = NewService(&fakeClient{granted: false}).HasPermission(context.Background(), 1, "province.write") + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + if granted { + t.Fatal("expected permission to not be granted") + } +} diff --git a/internal/admin/role/db/postgresql.go b/internal/identity/role/db/postgresql.go similarity index 56% rename from internal/admin/role/db/postgresql.go rename to internal/identity/role/db/postgresql.go index 2f01752..fd494a5 100644 --- a/internal/admin/role/db/postgresql.go +++ b/internal/identity/role/db/postgresql.go @@ -6,20 +6,26 @@ import ( "fmt" "strings" - "online-back/internal/admin/role" + "online-back/internal/identity/role" "online-back/pkg/client/postgresql" "online-back/pkg/logging" + "online-back/pkg/repository/genericrepo" "github.com/jackc/pgx/v4" ) type repository struct { - client postgresql.Client - logger *logging.Logger + client postgresql.Client + generic *genericrepo.Repository[role.RoleDTO] + logger *logging.Logger } func NewRepository(client postgresql.Client, logger *logging.Logger) role.Repository { - return &repository{client: client, logger: logger} + return &repository{ + client: client, + generic: genericrepo.New(client, "roles r", roleColumns, scanRole), + logger: logger, + } } const roleColumns = `r.id, r.code, r.name, r.guard_name, r.created_at, r.updated_at` @@ -27,45 +33,17 @@ const roleColumns = `r.id, r.code, r.name, r.guard_name, r.created_at, r.updated const roleReturningColumns = `id, code, name, guard_name, created_at, updated_at` func (r *repository) List(ctx context.Context, filter role.ListFilter) (role.ListRoleDTO, error) { - fromClause, whereClause, args := buildListQuery(filter) + whereClause, args := buildListQuery(filter) - var count int64 - if err := r.client.QueryRow(ctx, `SELECT COUNT(*) `+fromClause+whereClause, args...).Scan(&count); err != nil { - return role.ListRoleDTO{}, err - } - - offset := (filter.Page - 1) * filter.Limit - limitPlaceholder := len(args) + 1 - offsetPlaceholder := len(args) + 2 - listQuery := fmt.Sprintf( - `SELECT %s%s%s ORDER BY r.id LIMIT $%d OFFSET $%d`, - roleColumns, fromClause, whereClause, limitPlaceholder, offsetPlaceholder, - ) - - rows, err := r.client.Query(ctx, listQuery, append(args, filter.Limit, offset)...) + items, count, err := r.generic.List(ctx, whereClause, args, filter.Page, filter.Limit, "id") if err != nil { return role.ListRoleDTO{}, err } - defer rows.Close() - - var items []role.RoleDTO - for rows.Next() { - item, err := scanRole(rows) - if err != nil { - return role.ListRoleDTO{}, err - } - items = append(items, item) - } - if err := rows.Err(); err != nil { - return role.ListRoleDTO{}, err - } return role.ListRoleDTO{Count: count, Roles: items}, nil } -func buildListQuery(filter role.ListFilter) (fromClause, whereClause string, args []interface{}) { - fromClause = ` FROM roles r` - +func buildListQuery(filter role.ListFilter) (whereClause string, args []interface{}) { var conditions []string if filter.RoleName != "" { args = append(args, likePattern(filter.RoleName)) @@ -74,10 +52,10 @@ func buildListQuery(filter role.ListFilter) (fromClause, whereClause string, arg } if len(conditions) == 0 { - return fromClause, "", args + return "", args } - return fromClause, " WHERE " + strings.Join(conditions, " AND "), args + return " WHERE " + strings.Join(conditions, " AND "), args } func likePattern(term string) string { @@ -88,12 +66,7 @@ func likePattern(term string) string { } func (r *repository) GetByID(ctx context.Context, id int64) (role.RoleDTO, error) { - query := fmt.Sprintf(`SELECT %s FROM roles r WHERE r.id = $1`, roleColumns) - item, err := scanRole(r.client.QueryRow(ctx, query, id)) - if errors.Is(err, pgx.ErrNoRows) { - return role.RoleDTO{}, err - } - return item, err + return r.generic.GetByID(ctx, id) } func (r *repository) Create(ctx context.Context, dto role.CreateRoleDTO) (role.RoleDTO, error) { @@ -121,21 +94,10 @@ func (r *repository) Update(ctx context.Context, id int64, dto role.UpdateRoleDT } func (r *repository) Delete(ctx context.Context, id int64) error { - tag, err := r.client.Exec(ctx, `DELETE FROM roles WHERE id = $1`, id) - if err != nil { - return err - } - if tag.RowsAffected() == 0 { - return pgx.ErrNoRows - } - return nil + return r.generic.Delete(ctx, id) } -type scannable interface { - Scan(dest ...interface{}) error -} - -func scanRole(row scannable) (role.RoleDTO, error) { +func scanRole(row genericrepo.Scanner) (role.RoleDTO, error) { var item role.RoleDTO if err := row.Scan( &item.Id, &item.Code, &item.Name, &item.GuardName, &item.CreatedAt, &item.UpdatedAt, diff --git a/internal/admin/role/dto.go b/internal/identity/role/dto.go similarity index 100% rename from internal/admin/role/dto.go rename to internal/identity/role/dto.go diff --git a/internal/admin/role/handler.go b/internal/identity/role/handler.go similarity index 100% rename from internal/admin/role/handler.go rename to internal/identity/role/handler.go diff --git a/internal/admin/role/storage.go b/internal/identity/role/storage.go similarity index 100% rename from internal/admin/role/storage.go rename to internal/identity/role/storage.go diff --git a/internal/identity/roleusers/db/postgresql.go b/internal/identity/roleusers/db/postgresql.go new file mode 100644 index 0000000..1c4c346 --- /dev/null +++ b/internal/identity/roleusers/db/postgresql.go @@ -0,0 +1,132 @@ +package db + +import ( + "context" + "errors" + "fmt" + "strings" + + "online-back/internal/identity/roleusers" + "online-back/pkg/client/postgresql" + "online-back/pkg/logging" + + "github.com/jackc/pgx/v4" +) + +type repository struct { + client postgresql.Client + logger *logging.Logger +} + +func NewRepository(client postgresql.Client, logger *logging.Logger) roleusers.Repository { + return &repository{client: client, logger: logger} +} + +const roleUserFromClause = ` FROM role_user ru + JOIN roles r ON r.id = ru.role_id + JOIN users u ON u.id = ru.user_id` + +const roleUserSelectColumns = `ru.id, ru.role_id, r.name, ru.user_id, u.name, ru.created_at, ru.updated_at` + +func (r *repository) List(ctx context.Context, filter roleusers.ListFilter) (roleusers.ListRoleUserDTO, error) { + whereClause, args := buildListQuery(filter) + + var count int64 + if err := r.client.QueryRow(ctx, `SELECT COUNT(*)`+roleUserFromClause+whereClause, args...).Scan(&count); err != nil { + return roleusers.ListRoleUserDTO{}, err + } + + query := `SELECT ` + roleUserSelectColumns + roleUserFromClause + whereClause + ` ORDER BY ru.id DESC` + rows, err := r.client.Query(ctx, query, args...) + if err != nil { + return roleusers.ListRoleUserDTO{}, err + } + defer rows.Close() + + var items []roleusers.RoleUserDTO + for rows.Next() { + item, err := scanRoleUser(rows) + if err != nil { + return roleusers.ListRoleUserDTO{}, err + } + items = append(items, item) + } + if err := rows.Err(); err != nil { + return roleusers.ListRoleUserDTO{}, err + } + + return roleusers.ListRoleUserDTO{Count: count, Items: items}, nil +} + +func buildListQuery(filter roleusers.ListFilter) (whereClause string, args []interface{}) { + var conditions []string + + if filter.UserId != nil { + args = append(args, *filter.UserId) + conditions = append(conditions, fmt.Sprintf("ru.user_id = $%d", len(args))) + } + + if filter.RoleName != "" { + args = append(args, likePattern(filter.RoleName)) + conditions = append(conditions, fmt.Sprintf("r.name ILIKE $%d", len(args))) + } + + if len(conditions) == 0 { + return "", args + } + + return " WHERE " + strings.Join(conditions, " AND "), args +} + +func likePattern(term string) string { + term = strings.ReplaceAll(term, `\`, `\\`) + term = strings.ReplaceAll(term, `%`, `\%`) + term = strings.ReplaceAll(term, `_`, `\_`) + return "%" + term + "%" +} + +func (r *repository) Create(ctx context.Context, dto roleusers.CreateRoleUserDTO) (roleusers.RoleUserDTO, error) { + query := ` + WITH inserted AS ( + INSERT INTO role_user (role_id, user_id) + VALUES ($1, $2) + RETURNING id, role_id, user_id, created_at, updated_at + ) + SELECT inserted.id, inserted.role_id, r.name, inserted.user_id, u.name, inserted.created_at, inserted.updated_at + FROM inserted + JOIN roles r ON r.id = inserted.role_id + JOIN users u ON u.id = inserted.user_id` + + row := r.client.QueryRow(ctx, query, dto.RoleId, dto.UserId) + return scanRoleUser(row) +} + +func (r *repository) Delete(ctx context.Context, id int64) error { + tag, err := r.client.Exec(ctx, `DELETE FROM role_user WHERE id = $1`, id) + if err != nil { + return err + } + if tag.RowsAffected() == 0 { + return pgx.ErrNoRows + } + return nil +} + +type scannable interface { + Scan(dest ...interface{}) error +} + +func scanRoleUser(row scannable) (roleusers.RoleUserDTO, error) { + var item roleusers.RoleUserDTO + + err := row.Scan( + &item.Id, &item.RoleId, &item.RoleName, &item.UserId, &item.UserName, &item.CreatedAt, &item.UpdatedAt, + ) + if errors.Is(err, pgx.ErrNoRows) { + return roleusers.RoleUserDTO{}, err + } + if err != nil { + return roleusers.RoleUserDTO{}, err + } + return item, nil +} diff --git a/internal/identity/roleusers/dto.go b/internal/identity/roleusers/dto.go new file mode 100644 index 0000000..fc193b7 --- /dev/null +++ b/internal/identity/roleusers/dto.go @@ -0,0 +1,28 @@ +package roleusers + +import "time" + +type RoleUserDTO struct { + Id int64 `json:"id"` + UserId int64 `json:"userId"` + UserName string `json:"userName"` + RoleId int64 `json:"roleId"` + RoleName string `json:"roleName"` + CreatedAt time.Time `json:"createdAt"` + UpdatedAt time.Time `json:"updatedAt"` +} + +type ListRoleUserDTO struct { + Count int64 `json:"count"` + Items []RoleUserDTO `json:"items"` +} + +type ListFilter struct { + UserId *int64 + RoleName string +} + +type CreateRoleUserDTO struct { + RoleId int64 `json:"roleId" binding:"required"` + UserId int64 `json:"userId" binding:"required"` +} diff --git a/internal/identity/roleusers/handler.go b/internal/identity/roleusers/handler.go new file mode 100644 index 0000000..b5987da --- /dev/null +++ b/internal/identity/roleusers/handler.go @@ -0,0 +1,152 @@ +package roleusers + +import ( + "errors" + "net/http" + "strconv" + "strings" + + "online-back/internal/appresult" + "online-back/internal/handlers" + "online-back/pkg/logging" + + "github.com/gin-gonic/gin" + "github.com/jackc/pgx/v4" +) + +const baseURL = "/role-users" + +type handler struct { + logger *logging.Logger + repository Repository +} + +func NewHandler(logger *logging.Logger, repository Repository) handlers.Handler { + return &handler{logger: logger, repository: repository} +} + +func (h *handler) Register(router *gin.RouterGroup) { + group := router.Group(baseURL, appresult.JwtTokenCheck()) + group.GET("", h.list) + group.POST("", h.create) + group.DELETE("/:id", h.delete) +} + +// list godoc +// @Summary List role users +// @Description Returns the authenticated user's role-user assignments with the related user and role +// @Tags role-users +// @Produce json +// @Security BearerAuth +// @Param role_name query string false "Filter by role name" +// @Success 200 {object} appresult.AppSuccess +// @Failure 401 {object} appresult.AppError +// @Failure 500 {object} appresult.AppError +// @Router /role-users [get] +func (h *handler) list(c *gin.Context) { + userID, ok := currentUserID(c) + if !ok { + c.JSON(http.StatusUnauthorized, appresult.ErrUnauthorized) + return + } + + filter := ListFilter{ + UserId: &userID, + RoleName: strings.TrimSpace(c.Query("role_name")), + } + + result, err := h.repository.List(c.Request.Context(), filter) + if err != nil { + h.logger.Errorf("list role users failed: %v", err) + c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer) + return + } + + c.JSON(http.StatusOK, appresult.SuccessWithData(result)) +} + +// create godoc +// @Summary Assign user to role +// @Description Creates a role-user assignment +// @Tags role-users +// @Accept json +// @Produce json +// @Security BearerAuth +// @Param body body CreateRoleUserDTO true "Role-user payload" +// @Success 201 {object} appresult.AppSuccess +// @Failure 400 {object} appresult.AppError +// @Failure 500 {object} appresult.AppError +// @Router /role-users [post] +func (h *handler) create(c *gin.Context) { + var dto CreateRoleUserDTO + if err := c.ShouldBindJSON(&dto); err != nil { + c.JSON(http.StatusBadRequest, appresult.ErrMissingParam) + return + } + + item, err := h.repository.Create(c.Request.Context(), dto) + if err != nil { + h.logger.Errorf("create role user failed: %v", err) + c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer) + return + } + + c.JSON(http.StatusCreated, appresult.SuccessWithData(item)) +} + +// delete godoc +// @Summary Remove user from role +// @Description Deletes a role-user assignment +// @Tags role-users +// @Produce json +// @Security BearerAuth +// @Param id path int true "Role-user ID" +// @Success 200 {object} appresult.AppSuccess +// @Failure 400 {object} appresult.AppError +// @Failure 404 {object} appresult.AppError +// @Failure 500 {object} appresult.AppError +// @Router /role-users/{id} [delete] +func (h *handler) delete(c *gin.Context) { + id, ok := parseID(c.Param("id")) + if !ok { + c.JSON(http.StatusBadRequest, appresult.ErrMissingParam) + return + } + + if err := h.repository.Delete(c.Request.Context(), id); errors.Is(err, pgx.ErrNoRows) { + c.JSON(http.StatusNotFound, appresult.ErrNotFound) + return + } else if err != nil { + h.logger.Errorf("delete role user failed: %v", err) + c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer) + return + } + + c.JSON(http.StatusOK, appresult.SuccessWithData("role user removed")) +} + +func parseID(raw string) (int64, bool) { + id, err := strconv.ParseInt(raw, 10, 64) + if err != nil || id <= 0 { + return 0, false + } + return id, true +} + +func currentUserID(c *gin.Context) (int64, bool) { + rawID, exists := c.Get("id") + if !exists { + return 0, false + } + + switch id := rawID.(type) { + case int64: + return id, id > 0 + case int: + return int64(id), id > 0 + case string: + return parseID(id) + default: + return 0, false + } +} diff --git a/internal/identity/roleusers/storage.go b/internal/identity/roleusers/storage.go new file mode 100644 index 0000000..f187060 --- /dev/null +++ b/internal/identity/roleusers/storage.go @@ -0,0 +1,9 @@ +package roleusers + +import "context" + +type Repository interface { + List(ctx context.Context, filter ListFilter) (ListRoleUserDTO, error) + Create(ctx context.Context, dto CreateRoleUserDTO) (RoleUserDTO, error) + Delete(ctx context.Context, id int64) error +} diff --git a/internal/identity/router.go b/internal/identity/router.go new file mode 100644 index 0000000..5e1d467 --- /dev/null +++ b/internal/identity/router.go @@ -0,0 +1,45 @@ +// Package identity groups authentication, users, and RBAC (roles, +// permissions, and their user/branch assignments) under one bounded +// context, replacing the flat internal/admin/* listing. +package identity + +import ( + "online-back/internal/handlers" + "online-back/internal/identity/auth" + authdb "online-back/internal/identity/auth/db" + "online-back/internal/identity/permission" + permissiondb "online-back/internal/identity/permission/db" + "online-back/internal/identity/permissionuser" + permissionuserdb "online-back/internal/identity/permissionuser/db" + "online-back/internal/identity/role" + roledb "online-back/internal/identity/role/db" + "online-back/internal/identity/roleusers" + roleusersdb "online-back/internal/identity/roleusers/db" + "online-back/internal/identity/user" + userdb "online-back/internal/identity/user/db" + "online-back/internal/identity/userbranch" + userbranchdb "online-back/internal/identity/userbranch/db" + "online-back/pkg/client/postgresql" + "online-back/pkg/logging" + + "github.com/gin-gonic/gin" +) + +// Register wires every identity module's handler onto router. +func Register(router *gin.RouterGroup, client postgresql.Client, logger *logging.Logger) { + for _, h := range Handlers(client, logger) { + h.Register(router) + } +} + +func Handlers(client postgresql.Client, logger *logging.Logger) []handlers.Handler { + return []handlers.Handler{ + auth.NewHandler(logger, authdb.NewRepository(client, logger)), + user.NewHandler(logger, userdb.NewRepository(client, logger)), + role.NewHandler(logger, roledb.NewRepository(client, logger)), + permission.NewHandler(logger, permissiondb.NewRepository(client, logger)), + roleusers.NewHandler(logger, roleusersdb.NewRepository(client, logger)), + permissionuser.NewHandler(logger, permissionuserdb.NewRepository(client, logger)), + userbranch.NewHandler(logger, userbranchdb.NewRepository(client, logger)), + } +} diff --git a/internal/admin/user/db/postgresql.go b/internal/identity/user/db/postgresql.go similarity index 78% rename from internal/admin/user/db/postgresql.go rename to internal/identity/user/db/postgresql.go index 285e6b9..9c56733 100644 --- a/internal/admin/user/db/postgresql.go +++ b/internal/identity/user/db/postgresql.go @@ -7,7 +7,7 @@ import ( "fmt" "strings" - "online-back/internal/admin/user" + "online-back/internal/identity/user" "online-back/pkg/client/postgresql" "online-back/pkg/logging" @@ -66,7 +66,11 @@ func (r *repository) List(ctx context.Context, filter user.ListFilter) (user.Lis } func buildListQuery(filter user.ListFilter) (fromClause, whereClause string, args []interface{}) { - fromClause = ` FROM users u` + return buildFilteredListQuery(filter, "") +} + +func buildFilteredListQuery(filter user.ListFilter, role string) (fromClause, whereClause string, args []interface{}) { + fromClause = ` FROM users u ` var conditions []string if filter.Username != "" { @@ -74,6 +78,11 @@ func buildListQuery(filter user.ListFilter) (fromClause, whereClause string, arg n := len(args) conditions = append(conditions, fmt.Sprintf(`u.username ILIKE $%d`, n)) } + if role != "" { + args = append(args, role) + n := len(args) + conditions = append(conditions, fmt.Sprintf(`u.role = $%d`, n)) + } if len(conditions) == 0 { return fromClause, "", args @@ -89,6 +98,43 @@ func likePattern(term string) string { return "%" + term + "%" } +func (r *repository) GetByRole(ctx context.Context, role string, filter user.ListFilter) (user.ListUserDTO, error) { + fromClause, whereClause, args := buildFilteredListQuery(filter, role) + + var count int64 + if err := r.client.QueryRow(ctx, `SELECT COUNT(*) `+fromClause+whereClause, args...).Scan(&count); err != nil { + return user.ListUserDTO{}, err + } + + offset := (filter.Page - 1) * filter.Limit + limitPlaceholder := len(args) + 1 + offsetPlaceholder := len(args) + 2 + listQuery := fmt.Sprintf( + `SELECT %s%s%s ORDER BY u.id LIMIT $%d OFFSET $%d `, + userColumns, fromClause, whereClause, limitPlaceholder, offsetPlaceholder, + ) + + rows, err := r.client.Query(ctx, listQuery, append(args, filter.Limit, offset)...) + if err != nil { + return user.ListUserDTO{}, err + } + defer rows.Close() + + var items []user.UserDTO + for rows.Next() { + item, err := scanUser(rows) + if err != nil { + return user.ListUserDTO{}, err + } + items = append(items, item) + } + if err := rows.Err(); err != nil { + return user.ListUserDTO{}, err + } + + return user.ListUserDTO{Count: count, Users: items}, nil +} + func (r *repository) GetByID(ctx context.Context, id int64) (user.UserDTO, error) { query := fmt.Sprintf(`SELECT %s FROM users u WHERE u.id = $1`, userColumns) item, err := scanUser(r.client.QueryRow(ctx, query, id)) diff --git a/internal/admin/user/dto.go b/internal/identity/user/dto.go similarity index 100% rename from internal/admin/user/dto.go rename to internal/identity/user/dto.go diff --git a/internal/admin/auth/handler.go b/internal/identity/user/handler.go old mode 100755 new mode 100644 similarity index 54% rename from internal/admin/auth/handler.go rename to internal/identity/user/handler.go index 0257e5a..f4af693 --- a/internal/admin/auth/handler.go +++ b/internal/identity/user/handler.go @@ -1,4 +1,4 @@ -package auth +package user import ( "context" @@ -8,6 +8,7 @@ import ( "net/http" "path/filepath" "strconv" + "strings" "time" "online-back/internal/appresult" @@ -15,19 +16,14 @@ import ( "online-back/internal/handlers" "online-back/pkg/logging" minioUpload "online-back/pkg/minio" - "online-back/pkg/utils" "github.com/gin-gonic/gin" "github.com/jackc/pgx/v4" "github.com/minio/minio-go/v7" - "golang.org/x/crypto/bcrypt" ) const ( - loginURL = "/login" - tokenURL = "/token" - profileURL = "/profile" - branchUserURL = "/branch-users" + baseURL = "/users" fileUploadURL = "/file" fileURL = "/file/:id" ) @@ -42,154 +38,150 @@ func NewHandler(logger *logging.Logger, repository Repository) handlers.Handler } func (h *handler) Register(router *gin.RouterGroup) { - router.POST(loginURL, h.login) - router.POST(tokenURL, h.refreshToken) + group := router.Group(baseURL, appresult.JwtTokenCheck()) + group.GET("", h.list) + group.GET("/role", h.listUsersByRole) + group.GET("/:id", h.getByID) + group.POST("", h.create) + group.PUT("/:id", h.update) + group.DELETE("/:id", h.delete) - protected := router.Group("", appresult.JwtTokenCheck()) - protected.GET(profileURL, h.getProfile) - protected.POST(fileUploadURL, h.fileUpload) - protected.GET(fileURL, h.getFile) - protected.DELETE(fileURL, h.deleteFile) - - branchUserGroup := router.Group(branchUserURL, appresult.JwtTokenCheck()) - branchUserGroup.POST("", h.createBranchUser) - branchUserGroup.DELETE("/:id", h.deleteBranchUser) + // Avatar/profile file storage — kept at the top-level /file path (not + // nested under /users) to preserve the existing API contract; this used + // to live in the auth handler purely incidentally. + files := router.Group("", appresult.JwtTokenCheck()) + files.POST(fileUploadURL, h.fileUpload) + files.GET(fileURL, h.getFile) + files.DELETE(fileURL, h.deleteFile) } -// login godoc -// @Summary Login -// @Description Authenticates a user by email and password -// @Tags auth -// @Accept json -// @Produce json -// @Param body body LoginDTO true "Login payload" -// @Success 200 {object} appresult.AppSuccess -// @Failure 400 {object} appresult.AppError -// @Failure 401 {object} appresult.AppError -// @Router /login [post] -func (h *handler) login(c *gin.Context) { - var dto LoginDTO - if err := c.ShouldBindJSON(&dto); err != nil { - c.JSON(http.StatusBadRequest, appresult.ErrMissingParam) - return - } - - user, err := h.repository.Login(c.Request.Context(), dto) - if err != nil { - h.logger.Errorf("login lookup failed: %v", err) - c.JSON(http.StatusUnauthorized, appresult.ErrUnauthorized) - return - } - - if err := bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(dto.Password)); err != nil { - c.JSON(http.StatusUnauthorized, appresult.ErrUnauthorized) - return - } - - tokenPair, err := utils.GenerateTokenPair(user.Id) - if err != nil { - c.JSON(http.StatusBadRequest, appresult.ErrNotAcceptable) - return - } - - c.JSON(http.StatusOK, appresult.SuccessWithData(tokenPair)) -} - -// refreshToken godoc -// @Summary Refresh tokens -// @Description Issues a new access and refresh token pair -// @Tags auth -// @Accept json -// @Produce json -// @Param body body RefreshTokenDTO true "Refresh token payload" -// @Success 200 {object} appresult.AppSuccess -// @Failure 400 {object} appresult.AppError -// @Failure 401 {object} appresult.AppError -// @Router /token [post] -func (h *handler) refreshToken(c *gin.Context) { - var dto RefreshTokenDTO - if err := c.ShouldBindJSON(&dto); err != nil { - c.JSON(http.StatusBadRequest, appresult.ErrMissingParam) - return - } - - claims, err := utils.ParseRefreshToken(dto.RefreshToken) - if err != nil { - c.JSON(http.StatusUnauthorized, appresult.ErrUnauthorized) - return - } - - id, ok := utils.ClaimID(claims) - if !ok { - c.JSON(http.StatusUnauthorized, appresult.ErrUnauthorized) - return - } - - user, err := h.repository.GetUserByID(c.Request.Context(), id) - if err != nil || user.Id != id { - c.JSON(http.StatusUnauthorized, appresult.ErrUnauthorized) - return - } - - tokenPair, err := utils.GenerateTokenPair(id) - if err != nil { - c.JSON(http.StatusBadRequest, appresult.ErrNotAcceptable) - return - } - - c.JSON(http.StatusOK, appresult.SuccessWithData(tokenPair)) -} - -// getProfile godoc -// @Summary Get profile -// @Description Returns the authenticated user's profile -// @Tags auth +// list godoc +// @Summary List users +// @Description Returns paginated users with optional filters +// @Tags user // @Produce json // @Security BearerAuth +// @Param username query string false "Filter by username" +// @Param page query int false "Page number" default(1) +// @Param limit query int false "Items per page" default(10) // @Success 200 {object} appresult.AppSuccess // @Failure 400 {object} appresult.AppError -// @Failure 401 {object} appresult.AppError -// @Failure 404 {object} appresult.AppError -// @Router /profile [get] -func (h *handler) getProfile(c *gin.Context) { - userID, ok := currentUserID(c) +// @Failure 500 {object} appresult.AppError +// @Router /users [get] +func (h *handler) list(c *gin.Context) { + filter, ok := parseListFilter(c) if !ok { - c.JSON(http.StatusUnauthorized, appresult.ErrUnauthorized) + c.JSON(http.StatusBadRequest, appresult.ErrMissingParam) return } - profile, err := h.repository.GetProfile(c.Request.Context(), userID) + result, err := h.repository.List(c.Request.Context(), filter) if err != nil { - h.logger.Errorf("get profile failed: %v", err) + h.logger.Errorf("list users failed: %v", err) + c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer) + return + } + + c.JSON(http.StatusOK, appresult.SuccessWithData(result)) +} + +// listUsersByRole godoc +// @Summary List users by role +// @Description Returns paginated users filtered by role +// @Tags user +// @Produce json +// @Security BearerAuth +// @Param role query string true "user role" +// @Param username query string false "Filter by username" +// @Param page query int false "Page number" default(1) +// @Param limit query int false "Items per page" default(10) +// @Success 200 {object} appresult.AppSuccess +// @Failure 400 {object} appresult.AppError +// @Failure 404 {object} appresult.AppError +// @Failure 500 {object} appresult.AppError +// @Router /users/role [get] +func (h *handler) listUsersByRole(c *gin.Context) { + role := strings.TrimSpace(c.Query("role")) + if role == "" { + c.JSON(http.StatusBadRequest, appresult.ErrMissingParam) + return + } + + filter, ok := parseListFilter(c) + if !ok { + c.JSON(http.StatusBadRequest, appresult.ErrMissingParam) + return + } + + item, err := h.repository.GetByRole(c.Request.Context(), role, filter) + if errors.Is(err, pgx.ErrNoRows) { c.JSON(http.StatusNotFound, appresult.ErrNotFound) return } + if err != nil { + h.logger.Errorf("get user failed: %v", err) + c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer) + return + } - c.JSON(http.StatusOK, appresult.SuccessWithData(profile)) + c.JSON(http.StatusOK, appresult.SuccessWithData(item)) } -// createBranchUser godoc -// @Summary Assign user to branch -// @Description Creates a branch-user assignment -// @Tags auth +// getByID godoc +// @Summary Get user by ID +// @Description Returns a single user +// @Tags user +// @Produce json +// @Security BearerAuth +// @Param id path int true "User ID" +// @Success 200 {object} appresult.AppSuccess +// @Failure 400 {object} appresult.AppError +// @Failure 404 {object} appresult.AppError +// @Failure 500 {object} appresult.AppError +// @Router /users/{id} [get] +func (h *handler) getByID(c *gin.Context) { + id, ok := parseID(c.Param("id")) + if !ok { + c.JSON(http.StatusBadRequest, appresult.ErrMissingParam) + return + } + + item, err := h.repository.GetByID(c.Request.Context(), id) + if errors.Is(err, pgx.ErrNoRows) { + c.JSON(http.StatusNotFound, appresult.ErrNotFound) + return + } + if err != nil { + h.logger.Errorf("get user failed: %v", err) + c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer) + return + } + + c.JSON(http.StatusOK, appresult.SuccessWithData(item)) +} + +// create godoc +// @Summary Create user +// @Description Creates a new user +// @Tags user // @Accept json // @Produce json // @Security BearerAuth -// @Param body body CreateBranchUserDTO true "Branch-user payload" +// @Param body body CreateUserDTO true "User payload" // @Success 201 {object} appresult.AppSuccess // @Failure 400 {object} appresult.AppError // @Failure 500 {object} appresult.AppError -// @Router /branch-users [post] -func (h *handler) createBranchUser(c *gin.Context) { - var dto CreateBranchUserDTO +// @Router /users [post] +func (h *handler) create(c *gin.Context) { + var dto CreateUserDTO if err := c.ShouldBindJSON(&dto); err != nil { c.JSON(http.StatusBadRequest, appresult.ErrMissingParam) return } - item, err := h.repository.CreateBranchUser(c.Request.Context(), dto) + item, err := h.repository.Create(c.Request.Context(), dto) if err != nil { - h.logger.Errorf("create branch user failed: %v", err) + h.logger.Errorf("create user failed: %v", err) c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer) return } @@ -197,35 +189,76 @@ func (h *handler) createBranchUser(c *gin.Context) { c.JSON(http.StatusCreated, appresult.SuccessWithData(item)) } -// deleteBranchUser godoc -// @Summary Remove user from branch -// @Description Deletes a branch-user assignment -// @Tags auth +// update godoc +// @Summary Update user +// @Description Updates an existing user +// @Tags user +// @Accept json // @Produce json // @Security BearerAuth -// @Param id path int true "Branch-user ID" +// @Param id path int true "User ID" +// @Param body body UpdateUserDTO true "User payload" // @Success 200 {object} appresult.AppSuccess // @Failure 400 {object} appresult.AppError // @Failure 404 {object} appresult.AppError // @Failure 500 {object} appresult.AppError -// @Router /branch-users/{id} [delete] -func (h *handler) deleteBranchUser(c *gin.Context) { +// @Router /users/{id} [put] +func (h *handler) update(c *gin.Context) { id, ok := parseID(c.Param("id")) if !ok { c.JSON(http.StatusBadRequest, appresult.ErrMissingParam) return } - if err := h.repository.DeleteBranchUser(c.Request.Context(), id); errors.Is(err, pgx.ErrNoRows) { + var dto UpdateUserDTO + if err := c.ShouldBindJSON(&dto); err != nil { + c.JSON(http.StatusBadRequest, appresult.ErrMissingParam) + return + } + + item, err := h.repository.Update(c.Request.Context(), id, dto) + if errors.Is(err, pgx.ErrNoRows) { c.JSON(http.StatusNotFound, appresult.ErrNotFound) return - } else if err != nil { - h.logger.Errorf("delete branch user failed: %v", err) + } + if err != nil { + h.logger.Errorf("update user failed: %v", err) c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer) return } - c.JSON(http.StatusOK, appresult.SuccessWithData("branch user removed")) + c.JSON(http.StatusOK, appresult.SuccessWithData(item)) +} + +// delete godoc +// @Summary Delete user +// @Description Deletes a user +// @Tags user +// @Produce json +// @Security BearerAuth +// @Param id path int true "User ID" +// @Success 200 {object} appresult.AppSuccess +// @Failure 400 {object} appresult.AppError +// @Failure 404 {object} appresult.AppError +// @Failure 500 {object} appresult.AppError +// @Router /users/{id} [delete] +func (h *handler) delete(c *gin.Context) { + id, ok := parseID(c.Param("id")) + if !ok { + c.JSON(http.StatusBadRequest, appresult.ErrMissingParam) + return + } + + if err := h.repository.Delete(c.Request.Context(), id); errors.Is(err, pgx.ErrNoRows) { + c.JSON(http.StatusNotFound, appresult.ErrNotFound) + return + } else if err != nil { + h.logger.Errorf("delete user failed: %v", err) + c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer) + return + } + + c.JSON(http.StatusOK, appresult.SuccessWithData("user removed")) } func parseID(raw string) (int64, bool) { @@ -236,21 +269,39 @@ func parseID(raw string) (int64, bool) { return id, true } -func currentUserID(c *gin.Context) (int, bool) { - rawID, exists := c.Get("id") - if !exists { - return 0, false +const ( + defaultPage = 1 + defaultLimit = 10 + maxLimit = 100 +) + +func parseListFilter(c *gin.Context) (ListFilter, bool) { + filter := ListFilter{ + Page: defaultPage, + Limit: defaultLimit, } - switch id := rawID.(type) { - case int: - return id, id > 0 - case string: - parsed, err := strconv.Atoi(id) - return parsed, err == nil && parsed > 0 - default: - return 0, false + if raw := c.Query("page"); raw != "" { + page, err := strconv.Atoi(raw) + if err != nil || page < 1 { + return ListFilter{}, false + } + filter.Page = page } + + if raw := c.Query("limit"); raw != "" { + limit, err := strconv.Atoi(raw) + if err != nil || limit < 1 || limit > maxLimit { + return ListFilter{}, false + } + filter.Limit = limit + } + + if raw := strings.TrimSpace(c.Query("username")); raw != "" { + filter.Username = raw + } + + return filter, true } // fileUpload godoc diff --git a/internal/admin/user/storage.go b/internal/identity/user/storage.go similarity index 81% rename from internal/admin/user/storage.go rename to internal/identity/user/storage.go index cbadb2b..da355b4 100644 --- a/internal/admin/user/storage.go +++ b/internal/identity/user/storage.go @@ -5,6 +5,7 @@ import "context" type Repository interface { List(ctx context.Context, filter ListFilter) (ListUserDTO, error) GetByID(ctx context.Context, id int64) (UserDTO, error) + GetByRole(ctx context.Context, role string, filter ListFilter) (ListUserDTO, error) Create(ctx context.Context, dto CreateUserDTO) (UserDTO, error) Update(ctx context.Context, id int64, dto UpdateUserDTO) (UserDTO, error) Delete(ctx context.Context, id int64) error diff --git a/internal/identity/userbranch/db/postgresql.go b/internal/identity/userbranch/db/postgresql.go new file mode 100644 index 0000000..cc61b96 --- /dev/null +++ b/internal/identity/userbranch/db/postgresql.go @@ -0,0 +1,140 @@ +package db + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "strings" + + "online-back/internal/identity/userbranch" + "online-back/pkg/client/postgresql" + "online-back/pkg/logging" + + "github.com/jackc/pgx/v4" +) + +type repository struct { + client postgresql.Client + logger *logging.Logger +} + +func NewRepository(client postgresql.Client, logger *logging.Logger) userbranch.Repository { + return &repository{client: client, logger: logger} +} + +const userBranchFromClause = ` FROM branch_user bu + JOIN branches b ON b.id = bu.branch_id + JOIN users u ON u.id = bu.user_id` + +const userBranchSelectColumns = `bu.id, bu.branch_id, b.name, bu.user_id, u.name, bu.created_at, bu.updated_at` + +func (r *repository) List(ctx context.Context, filter userbranch.ListFilter) (userbranch.ListUserBranchDTO, error) { + whereClause, args := buildListQuery(filter) + + var count int64 + if err := r.client.QueryRow(ctx, `SELECT COUNT(*)`+userBranchFromClause+whereClause, args...).Scan(&count); err != nil { + return userbranch.ListUserBranchDTO{}, err + } + + query := `SELECT ` + userBranchSelectColumns + userBranchFromClause + whereClause + ` ORDER BY bu.id DESC` + rows, err := r.client.Query(ctx, query, args...) + if err != nil { + return userbranch.ListUserBranchDTO{}, err + } + defer rows.Close() + + var items []userbranch.UserBranchDTO + for rows.Next() { + item, err := scanUserBranch(rows) + if err != nil { + return userbranch.ListUserBranchDTO{}, err + } + items = append(items, item) + } + if err := rows.Err(); err != nil { + return userbranch.ListUserBranchDTO{}, err + } + + return userbranch.ListUserBranchDTO{Count: count, Items: items}, nil +} + +func buildListQuery(filter userbranch.ListFilter) (whereClause string, args []interface{}) { + var conditions []string + + if filter.UserId != nil { + args = append(args, *filter.UserId) + conditions = append(conditions, fmt.Sprintf("bu.user_id = $%d", len(args))) + } + + if filter.BranchName != "" { + args = append(args, likePattern(filter.BranchName)) + n := len(args) + conditions = append(conditions, fmt.Sprintf(`( + b.name->>'en' ILIKE $%[1]d OR b.name->>'ru' ILIKE $%[1]d OR b.name->>'tm' ILIKE $%[1]d + )`, n)) + } + + if len(conditions) == 0 { + return "", args + } + + return " WHERE " + strings.Join(conditions, " AND "), args +} + +func likePattern(term string) string { + term = strings.ReplaceAll(term, `\`, `\\`) + term = strings.ReplaceAll(term, `%`, `\%`) + term = strings.ReplaceAll(term, `_`, `\_`) + return "%" + term + "%" +} + +func (r *repository) Create(ctx context.Context, dto userbranch.CreateUserBranchDTO) (userbranch.UserBranchDTO, error) { + query := ` + WITH inserted AS ( + INSERT INTO branch_user (branch_id, user_id) + VALUES ($1, $2) + RETURNING id, branch_id, user_id, created_at, updated_at + ) + SELECT inserted.id, inserted.branch_id, b.name, inserted.user_id, u.name, inserted.created_at, inserted.updated_at + FROM inserted + JOIN branches b ON b.id = inserted.branch_id + JOIN users u ON u.id = inserted.user_id` + + row := r.client.QueryRow(ctx, query, dto.BranchId, dto.UserId) + return scanUserBranch(row) +} + +func (r *repository) Delete(ctx context.Context, id int64) error { + tag, err := r.client.Exec(ctx, `DELETE FROM branch_user WHERE id = $1`, id) + if err != nil { + return err + } + if tag.RowsAffected() == 0 { + return pgx.ErrNoRows + } + return nil +} + +type scannable interface { + Scan(dest ...interface{}) error +} + +func scanUserBranch(row scannable) (userbranch.UserBranchDTO, error) { + var item userbranch.UserBranchDTO + var branchNameJSON []byte + + err := row.Scan( + &item.Id, &item.BranchId, &branchNameJSON, &item.UserId, &item.UserName, &item.CreatedAt, &item.UpdatedAt, + ) + if errors.Is(err, pgx.ErrNoRows) { + return userbranch.UserBranchDTO{}, err + } + if err != nil { + return userbranch.UserBranchDTO{}, err + } + if err := json.Unmarshal(branchNameJSON, &item.BranchName); err != nil { + return userbranch.UserBranchDTO{}, err + } + return item, nil +} diff --git a/internal/identity/userbranch/dto.go b/internal/identity/userbranch/dto.go new file mode 100644 index 0000000..b3e6abc --- /dev/null +++ b/internal/identity/userbranch/dto.go @@ -0,0 +1,34 @@ +package userbranch + +import "time" + +type LocalizedText struct { + En string `json:"en"` + Ru string `json:"ru"` + Tm string `json:"tm"` +} + +type UserBranchDTO struct { + Id int64 `json:"id"` + UserId int64 `json:"userId"` + UserName string `json:"userName"` + BranchId int64 `json:"branchId"` + BranchName LocalizedText `json:"branchName"` + CreatedAt time.Time `json:"createdAt"` + UpdatedAt time.Time `json:"updatedAt"` +} + +type ListUserBranchDTO struct { + Count int64 `json:"count"` + Items []UserBranchDTO `json:"items"` +} + +type ListFilter struct { + UserId *int64 + BranchName string +} + +type CreateUserBranchDTO struct { + BranchId int64 `json:"branchId" binding:"required"` + UserId int64 `json:"userId" binding:"required"` +} diff --git a/internal/identity/userbranch/handler.go b/internal/identity/userbranch/handler.go new file mode 100644 index 0000000..1916db7 --- /dev/null +++ b/internal/identity/userbranch/handler.go @@ -0,0 +1,152 @@ +package userbranch + +import ( + "errors" + "net/http" + "strconv" + "strings" + + "online-back/internal/appresult" + "online-back/internal/handlers" + "online-back/pkg/logging" + + "github.com/gin-gonic/gin" + "github.com/jackc/pgx/v4" +) + +const baseURL = "/branch-users" + +type handler struct { + logger *logging.Logger + repository Repository +} + +func NewHandler(logger *logging.Logger, repository Repository) handlers.Handler { + return &handler{logger: logger, repository: repository} +} + +func (h *handler) Register(router *gin.RouterGroup) { + group := router.Group(baseURL, appresult.JwtTokenCheck()) + group.GET("", h.list) + group.POST("", h.create) + group.DELETE("/:id", h.delete) +} + +// list godoc +// @Summary List branch users +// @Description Returns the authenticated user's branch-user assignments with the related user and branch +// @Tags branch-users +// @Produce json +// @Security BearerAuth +// @Param branch_name query string false "Filter by branch name (en, ru, tm)" +// @Success 200 {object} appresult.AppSuccess +// @Failure 401 {object} appresult.AppError +// @Failure 500 {object} appresult.AppError +// @Router /branch-users [get] +func (h *handler) list(c *gin.Context) { + userID, ok := currentUserID(c) + if !ok { + c.JSON(http.StatusUnauthorized, appresult.ErrUnauthorized) + return + } + + filter := ListFilter{ + UserId: &userID, + BranchName: strings.TrimSpace(c.Query("branch_name")), + } + + result, err := h.repository.List(c.Request.Context(), filter) + if err != nil { + h.logger.Errorf("list branch users failed: %v", err) + c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer) + return + } + + c.JSON(http.StatusOK, appresult.SuccessWithData(result)) +} + +// create godoc +// @Summary Assign user to branch +// @Description Creates a branch-user assignment +// @Tags branch-users +// @Accept json +// @Produce json +// @Security BearerAuth +// @Param body body CreateUserBranchDTO true "Branch-user payload" +// @Success 201 {object} appresult.AppSuccess +// @Failure 400 {object} appresult.AppError +// @Failure 500 {object} appresult.AppError +// @Router /branch-users [post] +func (h *handler) create(c *gin.Context) { + var dto CreateUserBranchDTO + if err := c.ShouldBindJSON(&dto); err != nil { + c.JSON(http.StatusBadRequest, appresult.ErrMissingParam) + return + } + + item, err := h.repository.Create(c.Request.Context(), dto) + if err != nil { + h.logger.Errorf("create branch user failed: %v", err) + c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer) + return + } + + c.JSON(http.StatusCreated, appresult.SuccessWithData(item)) +} + +// delete godoc +// @Summary Remove user from branch +// @Description Deletes a branch-user assignment +// @Tags branch-users +// @Produce json +// @Security BearerAuth +// @Param id path int true "Branch-user ID" +// @Success 200 {object} appresult.AppSuccess +// @Failure 400 {object} appresult.AppError +// @Failure 404 {object} appresult.AppError +// @Failure 500 {object} appresult.AppError +// @Router /branch-users/{id} [delete] +func (h *handler) delete(c *gin.Context) { + id, ok := parseID(c.Param("id")) + if !ok { + c.JSON(http.StatusBadRequest, appresult.ErrMissingParam) + return + } + + if err := h.repository.Delete(c.Request.Context(), id); errors.Is(err, pgx.ErrNoRows) { + c.JSON(http.StatusNotFound, appresult.ErrNotFound) + return + } else if err != nil { + h.logger.Errorf("delete branch user failed: %v", err) + c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer) + return + } + + c.JSON(http.StatusOK, appresult.SuccessWithData("branch user removed")) +} + +func parseID(raw string) (int64, bool) { + id, err := strconv.ParseInt(raw, 10, 64) + if err != nil || id <= 0 { + return 0, false + } + return id, true +} + +func currentUserID(c *gin.Context) (int64, bool) { + rawID, exists := c.Get("id") + if !exists { + return 0, false + } + + switch id := rawID.(type) { + case int64: + return id, id > 0 + case int: + return int64(id), id > 0 + case string: + return parseID(id) + default: + return 0, false + } +} diff --git a/internal/identity/userbranch/storage.go b/internal/identity/userbranch/storage.go new file mode 100644 index 0000000..9922453 --- /dev/null +++ b/internal/identity/userbranch/storage.go @@ -0,0 +1,9 @@ +package userbranch + +import "context" + +type Repository interface { + List(ctx context.Context, filter ListFilter) (ListUserBranchDTO, error) + Create(ctx context.Context, dto CreateUserBranchDTO) (UserBranchDTO, error) + Delete(ctx context.Context, id int64) error +} diff --git a/internal/admin/loanorders/db/postgresql.go b/internal/lending/loanorders/db/postgresql.go similarity index 85% rename from internal/admin/loanorders/db/postgresql.go rename to internal/lending/loanorders/db/postgresql.go index 270214b..10b3c72 100644 --- a/internal/admin/loanorders/db/postgresql.go +++ b/internal/lending/loanorders/db/postgresql.go @@ -5,20 +5,24 @@ import ( "fmt" "strings" - "online-back/internal/admin/loanorders" + "online-back/internal/lending/loanorders" "online-back/pkg/client/postgresql" "online-back/pkg/logging" - - "github.com/jackc/pgx/v4" + "online-back/pkg/repository/genericrepo" ) type repository struct { - client postgresql.Client - logger *logging.Logger + client postgresql.Client + generic *genericrepo.Repository[loanorders.LoanOrderDTO] + logger *logging.Logger } func NewRepository(client postgresql.Client, logger *logging.Logger) loanorders.Repository { - return &repository{client: client, logger: logger} + return &repository{ + client: client, + generic: genericrepo.New(client, "loan_orders", loanOrderColumnsSQL, scanLoanOrder), + logger: logger, + } } // loanOrderWritableColumns lists every loan_orders column except id, created_at and @@ -95,37 +99,10 @@ func updateArgs(dto loanorders.UpdateLoanOrderDTO) []interface{} { func (r *repository) List(ctx context.Context, filter loanorders.ListFilter) (loanorders.ListLoanOrderDTO, error) { whereClause, args := buildListQuery(filter) - var count int64 - countQuery := `SELECT COUNT(*) FROM loan_orders` + whereClause - if err := r.client.QueryRow(ctx, countQuery, args...).Scan(&count); err != nil { - return loanorders.ListLoanOrderDTO{}, err - } - - offset := (filter.Page - 1) * filter.Limit - limitPlaceholder := len(args) + 1 - offsetPlaceholder := len(args) + 2 - listQuery := fmt.Sprintf( - `SELECT %s FROM loan_orders%s ORDER BY id DESC LIMIT $%d OFFSET $%d`, - loanOrderColumnsSQL, whereClause, limitPlaceholder, offsetPlaceholder, - ) - - rows, err := r.client.Query(ctx, listQuery, append(args, filter.Limit, offset)...) + items, count, err := r.generic.List(ctx, whereClause, args, filter.Page, filter.Limit, "id DESC") if err != nil { return loanorders.ListLoanOrderDTO{}, err } - defer rows.Close() - - var items []loanorders.LoanOrderDTO - for rows.Next() { - item, err := scanLoanOrder(rows) - if err != nil { - return loanorders.ListLoanOrderDTO{}, err - } - items = append(items, item) - } - if err := rows.Err(); err != nil { - return loanorders.ListLoanOrderDTO{}, err - } return loanorders.ListLoanOrderDTO{Count: count, LoanOrders: items}, nil } @@ -161,12 +138,7 @@ func buildListQuery(filter loanorders.ListFilter) (whereClause string, args []in } func (r *repository) GetByID(ctx context.Context, id int64) (loanorders.LoanOrderDTO, error) { - query := fmt.Sprintf(`SELECT %s FROM loan_orders WHERE id = $1`, loanOrderColumnsSQL) - item, err := scanLoanOrder(r.client.QueryRow(ctx, query, id)) - if err != nil { - return loanorders.LoanOrderDTO{}, err - } - return item, nil + return r.generic.GetByID(ctx, id) } // nextUniqueIDSQL computes unique_id as the last value stored in loan_orders plus @@ -213,21 +185,10 @@ func (r *repository) Update(ctx context.Context, id int64, dto loanorders.Update } func (r *repository) Delete(ctx context.Context, id int64) error { - tag, err := r.client.Exec(ctx, `DELETE FROM loan_orders WHERE id = $1`, id) - if err != nil { - return err - } - if tag.RowsAffected() == 0 { - return pgx.ErrNoRows - } - return nil + return r.generic.Delete(ctx, id) } -type scannable interface { - Scan(dest ...interface{}) error -} - -func scanLoanOrder(row scannable) (loanorders.LoanOrderDTO, error) { +func scanLoanOrder(row genericrepo.Scanner) (loanorders.LoanOrderDTO, error) { var item loanorders.LoanOrderDTO err := row.Scan( &item.Id, &item.UniqueId, &item.Source, &item.UserId, &item.LoanType, &item.Region, &item.BranchId, diff --git a/internal/admin/loanorders/dto.go b/internal/lending/loanorders/dto.go similarity index 100% rename from internal/admin/loanorders/dto.go rename to internal/lending/loanorders/dto.go diff --git a/internal/admin/loanorders/handler.go b/internal/lending/loanorders/handler.go similarity index 100% rename from internal/admin/loanorders/handler.go rename to internal/lending/loanorders/handler.go diff --git a/internal/admin/loanorders/storage.go b/internal/lending/loanorders/storage.go similarity index 100% rename from internal/admin/loanorders/storage.go rename to internal/lending/loanorders/storage.go diff --git a/internal/admin/loanpaidletter/db/postgresql.go b/internal/lending/loanpaidletter/db/postgresql.go similarity index 75% rename from internal/admin/loanpaidletter/db/postgresql.go rename to internal/lending/loanpaidletter/db/postgresql.go index 8034295..41e19d9 100644 --- a/internal/admin/loanpaidletter/db/postgresql.go +++ b/internal/lending/loanpaidletter/db/postgresql.go @@ -5,20 +5,24 @@ import ( "fmt" "strings" - "online-back/internal/admin/loanpaidletter" + "online-back/internal/lending/loanpaidletter" "online-back/pkg/client/postgresql" "online-back/pkg/logging" - - "github.com/jackc/pgx/v4" + "online-back/pkg/repository/genericrepo" ) type repository struct { - client postgresql.Client - logger *logging.Logger + client postgresql.Client + generic *genericrepo.Repository[loanpaidletter.LoanPaidLetterDTO] + logger *logging.Logger } func NewRepository(client postgresql.Client, logger *logging.Logger) loanpaidletter.Repository { - return &repository{client: client, logger: logger} + return &repository{ + client: client, + generic: genericrepo.New(client, "loan_paid_off_letters", letterColumnsSQL, scanLoanPaidLetter), + logger: logger, + } } // letterWritableColumns lists every loan_paid_off_letters column except id, created_at @@ -60,37 +64,10 @@ func updateArgs(dto loanpaidletter.UpdateLoanPaidLetterDTO) []interface{} { func (r *repository) List(ctx context.Context, filter loanpaidletter.ListFilter) (loanpaidletter.ListLoanPaidLetterDTO, error) { whereClause, args := buildListQuery(filter) - var count int64 - countQuery := `SELECT COUNT(*) FROM loan_paid_off_letters` + whereClause - if err := r.client.QueryRow(ctx, countQuery, args...).Scan(&count); err != nil { - return loanpaidletter.ListLoanPaidLetterDTO{}, err - } - - offset := (filter.Page - 1) * filter.Limit - limitPlaceholder := len(args) + 1 - offsetPlaceholder := len(args) + 2 - listQuery := fmt.Sprintf( - `SELECT %s FROM loan_paid_off_letters%s ORDER BY id DESC LIMIT $%d OFFSET $%d`, - letterColumnsSQL, whereClause, limitPlaceholder, offsetPlaceholder, - ) - - rows, err := r.client.Query(ctx, listQuery, append(args, filter.Limit, offset)...) + items, count, err := r.generic.List(ctx, whereClause, args, filter.Page, filter.Limit, "id DESC") if err != nil { return loanpaidletter.ListLoanPaidLetterDTO{}, err } - defer rows.Close() - - var items []loanpaidletter.LoanPaidLetterDTO - for rows.Next() { - item, err := scanLoanPaidLetter(rows) - if err != nil { - return loanpaidletter.ListLoanPaidLetterDTO{}, err - } - items = append(items, item) - } - if err := rows.Err(); err != nil { - return loanpaidletter.ListLoanPaidLetterDTO{}, err - } return loanpaidletter.ListLoanPaidLetterDTO{Count: count, LoanPaidLetters: items}, nil } @@ -133,12 +110,7 @@ func likePattern(term string) string { } func (r *repository) GetByID(ctx context.Context, id int64) (loanpaidletter.LoanPaidLetterDTO, error) { - query := fmt.Sprintf(`SELECT %s FROM loan_paid_off_letters WHERE id = $1`, letterColumnsSQL) - item, err := scanLoanPaidLetter(r.client.QueryRow(ctx, query, id)) - if err != nil { - return loanpaidletter.LoanPaidLetterDTO{}, err - } - return item, nil + return r.generic.GetByID(ctx, id) } func (r *repository) Create(ctx context.Context, dto loanpaidletter.CreateLoanPaidLetterDTO) (loanpaidletter.LoanPaidLetterDTO, error) { @@ -179,21 +151,10 @@ func (r *repository) Update(ctx context.Context, id int64, dto loanpaidletter.Up } func (r *repository) Delete(ctx context.Context, id int64) error { - tag, err := r.client.Exec(ctx, `DELETE FROM loan_paid_off_letters WHERE id = $1`, id) - if err != nil { - return err - } - if tag.RowsAffected() == 0 { - return pgx.ErrNoRows - } - return nil + return r.generic.Delete(ctx, id) } -type scannable interface { - Scan(dest ...interface{}) error -} - -func scanLoanPaidLetter(row scannable) (loanpaidletter.LoanPaidLetterDTO, error) { +func scanLoanPaidLetter(row genericrepo.Scanner) (loanpaidletter.LoanPaidLetterDTO, error) { var item loanpaidletter.LoanPaidLetterDTO err := row.Scan( &item.Id, &item.UniqueId, &item.Region, &item.BranchId, &item.UserId, diff --git a/internal/admin/loanpaidletter/dto.go b/internal/lending/loanpaidletter/dto.go similarity index 100% rename from internal/admin/loanpaidletter/dto.go rename to internal/lending/loanpaidletter/dto.go diff --git a/internal/admin/loanpaidletter/handler.go b/internal/lending/loanpaidletter/handler.go similarity index 100% rename from internal/admin/loanpaidletter/handler.go rename to internal/lending/loanpaidletter/handler.go diff --git a/internal/admin/loanpaidletter/storage.go b/internal/lending/loanpaidletter/storage.go similarity index 100% rename from internal/admin/loanpaidletter/storage.go rename to internal/lending/loanpaidletter/storage.go diff --git a/internal/admin/loansdocument/db/postgresql.go b/internal/lending/loansdocument/db/postgresql.go similarity index 62% rename from internal/admin/loansdocument/db/postgresql.go rename to internal/lending/loansdocument/db/postgresql.go index 85146bb..de2a937 100644 --- a/internal/admin/loansdocument/db/postgresql.go +++ b/internal/lending/loansdocument/db/postgresql.go @@ -6,20 +6,26 @@ import ( "fmt" "strings" - "online-back/internal/admin/loansdocument" + "online-back/internal/lending/loansdocument" "online-back/pkg/client/postgresql" "online-back/pkg/logging" + "online-back/pkg/repository/genericrepo" "github.com/jackc/pgx/v4" ) type repository struct { - client postgresql.Client - logger *logging.Logger + client postgresql.Client + generic *genericrepo.Repository[loansdocument.LoanDocumentDTO] + logger *logging.Logger } func NewRepository(client postgresql.Client, logger *logging.Logger) loansdocument.Repository { - return &repository{client: client, logger: logger} + return &repository{ + client: client, + generic: genericrepo.New(client, "loan_order_required_docs d", documentColumns, scanLoanDocument), + logger: logger, + } } const documentColumns = `d.id, d.name, d.value, d.active, d.created_at, d.updated_at` @@ -27,45 +33,17 @@ const documentColumns = `d.id, d.name, d.value, d.active, d.created_at, d.update const documentReturningColumns = `id, name, value, active, created_at, updated_at` func (r *repository) List(ctx context.Context, filter loansdocument.ListFilter) (loansdocument.ListLoanDocumentDTO, error) { - fromClause, whereClause, args := buildListQuery(filter) + whereClause, args := buildListQuery(filter) - var count int64 - if err := r.client.QueryRow(ctx, `SELECT COUNT(*) `+fromClause+whereClause, args...).Scan(&count); err != nil { - return loansdocument.ListLoanDocumentDTO{}, err - } - - offset := (filter.Page - 1) * filter.Limit - limitPlaceholder := len(args) + 1 - offsetPlaceholder := len(args) + 2 - listQuery := fmt.Sprintf( - `SELECT %s%s%s ORDER BY d.id LIMIT $%d OFFSET $%d`, - documentColumns, fromClause, whereClause, limitPlaceholder, offsetPlaceholder, - ) - - rows, err := r.client.Query(ctx, listQuery, append(args, filter.Limit, offset)...) + items, count, err := r.generic.List(ctx, whereClause, args, filter.Page, filter.Limit, "id") if err != nil { return loansdocument.ListLoanDocumentDTO{}, err } - defer rows.Close() - - var items []loansdocument.LoanDocumentDTO - for rows.Next() { - item, err := scanLoanDocument(rows) - if err != nil { - return loansdocument.ListLoanDocumentDTO{}, err - } - items = append(items, item) - } - if err := rows.Err(); err != nil { - return loansdocument.ListLoanDocumentDTO{}, err - } return loansdocument.ListLoanDocumentDTO{Count: count, LoansDocuments: items}, nil } -func buildListQuery(filter loansdocument.ListFilter) (fromClause, whereClause string, args []interface{}) { - fromClause = ` FROM loan_order_required_docs d` - +func buildListQuery(filter loansdocument.ListFilter) (whereClause string, args []interface{}) { var conditions []string if filter.DocumentName != "" { @@ -80,10 +58,10 @@ func buildListQuery(filter loansdocument.ListFilter) (fromClause, whereClause st } if len(conditions) == 0 { - return fromClause, "", args + return "", args } - return fromClause, " WHERE " + strings.Join(conditions, " AND "), args + return " WHERE " + strings.Join(conditions, " AND "), args } func likePattern(term string) string { @@ -94,12 +72,7 @@ func likePattern(term string) string { } func (r *repository) GetByID(ctx context.Context, id int64) (loansdocument.LoanDocumentDTO, error) { - query := fmt.Sprintf(`SELECT %s FROM loan_order_required_docs d WHERE d.id = $1`, documentColumns) - item, err := scanLoanDocument(r.client.QueryRow(ctx, query, id)) - if errors.Is(err, pgx.ErrNoRows) { - return loansdocument.LoanDocumentDTO{}, err - } - return item, err + return r.generic.GetByID(ctx, id) } func (r *repository) Create(ctx context.Context, dto loansdocument.CreateLoanDocumentDTO) (loansdocument.LoanDocumentDTO, error) { @@ -147,21 +120,10 @@ func (r *repository) UpdateActive(ctx context.Context, id int64, active bool) (l } func (r *repository) Delete(ctx context.Context, id int64) error { - tag, err := r.client.Exec(ctx, `DELETE FROM loan_order_required_docs WHERE id = $1`, id) - if err != nil { - return err - } - if tag.RowsAffected() == 0 { - return pgx.ErrNoRows - } - return nil + return r.generic.Delete(ctx, id) } -type scannable interface { - Scan(dest ...interface{}) error -} - -func scanLoanDocument(row scannable) (loansdocument.LoanDocumentDTO, error) { +func scanLoanDocument(row genericrepo.Scanner) (loansdocument.LoanDocumentDTO, error) { var item loansdocument.LoanDocumentDTO if err := row.Scan( diff --git a/internal/admin/loansdocument/dto.go b/internal/lending/loansdocument/dto.go similarity index 100% rename from internal/admin/loansdocument/dto.go rename to internal/lending/loansdocument/dto.go diff --git a/internal/admin/loansdocument/handler.go b/internal/lending/loansdocument/handler.go similarity index 100% rename from internal/admin/loansdocument/handler.go rename to internal/lending/loansdocument/handler.go diff --git a/internal/admin/loansdocument/storage.go b/internal/lending/loansdocument/storage.go similarity index 100% rename from internal/admin/loansdocument/storage.go rename to internal/lending/loansdocument/storage.go diff --git a/internal/admin/loansrepayment/db/postgresql.go b/internal/lending/loansrepayment/db/postgresql.go similarity index 59% rename from internal/admin/loansrepayment/db/postgresql.go rename to internal/lending/loansrepayment/db/postgresql.go index 883a2bc..f0c6b5b 100644 --- a/internal/admin/loansrepayment/db/postgresql.go +++ b/internal/lending/loansrepayment/db/postgresql.go @@ -6,20 +6,26 @@ import ( "fmt" "strings" - "online-back/internal/admin/loansrepayment" + "online-back/internal/lending/loansrepayment" "online-back/pkg/client/postgresql" "online-back/pkg/logging" + "online-back/pkg/repository/genericrepo" "github.com/jackc/pgx/v4" ) type repository struct { - client postgresql.Client - logger *logging.Logger + client postgresql.Client + generic *genericrepo.Repository[loansrepayment.LoanRepaymentDTO] + logger *logging.Logger } func NewRepository(client postgresql.Client, logger *logging.Logger) loansrepayment.Repository { - return &repository{client: client, logger: logger} + return &repository{ + client: client, + generic: genericrepo.New(client, "loans l", loanColumns, scanLoanRepayment), + logger: logger, + } } const loanColumns = `l.id, l.user_id, l.passport_serie, l.passport_id, l.account_number, l.created_at, l.updated_at` @@ -27,45 +33,17 @@ const loanColumns = `l.id, l.user_id, l.passport_serie, l.passport_id, l.account const loanReturningColumns = `id, user_id, passport_serie, passport_id, account_number, created_at, updated_at` func (r *repository) List(ctx context.Context, filter loansrepayment.ListFilter) (loansrepayment.ListLoanRepaymentDTO, error) { - fromClause, whereClause, args := buildListQuery(filter) + whereClause, args := buildListQuery(filter) - var count int64 - if err := r.client.QueryRow(ctx, `SELECT COUNT(*) `+fromClause+whereClause, args...).Scan(&count); err != nil { - return loansrepayment.ListLoanRepaymentDTO{}, err - } - - offset := (filter.Page - 1) * filter.Limit - limitPlaceholder := len(args) + 1 - offsetPlaceholder := len(args) + 2 - listQuery := fmt.Sprintf( - `SELECT %s%s%s ORDER BY l.id LIMIT $%d OFFSET $%d`, - loanColumns, fromClause, whereClause, limitPlaceholder, offsetPlaceholder, - ) - - rows, err := r.client.Query(ctx, listQuery, append(args, filter.Limit, offset)...) + items, count, err := r.generic.List(ctx, whereClause, args, filter.Page, filter.Limit, "id") if err != nil { return loansrepayment.ListLoanRepaymentDTO{}, err } - defer rows.Close() - - var items []loansrepayment.LoanRepaymentDTO - for rows.Next() { - item, err := scanLoanRepayment(rows) - if err != nil { - return loansrepayment.ListLoanRepaymentDTO{}, err - } - items = append(items, item) - } - if err := rows.Err(); err != nil { - return loansrepayment.ListLoanRepaymentDTO{}, err - } return loansrepayment.ListLoanRepaymentDTO{Count: count, Loans: items}, nil } -func buildListQuery(filter loansrepayment.ListFilter) (fromClause, whereClause string, args []interface{}) { - fromClause = ` FROM loans l` - +func buildListQuery(filter loansrepayment.ListFilter) (whereClause string, args []interface{}) { var conditions []string if filter.PassportId != "" { args = append(args, likePattern(filter.PassportId)) @@ -73,10 +51,10 @@ func buildListQuery(filter loansrepayment.ListFilter) (fromClause, whereClause s } if len(conditions) == 0 { - return fromClause, "", args + return "", args } - return fromClause, " WHERE " + strings.Join(conditions, " AND "), args + return " WHERE " + strings.Join(conditions, " AND "), args } func likePattern(term string) string { @@ -87,12 +65,7 @@ func likePattern(term string) string { } func (r *repository) GetByID(ctx context.Context, id int64) (loansrepayment.LoanRepaymentDTO, error) { - query := fmt.Sprintf(`SELECT %s FROM loans l WHERE l.id = $1`, loanColumns) - item, err := scanLoanRepayment(r.client.QueryRow(ctx, query, id)) - if errors.Is(err, pgx.ErrNoRows) { - return loansrepayment.LoanRepaymentDTO{}, err - } - return item, err + return r.generic.GetByID(ctx, id) } func (r *repository) Create(ctx context.Context, dto loansrepayment.CreateLoanRepaymentDTO) (loansrepayment.LoanRepaymentDTO, error) { @@ -120,21 +93,10 @@ func (r *repository) Update(ctx context.Context, id int64, dto loansrepayment.Up } func (r *repository) Delete(ctx context.Context, id int64) error { - tag, err := r.client.Exec(ctx, `DELETE FROM loans WHERE id = $1`, id) - if err != nil { - return err - } - if tag.RowsAffected() == 0 { - return pgx.ErrNoRows - } - return nil + return r.generic.Delete(ctx, id) } -type scannable interface { - Scan(dest ...interface{}) error -} - -func scanLoanRepayment(row scannable) (loansrepayment.LoanRepaymentDTO, error) { +func scanLoanRepayment(row genericrepo.Scanner) (loansrepayment.LoanRepaymentDTO, error) { var item loansrepayment.LoanRepaymentDTO if err := row.Scan( diff --git a/internal/admin/loansrepayment/dto.go b/internal/lending/loansrepayment/dto.go similarity index 100% rename from internal/admin/loansrepayment/dto.go rename to internal/lending/loansrepayment/dto.go diff --git a/internal/admin/loansrepayment/handler.go b/internal/lending/loansrepayment/handler.go similarity index 100% rename from internal/admin/loansrepayment/handler.go rename to internal/lending/loansrepayment/handler.go diff --git a/internal/admin/loansrepayment/storage.go b/internal/lending/loansrepayment/storage.go similarity index 100% rename from internal/admin/loansrepayment/storage.go rename to internal/lending/loansrepayment/storage.go diff --git a/internal/admin/loantype/db/postgresql.go b/internal/lending/loantype/db/postgresql.go similarity index 65% rename from internal/admin/loantype/db/postgresql.go rename to internal/lending/loantype/db/postgresql.go index 15c5e7a..e0448f3 100644 --- a/internal/admin/loantype/db/postgresql.go +++ b/internal/lending/loantype/db/postgresql.go @@ -7,20 +7,26 @@ import ( "fmt" "strings" - "online-back/internal/admin/loantype" + "online-back/internal/lending/loantype" "online-back/pkg/client/postgresql" "online-back/pkg/logging" + "online-back/pkg/repository/genericrepo" "github.com/jackc/pgx/v4" ) type repository struct { - client postgresql.Client - logger *logging.Logger + client postgresql.Client + generic *genericrepo.Repository[loantype.LoanTypeDTO] + logger *logging.Logger } func NewRepository(client postgresql.Client, logger *logging.Logger) loantype.Repository { - return &repository{client: client, logger: logger} + return &repository{ + client: client, + generic: genericrepo.New(client, "loan_types lt", loanTypeColumns, scanLoanType), + logger: logger, + } } const loanTypeColumns = `lt.id, lt.name, lt.tax, lt.maturity, lt.notes, lt.active, lt.created_at, lt.updated_at` @@ -28,45 +34,17 @@ const loanTypeColumns = `lt.id, lt.name, lt.tax, lt.maturity, lt.notes, lt.activ const loanTypeReturningColumns = `id, name, tax, maturity, notes, active, created_at, updated_at` func (r *repository) List(ctx context.Context, filter loantype.ListFilter) (loantype.ListLoanTypeDTO, error) { - fromClause, whereClause, args := buildListQuery(filter) + whereClause, args := buildListQuery(filter) - var count int64 - if err := r.client.QueryRow(ctx, `SELECT COUNT(*) `+fromClause+whereClause, args...).Scan(&count); err != nil { - return loantype.ListLoanTypeDTO{}, err - } - - offset := (filter.Page - 1) * filter.Limit - limitPlaceholder := len(args) + 1 - offsetPlaceholder := len(args) + 2 - listQuery := fmt.Sprintf( - `SELECT %s%s%s ORDER BY lt.id LIMIT $%d OFFSET $%d`, - loanTypeColumns, fromClause, whereClause, limitPlaceholder, offsetPlaceholder, - ) - - rows, err := r.client.Query(ctx, listQuery, append(args, filter.Limit, offset)...) + items, count, err := r.generic.List(ctx, whereClause, args, filter.Page, filter.Limit, "id") if err != nil { return loantype.ListLoanTypeDTO{}, err } - defer rows.Close() - - var items []loantype.LoanTypeDTO - for rows.Next() { - item, err := scanLoanType(rows) - if err != nil { - return loantype.ListLoanTypeDTO{}, err - } - items = append(items, item) - } - if err := rows.Err(); err != nil { - return loantype.ListLoanTypeDTO{}, err - } return loantype.ListLoanTypeDTO{Count: count, LoanTypes: items}, nil } -func buildListQuery(filter loantype.ListFilter) (fromClause, whereClause string, args []interface{}) { - fromClause = ` FROM loan_types lt` - +func buildListQuery(filter loantype.ListFilter) (whereClause string, args []interface{}) { var conditions []string if filter.LoanTypeName != "" { args = append(args, likePattern(filter.LoanTypeName)) @@ -77,10 +55,10 @@ func buildListQuery(filter loantype.ListFilter) (fromClause, whereClause string, } if len(conditions) == 0 { - return fromClause, "", args + return "", args } - return fromClause, " WHERE " + strings.Join(conditions, " AND "), args + return " WHERE " + strings.Join(conditions, " AND "), args } func likePattern(term string) string { @@ -91,12 +69,7 @@ func likePattern(term string) string { } func (r *repository) GetByID(ctx context.Context, id int64) (loantype.LoanTypeDTO, error) { - query := fmt.Sprintf(`SELECT %s FROM loan_types lt WHERE lt.id = $1`, loanTypeColumns) - item, err := scanLoanType(r.client.QueryRow(ctx, query, id)) - if errors.Is(err, pgx.ErrNoRows) { - return loantype.LoanTypeDTO{}, err - } - return item, err + return r.generic.GetByID(ctx, id) } func (r *repository) Create(ctx context.Context, dto loantype.CreateLoanTypeDTO) (loantype.LoanTypeDTO, error) { @@ -139,14 +112,7 @@ func (r *repository) Update(ctx context.Context, id int64, dto loantype.UpdateLo } func (r *repository) Delete(ctx context.Context, id int64) error { - tag, err := r.client.Exec(ctx, `DELETE FROM loan_types WHERE id = $1`, id) - if err != nil { - return err - } - if tag.RowsAffected() == 0 { - return pgx.ErrNoRows - } - return nil + return r.generic.Delete(ctx, id) } func marshalJSON(title, content loantype.LocalizedTitle) ([]byte, []byte, error) { @@ -161,11 +127,7 @@ func marshalJSON(title, content loantype.LocalizedTitle) ([]byte, []byte, error) return titleJSON, contentJSON, nil } -type scannable interface { - Scan(dest ...interface{}) error -} - -func scanLoanType(row scannable) (loantype.LoanTypeDTO, error) { +func scanLoanType(row genericrepo.Scanner) (loantype.LoanTypeDTO, error) { var item loantype.LoanTypeDTO var nameJSON, notesJSON []byte diff --git a/internal/admin/loantype/dto.go b/internal/lending/loantype/dto.go similarity index 100% rename from internal/admin/loantype/dto.go rename to internal/lending/loantype/dto.go diff --git a/internal/admin/loantype/handler.go b/internal/lending/loantype/handler.go similarity index 100% rename from internal/admin/loantype/handler.go rename to internal/lending/loantype/handler.go diff --git a/internal/admin/loantype/storage.go b/internal/lending/loantype/storage.go similarity index 100% rename from internal/admin/loantype/storage.go rename to internal/lending/loantype/storage.go diff --git a/internal/lending/router.go b/internal/lending/router.go new file mode 100644 index 0000000..a178b5b --- /dev/null +++ b/internal/lending/router.go @@ -0,0 +1,39 @@ +// Package lending groups loan orders and their related documents, +// repayments, types, and paid-off letters under one bounded context, +// replacing the flat internal/admin/* listing. +package lending + +import ( + "online-back/internal/handlers" + "online-back/internal/lending/loanorders" + loanordersdb "online-back/internal/lending/loanorders/db" + "online-back/internal/lending/loanpaidletter" + loanpaidletterdb "online-back/internal/lending/loanpaidletter/db" + "online-back/internal/lending/loansdocument" + loansdocumentdb "online-back/internal/lending/loansdocument/db" + "online-back/internal/lending/loansrepayment" + loansrepaymentdb "online-back/internal/lending/loansrepayment/db" + "online-back/internal/lending/loantype" + loantypedb "online-back/internal/lending/loantype/db" + "online-back/pkg/client/postgresql" + "online-back/pkg/logging" + + "github.com/gin-gonic/gin" +) + +// Register wires every lending module's handler into router. +func Register(router *gin.RouterGroup, client postgresql.Client, logger *logging.Logger) { + for _, h := range Handlers(client, logger) { + h.Register(router) + } +} + +func Handlers(client postgresql.Client, logger *logging.Logger) []handlers.Handler { + return []handlers.Handler{ + loantype.NewHandler(logger, loantypedb.NewRepository(client, logger)), + loansdocument.NewHandler(logger, loansdocumentdb.NewRepository(client, logger)), + loansrepayment.NewHandler(logger, loansrepaymentdb.NewRepository(client, logger)), + loanorders.NewHandler(logger, loanordersdb.NewRepository(client, logger)), + loanpaidletter.NewHandler(logger, loanpaidletterdb.NewRepository(client, logger)), + } +} diff --git a/internal/admin/branches/db/postgresql.go b/internal/org/branches/db/postgresql.go similarity index 87% rename from internal/admin/branches/db/postgresql.go rename to internal/org/branches/db/postgresql.go index c7164f3..af7341c 100644 --- a/internal/admin/branches/db/postgresql.go +++ b/internal/org/branches/db/postgresql.go @@ -7,21 +7,27 @@ import ( "fmt" "strings" - "online-back/internal/admin/branches" + "online-back/internal/org/branches" "online-back/pkg/client/postgresql" "online-back/pkg/logging" + "online-back/pkg/repository/genericrepo" "github.com/jackc/pgconn" "github.com/jackc/pgx/v4" ) type repository struct { - client postgresql.Client - logger *logging.Logger + client postgresql.Client + generic *genericrepo.Repository[branches.BranchDTO] + logger *logging.Logger } func NewRepository(client postgresql.Client, logger *logging.Logger) branches.Repository { - return &repository{client: client, logger: logger} + return &repository{ + client: client, + generic: genericrepo.New(client, "branches", branchSelectColumns, scanBranch), + logger: logger, + } } const branchFromClause = ` FROM branches b @@ -148,7 +154,7 @@ func (r *repository) Create(ctx context.Context, dto branches.CreateBranchDTO) ( return branches.BranchDTO{}, err } - name, address, phoneNumbers, err := marshalBranchJSON(dto.Name, dto.Address, dto.PhoneNumbers) + name, address, err := marshalBranchJSON(dto.Name, dto.Address) if err != nil { return branches.BranchDTO{}, err } @@ -173,7 +179,7 @@ func (r *repository) Create(ctx context.Context, dto branches.CreateBranchDTO) ( LEFT JOIN provinces p ON p.id = i.province_id` row := r.client.QueryRow(ctx, query, - nullIfEmpty(dto.UniqueCode), name, address, dto.Region, dto.ProvinceId, phoneNumbers, + nullIfEmpty(dto.UniqueCode), name, address, dto.Region, dto.ProvinceId, dto.PhoneNumbers, dto.BillingUsername, dto.BillingPassword, dto.BillingSberUsername, dto.BillingSberPassword, dto.BillingVisaMasterUsername, dto.BillingVisaMasterPassword, dto.BillingSwiftUsername, dto.BillingSwiftPassword, active, @@ -190,7 +196,7 @@ func (r *repository) Update(ctx context.Context, id int64, dto branches.UpdateBr return branches.BranchDTO{}, err } - name, address, phoneNumbers, err := marshalBranchJSON(dto.Name, dto.Address, dto.PhoneNumbers) + name, address, err := marshalBranchJSON(dto.Name, dto.Address) if err != nil { return branches.BranchDTO{}, err } @@ -211,7 +217,7 @@ func (r *repository) Update(ctx context.Context, id int64, dto branches.UpdateBr LEFT JOIN provinces p ON p.id = u.province_id` row := r.client.QueryRow(ctx, query, - nullIfEmpty(dto.UniqueCode), name, address, dto.Region, dto.ProvinceId, phoneNumbers, + nullIfEmpty(dto.UniqueCode), name, address, dto.Region, dto.ProvinceId, dto.PhoneNumbers, dto.BillingUsername, dto.BillingPassword, dto.BillingSberUsername, dto.BillingSberPassword, dto.BillingVisaMasterUsername, dto.BillingVisaMasterPassword, dto.BillingSwiftUsername, dto.BillingSwiftPassword, dto.Active, id, @@ -227,14 +233,7 @@ func (r *repository) Update(ctx context.Context, id int64, dto branches.UpdateBr } func (r *repository) Delete(ctx context.Context, id int64) error { - tag, err := r.client.Exec(ctx, `DELETE FROM branches WHERE id = $1`, id) - if err != nil { - return err - } - if tag.RowsAffected() == 0 { - return pgx.ErrNoRows - } - return nil + return r.generic.Delete(ctx, id) } func (r *repository) ensureProvince(ctx context.Context, provinceID *int64) error { @@ -251,23 +250,16 @@ func (r *repository) ensureProvince(ctx context.Context, provinceID *int64) erro return err } -func marshalBranchJSON(name, address branches.LocalizedText, phoneNumbers []string) ([]byte, []byte, []byte, error) { +func marshalBranchJSON(name, address branches.LocalizedText) ([]byte, []byte, error) { nameJSON, err := json.Marshal(name) if err != nil { - return nil, nil, nil, err + return nil, nil, err } addressJSON, err := json.Marshal(address) if err != nil { - return nil, nil, nil, err + return nil, nil, err } - if phoneNumbers == nil { - phoneNumbers = []string{} - } - phoneNumbersJSON, err := json.Marshal(phoneNumbers) - if err != nil { - return nil, nil, nil, err - } - return nameJSON, addressJSON, phoneNumbersJSON, nil + return nameJSON, addressJSON, nil } func nullIfEmpty(value string) interface{} { @@ -282,18 +274,14 @@ func isUniqueViolation(err error) bool { return errors.As(err, &pgErr) && pgErr.Code == "23505" } -type scannable interface { - Scan(dest ...interface{}) error -} - -func scanBranch(row scannable) (branches.BranchDTO, error) { +func scanBranch(row genericrepo.Scanner) (branches.BranchDTO, error) { var item branches.BranchDTO - var nameJSON, addressJSON, provinceNameJSON, phoneNumbersJSON []byte + var nameJSON, addressJSON, provinceNameJSON []byte var uniqueCode *string err := row.Scan( &item.Id, &uniqueCode, &nameJSON, &addressJSON, &item.Region, &item.ProvinceId, &provinceNameJSON, - &phoneNumbersJSON, + &item.PhoneNumbers, &item.BillingUsername, &item.BillingPassword, &item.BillingSberUsername, &item.BillingSberPassword, &item.BillingVisaMasterUsername, &item.BillingVisaMasterPassword, @@ -316,11 +304,5 @@ func scanBranch(row scannable) (branches.BranchDTO, error) { return branches.BranchDTO{}, err } } - if err := json.Unmarshal(phoneNumbersJSON, &item.PhoneNumbers); err != nil { - return branches.BranchDTO{}, err - } - if item.PhoneNumbers == nil { - item.PhoneNumbers = []string{} - } return item, nil } diff --git a/internal/admin/branches/dto.go b/internal/org/branches/dto.go similarity index 94% rename from internal/admin/branches/dto.go rename to internal/org/branches/dto.go index 283f1b5..fe10a71 100644 --- a/internal/admin/branches/dto.go +++ b/internal/org/branches/dto.go @@ -14,7 +14,7 @@ type BranchDTO struct { Region string `json:"region"` ProvinceId *int64 `json:"provinceId"` ProvinceName LocalizedText `json:"provinceName"` - PhoneNumbers []string `json:"phoneNumbers"` + PhoneNumbers string `json:"phoneNumbers"` BillingUsername string `json:"billingUsername"` BillingPassword string `json:"billingPassword"` BillingSberUsername string `json:"billingSberUsername"` @@ -32,7 +32,7 @@ type CreateBranchDTO struct { Address LocalizedText `json:"address" binding:"required"` Region string `json:"region" binding:"required"` ProvinceId *int64 `json:"provinceId"` - PhoneNumbers []string `json:"phoneNumbers"` + PhoneNumbers string `json:"phoneNumbers"` BillingUsername string `json:"billingUsername"` BillingPassword string `json:"billingPassword"` BillingSberUsername string `json:"billingSberUsername"` @@ -50,7 +50,7 @@ type UpdateBranchDTO struct { Address LocalizedText `json:"address" binding:"required"` Region string `json:"region" binding:"required"` ProvinceId *int64 `json:"provinceId"` - PhoneNumbers []string `json:"phoneNumbers"` + PhoneNumbers string `json:"phoneNumbers"` BillingUsername string `json:"billingUsername"` BillingPassword string `json:"billingPassword"` BillingSberUsername string `json:"billingSberUsername"` diff --git a/internal/admin/branches/handler.go b/internal/org/branches/handler.go similarity index 100% rename from internal/admin/branches/handler.go rename to internal/org/branches/handler.go diff --git a/internal/admin/branches/storage.go b/internal/org/branches/storage.go similarity index 100% rename from internal/admin/branches/storage.go rename to internal/org/branches/storage.go diff --git a/internal/admin/province/db/postgresql.go b/internal/org/province/db/postgresql.go similarity index 54% rename from internal/admin/province/db/postgresql.go rename to internal/org/province/db/postgresql.go index 07436c2..60b4ad0 100644 --- a/internal/admin/province/db/postgresql.go +++ b/internal/org/province/db/postgresql.go @@ -4,51 +4,84 @@ import ( "context" "encoding/json" "errors" + "fmt" + "strings" - "online-back/internal/admin/province" + "online-back/internal/org/province" "online-back/pkg/client/postgresql" "online-back/pkg/logging" + "online-back/pkg/repository/genericrepo" "github.com/jackc/pgx/v4" ) type repository struct { - client postgresql.Client - logger *logging.Logger + client postgresql.Client + generic *genericrepo.Repository[province.ProvinceDTO] + logger *logging.Logger } func NewRepository(client postgresql.Client, logger *logging.Logger) province.Repository { - return &repository{client: client, logger: logger} + return &repository{ + client: client, + generic: genericrepo.New(client, "provinces", provinceSelectColumns, scanProvince), + logger: logger, + } } const provinceSelectColumns = `id, name, region, active` -func (r *repository) List(ctx context.Context) ([]province.ProvinceDTO, error) { - rows, err := r.client.Query(ctx, `SELECT `+provinceSelectColumns+` FROM provinces ORDER BY id`) +func (r *repository) List(ctx context.Context, filter province.ListFilter) (province.ListProvinceDTO, error) { + whereClause, args := buildListQuery(filter) + + items, count, err := r.generic.List(ctx, whereClause, args, filter.Page, filter.Limit, "id") if err != nil { - return nil, err - } - defer rows.Close() - - var items []province.ProvinceDTO - for rows.Next() { - item, err := scanProvince(rows) - if err != nil { - return nil, err - } - items = append(items, item) + return province.ListProvinceDTO{}, err } - return items, rows.Err() + return province.ListProvinceDTO{Count: count, Provinces: items}, nil +} + +func buildListQuery(filter province.ListFilter) (whereClause string, args []interface{}) { + var conditions []string + + if filter.Name != "" { + args = append(args, likePattern(filter.Name)) + n := len(args) + conditions = append(conditions, fmt.Sprintf(`( + name->>'en' ILIKE $%[1]d OR name->>'ru' ILIKE $%[1]d OR name->>'tm' ILIKE $%[1]d + )`, n)) + } + + if filter.Region != "" { + args = append(args, likePattern(filter.Region)) + n := len(args) + conditions = append(conditions, fmt.Sprintf(`( + region->>'en' ILIKE $%[1]d OR region->>'ru' ILIKE $%[1]d OR region->>'tm' ILIKE $%[1]d + )`, n)) + } + + if filter.Active != nil { + args = append(args, *filter.Active) + conditions = append(conditions, fmt.Sprintf("active = $%d", len(args))) + } + + if len(conditions) == 0 { + return "", args + } + + return " WHERE " + strings.Join(conditions, " AND "), args +} + +func likePattern(term string) string { + term = strings.ReplaceAll(term, `\`, `\\`) + term = strings.ReplaceAll(term, `%`, `\%`) + term = strings.ReplaceAll(term, `_`, `\_`) + return "%" + term + "%" } func (r *repository) GetByID(ctx context.Context, id int64) (province.ProvinceDTO, error) { - row := r.client.QueryRow(ctx, `SELECT `+provinceSelectColumns+` FROM provinces WHERE id = $1`, id) - item, err := scanProvince(row) - if errors.Is(err, pgx.ErrNoRows) { - return province.ProvinceDTO{}, err - } - return item, err + return r.generic.GetByID(ctx, id) } func (r *repository) Create(ctx context.Context, dto province.CreateProvinceDTO) (province.ProvinceDTO, error) { @@ -87,14 +120,7 @@ func (r *repository) Update(ctx context.Context, id int64, dto province.UpdatePr } func (r *repository) Delete(ctx context.Context, id int64) error { - tag, err := r.client.Exec(ctx, `DELETE FROM provinces WHERE id = $1`, id) - if err != nil { - return err - } - if tag.RowsAffected() == 0 { - return pgx.ErrNoRows - } - return nil + return r.generic.Delete(ctx, id) } func marshalProvinceJSON(name, region province.LocalizedName) ([]byte, []byte, error) { @@ -109,11 +135,7 @@ func marshalProvinceJSON(name, region province.LocalizedName) ([]byte, []byte, e return nameJSON, regionJSON, nil } -type scannable interface { - Scan(dest ...interface{}) error -} - -func scanProvince(row scannable) (province.ProvinceDTO, error) { +func scanProvince(row genericrepo.Scanner) (province.ProvinceDTO, error) { var item province.ProvinceDTO var nameJSON, regionJSON []byte if err := row.Scan(&item.Id, &nameJSON, ®ionJSON, &item.Active); err != nil { diff --git a/internal/admin/province/dto.go b/internal/org/province/dto.go similarity index 75% rename from internal/admin/province/dto.go rename to internal/org/province/dto.go index 6c59d1c..0598e56 100644 --- a/internal/admin/province/dto.go +++ b/internal/org/province/dto.go @@ -24,3 +24,16 @@ type UpdateProvinceDTO struct { Region LocalizedName `json:"region" binding:"required"` Active bool `json:"active"` } + +type ListFilter struct { + Name string + Region string + Active *bool + Page int + Limit int +} + +type ListProvinceDTO struct { + Count int64 `json:"count"` + Provinces []ProvinceDTO `json:"provinces"` +} diff --git a/internal/admin/province/handler.go b/internal/org/province/handler.go similarity index 77% rename from internal/admin/province/handler.go rename to internal/org/province/handler.go index cb1c39c..5bcb777 100644 --- a/internal/admin/province/handler.go +++ b/internal/org/province/handler.go @@ -4,6 +4,7 @@ import ( "errors" "net/http" "strconv" + "strings" "online-back/internal/appresult" "online-back/internal/handlers" @@ -35,23 +36,34 @@ func (h *handler) Register(router *gin.RouterGroup) { // list godoc // @Summary List provinces -// @Description Returns all provinces +// @Description Returns paginated provinces with optional filters // @Tags province // @Produce json // @Security BearerAuth +// @Param name query string false "Filter by province name (en, ru, tm)" +// @Param region query string false "Filter by region (en, ru, tm)" +// @Param active query bool false "Filter by active status" +// @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 /provinces [get] func (h *handler) list(c *gin.Context) { - items, err := h.repository.List(c.Request.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 provinces failed: %v", err) c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer) return } - c.JSON(http.StatusOK, appresult.SuccessWithData(items)) + c.JSON(http.StatusOK, appresult.SuccessWithData(result)) } // getByID godoc @@ -195,3 +207,50 @@ func parseID(raw string) (int64, bool) { } return id, true } + +const ( + defaultPage = 1 + defaultLimit = 10 + maxLimit = 100 +) + +func parseListFilter(c *gin.Context) (ListFilter, bool) { + filter := ListFilter{ + Page: defaultPage, + Limit: defaultLimit, + } + + if raw := c.Query("page"); raw != "" { + page, err := strconv.Atoi(raw) + if err != nil || page < 1 { + return ListFilter{}, false + } + filter.Page = page + } + + if raw := c.Query("limit"); raw != "" { + limit, err := strconv.Atoi(raw) + if err != nil || limit < 1 || limit > maxLimit { + return ListFilter{}, false + } + filter.Limit = limit + } + + if raw := strings.TrimSpace(c.Query("name")); raw != "" { + filter.Name = raw + } + + if raw := strings.TrimSpace(c.Query("region")); raw != "" { + filter.Region = raw + } + + if raw := c.Query("active"); raw != "" { + active, err := strconv.ParseBool(raw) + if err != nil { + return ListFilter{}, false + } + filter.Active = &active + } + + return filter, true +} diff --git a/internal/admin/province/storage.go b/internal/org/province/storage.go similarity index 82% rename from internal/admin/province/storage.go rename to internal/org/province/storage.go index 124c51a..a5b5ee3 100644 --- a/internal/admin/province/storage.go +++ b/internal/org/province/storage.go @@ -3,7 +3,7 @@ package province import "context" type Repository interface { - List(ctx context.Context) ([]ProvinceDTO, error) + List(ctx context.Context, filter ListFilter) (ListProvinceDTO, error) GetByID(ctx context.Context, id int64) (ProvinceDTO, error) Create(ctx context.Context, dto CreateProvinceDTO) (ProvinceDTO, error) Update(ctx context.Context, id int64, dto UpdateProvinceDTO) (ProvinceDTO, error) diff --git a/internal/org/router.go b/internal/org/router.go new file mode 100644 index 0000000..ff3ae29 --- /dev/null +++ b/internal/org/router.go @@ -0,0 +1,30 @@ +// Package org groups the organizational/geographic hierarchy (provinces and +// branches) under one bounded context, replacing the flat internal/admin/* +// listing. +package org + +import ( + "online-back/internal/handlers" + "online-back/internal/org/branches" + branchesdb "online-back/internal/org/branches/db" + "online-back/internal/org/province" + provincedb "online-back/internal/org/province/db" + "online-back/pkg/client/postgresql" + "online-back/pkg/logging" + + "github.com/gin-gonic/gin" +) + +// Register wires every org module's handler onto router. +func Register(router *gin.RouterGroup, client postgresql.Client, logger *logging.Logger) { + for _, h := range Handlers(client, logger) { + h.Register(router) + } +} + +func Handlers(client postgresql.Client, logger *logging.Logger) []handlers.Handler { + return []handlers.Handler{ + province.NewHandler(logger, provincedb.NewRepository(client, logger)), + branches.NewHandler(logger, branchesdb.NewRepository(client, logger)), + } +} diff --git a/kickbacks.vsix b/kickbacks.vsix new file mode 100644 index 0000000..68b3455 Binary files /dev/null and b/kickbacks.vsix differ diff --git a/logs/all.log b/logs/all.log index 07e95e2..e69de29 100644 --- a/logs/all.log +++ b/logs/all.log @@ -1,33 +0,0 @@ -time="2026-07-06T12:22:36+05:00" level=info msg="read application configuration" func="online-back/internal/config.GetConfig.func1()" file="config.go:41" -time="2026-07-06T12:22:36+05:00" level=info msg="starting server on 0.0.0.0:5050" func="main.main()" file="app.go:54" -time="2026-07-06T12:22:36+05:00" level=fatal msg="listen tcp 0.0.0.0:5050: bind: address already in use" func="main.main()" file="app.go:56" -time="2026-07-06T12:23:43+05:00" level=info msg="read application configuration" func="online-back/internal/config.GetConfig.func1()" file="config.go:41" -time="2026-07-06T12:23:43+05:00" level=info msg="starting server on 0.0.0.0:5050" func="main.main()" file="app.go:54" -time="2026-07-06T12:31:34+05:00" level=info msg="read application configuration" func="online-back/internal/config.GetConfig.func1()" file="config.go:41" -time="2026-07-06T12:31:34+05:00" level=info msg="starting server on 0.0.0.0:5050" func="main.main()" file="app.go:45" -time="2026-07-06T12:41:53+05:00" level=info msg="read application configuration" func="online-back/internal/config.GetConfig.func1()" file="config.go:41" -time="2026-07-06T12:41:53+05:00" level=info msg="starting server on 0.0.0.0:5050" func="main.main()" file="app.go:45" -time="2026-07-06T12:51:53+05:00" level=info msg="read application configuration" func="online-back/internal/config.GetConfig.func1()" file="config.go:41" -time="2026-07-06T12:51:53+05:00" level=info msg="starting server on 0.0.0.0:5050" func="main.main()" file="app.go:61" -time="2026-07-06T12:59:05+05:00" level=info msg="read application configuration" func="online-back/internal/config.GetConfig.func1()" file="config.go:41" -time="2026-07-06T12:59:05+05:00" level=info msg="starting server on 0.0.0.0:5050" func="main.main()" file="app.go:61" -time="2026-07-06T14:03:17+05:00" level=info msg="read application configuration" func="online-back/internal/config.GetConfig.func1()" file="config.go:41" -time="2026-07-06T14:03:17+05:00" level=info msg="starting server on 0.0.0.0:5050" func="main.main()" file="app.go:61" -time="2026-07-06T14:07:23+05:00" level=info msg="read application configuration" func="online-back/internal/config.GetConfig.func1()" file="config.go:41" -time="2026-07-06T14:07:23+05:00" level=info msg="starting server on 0.0.0.0:5050" func="main.main()" file="app.go:59" -time="2026-07-06T14:36:02+05:00" level=info msg="read application configuration" func="online-back/internal/config.GetConfig.func1()" file="config.go:41" -time="2026-07-06T14:36:03+05:00" level=info msg="starting server on 0.0.0.0:5050" func="main.main()" file="app.go:59" -time="2026-07-06T14:36:03+05:00" level=fatal msg="listen tcp 0.0.0.0:5050: bind: address already in use" func="main.main()" file="app.go:61" -time="2026-07-06T14:36:16+05:00" level=info msg="read application configuration" func="online-back/internal/config.GetConfig.func1()" file="config.go:41" -time="2026-07-06T14:36:16+05:00" level=info msg="starting server on 0.0.0.0:5050" func="main.main()" file="app.go:59" -time="2026-07-06T14:38:41+05:00" level=error msg="create branch failed: ERROR: missing FROM-clause entry for table \"b\" (SQLSTATE 42P01)" func="online-back/internal/admin/branches.(*handler).create()" file="handler.go:129" -time="2026-07-06T14:40:42+05:00" level=info msg="read application configuration" func="online-back/internal/config.GetConfig.func1()" file="config.go:41" -time="2026-07-06T14:40:42+05:00" level=info msg="starting server on 0.0.0.0:5050" func="main.main()" file="app.go:59" -time="2026-07-06T14:43:25+05:00" level=info msg="read application configuration" func="online-back/internal/config.GetConfig.func1()" file="config.go:41" -time="2026-07-06T14:43:25+05:00" level=info msg="starting server on 0.0.0.0:5050" func="main.main()" file="app.go:59" -time="2026-07-06T14:56:42+05:00" level=error msg="create loan type failed: ERROR: missing FROM-clause entry for table \"lt\" (SQLSTATE 42P01)" func="online-back/internal/admin/loantype.(*handler).create()" file="handler.go:121" -time="2026-07-06T14:58:32+05:00" level=info msg="read application configuration" func="online-back/internal/config.GetConfig.func1()" file="config.go:41" -time="2026-07-06T14:58:32+05:00" level=info msg="starting server on 0.0.0.0:5050" func="main.main()" file="app.go:59" -time="2026-07-06T15:53:35+05:00" level=info msg="read application configuration" func="online-back/internal/config.GetConfig.func1()" file="config.go:41" -time="2026-07-06T15:53:35+05:00" level=info msg="starting server on 0.0.0.0:5050" func="main.main()" file="app.go:59" -time="2026-07-06T15:53:35+05:00" level=fatal msg="listen tcp 0.0.0.0:5050: bind: address already in use" func="main.main()" file="app.go:61" diff --git a/pkg/repository/genericrepo/repository.go b/pkg/repository/genericrepo/repository.go new file mode 100644 index 0000000..a76f6fa --- /dev/null +++ b/pkg/repository/genericrepo/repository.go @@ -0,0 +1,97 @@ +// Package genericrepo factors out the List/GetByID/Delete/pagination +// pattern that was previously copy-pasted across every CRUD module's +// db/postgresql.go. Create and Update stay hand-written per module since +// their column lists and DTO mapping genuinely differ per entity. +package genericrepo + +import ( + "context" + "errors" + "fmt" + + "online-back/pkg/client/postgresql" + + "github.com/jackc/pgx/v4" +) + +// Scanner is satisfied by both pgx.Row and pgx.Rows. +type Scanner interface { + Scan(dest ...interface{}) error +} + +type Repository[T any] struct { + client postgresql.Client + table string + columns string + scan func(Scanner) (T, error) +} + +func New[T any](client postgresql.Client, table, columns string, scan func(Scanner) (T, error)) *Repository[T] { + return &Repository[T]{client: client, table: table, columns: columns, scan: scan} +} + +func (r *Repository[T]) GetByID(ctx context.Context, id int64) (T, error) { + row := r.client.QueryRow(ctx, `SELECT `+r.columns+` FROM `+r.table+` WHERE id = $1`, id) + item, err := r.scan(row) + if errors.Is(err, pgx.ErrNoRows) { + var zero T + return zero, err + } + return item, err +} + +func (r *Repository[T]) Delete(ctx context.Context, id int64) error { + tag, err := r.client.Exec(ctx, `DELETE FROM `+r.table+` WHERE id = $1`, id) + if err != nil { + return err + } + if tag.RowsAffected() == 0 { + return pgx.ErrNoRows + } + return nil +} + +// List runs a paginated query. where must be empty or start with " WHERE " +// (see province's buildListQuery for the convention); args are the +// positional parameters referenced by where, in order. orderBy is the raw +// ORDER BY clause body (e.g. "id" or "id DESC"); pass "" to default to "id". +func (r *Repository[T]) List(ctx context.Context, where string, args []interface{}, page, limit int, orderBy string) ([]T, int64, error) { + if orderBy == "" { + orderBy = "id" + } + + var count int64 + countQuery := `SELECT COUNT(*) FROM ` + r.table + where + if err := r.client.QueryRow(ctx, countQuery, args...).Scan(&count); err != nil { + return nil, 0, err + } + + offset := (page - 1) * limit + limitPlaceholder := len(args) + 1 + offsetPlaceholder := len(args) + 2 + listQuery := fmt.Sprintf( + `SELECT %s FROM %s%s ORDER BY %s LIMIT $%d OFFSET $%d`, + r.columns, r.table, where, orderBy, limitPlaceholder, offsetPlaceholder, + ) + listArgs := append(append([]interface{}{}, args...), limit, offset) + + rows, err := r.client.Query(ctx, listQuery, listArgs...) + if err != nil { + return nil, 0, err + } + defer rows.Close() + + var items []T + for rows.Next() { + item, err := r.scan(rows) + if err != nil { + return nil, 0, err + } + items = append(items, item) + } + if err := rows.Err(); err != nil { + return nil, 0, err + } + + return items, count, nil +}