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:
47
app.go
47
app.go
@@ -3,8 +3,7 @@ package main
|
||||
import (
|
||||
"context"
|
||||
|
||||
_ "online-back/docs"
|
||||
"online-back/internal/admin/auth"
|
||||
"online-back/docs"
|
||||
"online-back/internal/config"
|
||||
handlermanager "online-back/internal/handlers/manager"
|
||||
"online-back/pkg/client/postgresql"
|
||||
@@ -15,32 +14,39 @@ import (
|
||||
ginSwagger "github.com/swaggo/gin-swagger"
|
||||
)
|
||||
|
||||
// @title Service APIs
|
||||
// @title Service APIs
|
||||
// @version 1.0
|
||||
// @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
|
||||
// @BasePath /v1/admin
|
||||
// @BasePath /api/admin
|
||||
// @securityDefinitions.apikey BearerAuth
|
||||
// @in header
|
||||
// @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
|
||||
// @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() {
|
||||
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()
|
||||
logger := logging.GetLogger()
|
||||
|
||||
@@ -48,7 +54,6 @@ func main() {
|
||||
router := handlermanager.New(cfg, pool, logger)
|
||||
|
||||
router.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler))
|
||||
router.GET("/images/:id", auth.GetObject)
|
||||
|
||||
addr := cfg.Listen.BindIP + ":" + cfg.Listen.Port
|
||||
logger.Infof("starting server on %s", addr)
|
||||
|
||||
@@ -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 reasons_cards;
|
||||
DROP TABLE IF EXISTS payment_cards;
|
||||
DROP TABLE IF EXISTS branches;
|
||||
DROP TABLE IF EXISTS location;
|
||||
DROP TABLE IF EXISTS province;
|
||||
DROP TABLE IF EXISTS admin;
|
||||
DROP TABLE IF EXISTS provinces;
|
||||
DROP TABLE IF EXISTS users;
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
CREATE TABLE IF NOT EXISTS admin (
|
||||
CREATE TABLE IF NOT EXISTS users (
|
||||
"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 '',
|
||||
"fullname" 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
|
||||
);
|
||||
|
||||
insert into admin(
|
||||
phone_number, password, fullname, login, role
|
||||
insert into users(
|
||||
phone_number, password, fullname, email, role
|
||||
) values (
|
||||
'61531216',
|
||||
'$2a$12$8ZbKmoSwna4CASQptM2/SubwvsBUR1YhABULd.2/QJB.13Wi2v55m',
|
||||
@@ -24,16 +24,17 @@ insert into admin(
|
||||
'admin'
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS province (
|
||||
CREATE TABLE IF NOT EXISTS provinces (
|
||||
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,
|
||||
"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 (
|
||||
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,
|
||||
status boolean NOT NULL DEFAULT true,
|
||||
"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 (
|
||||
id bigserial PRIMARY KEY,
|
||||
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,
|
||||
unikal_nomer character varying(250) NOT NULL UNIQUE,
|
||||
address json NOT NULL DEFAULT '{}'::json,
|
||||
billing_login character varying(250) NOT NULL DEFAULT '',
|
||||
"address" text NOT NULL DEFAULT '',
|
||||
billing_username character varying(250) NOT NULL DEFAULT '',
|
||||
billing_password 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_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,
|
||||
"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
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS loans_documents (
|
||||
CREATE TABLE IF NOT EXISTS loan_required_documents (
|
||||
id bigserial PRIMARY KEY,
|
||||
title json NOT NULL DEFAULT '{}'::json,
|
||||
content_en text NOT NULL DEFAULT '',
|
||||
|
||||
1548
docs/docs.go
1548
docs/docs.go
File diff suppressed because it is too large
Load Diff
1542
docs/swagger.json
1542
docs/swagger.json
File diff suppressed because it is too large
Load Diff
1027
docs/swagger.yaml
1027
docs/swagger.yaml
File diff suppressed because it is too large
Load Diff
60
docs/tag_order.go
Normal file
60
docs/tag_order.go
Normal 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, `"`, `\"`) + `"`
|
||||
}
|
||||
@@ -2,7 +2,6 @@ package db
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strconv"
|
||||
|
||||
"online-back/internal/admin/auth"
|
||||
"online-back/pkg/client/postgresql"
|
||||
@@ -22,32 +21,27 @@ func NewRepository(client postgresql.Client, logger *logging.Logger) auth.Reposi
|
||||
}
|
||||
|
||||
const (
|
||||
loginQuery = `SELECT id, password FROM admin WHERE login = $1`
|
||||
adminQuery = `SELECT id, password FROM admin WHERE id = $1`
|
||||
loginQuery = `SELECT id, password FROM users WHERE email = $1`
|
||||
userByIDQuery = `SELECT id, password FROM users WHERE id = $1`
|
||||
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) {
|
||||
var result auth.ResLoginDTO
|
||||
err := r.client.QueryRow(ctx, loginQuery, dto.Login).Scan(&result.Id, &result.Password)
|
||||
func (r *repository) Login(ctx context.Context, dto auth.LoginDTO) (auth.UserCredentials, error) {
|
||||
var result auth.UserCredentials
|
||||
err := r.client.QueryRow(ctx, loginQuery, dto.Email).Scan(&result.Id, &result.Password)
|
||||
return result, err
|
||||
}
|
||||
|
||||
func (r *repository) CheckAdmin(ctx context.Context, id int) (auth.ResLoginDTO, error) {
|
||||
var result auth.ResLoginDTO
|
||||
err := r.client.QueryRow(ctx, adminQuery, id).Scan(&result.Id, &result.Password)
|
||||
func (r *repository) GetUserByID(ctx context.Context, id int) (auth.UserCredentials, error) {
|
||||
var result auth.UserCredentials
|
||||
err := r.client.QueryRow(ctx, userByIDQuery, id).Scan(&result.Id, &result.Password)
|
||||
return result, err
|
||||
}
|
||||
|
||||
func (r *repository) GetProfile(ctx context.Context, id string) (auth.ResUserDTO, error) {
|
||||
var profile auth.ResUserDTO
|
||||
adminID, err := strconv.Atoi(id)
|
||||
if err != nil {
|
||||
return profile, err
|
||||
}
|
||||
|
||||
err = r.client.QueryRow(ctx, profileQuery, adminID).Scan(
|
||||
func (r *repository) GetProfile(ctx context.Context, id int) (auth.UserProfileDTO, error) {
|
||||
var profile auth.UserProfileDTO
|
||||
err := r.client.QueryRow(ctx, profileQuery, id).Scan(
|
||||
&profile.Id,
|
||||
&profile.FullName,
|
||||
&profile.PhoneNumber,
|
||||
|
||||
@@ -3,23 +3,23 @@ package auth
|
||||
import "time"
|
||||
|
||||
type LoginDTO struct {
|
||||
Login string `json:"login" binding:"required"`
|
||||
Email string `json:"email" binding:"required"`
|
||||
Password string `json:"password" binding:"required"`
|
||||
}
|
||||
|
||||
type ResLoginDTO struct {
|
||||
Id int `json:"id"`
|
||||
Password string `json:"-"`
|
||||
}
|
||||
|
||||
type TokenReqBody struct {
|
||||
type RefreshTokenDTO struct {
|
||||
RefreshToken string `json:"refreshToken" binding:"required"`
|
||||
}
|
||||
|
||||
type ResUserDTO struct {
|
||||
type UserProfileDTO struct {
|
||||
Id int `json:"id"`
|
||||
FullName string `json:"fullName"`
|
||||
PhoneNumber string `json:"phoneNumber"`
|
||||
Avatar string `json:"avatar"`
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
}
|
||||
|
||||
type UserCredentials struct {
|
||||
Id int
|
||||
Password string
|
||||
}
|
||||
|
||||
@@ -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))
|
||||
}
|
||||
@@ -1,13 +1,10 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
|
||||
"online-back/internal/appresult"
|
||||
"online-back/internal/config"
|
||||
"online-back/internal/handlers"
|
||||
"online-back/pkg/logging"
|
||||
"online-back/pkg/utils"
|
||||
@@ -17,11 +14,9 @@ import (
|
||||
)
|
||||
|
||||
const (
|
||||
loginURL = "/login"
|
||||
tokenURL = "/token"
|
||||
getProfileURL = "/get-profile"
|
||||
fileUploadURL = "/file"
|
||||
fileRemoveURL = "/file/:id"
|
||||
loginURL = "/login"
|
||||
tokenURL = "/token"
|
||||
profileURL = "/profile"
|
||||
)
|
||||
|
||||
type handler struct {
|
||||
@@ -30,50 +25,48 @@ type handler struct {
|
||||
}
|
||||
|
||||
func NewHandler(logger *logging.Logger, repository Repository) handlers.Handler {
|
||||
return &handler{
|
||||
logger: logger,
|
||||
repository: repository,
|
||||
}
|
||||
return &handler{logger: logger, repository: repository}
|
||||
}
|
||||
|
||||
func (h *handler) Register(router *gin.RouterGroup) {
|
||||
router.POST(loginURL, h.login)
|
||||
router.POST(tokenURL, h.token)
|
||||
router.GET(getProfileURL, appresult.JwtTokenCheck(), h.getProfile)
|
||||
router.POST(fileUploadURL, appresult.JwtTokenCheck(), h.fileUpload)
|
||||
router.DELETE(fileRemoveURL, appresult.JwtTokenCheck(), h.deleteObject)
|
||||
router.POST(tokenURL, h.refreshToken)
|
||||
|
||||
protected := router.Group("", appresult.JwtTokenCheck())
|
||||
protected.GET(profileURL, h.getProfile)
|
||||
}
|
||||
|
||||
// login godoc
|
||||
// @Description login for Admin
|
||||
// @Tags auth
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param auth body LoginDTO true "Login JSON"
|
||||
// @Success 200 {object} appresult.AppSuccess
|
||||
// @Failure 400 {object} appresult.AppError
|
||||
// @Router /login [post]
|
||||
// @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 loginReq LoginDTO
|
||||
if err := c.ShouldBindJSON(&loginReq); err != nil {
|
||||
var dto LoginDTO
|
||||
if err := c.ShouldBindJSON(&dto); err != nil {
|
||||
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
|
||||
return
|
||||
}
|
||||
|
||||
ctx := c.Request.Context()
|
||||
res, err := h.repository.Login(ctx, loginReq)
|
||||
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(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)
|
||||
return
|
||||
}
|
||||
|
||||
tokenPair, err := utils.GenerateTokenPair(res.Id)
|
||||
tokenPair, err := utils.GenerateTokenPair(user.Id)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, appresult.ErrNotAcceptable)
|
||||
return
|
||||
@@ -82,23 +75,25 @@ func (h *handler) login(c *gin.Context) {
|
||||
c.JSON(http.StatusOK, appresult.SuccessWithData(tokenPair))
|
||||
}
|
||||
|
||||
// token godoc
|
||||
// @Description refresh admin tokens
|
||||
// @Tags auth
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param auth body TokenReqBody true "Token JSON"
|
||||
// @Success 200 {object} appresult.AppSuccess
|
||||
// @Failure 400 {object} appresult.AppError
|
||||
// @Router /token [post]
|
||||
func (h *handler) token(c *gin.Context) {
|
||||
var tokenReq TokenReqBody
|
||||
if err := c.ShouldBindJSON(&tokenReq); err != nil {
|
||||
// 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(tokenReq.RefreshToken)
|
||||
claims, err := utils.ParseRefreshToken(dto.RefreshToken)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusUnauthorized, appresult.ErrUnauthorized)
|
||||
return
|
||||
@@ -110,8 +105,8 @@ func (h *handler) token(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
admin, err := h.repository.CheckAdmin(c.Request.Context(), id)
|
||||
if err != nil || admin.Id != id {
|
||||
user, err := h.repository.GetUserByID(c.Request.Context(), id)
|
||||
if err != nil || user.Id != id {
|
||||
c.JSON(http.StatusUnauthorized, appresult.ErrUnauthorized)
|
||||
return
|
||||
}
|
||||
@@ -126,100 +121,46 @@ func (h *handler) token(c *gin.Context) {
|
||||
}
|
||||
|
||||
// getProfile godoc
|
||||
// @Description profile data for Admin
|
||||
// @Tags admin
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Success 200 {object} appresult.AppSuccess
|
||||
// @Failure 400 {object} appresult.AppError
|
||||
// @Router /get-profile [get]
|
||||
// @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) {
|
||||
adminID, _ := c.Get("id")
|
||||
profile, err := h.repository.GetProfile(c.Request.Context(), fmt.Sprint(adminID))
|
||||
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.StatusBadRequest, appresult.ErrNotFound)
|
||||
c.JSON(http.StatusNotFound, appresult.ErrNotFound)
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, appresult.SuccessWithData(profile))
|
||||
}
|
||||
|
||||
// fileUpload godoc
|
||||
// @Description file upload
|
||||
// @Tags file-upload
|
||||
// @Accept multipart/form-data
|
||||
// @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
|
||||
func currentUserID(c *gin.Context) (int, bool) {
|
||||
rawID, exists := c.Get("id")
|
||||
if !exists {
|
||||
return 0, false
|
||||
}
|
||||
|
||||
cfg := config.GetConfig()
|
||||
dir := imageStorageDir(cfg.PublicFilePath)
|
||||
if err := os.MkdirAll(dir, 0755); err != nil {
|
||||
h.logger.Errorf("create upload dir failed: %v", err)
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
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
|
||||
}
|
||||
|
||||
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,7 +3,7 @@ package auth
|
||||
import "context"
|
||||
|
||||
type Repository interface {
|
||||
Login(ctx context.Context, dto LoginDTO) (ResLoginDTO, error)
|
||||
CheckAdmin(ctx context.Context, id int) (ResLoginDTO, error)
|
||||
GetProfile(ctx context.Context, req string) (ResUserDTO, error)
|
||||
Login(ctx context.Context, dto LoginDTO) (UserCredentials, error)
|
||||
GetUserByID(ctx context.Context, id int) (UserCredentials, error)
|
||||
GetProfile(ctx context.Context, id int) (UserProfileDTO, error)
|
||||
}
|
||||
|
||||
@@ -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,
|
||||
b.billing_login, b.billing_password, b.billing_username_sber, b.billing_password_sber,
|
||||
b.billing_username_visa, b.billing_password_visa`
|
||||
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_swift, b.billing_password_swift`
|
||||
|
||||
func (r *repository) List(ctx context.Context, filter branches.ListFilter) (branches.ListBranchDTO, error) {
|
||||
fromClause, whereClause, args := buildListQuery(filter)
|
||||
@@ -71,7 +72,7 @@ func buildListQuery(filter branches.ListFilter) (fromClause, whereClause string,
|
||||
fromClause = ` FROM branches b`
|
||||
|
||||
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
|
||||
@@ -145,15 +146,17 @@ func (r *repository) Create(ctx context.Context, dto branches.CreateBranchDTO) (
|
||||
query := fmt.Sprintf(`
|
||||
INSERT INTO branches (
|
||||
title, province_id, location_id, unikal_nomer, address,
|
||||
billing_login, billing_password, billing_username_sber, billing_password_sber,
|
||||
billing_username_visa, billing_password_visa
|
||||
) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11)
|
||||
billing_username, billing_password, billing_username_sber, billing_password_sber,
|
||||
billing_username_visa, billing_password_visa,
|
||||
billing_username_swift, billing_password_swift
|
||||
) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13)
|
||||
RETURNING %s`, branchColumns)
|
||||
|
||||
row := r.client.QueryRow(ctx, query,
|
||||
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.BillingUsernameSwift, dto.BillingPasswordSwift,
|
||||
)
|
||||
item, err := scanBranch(row)
|
||||
if isUniqueViolation(err) {
|
||||
@@ -175,15 +178,17 @@ func (r *repository) Update(ctx context.Context, id int64, dto branches.UpdateBr
|
||||
query := fmt.Sprintf(`
|
||||
UPDATE branches SET
|
||||
title = $1, province_id = $2, location_id = $3, unikal_nomer = $4, address = $5,
|
||||
billing_login = $6, billing_password = $7, billing_username_sber = $8,
|
||||
billing_password_sber = $9, billing_username_visa = $10, billing_password_visa = $11
|
||||
WHERE id = $12
|
||||
billing_username = $6, billing_password = $7, billing_username_sber = $8,
|
||||
billing_password_sber = $9, billing_username_visa = $10, billing_password_visa = $11,
|
||||
billing_username_swift = $12, billing_password_swift = $13
|
||||
WHERE id = $14
|
||||
RETURNING %s`, branchColumns)
|
||||
|
||||
row := r.client.QueryRow(ctx, query,
|
||||
title, dto.ProvinceId, dto.LocationId, dto.UnikalNomer, address,
|
||||
dto.BillingLogin, dto.BillingPassword, dto.BillingUsernameSber, dto.BillingPasswordSber,
|
||||
dto.BillingUsernameVisa, dto.BillingPasswordVisa, id,
|
||||
dto.BillingUsername, dto.BillingPassword, dto.BillingUsernameSber, dto.BillingPasswordSber,
|
||||
dto.BillingUsernameVisa, dto.BillingPasswordVisa,
|
||||
dto.BillingUsernameSwift, dto.BillingPasswordSwift, id,
|
||||
)
|
||||
item, err := scanBranch(row)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
@@ -244,8 +249,9 @@ func scanBranch(row scannable) (branches.BranchDTO, error) {
|
||||
|
||||
err := row.Scan(
|
||||
&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.BillingUsernameSwift, &item.BillingPasswordSwift,
|
||||
)
|
||||
if err != nil {
|
||||
return branches.BranchDTO{}, err
|
||||
|
||||
@@ -13,12 +13,14 @@ type BranchDTO struct {
|
||||
LocationId int64 `json:"locationId"`
|
||||
UnikalNomer string `json:"unikalNomer"`
|
||||
Address LocalizedText `json:"address"`
|
||||
BillingLogin string `json:"billingLogin"`
|
||||
BillingUsername string `json:"billingUsername"`
|
||||
BillingPassword string `json:"billingPassword"`
|
||||
BillingUsernameSber string `json:"billingUsernameSber"`
|
||||
BillingPasswordSber string `json:"billingPasswordSber"`
|
||||
BillingUsernameVisa string `json:"billingUsernameVisa"`
|
||||
BillingPasswordVisa string `json:"billingPasswordVisa"`
|
||||
BillingUsernameVisa string `json:"billingUsernameVisa"`
|
||||
BillingPasswordVisa string `json:"billingPasswordVisa"`
|
||||
BillingUsernameSwift string `json:"billingUsernameSwift"`
|
||||
BillingPasswordSwift string `json:"billingPasswordSwift"`
|
||||
}
|
||||
|
||||
type CreateBranchDTO struct {
|
||||
@@ -27,12 +29,14 @@ type CreateBranchDTO struct {
|
||||
LocationId int64 `json:"locationId" binding:"required"`
|
||||
UnikalNomer string `json:"unikalNomer" binding:"required"`
|
||||
Address LocalizedText `json:"address" binding:"required"`
|
||||
BillingLogin string `json:"billingLogin"`
|
||||
BillingUsername string `json:"billingUsername"`
|
||||
BillingPassword string `json:"billingPassword"`
|
||||
BillingUsernameSber string `json:"billingUsernameSber"`
|
||||
BillingPasswordSber string `json:"billingPasswordSber"`
|
||||
BillingUsernameVisa string `json:"billingUsernameVisa"`
|
||||
BillingPasswordVisa string `json:"billingPasswordVisa"`
|
||||
BillingUsernameVisa string `json:"billingUsernameVisa"`
|
||||
BillingPasswordVisa string `json:"billingPasswordVisa"`
|
||||
BillingUsernameSwift string `json:"billingUsernameSwift"`
|
||||
BillingPasswordSwift string `json:"billingPasswordSwift"`
|
||||
}
|
||||
|
||||
type UpdateBranchDTO struct {
|
||||
@@ -41,12 +45,14 @@ type UpdateBranchDTO struct {
|
||||
LocationId int64 `json:"locationId" binding:"required"`
|
||||
UnikalNomer string `json:"unikalNomer" binding:"required"`
|
||||
Address LocalizedText `json:"address" binding:"required"`
|
||||
BillingLogin string `json:"billingLogin"`
|
||||
BillingUsername string `json:"billingUsername"`
|
||||
BillingPassword string `json:"billingPassword"`
|
||||
BillingUsernameSber string `json:"billingUsernameSber"`
|
||||
BillingPasswordSber string `json:"billingPasswordSber"`
|
||||
BillingUsernameVisa string `json:"billingUsernameVisa"`
|
||||
BillingPasswordVisa string `json:"billingPasswordVisa"`
|
||||
BillingUsernameVisa string `json:"billingUsernameVisa"`
|
||||
BillingPasswordVisa string `json:"billingPasswordVisa"`
|
||||
BillingUsernameSwift string `json:"billingUsernameSwift"`
|
||||
BillingPasswordSwift string `json:"billingPasswordSwift"`
|
||||
}
|
||||
|
||||
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{}) {
|
||||
fromClause = ` FROM loans_documents d`
|
||||
fromClause = ` FROM loan_required_documents d`
|
||||
|
||||
var conditions []string
|
||||
|
||||
@@ -95,7 +95,7 @@ func likePattern(term string) string {
|
||||
}
|
||||
|
||||
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))
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return loansdocument.LoanDocumentDTO{}, err
|
||||
@@ -115,7 +115,7 @@ func (r *repository) Create(ctx context.Context, dto loansdocument.CreateLoanDoc
|
||||
}
|
||||
|
||||
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)
|
||||
RETURNING %s`, documentColumns)
|
||||
|
||||
@@ -129,7 +129,7 @@ func (r *repository) Update(ctx context.Context, id int64, dto loansdocument.Upd
|
||||
}
|
||||
|
||||
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,
|
||||
updated_at = (CURRENT_TIMESTAMP AT TIME ZONE 'UTC')
|
||||
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) {
|
||||
query := fmt.Sprintf(`
|
||||
UPDATE loans_documents SET
|
||||
UPDATE loan_required_documents SET
|
||||
status = $1,
|
||||
updated_at = (CURRENT_TIMESTAMP AT TIME ZONE 'UTC')
|
||||
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 {
|
||||
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 {
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -31,7 +31,7 @@ func (h *handler) Register(router *gin.RouterGroup) {
|
||||
group.GET("/:id", h.getByID)
|
||||
group.POST("", h.create)
|
||||
group.PUT("/:id", h.update)
|
||||
group.PATCH("/:id/status", h.updateStatus)
|
||||
group.PUT("/:id/status", h.updateStatus)
|
||||
group.DELETE("/:id", h.delete)
|
||||
}
|
||||
|
||||
@@ -182,7 +182,7 @@ func (h *handler) update(c *gin.Context) {
|
||||
// @Failure 400 {object} appresult.AppError
|
||||
// @Failure 404 {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) {
|
||||
id, ok := parseID(c.Param("id"))
|
||||
if !ok {
|
||||
|
||||
@@ -69,7 +69,7 @@ func buildListQuery(filter location.ListFilter) (fromClause, whereClause string,
|
||||
fromClause = ` FROM location l`
|
||||
|
||||
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
|
||||
@@ -197,7 +197,7 @@ func (r *repository) Delete(ctx context.Context, id int64) error {
|
||||
|
||||
func (r *repository) ensureProvinceExists(ctx context.Context, provinceID int64) error {
|
||||
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) {
|
||||
return fmt.Errorf("province not found")
|
||||
}
|
||||
|
||||
@@ -31,7 +31,7 @@ func (h *handler) Register(router *gin.RouterGroup) {
|
||||
group.GET("/:id", h.getByID)
|
||||
group.POST("", h.create)
|
||||
group.PUT("/:id", h.update)
|
||||
group.PATCH("/:id/status", h.updateStatus)
|
||||
group.PUT("/:id/status", h.updateStatus)
|
||||
group.DELETE("/:id", h.delete)
|
||||
}
|
||||
|
||||
@@ -192,7 +192,7 @@ func (h *handler) update(c *gin.Context) {
|
||||
// @Failure 400 {object} appresult.AppError
|
||||
// @Failure 404 {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) {
|
||||
id, ok := parseID(c.Param("id"))
|
||||
if !ok {
|
||||
|
||||
@@ -31,7 +31,7 @@ func (h *handler) Register(router *gin.RouterGroup) {
|
||||
group.GET("/:id", h.getByID)
|
||||
group.POST("", h.create)
|
||||
group.PUT("/:id", h.update)
|
||||
group.PATCH("/:id/status", h.updateStatus)
|
||||
group.PUT("/:id/status", h.updateStatus)
|
||||
group.DELETE("/:id", h.delete)
|
||||
}
|
||||
|
||||
@@ -182,7 +182,7 @@ func (h *handler) update(c *gin.Context) {
|
||||
// @Failure 400 {object} appresult.AppError
|
||||
// @Failure 404 {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) {
|
||||
id, ok := parseID(c.Param("id"))
|
||||
if !ok {
|
||||
|
||||
@@ -22,7 +22,7 @@ func NewRepository(client postgresql.Client, logger *logging.Logger) province.Re
|
||||
}
|
||||
|
||||
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 {
|
||||
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) {
|
||||
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)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return province.ProvinceDTO{}, err
|
||||
@@ -55,7 +55,15 @@ func (r *repository) Create(ctx context.Context, dto province.CreateProvinceDTO)
|
||||
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)
|
||||
}
|
||||
|
||||
@@ -66,8 +74,8 @@ func (r *repository) Update(ctx context.Context, id int64, dto province.UpdatePr
|
||||
}
|
||||
|
||||
row := r.client.QueryRow(ctx,
|
||||
`UPDATE province SET title = $1 WHERE id = $2 RETURNING id, title`,
|
||||
title, id,
|
||||
`UPDATE provinces SET title = $1, status = $2 WHERE id = $3 RETURNING id, title, status`,
|
||||
title, dto.Status, id,
|
||||
)
|
||||
item, err := scanProvince(row)
|
||||
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 {
|
||||
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 {
|
||||
return err
|
||||
}
|
||||
@@ -94,7 +102,7 @@ type scannable interface {
|
||||
func scanProvince(row scannable) (province.ProvinceDTO, error) {
|
||||
var item province.ProvinceDTO
|
||||
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
|
||||
}
|
||||
if err := json.Unmarshal(titleJSON, &item.Title); err != nil {
|
||||
|
||||
@@ -7,14 +7,17 @@ type LocalizedTitle struct {
|
||||
}
|
||||
|
||||
type ProvinceDTO struct {
|
||||
Id int64 `json:"id"`
|
||||
Title LocalizedTitle `json:"title"`
|
||||
Id int64 `json:"id"`
|
||||
Title LocalizedTitle `json:"title"`
|
||||
Status bool `json:"status"`
|
||||
}
|
||||
|
||||
type CreateProvinceDTO struct {
|
||||
Title LocalizedTitle `json:"title" binding:"required"`
|
||||
Title LocalizedTitle `json:"title" binding:"required"`
|
||||
Status *bool `json:"status"`
|
||||
}
|
||||
|
||||
type UpdateProvinceDTO struct {
|
||||
Title LocalizedTitle `json:"title" binding:"required"`
|
||||
Title LocalizedTitle `json:"title" binding:"required"`
|
||||
Status bool `json:"status"`
|
||||
}
|
||||
|
||||
@@ -28,7 +28,7 @@ import (
|
||||
"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 {
|
||||
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.MethodPost,
|
||||
http.MethodPut,
|
||||
http.MethodPatch,
|
||||
http.MethodDelete,
|
||||
},
|
||||
AllowHeaders: []string{
|
||||
|
||||
Reference in New Issue
Block a user