Align schema, API routes, and auth with updated admin domain model.

Rename users table fields and loan documents table, expand branch billing credentials, switch to /api/admin prefix, refactor auth endpoints, replace PATCH with PUT for status updates, remove file upload APIs, and regenerate Swagger with ordered tags.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
guwandykandCursor committed 2026-07-06 14:09:45 +05:00
1 parent 0c717101da
commit 82e1aad016
22 files changed
+4248 -418

No files matched your search

+26 -21
View File
@@ -3,8 +3,7 @@ package main
import ( import (
"context" "context"
_ "online-back/docs" "online-back/docs"
"online-back/internal/admin/auth"
"online-back/internal/config" "online-back/internal/config"
handlermanager "online-back/internal/handlers/manager" handlermanager "online-back/internal/handlers/manager"
"online-back/pkg/client/postgresql" "online-back/pkg/client/postgresql"
@@ -15,32 +14,39 @@ import (
ginSwagger "github.com/swaggo/gin-swagger" ginSwagger "github.com/swaggo/gin-swagger"
) )
// @title Service APIs // @title Service APIs
// @version 1.0 // @version 1.0
// @description Online payment system admin API. // @description Online payment system admin API.
// @termsOfService http://swagger.io/terms/
// @contact.name API Support
// @contact.url http://www.swagger.io/support
// @contact.email support@swagger.io
// @license.name Apache 2.0
// @license.url http://www.apache.org/licenses/LICENSE-2.0.html
// @host localhost:5050 // @host localhost:5050
// @BasePath /v1/admin // @BasePath /api/admin
// @securityDefinitions.apikey BearerAuth // @securityDefinitions.apikey BearerAuth
// @in header // @in header
// @name Authorization // @name Authorization
// @tag.name auth
// @tag.name province
// @tag.name location
// @tag.name branches
// @tag.name payment-card
// @tag.name reason-card
// @tag.name loan-type
// @tag.name loan-document
// @Success 200 {object} appresult.AppSuccess "Success Code"
// @Failure 400 {object} appresult.AppError "Error Code"
// @schemes http // @schemes http
// @tag.name auth
// @tag.description Authentication
// @tag.name location
// @tag.description Locations
// @tag.name province
// @tag.description Provinces
// @tag.name branches
// @tag.description Branches
// @tag.name payment-card
// @tag.description Payment cards
// @tag.name reason-card
// @tag.description Reason cards
// @tag.name loan-type
// @tag.description Loan types
// @tag.name loan-document
// @tag.description Loan required documents
func main() { func main() {
docs.SwaggerInfo.Title = "Service APIs"
docs.SwaggerInfo.Version = "1.0"
docs.SwaggerInfo.Description = "Online payment system admin API."
docs.SwaggerInfo.Host = "localhost:5050"
docs.SwaggerInfo.BasePath = "/api/admin"
docs.SwaggerInfo.Schemes = []string{"http"}
cfg := config.GetConfig() cfg := config.GetConfig()
logger := logging.GetLogger() logger := logging.GetLogger()
@@ -48,7 +54,6 @@ func main() {
router := handlermanager.New(cfg, pool, logger) router := handlermanager.New(cfg, pool, logger)
router.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler)) router.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler))
router.GET("/images/:id", auth.GetObject)
addr := cfg.Listen.BindIP + ":" + cfg.Listen.Port addr := cfg.Listen.BindIP + ":" + cfg.Listen.Port
logger.Infof("starting server on %s", addr) logger.Infof("starting server on %s", addr)
+3 -3
View File
@@ -1,8 +1,8 @@
DROP TABLE IF EXISTS loans_documents; DROP TABLE IF EXISTS loan_required_documents;
DROP TABLE IF EXISTS loan_types; DROP TABLE IF EXISTS loan_types;
DROP TABLE IF EXISTS reasons_cards; DROP TABLE IF EXISTS reasons_cards;
DROP TABLE IF EXISTS payment_cards; DROP TABLE IF EXISTS payment_cards;
DROP TABLE IF EXISTS branches; DROP TABLE IF EXISTS branches;
DROP TABLE IF EXISTS location; DROP TABLE IF EXISTS location;
DROP TABLE IF EXISTS province; DROP TABLE IF EXISTS provinces;
DROP TABLE IF EXISTS admin; DROP TABLE IF EXISTS users;
+16 -12
View File
@@ -1,6 +1,6 @@
CREATE TABLE IF NOT EXISTS admin ( CREATE TABLE IF NOT EXISTS users (
"id" bigserial primary key, "id" bigserial primary key,
"login" character varying(250) NOT NULL DEFAULT '', "email" character varying(250) NOT NULL DEFAULT '',
"password" character varying(250) NOT NULL DEFAULT '', "password" character varying(250) NOT NULL DEFAULT '',
"fullname" character varying(250) NOT NULL DEFAULT '', "fullname" character varying(250) NOT NULL DEFAULT '',
"username" character varying(250) NOT NULL DEFAULT '', "username" character varying(250) NOT NULL DEFAULT '',
@@ -14,8 +14,8 @@ CREATE TABLE IF NOT EXISTS admin (
"created_at" TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL "created_at" TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL
); );
insert into admin( insert into users(
phone_number, password, fullname, login, role phone_number, password, fullname, email, role
) values ( ) values (
'61531216', '61531216',
'$2a$12$8ZbKmoSwna4CASQptM2/SubwvsBUR1YhABULd.2/QJB.13Wi2v55m', '$2a$12$8ZbKmoSwna4CASQptM2/SubwvsBUR1YhABULd.2/QJB.13Wi2v55m',
@@ -24,16 +24,17 @@ insert into admin(
'admin' 'admin'
); );
CREATE TABLE IF NOT EXISTS province ( CREATE TABLE IF NOT EXISTS provinces (
id bigserial PRIMARY KEY, id bigserial PRIMARY KEY,
title json NOT NULL DEFAULT '{}'::json title json NOT NULL DEFAULT '{}'::json,
status boolean NOT NULL DEFAULT true,
"updated_at" TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL, "updated_at" TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL,
"created_at" TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL, "created_at" TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL
); );
CREATE TABLE IF NOT EXISTS location ( CREATE TABLE IF NOT EXISTS location (
id bigserial PRIMARY KEY, id bigserial PRIMARY KEY,
province_id bigint NOT NULL REFERENCES province(id) ON DELETE CASCADE, province_id bigint NOT NULL REFERENCES provinces(id) ON DELETE CASCADE,
title json NOT NULL DEFAULT '{}'::json, title json NOT NULL DEFAULT '{}'::json,
status boolean NOT NULL DEFAULT true, status boolean NOT NULL DEFAULT true,
"updated_at" TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL, "updated_at" TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL,
@@ -43,15 +44,18 @@ CREATE TABLE IF NOT EXISTS location (
CREATE TABLE IF NOT EXISTS branches ( CREATE TABLE IF NOT EXISTS branches (
id bigserial PRIMARY KEY, id bigserial PRIMARY KEY,
title json NOT NULL DEFAULT '{}'::json, title json NOT NULL DEFAULT '{}'::json,
province_id bigint NOT NULL REFERENCES province(id) ON DELETE CASCADE, province_id bigint NOT NULL REFERENCES provinces(id) ON DELETE CASCADE,
location_id bigint NOT NULL REFERENCES location(id) ON DELETE CASCADE, location_id bigint NOT NULL REFERENCES location(id) ON DELETE CASCADE,
unikal_nomer character varying(250) NOT NULL UNIQUE, unikal_nomer character varying(250) NOT NULL UNIQUE,
address json NOT NULL DEFAULT '{}'::json, "address" text NOT NULL DEFAULT '',
billing_login character varying(250) NOT NULL DEFAULT '', billing_username character varying(250) NOT NULL DEFAULT '',
billing_password character varying(250) NOT NULL DEFAULT '', billing_password character varying(250) NOT NULL DEFAULT '',
billing_username_sber character varying(250) NOT NULL DEFAULT '', billing_username_sber character varying(250) NOT NULL DEFAULT '',
billing_password_sber character varying(250) NOT NULL DEFAULT '', billing_password_sber character varying(250) NOT NULL DEFAULT '',
billing_username_visa character varying(250) NOT NULL DEFAULT '', billing_username_visa character varying(250) NOT NULL DEFAULT '',
billing_password_visa character varying(250) NOT NULL DEFAULT '',
billing_username_swift character varying(250) NOT NULL DEFAULT '',
billing_password_swift character varying(250) NOT NULL DEFAULT '',
"updated_at" TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL, "updated_at" TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL,
"created_at" TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL "created_at" TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL
); );
@@ -85,7 +89,7 @@ CREATE TABLE IF NOT EXISTS loan_types (
updated_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 loans_documents ( CREATE TABLE IF NOT EXISTS loan_required_documents (
id bigserial PRIMARY KEY, id bigserial PRIMARY KEY,
title json NOT NULL DEFAULT '{}'::json, title json NOT NULL DEFAULT '{}'::json,
content_en text NOT NULL DEFAULT '', content_en text NOT NULL DEFAULT '',
+1497 -51
View File
File diff suppressed because it is too large. Load diff
+1496 -46
View File
File diff suppressed because it is too large. Load diff
+985 -42
View File
File diff suppressed because it is too large. Load diff
+60
View File
@@ -0,0 +1,60 @@
package docs
import "strings"
// Swagger tag order for Swagger UI. Listed first appears at the top.
var swaggerTagOrder = []struct {
Name string
Description string
}{
{Name: "auth", Description: "Authentication"},
{Name: "location", Description: "Locations"},
{Name: "province", Description: "Provinces"},
{Name: "branches", Description: "Branches"},
{Name: "payment-card", Description: "Payment cards"},
{Name: "reason-card", Description: "Reason cards"},
{Name: "loan-type", Description: "Loan types"},
{Name: "loan-document", Description: "Loan required documents"},
}
func applySwaggerTagOrder() {
const anchor = ` },
"securityDefinitions": {`
if !strings.Contains(SwaggerInfo.SwaggerTemplate, anchor) {
return
}
if strings.Contains(SwaggerInfo.SwaggerTemplate, ` "tags": [
{"name": "auth"`) {
return
}
SwaggerInfo.SwaggerTemplate = strings.Replace(
SwaggerInfo.SwaggerTemplate,
anchor,
` },
`+buildSwaggerTagsJSON()+`"securityDefinitions": {`,
1,
)
}
func buildSwaggerTagsJSON() string {
var b strings.Builder
b.WriteString(`"tags": [`)
for i, tag := range swaggerTagOrder {
if i > 0 {
b.WriteString(",")
}
b.WriteString(`{"name":`)
b.WriteString(jsonString(tag.Name))
b.WriteString(`,"description":`)
b.WriteString(jsonString(tag.Description))
b.WriteString("}")
}
b.WriteString(`],
`)
return b.String()
}
func jsonString(value string) string {
return `"` + strings.ReplaceAll(value, `"`, `\"`) + `"`
}
+12 -18
View File
@@ -2,7 +2,6 @@ package db
import ( import (
"context" "context"
"strconv"
"online-back/internal/admin/auth" "online-back/internal/admin/auth"
"online-back/pkg/client/postgresql" "online-back/pkg/client/postgresql"
@@ -22,32 +21,27 @@ func NewRepository(client postgresql.Client, logger *logging.Logger) auth.Reposi
} }
const ( const (
loginQuery = `SELECT id, password FROM admin WHERE login = $1` loginQuery = `SELECT id, password FROM users WHERE email = $1`
adminQuery = `SELECT id, password FROM admin WHERE id = $1` userByIDQuery = `SELECT id, password FROM users WHERE id = $1`
profileQuery = `SELECT id, fullname, phone_number, avatar, created_at profileQuery = `SELECT id, fullname, phone_number, avatar, created_at
FROM admin WHERE id = $1` FROM users WHERE id = $1`
) )
func (r *repository) Login(ctx context.Context, dto auth.LoginDTO) (auth.ResLoginDTO, error) { func (r *repository) Login(ctx context.Context, dto auth.LoginDTO) (auth.UserCredentials, error) {
var result auth.ResLoginDTO var result auth.UserCredentials
err := r.client.QueryRow(ctx, loginQuery, dto.Login).Scan(&result.Id, &result.Password) err := r.client.QueryRow(ctx, loginQuery, dto.Email).Scan(&result.Id, &result.Password)
return result, err return result, err
} }
func (r *repository) CheckAdmin(ctx context.Context, id int) (auth.ResLoginDTO, error) { func (r *repository) GetUserByID(ctx context.Context, id int) (auth.UserCredentials, error) {
var result auth.ResLoginDTO var result auth.UserCredentials
err := r.client.QueryRow(ctx, adminQuery, id).Scan(&result.Id, &result.Password) err := r.client.QueryRow(ctx, userByIDQuery, id).Scan(&result.Id, &result.Password)
return result, err return result, err
} }
func (r *repository) GetProfile(ctx context.Context, id string) (auth.ResUserDTO, error) { func (r *repository) GetProfile(ctx context.Context, id int) (auth.UserProfileDTO, error) {
var profile auth.ResUserDTO var profile auth.UserProfileDTO
adminID, err := strconv.Atoi(id) err := r.client.QueryRow(ctx, profileQuery, id).Scan(
if err != nil {
return profile, err
}
err = r.client.QueryRow(ctx, profileQuery, adminID).Scan(
&profile.Id, &profile.Id,
&profile.FullName, &profile.FullName,
&profile.PhoneNumber, &profile.PhoneNumber,
+8 -8
View File
@@ -3,23 +3,23 @@ package auth
import "time" import "time"
type LoginDTO struct { type LoginDTO struct {
Login string `json:"login" binding:"required"` Email string `json:"email" binding:"required"`
Password string `json:"password" binding:"required"` Password string `json:"password" binding:"required"`
} }
type ResLoginDTO struct { type RefreshTokenDTO struct {
Id int `json:"id"`
Password string `json:"-"`
}
type TokenReqBody struct {
RefreshToken string `json:"refreshToken" binding:"required"` RefreshToken string `json:"refreshToken" binding:"required"`
} }
type ResUserDTO struct { type UserProfileDTO struct {
Id int `json:"id"` Id int `json:"id"`
FullName string `json:"fullName"` FullName string `json:"fullName"`
PhoneNumber string `json:"phoneNumber"` PhoneNumber string `json:"phoneNumber"`
Avatar string `json:"avatar"` Avatar string `json:"avatar"`
CreatedAt time.Time `json:"createdAt"` CreatedAt time.Time `json:"createdAt"`
} }
type UserCredentials struct {
Id int
Password string
}
-35
View File
@@ -1,35 +0,0 @@
package auth
import (
"fmt"
"os"
"path/filepath"
"strings"
"time"
)
func imageStorageDir(publicRoot string) string {
return filepath.Join(publicRoot, "images")
}
func imagePublicPath(filename string) string {
return "/images/" + filename
}
func resolveImagePath(publicRoot, filename string) (string, error) {
if filename == "" || strings.Contains(filename, "..") || strings.ContainsAny(filename, `/\`) {
return "", fmt.Errorf("invalid file name")
}
base := filepath.Clean(imageStorageDir(publicRoot))
path := filepath.Clean(filepath.Join(base, filepath.Base(filename)))
if !strings.HasPrefix(path, base+string(os.PathSeparator)) && path != base {
return "", fmt.Errorf("invalid file path")
}
return path, nil
}
func newUploadFilename(original string) string {
return fmt.Sprintf("%d%s", time.Now().UnixNano(), filepath.Ext(original))
}
+71 -130
View File
@@ -1,13 +1,10 @@
package auth package auth
import ( import (
"fmt"
"net/http" "net/http"
"os" "strconv"
"path/filepath"
"online-back/internal/appresult" "online-back/internal/appresult"
"online-back/internal/config"
"online-back/internal/handlers" "online-back/internal/handlers"
"online-back/pkg/logging" "online-back/pkg/logging"
"online-back/pkg/utils" "online-back/pkg/utils"
@@ -17,11 +14,9 @@ import (
) )
const ( const (
loginURL = "/login" loginURL = "/login"
tokenURL = "/token" tokenURL = "/token"
getProfileURL = "/get-profile" profileURL = "/profile"
fileUploadURL = "/file"
fileRemoveURL = "/file/:id"
) )
type handler struct { type handler struct {
@@ -30,50 +25,48 @@ type handler struct {
} }
func NewHandler(logger *logging.Logger, repository Repository) handlers.Handler { func NewHandler(logger *logging.Logger, repository Repository) handlers.Handler {
return &handler{ return &handler{logger: logger, repository: repository}
logger: logger,
repository: repository,
}
} }
func (h *handler) Register(router *gin.RouterGroup) { func (h *handler) Register(router *gin.RouterGroup) {
router.POST(loginURL, h.login) router.POST(loginURL, h.login)
router.POST(tokenURL, h.token) router.POST(tokenURL, h.refreshToken)
router.GET(getProfileURL, appresult.JwtTokenCheck(), h.getProfile)
router.POST(fileUploadURL, appresult.JwtTokenCheck(), h.fileUpload) protected := router.Group("", appresult.JwtTokenCheck())
router.DELETE(fileRemoveURL, appresult.JwtTokenCheck(), h.deleteObject) protected.GET(profileURL, h.getProfile)
} }
// login godoc // login godoc
// @Description login for Admin // @Summary Login
// @Tags auth // @Description Authenticates a user by email and password
// @Accept json // @Tags auth
// @Produce json // @Accept json
// @Param auth body LoginDTO true "Login JSON" // @Produce json
// @Success 200 {object} appresult.AppSuccess // @Param body body LoginDTO true "Login payload"
// @Failure 400 {object} appresult.AppError // @Success 200 {object} appresult.AppSuccess
// @Router /login [post] // @Failure 400 {object} appresult.AppError
// @Failure 401 {object} appresult.AppError
// @Router /login [post]
func (h *handler) login(c *gin.Context) { func (h *handler) login(c *gin.Context) {
var loginReq LoginDTO var dto LoginDTO
if err := c.ShouldBindJSON(&loginReq); err != nil { if err := c.ShouldBindJSON(&dto); err != nil {
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam) c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
return return
} }
ctx := c.Request.Context() user, err := h.repository.Login(c.Request.Context(), dto)
res, err := h.repository.Login(ctx, loginReq)
if err != nil { if err != nil {
h.logger.Errorf("login lookup failed: %v", err) h.logger.Errorf("login lookup failed: %v", err)
c.JSON(http.StatusUnauthorized, appresult.ErrUnauthorized) c.JSON(http.StatusUnauthorized, appresult.ErrUnauthorized)
return return
} }
if err := bcrypt.CompareHashAndPassword([]byte(res.Password), []byte(loginReq.Password)); err != nil { if err := bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(dto.Password)); err != nil {
c.JSON(http.StatusUnauthorized, appresult.ErrUnauthorized) c.JSON(http.StatusUnauthorized, appresult.ErrUnauthorized)
return return
} }
tokenPair, err := utils.GenerateTokenPair(res.Id) tokenPair, err := utils.GenerateTokenPair(user.Id)
if err != nil { if err != nil {
c.JSON(http.StatusBadRequest, appresult.ErrNotAcceptable) c.JSON(http.StatusBadRequest, appresult.ErrNotAcceptable)
return return
@@ -82,23 +75,25 @@ func (h *handler) login(c *gin.Context) {
c.JSON(http.StatusOK, appresult.SuccessWithData(tokenPair)) c.JSON(http.StatusOK, appresult.SuccessWithData(tokenPair))
} }
// token godoc // refreshToken godoc
// @Description refresh admin tokens // @Summary Refresh tokens
// @Tags auth // @Description Issues a new access and refresh token pair
// @Accept json // @Tags auth
// @Produce json // @Accept json
// @Param auth body TokenReqBody true "Token JSON" // @Produce json
// @Success 200 {object} appresult.AppSuccess // @Param body body RefreshTokenDTO true "Refresh token payload"
// @Failure 400 {object} appresult.AppError // @Success 200 {object} appresult.AppSuccess
// @Router /token [post] // @Failure 400 {object} appresult.AppError
func (h *handler) token(c *gin.Context) { // @Failure 401 {object} appresult.AppError
var tokenReq TokenReqBody // @Router /token [post]
if err := c.ShouldBindJSON(&tokenReq); err != nil { func (h *handler) refreshToken(c *gin.Context) {
var dto RefreshTokenDTO
if err := c.ShouldBindJSON(&dto); err != nil {
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam) c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
return return
} }
claims, err := utils.ParseRefreshToken(tokenReq.RefreshToken) claims, err := utils.ParseRefreshToken(dto.RefreshToken)
if err != nil { if err != nil {
c.JSON(http.StatusUnauthorized, appresult.ErrUnauthorized) c.JSON(http.StatusUnauthorized, appresult.ErrUnauthorized)
return return
@@ -110,8 +105,8 @@ func (h *handler) token(c *gin.Context) {
return return
} }
admin, err := h.repository.CheckAdmin(c.Request.Context(), id) user, err := h.repository.GetUserByID(c.Request.Context(), id)
if err != nil || admin.Id != id { if err != nil || user.Id != id {
c.JSON(http.StatusUnauthorized, appresult.ErrUnauthorized) c.JSON(http.StatusUnauthorized, appresult.ErrUnauthorized)
return return
} }
@@ -126,100 +121,46 @@ func (h *handler) token(c *gin.Context) {
} }
// getProfile godoc // getProfile godoc
// @Description profile data for Admin // @Summary Get profile
// @Tags admin // @Description Returns the authenticated user's profile
// @Accept json // @Tags auth
// @Produce json // @Produce json
// @Security BearerAuth // @Security BearerAuth
// @Success 200 {object} appresult.AppSuccess // @Success 200 {object} appresult.AppSuccess
// @Failure 400 {object} appresult.AppError // @Failure 400 {object} appresult.AppError
// @Router /get-profile [get] // @Failure 401 {object} appresult.AppError
// @Failure 404 {object} appresult.AppError
// @Router /profile [get]
func (h *handler) getProfile(c *gin.Context) { func (h *handler) getProfile(c *gin.Context) {
adminID, _ := c.Get("id") userID, ok := currentUserID(c)
profile, err := h.repository.GetProfile(c.Request.Context(), fmt.Sprint(adminID)) if !ok {
c.JSON(http.StatusUnauthorized, appresult.ErrUnauthorized)
return
}
profile, err := h.repository.GetProfile(c.Request.Context(), userID)
if err != nil { if err != nil {
h.logger.Errorf("get profile failed: %v", err) h.logger.Errorf("get profile failed: %v", err)
c.JSON(http.StatusBadRequest, appresult.ErrNotFound) c.JSON(http.StatusNotFound, appresult.ErrNotFound)
return return
} }
c.JSON(http.StatusOK, appresult.SuccessWithData(profile)) c.JSON(http.StatusOK, appresult.SuccessWithData(profile))
} }
// fileUpload godoc func currentUserID(c *gin.Context) (int, bool) {
// @Description file upload rawID, exists := c.Get("id")
// @Tags file-upload if !exists {
// @Accept multipart/form-data return 0, false
// @Produce json
// @Param file formData file true "upload file"
// @Security BearerAuth
// @Success 200 {object} appresult.AppSuccess
// @Failure 400 {object} appresult.AppError
// @Router /file [post]
func (h *handler) fileUpload(c *gin.Context) {
header, err := c.FormFile("file")
if err != nil {
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
return
} }
cfg := config.GetConfig() switch id := rawID.(type) {
dir := imageStorageDir(cfg.PublicFilePath) case int:
if err := os.MkdirAll(dir, 0755); err != nil { return id, id > 0
h.logger.Errorf("create upload dir failed: %v", err) case string:
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer) parsed, err := strconv.Atoi(id)
return return parsed, err == nil && parsed > 0
default:
return 0, false
} }
filename := newUploadFilename(header.Filename)
if err := c.SaveUploadedFile(header, filepath.Join(dir, filename)); err != nil {
h.logger.Errorf("save upload failed: %v", err)
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return
}
c.JSON(http.StatusOK, appresult.SuccessWithData(imagePublicPath(filename)))
}
// GetObject serves uploaded images from local storage.
func GetObject(c *gin.Context) {
path, err := resolveImagePath(config.GetConfig().PublicFilePath, c.Param("id"))
if err != nil {
c.JSON(http.StatusBadRequest, appresult.ErrNotAcceptable)
return
}
content, err := os.ReadFile(path)
if err != nil {
c.JSON(http.StatusNotFound, appresult.ErrNotFound)
return
}
c.Data(http.StatusOK, http.DetectContentType(content), content)
}
// deleteObject godoc
// @Description remove file
// @Tags file-upload
// @Accept json
// @Produce json
// @Param id path string true "file name"
// @Security BearerAuth
// @Success 200 {object} appresult.AppSuccess
// @Failure 400 {object} appresult.AppError
// @Router /file/{id} [delete]
func (h *handler) deleteObject(c *gin.Context) {
path, err := resolveImagePath(config.GetConfig().PublicFilePath, c.Param("id"))
if err != nil {
c.JSON(http.StatusBadRequest, appresult.ErrNotAcceptable)
return
}
if err := os.Remove(path); err != nil {
h.logger.Errorf("delete file failed: %v", err)
c.JSON(http.StatusNotFound, appresult.ErrNotFound)
return
}
c.JSON(http.StatusOK, appresult.SuccessWithData("file removed"))
} }
+3 -3
View File
@@ -3,7 +3,7 @@ package auth
import "context" import "context"
type Repository interface { type Repository interface {
Login(ctx context.Context, dto LoginDTO) (ResLoginDTO, error) Login(ctx context.Context, dto LoginDTO) (UserCredentials, error)
CheckAdmin(ctx context.Context, id int) (ResLoginDTO, error) GetUserByID(ctx context.Context, id int) (UserCredentials, error)
GetProfile(ctx context.Context, req string) (ResUserDTO, error) GetProfile(ctx context.Context, id int) (UserProfileDTO, error)
} }
+19 -13
View File
@@ -25,8 +25,9 @@ func NewRepository(client postgresql.Client, logger *logging.Logger) branches.Re
} }
const branchColumns = `b.id, b.title, b.province_id, b.location_id, b.unikal_nomer, b.address, const branchColumns = `b.id, b.title, b.province_id, b.location_id, b.unikal_nomer, b.address,
b.billing_login, b.billing_password, b.billing_username_sber, b.billing_password_sber, b.billing_username, b.billing_password, b.billing_username_sber, b.billing_password_sber,
b.billing_username_visa, b.billing_password_visa` b.billing_username_visa, b.billing_password_visa,
b.billing_username_swift, b.billing_password_swift`
func (r *repository) List(ctx context.Context, filter branches.ListFilter) (branches.ListBranchDTO, error) { func (r *repository) List(ctx context.Context, filter branches.ListFilter) (branches.ListBranchDTO, error) {
fromClause, whereClause, args := buildListQuery(filter) fromClause, whereClause, args := buildListQuery(filter)
@@ -71,7 +72,7 @@ func buildListQuery(filter branches.ListFilter) (fromClause, whereClause string,
fromClause = ` FROM branches b` fromClause = ` FROM branches b`
if filter.ProvinceName != "" { if filter.ProvinceName != "" {
fromClause += ` JOIN province p ON p.id = b.province_id` fromClause += ` JOIN provinces p ON p.id = b.province_id`
} }
var conditions []string var conditions []string
@@ -145,15 +146,17 @@ func (r *repository) Create(ctx context.Context, dto branches.CreateBranchDTO) (
query := fmt.Sprintf(` query := fmt.Sprintf(`
INSERT INTO branches ( INSERT INTO branches (
title, province_id, location_id, unikal_nomer, address, title, province_id, location_id, unikal_nomer, address,
billing_login, billing_password, billing_username_sber, billing_password_sber, billing_username, billing_password, billing_username_sber, billing_password_sber,
billing_username_visa, billing_password_visa billing_username_visa, billing_password_visa,
) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11) billing_username_swift, billing_password_swift
) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13)
RETURNING %s`, branchColumns) RETURNING %s`, branchColumns)
row := r.client.QueryRow(ctx, query, row := r.client.QueryRow(ctx, query,
title, dto.ProvinceId, dto.LocationId, dto.UnikalNomer, address, title, dto.ProvinceId, dto.LocationId, dto.UnikalNomer, address,
dto.BillingLogin, dto.BillingPassword, dto.BillingUsernameSber, dto.BillingPasswordSber, dto.BillingUsername, dto.BillingPassword, dto.BillingUsernameSber, dto.BillingPasswordSber,
dto.BillingUsernameVisa, dto.BillingPasswordVisa, dto.BillingUsernameVisa, dto.BillingPasswordVisa,
dto.BillingUsernameSwift, dto.BillingPasswordSwift,
) )
item, err := scanBranch(row) item, err := scanBranch(row)
if isUniqueViolation(err) { if isUniqueViolation(err) {
@@ -175,15 +178,17 @@ func (r *repository) Update(ctx context.Context, id int64, dto branches.UpdateBr
query := fmt.Sprintf(` query := fmt.Sprintf(`
UPDATE branches SET UPDATE branches SET
title = $1, province_id = $2, location_id = $3, unikal_nomer = $4, address = $5, title = $1, province_id = $2, location_id = $3, unikal_nomer = $4, address = $5,
billing_login = $6, billing_password = $7, billing_username_sber = $8, billing_username = $6, billing_password = $7, billing_username_sber = $8,
billing_password_sber = $9, billing_username_visa = $10, billing_password_visa = $11 billing_password_sber = $9, billing_username_visa = $10, billing_password_visa = $11,
WHERE id = $12 billing_username_swift = $12, billing_password_swift = $13
WHERE id = $14
RETURNING %s`, branchColumns) RETURNING %s`, branchColumns)
row := r.client.QueryRow(ctx, query, row := r.client.QueryRow(ctx, query,
title, dto.ProvinceId, dto.LocationId, dto.UnikalNomer, address, title, dto.ProvinceId, dto.LocationId, dto.UnikalNomer, address,
dto.BillingLogin, dto.BillingPassword, dto.BillingUsernameSber, dto.BillingPasswordSber, dto.BillingUsername, dto.BillingPassword, dto.BillingUsernameSber, dto.BillingPasswordSber,
dto.BillingUsernameVisa, dto.BillingPasswordVisa, id, dto.BillingUsernameVisa, dto.BillingPasswordVisa,
dto.BillingUsernameSwift, dto.BillingPasswordSwift, id,
) )
item, err := scanBranch(row) item, err := scanBranch(row)
if errors.Is(err, pgx.ErrNoRows) { if errors.Is(err, pgx.ErrNoRows) {
@@ -244,8 +249,9 @@ func scanBranch(row scannable) (branches.BranchDTO, error) {
err := row.Scan( err := row.Scan(
&item.Id, &titleJSON, &item.ProvinceId, &item.LocationId, &item.UnikalNomer, &addressJSON, &item.Id, &titleJSON, &item.ProvinceId, &item.LocationId, &item.UnikalNomer, &addressJSON,
&item.BillingLogin, &item.BillingPassword, &item.BillingUsernameSber, &item.BillingPasswordSber, &item.BillingUsername, &item.BillingPassword, &item.BillingUsernameSber, &item.BillingPasswordSber,
&item.BillingUsernameVisa, &item.BillingPasswordVisa, &item.BillingUsernameVisa, &item.BillingPasswordVisa,
&item.BillingUsernameSwift, &item.BillingPasswordSwift,
) )
if err != nil { if err != nil {
return branches.BranchDTO{}, err return branches.BranchDTO{}, err
+15 -9
View File
@@ -13,12 +13,14 @@ type BranchDTO struct {
LocationId int64 `json:"locationId"` LocationId int64 `json:"locationId"`
UnikalNomer string `json:"unikalNomer"` UnikalNomer string `json:"unikalNomer"`
Address LocalizedText `json:"address"` Address LocalizedText `json:"address"`
BillingLogin string `json:"billingLogin"` BillingUsername string `json:"billingUsername"`
BillingPassword string `json:"billingPassword"` BillingPassword string `json:"billingPassword"`
BillingUsernameSber string `json:"billingUsernameSber"` BillingUsernameSber string `json:"billingUsernameSber"`
BillingPasswordSber string `json:"billingPasswordSber"` BillingPasswordSber string `json:"billingPasswordSber"`
BillingUsernameVisa string `json:"billingUsernameVisa"` BillingUsernameVisa string `json:"billingUsernameVisa"`
BillingPasswordVisa string `json:"billingPasswordVisa"` BillingPasswordVisa string `json:"billingPasswordVisa"`
BillingUsernameSwift string `json:"billingUsernameSwift"`
BillingPasswordSwift string `json:"billingPasswordSwift"`
} }
type CreateBranchDTO struct { type CreateBranchDTO struct {
@@ -27,12 +29,14 @@ type CreateBranchDTO struct {
LocationId int64 `json:"locationId" binding:"required"` LocationId int64 `json:"locationId" binding:"required"`
UnikalNomer string `json:"unikalNomer" binding:"required"` UnikalNomer string `json:"unikalNomer" binding:"required"`
Address LocalizedText `json:"address" binding:"required"` Address LocalizedText `json:"address" binding:"required"`
BillingLogin string `json:"billingLogin"` BillingUsername string `json:"billingUsername"`
BillingPassword string `json:"billingPassword"` BillingPassword string `json:"billingPassword"`
BillingUsernameSber string `json:"billingUsernameSber"` BillingUsernameSber string `json:"billingUsernameSber"`
BillingPasswordSber string `json:"billingPasswordSber"` BillingPasswordSber string `json:"billingPasswordSber"`
BillingUsernameVisa string `json:"billingUsernameVisa"` BillingUsernameVisa string `json:"billingUsernameVisa"`
BillingPasswordVisa string `json:"billingPasswordVisa"` BillingPasswordVisa string `json:"billingPasswordVisa"`
BillingUsernameSwift string `json:"billingUsernameSwift"`
BillingPasswordSwift string `json:"billingPasswordSwift"`
} }
type UpdateBranchDTO struct { type UpdateBranchDTO struct {
@@ -41,12 +45,14 @@ type UpdateBranchDTO struct {
LocationId int64 `json:"locationId" binding:"required"` LocationId int64 `json:"locationId" binding:"required"`
UnikalNomer string `json:"unikalNomer" binding:"required"` UnikalNomer string `json:"unikalNomer" binding:"required"`
Address LocalizedText `json:"address" binding:"required"` Address LocalizedText `json:"address" binding:"required"`
BillingLogin string `json:"billingLogin"` BillingUsername string `json:"billingUsername"`
BillingPassword string `json:"billingPassword"` BillingPassword string `json:"billingPassword"`
BillingUsernameSber string `json:"billingUsernameSber"` BillingUsernameSber string `json:"billingUsernameSber"`
BillingPasswordSber string `json:"billingPasswordSber"` BillingPasswordSber string `json:"billingPasswordSber"`
BillingUsernameVisa string `json:"billingUsernameVisa"` BillingUsernameVisa string `json:"billingUsernameVisa"`
BillingPasswordVisa string `json:"billingPasswordVisa"` BillingPasswordVisa string `json:"billingPasswordVisa"`
BillingUsernameSwift string `json:"billingUsernameSwift"`
BillingPasswordSwift string `json:"billingPasswordSwift"`
} }
type ListFilter struct { type ListFilter struct {
@@ -63,7 +63,7 @@ func (r *repository) List(ctx context.Context, filter loansdocument.ListFilter)
} }
func buildListQuery(filter loansdocument.ListFilter) (fromClause, whereClause string, args []interface{}) { func buildListQuery(filter loansdocument.ListFilter) (fromClause, whereClause string, args []interface{}) {
fromClause = ` FROM loans_documents d` fromClause = ` FROM loan_required_documents d`
var conditions []string var conditions []string
@@ -95,7 +95,7 @@ func likePattern(term string) string {
} }
func (r *repository) GetByID(ctx context.Context, id int64) (loansdocument.LoanDocumentDTO, error) { func (r *repository) GetByID(ctx context.Context, id int64) (loansdocument.LoanDocumentDTO, error) {
query := fmt.Sprintf(`SELECT %s FROM loans_documents d WHERE d.id = $1`, documentColumns) query := fmt.Sprintf(`SELECT %s FROM loan_required_documents d WHERE d.id = $1`, documentColumns)
item, err := scanLoanDocument(r.client.QueryRow(ctx, query, id)) item, err := scanLoanDocument(r.client.QueryRow(ctx, query, id))
if errors.Is(err, pgx.ErrNoRows) { if errors.Is(err, pgx.ErrNoRows) {
return loansdocument.LoanDocumentDTO{}, err return loansdocument.LoanDocumentDTO{}, err
@@ -115,7 +115,7 @@ func (r *repository) Create(ctx context.Context, dto loansdocument.CreateLoanDoc
} }
query := fmt.Sprintf(` query := fmt.Sprintf(`
INSERT INTO loans_documents (title, content_en, content_ru, content_tm, status) INSERT INTO loan_required_documents (title, content_en, content_ru, content_tm, status)
VALUES ($1, $2, $3, $4, $5) VALUES ($1, $2, $3, $4, $5)
RETURNING %s`, documentColumns) RETURNING %s`, documentColumns)
@@ -129,7 +129,7 @@ func (r *repository) Update(ctx context.Context, id int64, dto loansdocument.Upd
} }
query := fmt.Sprintf(` query := fmt.Sprintf(`
UPDATE loans_documents SET UPDATE loan_required_documents SET
title = $1, content_en = $2, content_ru = $3, content_tm = $4, status = $5, title = $1, content_en = $2, content_ru = $3, content_tm = $4, status = $5,
updated_at = (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') updated_at = (CURRENT_TIMESTAMP AT TIME ZONE 'UTC')
WHERE id = $6 WHERE id = $6
@@ -144,7 +144,7 @@ func (r *repository) Update(ctx context.Context, id int64, dto loansdocument.Upd
func (r *repository) UpdateStatus(ctx context.Context, id int64, status bool) (loansdocument.LoanDocumentDTO, error) { func (r *repository) UpdateStatus(ctx context.Context, id int64, status bool) (loansdocument.LoanDocumentDTO, error) {
query := fmt.Sprintf(` query := fmt.Sprintf(`
UPDATE loans_documents SET UPDATE loan_required_documents SET
status = $1, status = $1,
updated_at = (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') updated_at = (CURRENT_TIMESTAMP AT TIME ZONE 'UTC')
WHERE id = $2 WHERE id = $2
@@ -158,7 +158,7 @@ func (r *repository) UpdateStatus(ctx context.Context, id int64, status bool) (l
} }
func (r *repository) Delete(ctx context.Context, id int64) error { func (r *repository) Delete(ctx context.Context, id int64) error {
tag, err := r.client.Exec(ctx, `DELETE FROM loans_documents WHERE id = $1`, id) tag, err := r.client.Exec(ctx, `DELETE FROM loan_required_documents WHERE id = $1`, id)
if err != nil { if err != nil {
return err return err
} }
+2 -2
View File
@@ -31,7 +31,7 @@ func (h *handler) Register(router *gin.RouterGroup) {
group.GET("/:id", h.getByID) group.GET("/:id", h.getByID)
group.POST("", h.create) group.POST("", h.create)
group.PUT("/:id", h.update) group.PUT("/:id", h.update)
group.PATCH("/:id/status", h.updateStatus) group.PUT("/:id/status", h.updateStatus)
group.DELETE("/:id", h.delete) group.DELETE("/:id", h.delete)
} }
@@ -182,7 +182,7 @@ func (h *handler) update(c *gin.Context) {
// @Failure 400 {object} appresult.AppError // @Failure 400 {object} appresult.AppError
// @Failure 404 {object} appresult.AppError // @Failure 404 {object} appresult.AppError
// @Failure 500 {object} appresult.AppError // @Failure 500 {object} appresult.AppError
// @Router /loans-documents/{id}/status [patch] // @Router /loans-documents/{id}/status [put]
func (h *handler) updateStatus(c *gin.Context) { func (h *handler) updateStatus(c *gin.Context) {
id, ok := parseID(c.Param("id")) id, ok := parseID(c.Param("id"))
if !ok { if !ok {
+2 -2
View File
@@ -69,7 +69,7 @@ func buildListQuery(filter location.ListFilter) (fromClause, whereClause string,
fromClause = ` FROM location l` fromClause = ` FROM location l`
if filter.ProvinceName != "" { if filter.ProvinceName != "" {
fromClause += ` JOIN province p ON p.id = l.province_id` fromClause += ` JOIN provinces p ON p.id = l.province_id`
} }
var conditions []string var conditions []string
@@ -197,7 +197,7 @@ func (r *repository) Delete(ctx context.Context, id int64) error {
func (r *repository) ensureProvinceExists(ctx context.Context, provinceID int64) error { func (r *repository) ensureProvinceExists(ctx context.Context, provinceID int64) error {
var id int64 var id int64
err := r.client.QueryRow(ctx, `SELECT id FROM province WHERE id = $1`, provinceID).Scan(&id) err := r.client.QueryRow(ctx, `SELECT id FROM provinces WHERE id = $1`, provinceID).Scan(&id)
if errors.Is(err, pgx.ErrNoRows) { if errors.Is(err, pgx.ErrNoRows) {
return fmt.Errorf("province not found") return fmt.Errorf("province not found")
} }
+2 -2
View File
@@ -31,7 +31,7 @@ func (h *handler) Register(router *gin.RouterGroup) {
group.GET("/:id", h.getByID) group.GET("/:id", h.getByID)
group.POST("", h.create) group.POST("", h.create)
group.PUT("/:id", h.update) group.PUT("/:id", h.update)
group.PATCH("/:id/status", h.updateStatus) group.PUT("/:id/status", h.updateStatus)
group.DELETE("/:id", h.delete) group.DELETE("/:id", h.delete)
} }
@@ -192,7 +192,7 @@ func (h *handler) update(c *gin.Context) {
// @Failure 400 {object} appresult.AppError // @Failure 400 {object} appresult.AppError
// @Failure 404 {object} appresult.AppError // @Failure 404 {object} appresult.AppError
// @Failure 500 {object} appresult.AppError // @Failure 500 {object} appresult.AppError
// @Router /locations/{id}/status [patch] // @Router /locations/{id}/status [put]
func (h *handler) updateStatus(c *gin.Context) { func (h *handler) updateStatus(c *gin.Context) {
id, ok := parseID(c.Param("id")) id, ok := parseID(c.Param("id"))
if !ok { if !ok {
+2 -2
View File
@@ -31,7 +31,7 @@ func (h *handler) Register(router *gin.RouterGroup) {
group.GET("/:id", h.getByID) group.GET("/:id", h.getByID)
group.POST("", h.create) group.POST("", h.create)
group.PUT("/:id", h.update) group.PUT("/:id", h.update)
group.PATCH("/:id/status", h.updateStatus) group.PUT("/:id/status", h.updateStatus)
group.DELETE("/:id", h.delete) group.DELETE("/:id", h.delete)
} }
@@ -182,7 +182,7 @@ func (h *handler) update(c *gin.Context) {
// @Failure 400 {object} appresult.AppError // @Failure 400 {object} appresult.AppError
// @Failure 404 {object} appresult.AppError // @Failure 404 {object} appresult.AppError
// @Failure 500 {object} appresult.AppError // @Failure 500 {object} appresult.AppError
// @Router /payment-cards/{id}/status [patch] // @Router /payment-cards/{id}/status [put]
func (h *handler) updateStatus(c *gin.Context) { func (h *handler) updateStatus(c *gin.Context) {
id, ok := parseID(c.Param("id")) id, ok := parseID(c.Param("id"))
if !ok { if !ok {
+15 -7
View File
@@ -22,7 +22,7 @@ func NewRepository(client postgresql.Client, logger *logging.Logger) province.Re
} }
func (r *repository) List(ctx context.Context) ([]province.ProvinceDTO, error) { func (r *repository) List(ctx context.Context) ([]province.ProvinceDTO, error) {
rows, err := r.client.Query(ctx, `SELECT id, title FROM province ORDER BY id`) rows, err := r.client.Query(ctx, `SELECT id, title, status FROM provinces ORDER BY id`)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@@ -41,7 +41,7 @@ func (r *repository) List(ctx context.Context) ([]province.ProvinceDTO, error) {
} }
func (r *repository) GetByID(ctx context.Context, id int64) (province.ProvinceDTO, error) { func (r *repository) GetByID(ctx context.Context, id int64) (province.ProvinceDTO, error) {
row := r.client.QueryRow(ctx, `SELECT id, title FROM province WHERE id = $1`, id) row := r.client.QueryRow(ctx, `SELECT id, title, status FROM provinces WHERE id = $1`, id)
item, err := scanProvince(row) item, err := scanProvince(row)
if errors.Is(err, pgx.ErrNoRows) { if errors.Is(err, pgx.ErrNoRows) {
return province.ProvinceDTO{}, err return province.ProvinceDTO{}, err
@@ -55,7 +55,15 @@ func (r *repository) Create(ctx context.Context, dto province.CreateProvinceDTO)
return province.ProvinceDTO{}, err return province.ProvinceDTO{}, err
} }
row := r.client.QueryRow(ctx, `INSERT INTO province (title) VALUES ($1) RETURNING id, title`, title) status := true
if dto.Status != nil {
status = *dto.Status
}
row := r.client.QueryRow(ctx,
`INSERT INTO provinces (title, status) VALUES ($1, $2) RETURNING id, title, status`,
title, status,
)
return scanProvince(row) return scanProvince(row)
} }
@@ -66,8 +74,8 @@ func (r *repository) Update(ctx context.Context, id int64, dto province.UpdatePr
} }
row := r.client.QueryRow(ctx, row := r.client.QueryRow(ctx,
`UPDATE province SET title = $1 WHERE id = $2 RETURNING id, title`, `UPDATE provinces SET title = $1, status = $2 WHERE id = $3 RETURNING id, title, status`,
title, id, title, dto.Status, id,
) )
item, err := scanProvince(row) item, err := scanProvince(row)
if errors.Is(err, pgx.ErrNoRows) { if errors.Is(err, pgx.ErrNoRows) {
@@ -77,7 +85,7 @@ func (r *repository) Update(ctx context.Context, id int64, dto province.UpdatePr
} }
func (r *repository) Delete(ctx context.Context, id int64) error { func (r *repository) Delete(ctx context.Context, id int64) error {
tag, err := r.client.Exec(ctx, `DELETE FROM province WHERE id = $1`, id) tag, err := r.client.Exec(ctx, `DELETE FROM provinces WHERE id = $1`, id)
if err != nil { if err != nil {
return err return err
} }
@@ -94,7 +102,7 @@ type scannable interface {
func scanProvince(row scannable) (province.ProvinceDTO, error) { func scanProvince(row scannable) (province.ProvinceDTO, error) {
var item province.ProvinceDTO var item province.ProvinceDTO
var titleJSON []byte var titleJSON []byte
if err := row.Scan(&item.Id, &titleJSON); err != nil { if err := row.Scan(&item.Id, &titleJSON, &item.Status); err != nil {
return province.ProvinceDTO{}, err return province.ProvinceDTO{}, err
} }
if err := json.Unmarshal(titleJSON, &item.Title); err != nil { if err := json.Unmarshal(titleJSON, &item.Title); err != nil {
+7 -4
View File
@@ -7,14 +7,17 @@ type LocalizedTitle struct {
} }
type ProvinceDTO struct { type ProvinceDTO struct {
Id int64 `json:"id"` Id int64 `json:"id"`
Title LocalizedTitle `json:"title"` Title LocalizedTitle `json:"title"`
Status bool `json:"status"`
} }
type CreateProvinceDTO struct { type CreateProvinceDTO struct {
Title LocalizedTitle `json:"title" binding:"required"` Title LocalizedTitle `json:"title" binding:"required"`
Status *bool `json:"status"`
} }
type UpdateProvinceDTO struct { type UpdateProvinceDTO struct {
Title LocalizedTitle `json:"title" binding:"required"` Title LocalizedTitle `json:"title" binding:"required"`
Status bool `json:"status"`
} }
+1 -2
View File
@@ -28,7 +28,7 @@ import (
"github.com/jackc/pgx/v4/pgxpool" "github.com/jackc/pgx/v4/pgxpool"
) )
const adminAPIPrefix = "/v1/admin" const adminAPIPrefix = "/api/admin"
func New(cfg *config.Config, client *pgxpool.Pool, logger *logging.Logger) *gin.Engine { func New(cfg *config.Config, client *pgxpool.Pool, logger *logging.Logger) *gin.Engine {
if cfg.IsDebug != nil && !*cfg.IsDebug { if cfg.IsDebug != nil && !*cfg.IsDebug {
@@ -43,7 +43,6 @@ func New(cfg *config.Config, client *pgxpool.Pool, logger *logging.Logger) *gin.
http.MethodGet, http.MethodGet,
http.MethodPost, http.MethodPost,
http.MethodPut, http.MethodPut,
http.MethodPatch,
http.MethodDelete, http.MethodDelete,
}, },
AllowHeaders: []string{ AllowHeaders: []string{