From 77bc4025d3615714afaa8dcf99ae46b4337563f5 Mon Sep 17 00:00:00 2001 From: GuwandykA Date: Wed, 8 Jul 2026 15:02:05 +0500 Subject: [PATCH] Add branch_user table and branch-user assignment endpoints Introduces a branch_user join table linking branches to users, plus create/delete API endpoints under the auth module for managing branch assignments. The create response includes the branch's localized name via a join. Regenerated swagger docs to include the new endpoints. Co-Authored-By: Claude Sonnet 5 --- db/migrations/20260702125108_init.down.sql | 1 + db/migrations/20260702125108_init.up.sql | 8 ++ docs/docs.go | 118 +++++++++++++++++++++ docs/swagger.json | 118 +++++++++++++++++++++ docs/swagger.yaml | 75 +++++++++++++ internal/admin/auth/db/postgresql.go | 42 ++++++++ internal/admin/auth/dto.go | 20 ++++ internal/admin/auth/handler.go | 81 +++++++++++++- internal/admin/auth/storage.go | 2 + 9 files changed, 462 insertions(+), 3 deletions(-) diff --git a/db/migrations/20260702125108_init.down.sql b/db/migrations/20260702125108_init.down.sql index f93da00..d3f4568 100644 --- a/db/migrations/20260702125108_init.down.sql +++ b/db/migrations/20260702125108_init.down.sql @@ -1,3 +1,4 @@ +DROP TABLE IF EXISTS branch_user; DROP TABLE IF EXISTS roles; DROP TABLE IF EXISTS loan_order_required_docs; DROP TABLE IF EXISTS loan_types; diff --git a/db/migrations/20260702125108_init.up.sql b/db/migrations/20260702125108_init.up.sql index bac0f71..1b2be42 100644 --- a/db/migrations/20260702125108_init.up.sql +++ b/db/migrations/20260702125108_init.up.sql @@ -110,4 +110,12 @@ CREATE TABLE IF NOT EXISTS permissions ( guard_name character varying(255) NOT NULL, created_at TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL, updated_at TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL +); + +CREATE TABLE IF NOT EXISTS branch_user ( + id bigserial PRIMARY KEY, + branch_id bigint REFERENCES branches(id) ON DELETE CASCADE, + user_id bigint REFERENCES users(id) ON DELETE CASCADE, + created_at TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL, + updated_at TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL ); \ No newline at end of file diff --git a/docs/docs.go b/docs/docs.go index 92f5316..71748b3 100644 --- a/docs/docs.go +++ b/docs/docs.go @@ -15,6 +15,109 @@ const docTemplate = `{ "host": "{{.Host}}", "basePath": "{{.BasePath}}", "paths": { + "/branch-users": { + "post": { + "security": [ + { + "BearerAuth": [] + } + ], + "description": "Creates a branch-user assignment", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "auth" + ], + "summary": "Assign user to branch", + "parameters": [ + { + "description": "Branch-user payload", + "name": "body", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/auth.CreateBranchUserDTO" + } + } + ], + "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" + } + } + } + } + }, + "/branch-users/{id}": { + "delete": { + "security": [ + { + "BearerAuth": [] + } + ], + "description": "Deletes a branch-user assignment", + "produces": [ + "application/json" + ], + "tags": [ + "auth" + ], + "summary": "Remove user from branch", + "parameters": [ + { + "type": "integer", + "description": "Branch-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" + } + } + } + } + }, "/branches": { "get": { "security": [ @@ -2765,6 +2868,21 @@ const docTemplate = `{ } } }, + "auth.CreateBranchUserDTO": { + "type": "object", + "required": [ + "branchId", + "userId" + ], + "properties": { + "branchId": { + "type": "integer" + }, + "userId": { + "type": "integer" + } + } + }, "auth.LoginDTO": { "type": "object", "required": [ diff --git a/docs/swagger.json b/docs/swagger.json index 0a2b439..16f8cbf 100644 --- a/docs/swagger.json +++ b/docs/swagger.json @@ -9,6 +9,109 @@ "host": "localhost:5050", "basePath": "/api/admin", "paths": { + "/branch-users": { + "post": { + "security": [ + { + "BearerAuth": [] + } + ], + "description": "Creates a branch-user assignment", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "auth" + ], + "summary": "Assign user to branch", + "parameters": [ + { + "description": "Branch-user payload", + "name": "body", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/auth.CreateBranchUserDTO" + } + } + ], + "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" + } + } + } + } + }, + "/branch-users/{id}": { + "delete": { + "security": [ + { + "BearerAuth": [] + } + ], + "description": "Deletes a branch-user assignment", + "produces": [ + "application/json" + ], + "tags": [ + "auth" + ], + "summary": "Remove user from branch", + "parameters": [ + { + "type": "integer", + "description": "Branch-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" + } + } + } + } + }, "/branches": { "get": { "security": [ @@ -2759,6 +2862,21 @@ } } }, + "auth.CreateBranchUserDTO": { + "type": "object", + "required": [ + "branchId", + "userId" + ], + "properties": { + "branchId": { + "type": "integer" + }, + "userId": { + "type": "integer" + } + } + }, "auth.LoginDTO": { "type": "object", "required": [ diff --git a/docs/swagger.yaml b/docs/swagger.yaml index c2e99ea..29b424b 100644 --- a/docs/swagger.yaml +++ b/docs/swagger.yaml @@ -19,6 +19,16 @@ definitions: status: type: boolean type: object + auth.CreateBranchUserDTO: + properties: + branchId: + type: integer + userId: + type: integer + required: + - branchId + - userId + type: object auth.LoginDTO: properties: email: @@ -430,6 +440,71 @@ info: title: Service APIs version: "1.0" paths: + /branch-users: + post: + consumes: + - application/json + description: Creates a branch-user assignment + parameters: + - description: Branch-user payload + in: body + name: body + required: true + schema: + $ref: '#/definitions/auth.CreateBranchUserDTO' + 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 branch + tags: + - auth + /branch-users/{id}: + delete: + description: Deletes a branch-user assignment + parameters: + - description: Branch-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 branch + tags: + - auth /branches: get: description: Returns paginated branches with optional filters diff --git a/internal/admin/auth/db/postgresql.go b/internal/admin/auth/db/postgresql.go index ea54701..d20a0e4 100755 --- a/internal/admin/auth/db/postgresql.go +++ b/internal/admin/auth/db/postgresql.go @@ -2,10 +2,13 @@ package db import ( "context" + "encoding/json" "online-back/internal/admin/auth" "online-back/pkg/client/postgresql" "online-back/pkg/logging" + + "github.com/jackc/pgx/v4" ) type repository struct { @@ -50,3 +53,42 @@ 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` +) + +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, + ) + if err != nil { + return auth.BranchUserDTO{}, 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 +} diff --git a/internal/admin/auth/dto.go b/internal/admin/auth/dto.go index 4fbb7c6..4a5813e 100755 --- a/internal/admin/auth/dto.go +++ b/internal/admin/auth/dto.go @@ -23,3 +23,23 @@ 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/admin/auth/handler.go b/internal/admin/auth/handler.go index de0278e..c0a3461 100755 --- a/internal/admin/auth/handler.go +++ b/internal/admin/auth/handler.go @@ -1,6 +1,7 @@ package auth import ( + "errors" "net/http" "strconv" @@ -10,13 +11,15 @@ import ( "online-back/pkg/utils" "github.com/gin-gonic/gin" + "github.com/jackc/pgx/v4" "golang.org/x/crypto/bcrypt" ) const ( - loginURL = "/login" - tokenURL = "/token" - profileURL = "/profile" + loginURL = "/login" + tokenURL = "/token" + profileURL = "/profile" + branchUserURL = "/branch-users" ) type handler struct { @@ -34,6 +37,10 @@ func (h *handler) Register(router *gin.RouterGroup) { protected := router.Group("", appresult.JwtTokenCheck()) protected.GET(profileURL, h.getProfile) + + branchUserGroup := router.Group(branchUserURL, appresult.JwtTokenCheck()) + branchUserGroup.POST("", h.createBranchUser) + branchUserGroup.DELETE("/:id", h.deleteBranchUser) } // login godoc @@ -148,6 +155,74 @@ func (h *handler) getProfile(c *gin.Context) { c.JSON(http.StatusOK, appresult.SuccessWithData(profile)) } +// createBranchUser godoc +// @Summary Assign user to branch +// @Description Creates a branch-user assignment +// @Tags auth +// @Accept json +// @Produce json +// @Security BearerAuth +// @Param body body CreateBranchUserDTO 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) createBranchUser(c *gin.Context) { + var dto CreateBranchUserDTO + if err := c.ShouldBindJSON(&dto); err != nil { + c.JSON(http.StatusBadRequest, appresult.ErrMissingParam) + return + } + + item, err := h.repository.CreateBranchUser(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)) +} + +// deleteBranchUser godoc +// @Summary Remove user from branch +// @Description Deletes a branch-user assignment +// @Tags auth +// @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) deleteBranchUser(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) { + 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) (int, bool) { rawID, exists := c.Get("id") if !exists { diff --git a/internal/admin/auth/storage.go b/internal/admin/auth/storage.go index 433d259..412a66c 100755 --- a/internal/admin/auth/storage.go +++ b/internal/admin/auth/storage.go @@ -6,4 +6,6 @@ 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 }