75 lines
2.0 KiB
Go
75 lines
2.0 KiB
Go
package handler
|
|
|
|
import (
|
|
"BE-MiniERP/database"
|
|
"BE-MiniERP/modules/inventory/models"
|
|
"BE-MiniERP/modules/inventory/repository"
|
|
"BE-MiniERP/modules/inventory/service"
|
|
"strconv"
|
|
|
|
"github.com/gofiber/fiber/v2"
|
|
)
|
|
|
|
type ProductHandler struct {
|
|
Repo *repository.ProductRepository
|
|
}
|
|
|
|
func NewProductHandler() *ProductHandler {
|
|
return &ProductHandler{
|
|
Repo: repository.NewProductRepository(database.DB),
|
|
}
|
|
}
|
|
|
|
func (h *ProductHandler) GetAll(c *fiber.Ctx) error {
|
|
products, err := h.Repo.FindAll()
|
|
if err != nil {
|
|
return c.Status(500).JSON(fiber.Map{"error": "Failed to fetch products"})
|
|
}
|
|
return c.JSON(products)
|
|
}
|
|
|
|
func (h *ProductHandler) Create(c *fiber.Ctx) error {
|
|
var input models.Product
|
|
if err := c.BodyParser(&input); err != nil {
|
|
return c.Status(400).JSON(fiber.Map{"error": "Invalid input"})
|
|
}
|
|
|
|
// Jika hanya terima ID, lakukan preload relasi
|
|
if err := h.Repo.PreloadRelations(&input); err != nil {
|
|
return c.Status(400).JSON(fiber.Map{"error": "Failed to preload relations"})
|
|
}
|
|
|
|
// Generate SKU
|
|
sku, err := service.GenerateSKU(&input)
|
|
if err != nil {
|
|
return c.Status(400).JSON(fiber.Map{"error": "Failed to generate SKU: " + err.Error()})
|
|
}
|
|
input.SKU = sku
|
|
|
|
if err := h.Repo.Create(&input); err != nil {
|
|
return c.Status(500).JSON(fiber.Map{"error": "Failed to create product"})
|
|
}
|
|
|
|
return c.JSON(input)
|
|
}
|
|
|
|
func (h *ProductHandler) Update(c *fiber.Ctx) error {
|
|
id, _ := strconv.Atoi(c.Params("id"))
|
|
var input models.Product
|
|
if err := c.BodyParser(&input); err != nil {
|
|
return c.Status(400).JSON(fiber.Map{"error": "Invalid input"})
|
|
}
|
|
if err := h.Repo.Update(uint(id), &input); err != nil {
|
|
return c.Status(500).JSON(fiber.Map{"error": "Failed to update product"})
|
|
}
|
|
return c.JSON(fiber.Map{"message": "Product updated"})
|
|
}
|
|
|
|
func (h *ProductHandler) Delete(c *fiber.Ctx) error {
|
|
id, _ := strconv.Atoi(c.Params("id"))
|
|
if err := h.Repo.Delete(uint(id)); err != nil {
|
|
return c.Status(500).JSON(fiber.Map{"error": "Failed to delete product"})
|
|
}
|
|
return c.JSON(fiber.Map{"message": "Product deleted"})
|
|
}
|