naise_pos/api/product_category.go

98 lines
2.6 KiB
Go
Raw Normal View History

2023-03-16 16:55:45 +07:00
package api
import (
"database/sql"
"net/http"
db "git.nochill.in/nochill/naice_pos/db/sqlc"
"git.nochill.in/nochill/naice_pos/token"
"github.com/gin-gonic/gin"
"github.com/google/uuid"
)
type createProductCategoryRequest struct {
MerchantID uuid.UUID `json:"merchant_id" binding:"required"`
Name string `json:"name" binding:"required"`
}
func (server *Server) createProductCategory(ctx *gin.Context) {
var req createProductCategoryRequest
if err := ctx.ShouldBindJSON(&req); err != nil {
2023-03-22 12:06:09 +07:00
ctx.JSON(http.StatusBadRequest, errorResponse(err, ""))
2023-03-16 16:55:45 +07:00
return
}
authPayload := ctx.MustGet(authorizationPayloadKey).(*token.Payload)
arg := db.CreateProductCategoryParams{
MerchantID: authPayload.MerchantID,
Name: req.Name,
}
ProductCategory, err := server.store.CreateProductCategory(ctx, arg)
if err != nil {
2023-03-22 12:06:09 +07:00
ctx.JSON(http.StatusInternalServerError, errorResponse(err, ""))
2023-03-16 16:55:45 +07:00
return
}
ctx.JSON(http.StatusOK, ProductCategory)
}
type listProductCategoriesRequest struct {
PageID int32 `form:"page_id" binding:"required,min=1"`
PageSize int32 `form:"page_size" binding:"required,min=5"`
}
func (server *Server) listProductCategories(ctx *gin.Context) {
var req listProductCategoriesRequest
if err := ctx.ShouldBindQuery(&req); err != nil {
2023-03-22 12:06:09 +07:00
ctx.JSON(http.StatusBadRequest, errorResponse(err, ""))
2023-03-16 16:55:45 +07:00
return
}
authPayload := ctx.MustGet(authorizationPayloadKey).(*token.Payload)
arg := db.ListProductCategoriesByMerchantIDParams{
MerchantID: authPayload.MerchantID,
Limit: req.PageSize,
Offset: (req.PageID - 1) * req.PageSize,
}
ProductCategories, err := server.store.ListProductCategoriesByMerchantID(ctx, arg)
if err != nil {
2023-03-22 12:06:09 +07:00
ctx.JSON(http.StatusInternalServerError, errorResponse(err, ""))
2023-03-16 16:55:45 +07:00
return
}
ctx.JSON(http.StatusOK, ProductCategories)
}
type updateProductCategoryRequest struct {
ProductCategoryID uuid.UUID `json:"ProductCategory_id" binding:"required"`
Name string `json:"name" binding:"required"`
}
func (server *Server) updateProductCategory(ctx *gin.Context) {
var req updateProductCategoryRequest
if err := ctx.ShouldBindJSON(&req); err != nil {
2023-03-22 12:06:09 +07:00
ctx.JSON(http.StatusBadRequest, errorResponse(err, ""))
2023-03-16 16:55:45 +07:00
return
}
arg := db.UpdateProductCategoryParams{
ID: req.ProductCategoryID,
Name: req.Name,
}
ProductCategory, err := server.store.UpdateProductCategory(ctx, arg)
if err != nil {
if err == sql.ErrNoRows {
2023-03-22 12:06:09 +07:00
ctx.JSON(http.StatusNotFound, errorResponse(err, ""))
2023-03-16 16:55:45 +07:00
return
}
2023-03-22 12:06:09 +07:00
ctx.JSON(http.StatusInternalServerError, errorResponse(err, ""))
2023-03-16 16:55:45 +07:00
return
}
ctx.JSON(http.StatusOK, ProductCategory)
}