naise_pos/api/product.go
2023-03-12 11:01:43 +07:00

104 lines
2.6 KiB
Go

package api
import (
"database/sql"
"net/http"
"time"
db "git.nochill.in/nochill/naice_pos/db/sqlc"
"github.com/gin-gonic/gin"
"github.com/google/uuid"
)
type createProductRequest struct {
MerchantID uuid.UUID `json:"merchant_id" binding:"required"`
Name string `json:"name" binding:"required"`
SellingPrice float64 `json:"selling_price" binding:"required"`
PurchasePrice float64 `json:"purchase_price" binding:"required"`
Stock float64 `json:"stock" binding:"number"`
}
func (server *Server) createProduct(ctx *gin.Context) {
var req createProductRequest
if err := ctx.ShouldBindJSON(&req); err != nil {
ctx.JSON(http.StatusBadRequest, errorResponse(err))
return
}
arg := db.CreateProductParams{
MerchantID: req.MerchantID,
Name: req.Name,
SellingPrice: req.SellingPrice,
PurchasePrice: req.PurchasePrice,
Stock: req.Stock,
}
product, err := server.store.CreateProduct(ctx, arg)
if err != nil {
ctx.JSON(http.StatusInternalServerError, errorResponse(err))
return
}
ctx.JSON(http.StatusOK, product)
}
type getProductRequest struct {
ID string `uri:"id" binding:"required,uuid"`
}
func (server *Server) getProduct(ctx *gin.Context) {
var req getProductRequest
if err := ctx.ShouldBindUri(&req); err != nil {
ctx.JSON(http.StatusBadRequest, errorResponse(err))
return
}
product, err := server.store.GetProduct(ctx, uuid.MustParse(req.ID))
if err != nil {
if err == sql.ErrNoRows {
ctx.JSON(http.StatusNotFound, errorResponse(err))
return
}
ctx.JSON(http.StatusInternalServerError, errorResponse(err))
return
}
ctx.JSON(http.StatusOK, product)
}
type updateProductRequest struct {
ProductID uuid.UUID `json:"product_id" binding:"required"`
Name string `json:"name" binding:"required"`
SellingPrice float64 `json:"selling_price" binding:"required"`
PurchasePrice float64 `json:"purchase_price" binding:"required"`
}
func (server *Server) updateProduct(ctx *gin.Context) {
var req updateProductRequest
if err := ctx.ShouldBindJSON(&req); err != nil {
ctx.JSON(http.StatusBadRequest, errorResponse(err))
return
}
arg := db.UpdateProductParams{
ID: req.ProductID,
Name: req.Name,
SellingPrice: req.SellingPrice,
PurchasePrice: req.PurchasePrice,
UpdatedAt: sql.NullTime{Time: time.Now(), Valid: true},
}
product, err := server.store.UpdateProduct(ctx, arg)
if err != nil {
if err == sql.ErrNoRows {
ctx.JSON(http.StatusNotFound, errorResponse(err))
return
}
ctx.JSON(http.StatusInternalServerError, errorResponse(err))
return
}
ctx.JSON(http.StatusOK, product)
}