naise_pos/api/product.go

104 lines
2.6 KiB
Go
Raw Normal View History

2023-03-07 18:52:37 +07:00
package api
import (
2023-03-12 11:01:43 +07:00
"database/sql"
2023-03-07 18:52:37 +07:00
"net/http"
2023-03-12 11:01:43 +07:00
"time"
2023-03-07 18:52:37 +07:00
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"`
2023-03-12 11:01:43 +07:00
Stock float64 `json:"stock" binding:"number"`
2023-03-07 18:52:37 +07:00
}
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)
}
2023-03-12 11:01:43 +07:00
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)
}