BE-MiniERP/modules/inventory/handler/collection_handler.go
2025-06-22 23:23:26 +07:00

60 lines
1.7 KiB
Go

package handler
import (
"BE-MiniERP/database"
"BE-MiniERP/modules/inventory/models"
"BE-MiniERP/modules/inventory/repository"
"strconv"
"github.com/gofiber/fiber/v2"
)
type CollectionHandler struct {
Repo *repository.CollectionRepository
}
func NewCollectionHandler() *CollectionHandler {
return &CollectionHandler{
Repo: repository.NewCollectionRepository(database.DB),
}
}
func (h *CollectionHandler) GetAll(c *fiber.Ctx) error {
collections, err := h.Repo.FindAll()
if err != nil {
return c.Status(500).JSON(fiber.Map{"error": "Failed to fetch collections"})
}
return c.JSON(collections)
}
func (h *CollectionHandler) Create(c *fiber.Ctx) error {
var input models.Collection
if err := c.BodyParser(&input); err != nil {
return c.Status(400).JSON(fiber.Map{"error": "Invalid input"})
}
if err := h.Repo.Create(&input); err != nil {
return c.Status(500).JSON(fiber.Map{"error": "Failed to create collection"})
}
return c.JSON(input)
}
func (h *CollectionHandler) Update(c *fiber.Ctx) error {
id, _ := strconv.Atoi(c.Params("id"))
var input models.Collection
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 collection"})
}
return c.JSON(fiber.Map{"message": "Collection updated"})
}
func (h *CollectionHandler) 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 collection"})
}
return c.JSON(fiber.Map{"message": "Collection deleted"})
}