mirror of
https://gitlab.com/mbugroup/lti-api.git
synced 2026-05-20 13:31:56 +00:00
Feat(BE-36,37,38,39): finish master data management api
This commit is contained in:
@@ -0,0 +1,140 @@
|
||||
package controller
|
||||
|
||||
import (
|
||||
"math"
|
||||
"strconv"
|
||||
|
||||
"gitlab.com/mbugroup/lti-api.git/internal/modules/master/products/dto"
|
||||
service "gitlab.com/mbugroup/lti-api.git/internal/modules/master/products/services"
|
||||
validation "gitlab.com/mbugroup/lti-api.git/internal/modules/master/products/validations"
|
||||
"gitlab.com/mbugroup/lti-api.git/internal/response"
|
||||
|
||||
"github.com/gofiber/fiber/v2"
|
||||
)
|
||||
|
||||
type ProductController struct {
|
||||
ProductService service.ProductService
|
||||
}
|
||||
|
||||
func NewProductController(productService service.ProductService) *ProductController {
|
||||
return &ProductController{
|
||||
ProductService: productService,
|
||||
}
|
||||
}
|
||||
|
||||
func (u *ProductController) GetAll(c *fiber.Ctx) error {
|
||||
query := &validation.Query{
|
||||
Page: c.QueryInt("page", 1),
|
||||
Limit: c.QueryInt("limit", 10),
|
||||
Search: c.Query("search", ""),
|
||||
}
|
||||
|
||||
result, totalResults, err := u.ProductService.GetAll(c, query)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return c.Status(fiber.StatusOK).
|
||||
JSON(response.SuccessWithPaginate[dto.ProductListDTO]{
|
||||
Code: fiber.StatusOK,
|
||||
Status: "success",
|
||||
Message: "Get all products successfully",
|
||||
Meta: response.Meta{
|
||||
Page: query.Page,
|
||||
Limit: query.Limit,
|
||||
TotalPages: int64(math.Ceil(float64(totalResults) / float64(query.Limit))),
|
||||
TotalResults: totalResults,
|
||||
},
|
||||
Data: dto.ToProductListDTOs(result),
|
||||
})
|
||||
}
|
||||
|
||||
func (u *ProductController) GetOne(c *fiber.Ctx) error {
|
||||
param := c.Params("id")
|
||||
|
||||
id, err := strconv.Atoi(param)
|
||||
if err != nil {
|
||||
return fiber.NewError(fiber.StatusBadRequest, "Invalid Id")
|
||||
}
|
||||
|
||||
result, err := u.ProductService.GetOne(c, uint(id))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return c.Status(fiber.StatusOK).
|
||||
JSON(response.Success{
|
||||
Code: fiber.StatusOK,
|
||||
Status: "success",
|
||||
Message: "Get product successfully",
|
||||
Data: dto.ToProductDetailDTO(*result),
|
||||
})
|
||||
}
|
||||
|
||||
func (u *ProductController) CreateOne(c *fiber.Ctx) error {
|
||||
req := new(validation.Create)
|
||||
|
||||
if err := c.BodyParser(req); err != nil {
|
||||
return fiber.NewError(fiber.StatusBadRequest, "Invalid request body")
|
||||
}
|
||||
|
||||
result, err := u.ProductService.CreateOne(c, req)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return c.Status(fiber.StatusCreated).
|
||||
JSON(response.Success{
|
||||
Code: fiber.StatusCreated,
|
||||
Status: "success",
|
||||
Message: "Create product successfully",
|
||||
Data: dto.ToProductDetailDTO(*result),
|
||||
})
|
||||
}
|
||||
|
||||
func (u *ProductController) UpdateOne(c *fiber.Ctx) error {
|
||||
req := new(validation.Update)
|
||||
param := c.Params("id")
|
||||
|
||||
id, err := strconv.Atoi(param)
|
||||
if err != nil {
|
||||
return fiber.NewError(fiber.StatusBadRequest, "Invalid Id")
|
||||
}
|
||||
|
||||
if err := c.BodyParser(req); err != nil {
|
||||
return fiber.NewError(fiber.StatusBadRequest, "Invalid request body")
|
||||
}
|
||||
|
||||
result, err := u.ProductService.UpdateOne(c, req, uint(id))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return c.Status(fiber.StatusOK).
|
||||
JSON(response.Success{
|
||||
Code: fiber.StatusOK,
|
||||
Status: "success",
|
||||
Message: "Update product successfully",
|
||||
Data: dto.ToProductDetailDTO(*result),
|
||||
})
|
||||
}
|
||||
|
||||
func (u *ProductController) DeleteOne(c *fiber.Ctx) error {
|
||||
param := c.Params("id")
|
||||
|
||||
id, err := strconv.Atoi(param)
|
||||
if err != nil {
|
||||
return fiber.NewError(fiber.StatusBadRequest, "Invalid Id")
|
||||
}
|
||||
|
||||
if err := u.ProductService.DeleteOne(c, uint(id)); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return c.Status(fiber.StatusOK).
|
||||
JSON(response.Common{
|
||||
Code: fiber.StatusOK,
|
||||
Status: "success",
|
||||
Message: "Delete product successfully",
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
package dto
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
entity "gitlab.com/mbugroup/lti-api.git/internal/entities"
|
||||
productCategoryDTO "gitlab.com/mbugroup/lti-api.git/internal/modules/master/product-categories/dto"
|
||||
supplierDTO "gitlab.com/mbugroup/lti-api.git/internal/modules/master/suppliers/dto"
|
||||
uomDTO "gitlab.com/mbugroup/lti-api.git/internal/modules/master/uoms/dto"
|
||||
userDTO "gitlab.com/mbugroup/lti-api.git/internal/modules/users/dto"
|
||||
)
|
||||
|
||||
// === DTO Structs ===
|
||||
|
||||
type ProductBaseDTO struct {
|
||||
Id uint `json:"id"`
|
||||
Name string `json:"name"`
|
||||
}
|
||||
|
||||
type ProductListDTO struct {
|
||||
ProductBaseDTO
|
||||
Brand string `json:"brand"`
|
||||
Sku *string `json:"sku,omitempty"`
|
||||
ProductPrice float64 `json:"product_price"`
|
||||
SellingPrice *float64 `json:"selling_price,omitempty"`
|
||||
Tax *float64 `json:"tax,omitempty"`
|
||||
ExpiryPeriod *int `json:"expiry_period,omitempty"`
|
||||
Uom *uomDTO.UomBaseDTO `json:"uom,omitempty"`
|
||||
ProductCategory *productCategoryDTO.ProductCategoryBaseDTO `json:"product_category,omitempty"`
|
||||
Suppliers []supplierDTO.SupplierBaseDTO `json:"suppliers"`
|
||||
Flags []string `json:"flags"`
|
||||
CreatedUser *userDTO.UserBaseDTO `json:"created_user"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
}
|
||||
|
||||
type ProductDetailDTO struct {
|
||||
ProductListDTO
|
||||
Flags []string `json:"flags"`
|
||||
}
|
||||
|
||||
// === Mapper Functions ===
|
||||
|
||||
func ToProductBaseDTO(e entity.Product) ProductBaseDTO {
|
||||
return ProductBaseDTO{
|
||||
Id: e.Id,
|
||||
Name: e.Name,
|
||||
}
|
||||
}
|
||||
|
||||
func ToProductListDTO(e entity.Product) ProductListDTO {
|
||||
var createdUser *userDTO.UserBaseDTO
|
||||
if e.CreatedUser.Id != 0 {
|
||||
mapped := userDTO.ToUserBaseDTO(e.CreatedUser)
|
||||
createdUser = &mapped
|
||||
}
|
||||
|
||||
var uomRef *uomDTO.UomBaseDTO
|
||||
if e.Uom.Id != 0 {
|
||||
mapped := uomDTO.ToUomBaseDTO(e.Uom)
|
||||
uomRef = &mapped
|
||||
}
|
||||
|
||||
var categoryRef *productCategoryDTO.ProductCategoryBaseDTO
|
||||
if e.ProductCategory.Id != 0 {
|
||||
mapped := productCategoryDTO.ToProductCategoryBaseDTO(e.ProductCategory)
|
||||
categoryRef = &mapped
|
||||
}
|
||||
|
||||
suppliers := make([]supplierDTO.SupplierBaseDTO, len(e.Suppliers))
|
||||
for i, s := range e.Suppliers {
|
||||
suppliers[i] = supplierDTO.ToSupplierBaseDTO(s)
|
||||
}
|
||||
|
||||
flags := make([]string, len(e.Flags))
|
||||
for i, f := range e.Flags {
|
||||
flags[i] = f.Name
|
||||
}
|
||||
|
||||
return ProductListDTO{
|
||||
Brand: e.Brand,
|
||||
Sku: e.Sku,
|
||||
ProductPrice: e.ProductPrice,
|
||||
SellingPrice: e.SellingPrice,
|
||||
Tax: e.Tax,
|
||||
ExpiryPeriod: e.ExpiryPeriod,
|
||||
ProductBaseDTO: ToProductBaseDTO(e),
|
||||
CreatedAt: e.CreatedAt,
|
||||
UpdatedAt: e.UpdatedAt,
|
||||
CreatedUser: createdUser,
|
||||
Uom: uomRef,
|
||||
ProductCategory: categoryRef,
|
||||
Suppliers: suppliers,
|
||||
Flags: flags,
|
||||
}
|
||||
}
|
||||
|
||||
func ToProductListDTOs(e []entity.Product) []ProductListDTO {
|
||||
result := make([]ProductListDTO, len(e))
|
||||
for i, r := range e {
|
||||
result[i] = ToProductListDTO(r)
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
func ToProductDetailDTO(e entity.Product) ProductDetailDTO {
|
||||
flags := make([]string, len(e.Flags))
|
||||
for i, f := range e.Flags {
|
||||
flags[i] = f.Name
|
||||
}
|
||||
|
||||
return ProductDetailDTO{
|
||||
ProductListDTO: ToProductListDTO(e),
|
||||
Flags: flags,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
package products
|
||||
|
||||
import (
|
||||
"github.com/go-playground/validator/v10"
|
||||
"github.com/gofiber/fiber/v2"
|
||||
"gorm.io/gorm"
|
||||
|
||||
rProduct "gitlab.com/mbugroup/lti-api.git/internal/modules/master/products/repositories"
|
||||
sProduct "gitlab.com/mbugroup/lti-api.git/internal/modules/master/products/services"
|
||||
|
||||
rUser "gitlab.com/mbugroup/lti-api.git/internal/modules/users/repositories"
|
||||
sUser "gitlab.com/mbugroup/lti-api.git/internal/modules/users/services"
|
||||
)
|
||||
|
||||
type ProductModule struct{}
|
||||
|
||||
func (ProductModule) RegisterRoutes(router fiber.Router, db *gorm.DB, validate *validator.Validate) {
|
||||
productRepo := rProduct.NewProductRepository(db)
|
||||
userRepo := rUser.NewUserRepository(db)
|
||||
|
||||
productService := sProduct.NewProductService(productRepo, validate)
|
||||
userService := sUser.NewUserService(userRepo, validate)
|
||||
|
||||
ProductRoutes(router, userService, productService)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,196 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"gitlab.com/mbugroup/lti-api.git/internal/common/repository"
|
||||
entity "gitlab.com/mbugroup/lti-api.git/internal/entities"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type ProductRepository interface {
|
||||
repository.BaseRepository[entity.Product]
|
||||
NameExists(ctx context.Context, name string, excludeID *uint) (bool, error)
|
||||
SkuExists(ctx context.Context, sku string, excludeID *uint) (bool, error)
|
||||
UomExists(ctx context.Context, uomID uint) (bool, error)
|
||||
CategoryExists(ctx context.Context, categoryID uint) (bool, error)
|
||||
GetSuppliersByIDs(ctx context.Context, supplierIDs []uint) ([]entity.Supplier, error)
|
||||
SyncSuppliersDiff(ctx context.Context, tx *gorm.DB, productID uint, supplierIDs []uint) error
|
||||
SyncFlags(ctx context.Context, tx *gorm.DB, productID uint, flags []string) error
|
||||
DeleteFlags(ctx context.Context, tx *gorm.DB, productID uint) error
|
||||
GetFlags(ctx context.Context, productID uint) ([]entity.Flag, error)
|
||||
}
|
||||
|
||||
type ProductRepositoryImpl struct {
|
||||
*repository.BaseRepositoryImpl[entity.Product]
|
||||
}
|
||||
|
||||
func NewProductRepository(db *gorm.DB) ProductRepository {
|
||||
return &ProductRepositoryImpl{
|
||||
BaseRepositoryImpl: repository.NewBaseRepository[entity.Product](db),
|
||||
}
|
||||
}
|
||||
|
||||
func (r *ProductRepositoryImpl) NameExists(ctx context.Context, name string, excludeID *uint) (bool, error) {
|
||||
return repository.ExistsByName[entity.Product](ctx, r.DB(), name, excludeID)
|
||||
}
|
||||
|
||||
func (r *ProductRepositoryImpl) SkuExists(ctx context.Context, sku string, excludeID *uint) (bool, error) {
|
||||
var count int64
|
||||
q := r.DB().WithContext(ctx).
|
||||
Model(new(entity.Product)).
|
||||
Where("sku = ?", sku).
|
||||
Where("deleted_at IS NULL")
|
||||
if excludeID != nil {
|
||||
q = q.Where("id <> ?", *excludeID)
|
||||
}
|
||||
if err := q.Count(&count).Error; err != nil {
|
||||
return false, err
|
||||
}
|
||||
return count > 0, nil
|
||||
}
|
||||
|
||||
func (r *ProductRepositoryImpl) UomExists(ctx context.Context, uomID uint) (bool, error) {
|
||||
var count int64
|
||||
if err := r.DB().WithContext(ctx).
|
||||
Model(&entity.Uom{}).
|
||||
Where("id = ?", uomID).
|
||||
Count(&count).
|
||||
Error; err != nil {
|
||||
return false, err
|
||||
}
|
||||
return count > 0, nil
|
||||
}
|
||||
|
||||
func (r *ProductRepositoryImpl) CategoryExists(ctx context.Context, categoryID uint) (bool, error) {
|
||||
var count int64
|
||||
if err := r.DB().WithContext(ctx).
|
||||
Model(&entity.ProductCategory{}).
|
||||
Where("id = ?", categoryID).
|
||||
Count(&count).
|
||||
Error; err != nil {
|
||||
return false, err
|
||||
}
|
||||
return count > 0, nil
|
||||
}
|
||||
|
||||
func (r *ProductRepositoryImpl) GetSuppliersByIDs(ctx context.Context, supplierIDs []uint) ([]entity.Supplier, error) {
|
||||
if len(supplierIDs) == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
var suppliers []entity.Supplier
|
||||
if err := r.DB().WithContext(ctx).
|
||||
Select("id", "category").
|
||||
Where("id IN ?", supplierIDs).
|
||||
Find(&suppliers).
|
||||
Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return suppliers, nil
|
||||
}
|
||||
|
||||
func (r *ProductRepositoryImpl) SyncSuppliersDiff(ctx context.Context, tx *gorm.DB, productID uint, supplierIDs []uint) error {
|
||||
db := tx
|
||||
if db == nil {
|
||||
db = r.DB()
|
||||
}
|
||||
|
||||
if supplierIDs == nil {
|
||||
return db.WithContext(ctx).
|
||||
Where("product_id = ?", productID).
|
||||
Delete(&entity.ProductSupplier{}).
|
||||
Error
|
||||
}
|
||||
|
||||
var existing []entity.ProductSupplier
|
||||
if err := db.WithContext(ctx).
|
||||
Where("product_id = ?", productID).
|
||||
Find(&existing).
|
||||
Error; err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
existingMap := make(map[uint]struct{}, len(existing))
|
||||
for _, rel := range existing {
|
||||
existingMap[rel.SupplierID] = struct{}{}
|
||||
}
|
||||
|
||||
incomingMap := make(map[uint]struct{}, len(supplierIDs))
|
||||
for _, id := range supplierIDs {
|
||||
incomingMap[id] = struct{}{}
|
||||
if _, exists := existingMap[id]; exists {
|
||||
continue
|
||||
}
|
||||
record := entity.ProductSupplier{ProductID: productID, SupplierID: id}
|
||||
if err := db.WithContext(ctx).Create(&record).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
for _, rel := range existing {
|
||||
if _, keep := incomingMap[rel.SupplierID]; !keep {
|
||||
if err := db.WithContext(ctx).
|
||||
Where("product_id = ? AND supplier_id = ?", productID, rel.SupplierID).
|
||||
Delete(&entity.ProductSupplier{}).
|
||||
Error; err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *ProductRepositoryImpl) SyncFlags(ctx context.Context, tx *gorm.DB, productID uint, flags []string) error {
|
||||
db := tx
|
||||
if db == nil {
|
||||
db = r.DB()
|
||||
}
|
||||
|
||||
// Hapus flags lama terlebih dahulu
|
||||
if err := db.WithContext(ctx).
|
||||
Where("flagable_id = ? AND flagable_type = ?", productID, entity.FlagableTypeProduct).
|
||||
Delete(&entity.Flag{}).
|
||||
Error; err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// Insert flags baru jika ada
|
||||
if len(flags) > 0 {
|
||||
newFlags := make([]entity.Flag, len(flags))
|
||||
for i, f := range flags {
|
||||
newFlags[i] = entity.Flag{
|
||||
Name: f,
|
||||
FlagableID: productID,
|
||||
FlagableType: entity.FlagableTypeProduct,
|
||||
}
|
||||
}
|
||||
if err := db.WithContext(ctx).Create(&newFlags).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *ProductRepositoryImpl) DeleteFlags(ctx context.Context, tx *gorm.DB, productID uint) error {
|
||||
db := tx
|
||||
if db == nil {
|
||||
db = r.DB()
|
||||
}
|
||||
return db.WithContext(ctx).
|
||||
Where("flagable_id = ? AND flagable_type = ?", productID, entity.FlagableTypeProduct).
|
||||
Delete(&entity.Flag{}).
|
||||
Error
|
||||
}
|
||||
|
||||
func (r *ProductRepositoryImpl) GetFlags(ctx context.Context, productID uint) ([]entity.Flag, error) {
|
||||
var flags []entity.Flag
|
||||
if err := r.DB().WithContext(ctx).
|
||||
Where("flagable_id = ? AND flagable_type = ?", productID, entity.FlagableTypeProduct).
|
||||
Find(&flags).
|
||||
Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return flags, nil
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
package products
|
||||
|
||||
import (
|
||||
// m "gitlab.com/mbugroup/lti-api.git/internal/middleware"
|
||||
controller "gitlab.com/mbugroup/lti-api.git/internal/modules/master/products/controllers"
|
||||
product "gitlab.com/mbugroup/lti-api.git/internal/modules/master/products/services"
|
||||
user "gitlab.com/mbugroup/lti-api.git/internal/modules/users/services"
|
||||
|
||||
"github.com/gofiber/fiber/v2"
|
||||
)
|
||||
|
||||
func ProductRoutes(v1 fiber.Router, u user.UserService, s product.ProductService) {
|
||||
ctrl := controller.NewProductController(s)
|
||||
|
||||
route := v1.Group("/products")
|
||||
|
||||
// route.Get("/", m.Auth(u), ctrl.GetAll)
|
||||
// route.Post("/", m.Auth(u), ctrl.CreateOne)
|
||||
// route.Get("/:id", m.Auth(u), ctrl.GetOne)
|
||||
// route.Patch("/:id", m.Auth(u), ctrl.UpdateOne)
|
||||
// route.Delete("/:id", m.Auth(u), ctrl.DeleteOne)
|
||||
|
||||
route.Get("/", ctrl.GetAll)
|
||||
route.Post("/", ctrl.CreateOne)
|
||||
route.Get("/:id", ctrl.GetOne)
|
||||
route.Patch("/:id", ctrl.UpdateOne)
|
||||
route.Delete("/:id", ctrl.DeleteOne)
|
||||
}
|
||||
@@ -0,0 +1,384 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
common "gitlab.com/mbugroup/lti-api.git/internal/common/service"
|
||||
entity "gitlab.com/mbugroup/lti-api.git/internal/entities"
|
||||
repository "gitlab.com/mbugroup/lti-api.git/internal/modules/master/products/repositories"
|
||||
validation "gitlab.com/mbugroup/lti-api.git/internal/modules/master/products/validations"
|
||||
"gitlab.com/mbugroup/lti-api.git/internal/utils"
|
||||
|
||||
"github.com/go-playground/validator/v10"
|
||||
"github.com/gofiber/fiber/v2"
|
||||
"github.com/sirupsen/logrus"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type ProductService interface {
|
||||
GetAll(ctx *fiber.Ctx, params *validation.Query) ([]entity.Product, int64, error)
|
||||
GetOne(ctx *fiber.Ctx, id uint) (*entity.Product, error)
|
||||
CreateOne(ctx *fiber.Ctx, req *validation.Create) (*entity.Product, error)
|
||||
UpdateOne(ctx *fiber.Ctx, req *validation.Update, id uint) (*entity.Product, error)
|
||||
DeleteOne(ctx *fiber.Ctx, id uint) error
|
||||
}
|
||||
|
||||
type productService struct {
|
||||
Log *logrus.Logger
|
||||
Validate *validator.Validate
|
||||
Repository repository.ProductRepository
|
||||
}
|
||||
|
||||
func normalizeProductFlags(raw []string) ([]string, error) {
|
||||
normalized, invalid := utils.NormalizeFlagsForGroup(raw, utils.FlagGroupProduct)
|
||||
if len(invalid) > 0 {
|
||||
invalidStr := strings.Join(utils.FlagTypesToStrings(invalid), ", ")
|
||||
allowedStr := strings.Join(utils.FlagTypesToStrings(utils.AllowedFlagTypes(utils.FlagGroupProduct)), ", ")
|
||||
return nil, fiber.NewError(fiber.StatusBadRequest, fmt.Sprintf("Invalid product flags: %s. Allowed flags: %s", invalidStr, allowedStr))
|
||||
}
|
||||
return utils.FlagTypesToStrings(normalized), nil
|
||||
}
|
||||
|
||||
func NewProductService(repo repository.ProductRepository, validate *validator.Validate) ProductService {
|
||||
return &productService{
|
||||
Log: utils.Log,
|
||||
Validate: validate,
|
||||
Repository: repo,
|
||||
}
|
||||
}
|
||||
|
||||
func (s productService) withRelations(db *gorm.DB) *gorm.DB {
|
||||
return db.
|
||||
Preload("CreatedUser").
|
||||
Preload("Uom").
|
||||
Preload("ProductCategory").
|
||||
Preload("Flags").
|
||||
Preload("Suppliers", func(db *gorm.DB) *gorm.DB {
|
||||
return db.Order("suppliers.name ASC")
|
||||
})
|
||||
}
|
||||
|
||||
func (s productService) GetAll(c *fiber.Ctx, params *validation.Query) ([]entity.Product, int64, error) {
|
||||
if err := s.Validate.Struct(params); err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
|
||||
offset := (params.Page - 1) * params.Limit
|
||||
|
||||
products, total, err := s.Repository.GetAll(c.Context(), offset, params.Limit, func(db *gorm.DB) *gorm.DB {
|
||||
db = s.withRelations(db)
|
||||
if params.Search != "" {
|
||||
return db.Where("name LIKE ?", "%"+params.Search+"%")
|
||||
}
|
||||
return db.Order("created_at DESC").Order("updated_at DESC")
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
s.Log.Errorf("Failed to get products: %+v", err)
|
||||
return nil, 0, err
|
||||
}
|
||||
return products, total, nil
|
||||
}
|
||||
|
||||
func (s productService) GetOne(c *fiber.Ctx, id uint) (*entity.Product, error) {
|
||||
product, err := s.Repository.GetByID(c.Context(), id, s.withRelations)
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil, fiber.NewError(fiber.StatusNotFound, "Product not found")
|
||||
}
|
||||
if err != nil {
|
||||
s.Log.Errorf("Failed get product by id: %+v", err)
|
||||
return nil, err
|
||||
}
|
||||
return product, nil
|
||||
}
|
||||
|
||||
func (s *productService) CreateOne(c *fiber.Ctx, req *validation.Create) (*entity.Product, error) {
|
||||
if err := s.Validate.Struct(req); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
ctx := c.Context()
|
||||
name := strings.TrimSpace(req.Name)
|
||||
brand := strings.TrimSpace(req.Brand)
|
||||
var sku *string
|
||||
if req.Sku != nil {
|
||||
trimmed := strings.ToUpper(strings.TrimSpace(*req.Sku))
|
||||
if trimmed != "" {
|
||||
sku = &trimmed
|
||||
}
|
||||
}
|
||||
|
||||
if exists, err := s.Repository.NameExists(ctx, name, nil); err != nil {
|
||||
s.Log.Errorf("Failed to check product name: %+v", err)
|
||||
return nil, fiber.NewError(fiber.StatusInternalServerError, "Failed to check product name")
|
||||
} else if exists {
|
||||
return nil, fiber.NewError(fiber.StatusConflict, fmt.Sprintf("Product with name %s already exists", name))
|
||||
}
|
||||
|
||||
if sku != nil {
|
||||
if exists, err := s.Repository.SkuExists(ctx, *sku, nil); err != nil {
|
||||
s.Log.Errorf("Failed to check product sku: %+v", err)
|
||||
return nil, fiber.NewError(fiber.StatusInternalServerError, "Failed to check product sku")
|
||||
} else if exists {
|
||||
return nil, fiber.NewError(fiber.StatusConflict, fmt.Sprintf("Product with sku %s already exists", *sku))
|
||||
}
|
||||
}
|
||||
|
||||
if err := common.EnsureRelations(ctx,
|
||||
common.RelationCheck{Name: "Uom", ID: &req.UomID, Exists: s.Repository.UomExists},
|
||||
common.RelationCheck{Name: "Product category", ID: &req.ProductCategoryID, Exists: s.Repository.CategoryExists},
|
||||
); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
supplierIDs := utils.UniqueUintSlice(req.SupplierIDs)
|
||||
var err error
|
||||
if len(supplierIDs) > 0 {
|
||||
suppliers, err := s.Repository.GetSuppliersByIDs(ctx, supplierIDs)
|
||||
if err != nil {
|
||||
s.Log.Errorf("Failed to validate suppliers: %+v", err)
|
||||
return nil, fiber.NewError(fiber.StatusInternalServerError, "Failed to validate suppliers")
|
||||
}
|
||||
if len(suppliers) != len(supplierIDs) {
|
||||
actual := make([]uint, len(suppliers))
|
||||
for i, supplier := range suppliers {
|
||||
actual[i] = supplier.Id
|
||||
}
|
||||
missing := utils.MissingUintIDs(supplierIDs, actual)
|
||||
return nil, fiber.NewError(fiber.StatusNotFound, fmt.Sprintf("Suppliers with ids %v not found", missing))
|
||||
}
|
||||
for _, sup := range suppliers {
|
||||
if strings.ToUpper(sup.Category) != string(utils.SupplierCategorySapronak) {
|
||||
return nil, fiber.NewError(fiber.StatusBadRequest, fmt.Sprintf("Supplier with id %d is not category SAPRONAK", sup.Id))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
productFlags, flagErr := normalizeProductFlags(req.Flags)
|
||||
if flagErr != nil {
|
||||
return nil, flagErr
|
||||
}
|
||||
|
||||
createBody := &entity.Product{
|
||||
Name: name,
|
||||
Brand: brand,
|
||||
Sku: sku,
|
||||
UomId: req.UomID,
|
||||
ProductCategoryId: req.ProductCategoryID,
|
||||
ProductPrice: req.ProductPrice,
|
||||
SellingPrice: req.SellingPrice,
|
||||
Tax: req.Tax,
|
||||
ExpiryPeriod: req.ExpiryPeriod,
|
||||
CreatedBy: 1,
|
||||
}
|
||||
|
||||
err = s.Repository.DB().WithContext(ctx).Transaction(func(tx *gorm.DB) error {
|
||||
repoTx := s.Repository.WithTx(tx)
|
||||
|
||||
if err := repoTx.CreateOne(ctx, createBody, nil); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err := s.Repository.SyncFlags(ctx, tx, createBody.Id, productFlags); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return s.Repository.SyncSuppliersDiff(ctx, tx, createBody.Id, supplierIDs)
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
s.Log.Errorf("Failed to create product: %+v", err)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return s.GetOne(c, createBody.Id)
|
||||
}
|
||||
|
||||
func (s productService) UpdateOne(c *fiber.Ctx, req *validation.Update, id uint) (*entity.Product, error) {
|
||||
if err := s.Validate.Struct(req); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
updateBody := make(map[string]any)
|
||||
|
||||
if req.Name != nil {
|
||||
name := strings.TrimSpace(*req.Name)
|
||||
if name == "" {
|
||||
return nil, fiber.NewError(fiber.StatusBadRequest, "Name cannot be empty")
|
||||
}
|
||||
if exists, err := s.Repository.NameExists(c.Context(), name, &id); err != nil {
|
||||
s.Log.Errorf("Failed to check product name: %+v", err)
|
||||
return nil, fiber.NewError(fiber.StatusInternalServerError, "Failed to check product name")
|
||||
} else if exists {
|
||||
return nil, fiber.NewError(fiber.StatusConflict, fmt.Sprintf("Product with name %s already exists", name))
|
||||
}
|
||||
updateBody["name"] = name
|
||||
}
|
||||
|
||||
if req.Brand != nil {
|
||||
brand := strings.TrimSpace(*req.Brand)
|
||||
if brand == "" {
|
||||
return nil, fiber.NewError(fiber.StatusBadRequest, "Brand cannot be empty")
|
||||
}
|
||||
updateBody["brand"] = brand
|
||||
}
|
||||
|
||||
if req.Sku != nil {
|
||||
sku := strings.ToUpper(strings.TrimSpace(*req.Sku))
|
||||
if sku == "" {
|
||||
updateBody["sku"] = nil
|
||||
} else {
|
||||
if exists, err := s.Repository.SkuExists(c.Context(), sku, &id); err != nil {
|
||||
s.Log.Errorf("Failed to check product sku: %+v", err)
|
||||
return nil, fiber.NewError(fiber.StatusInternalServerError, "Failed to check product sku")
|
||||
} else if exists {
|
||||
return nil, fiber.NewError(fiber.StatusConflict, fmt.Sprintf("Product with sku %s already exists", sku))
|
||||
}
|
||||
updateBody["sku"] = sku
|
||||
}
|
||||
}
|
||||
|
||||
if err := common.EnsureRelations(c.Context(),
|
||||
common.RelationCheck{Name: "Uom", ID: req.UomID, Exists: s.Repository.UomExists},
|
||||
common.RelationCheck{Name: "Product category", ID: req.ProductCategoryID, Exists: s.Repository.CategoryExists},
|
||||
); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if req.UomID != nil {
|
||||
updateBody["uom_id"] = *req.UomID
|
||||
}
|
||||
|
||||
if req.ProductCategoryID != nil {
|
||||
updateBody["product_category_id"] = *req.ProductCategoryID
|
||||
}
|
||||
|
||||
if req.ProductPrice != nil {
|
||||
updateBody["product_price"] = *req.ProductPrice
|
||||
}
|
||||
if req.SellingPrice != nil {
|
||||
updateBody["selling_price"] = req.SellingPrice
|
||||
}
|
||||
if req.Tax != nil {
|
||||
updateBody["tax"] = req.Tax
|
||||
}
|
||||
if req.ExpiryPeriod != nil {
|
||||
updateBody["expiry_period"] = req.ExpiryPeriod
|
||||
}
|
||||
|
||||
ctx := c.Context()
|
||||
|
||||
var suppliers []entity.Supplier
|
||||
var supplierIDs []uint
|
||||
var supplierUpdate bool
|
||||
if req.SupplierIDs != nil {
|
||||
supplierUpdate = true
|
||||
supplierIDs = utils.UniqueUintSlice(*req.SupplierIDs)
|
||||
if len(supplierIDs) > 0 {
|
||||
var err error
|
||||
suppliers, err = s.Repository.GetSuppliersByIDs(ctx, supplierIDs)
|
||||
if err != nil {
|
||||
s.Log.Errorf("Failed to validate suppliers: %+v", err)
|
||||
return nil, fiber.NewError(fiber.StatusInternalServerError, "Failed to validate suppliers")
|
||||
}
|
||||
if len(suppliers) != len(supplierIDs) {
|
||||
actual := make([]uint, len(suppliers))
|
||||
for i, supplier := range suppliers {
|
||||
actual[i] = supplier.Id
|
||||
}
|
||||
missing := utils.MissingUintIDs(supplierIDs, actual)
|
||||
return nil, fiber.NewError(fiber.StatusNotFound, fmt.Sprintf("Suppliers with ids %v not found", missing))
|
||||
}
|
||||
for _, sup := range suppliers {
|
||||
if strings.ToUpper(sup.Category) != string(utils.SupplierCategorySapronak) {
|
||||
return nil, fiber.NewError(fiber.StatusBadRequest, fmt.Sprintf("Supplier with id %d is not category SAPRONAK", sup.Id))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
var (
|
||||
flagUpdate bool
|
||||
flagValues []string
|
||||
)
|
||||
if req.Flags != nil {
|
||||
flagUpdate = true
|
||||
var flagErr error
|
||||
flagValues, flagErr = normalizeProductFlags(*req.Flags)
|
||||
if flagErr != nil {
|
||||
return nil, flagErr
|
||||
}
|
||||
}
|
||||
|
||||
if len(updateBody) == 0 && !supplierUpdate && !flagUpdate {
|
||||
return s.GetOne(c, id)
|
||||
}
|
||||
|
||||
err := s.Repository.DB().WithContext(ctx).Transaction(func(tx *gorm.DB) error {
|
||||
repoTx := s.Repository.WithTx(tx)
|
||||
|
||||
if len(updateBody) > 0 {
|
||||
if err := repoTx.PatchOne(ctx, id, updateBody, nil); err != nil {
|
||||
return err
|
||||
}
|
||||
} else {
|
||||
if _, err := repoTx.GetByID(ctx, id, nil); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
if supplierUpdate {
|
||||
var ids []uint
|
||||
if len(supplierIDs) > 0 {
|
||||
ids = supplierIDs
|
||||
}
|
||||
if err := s.Repository.SyncSuppliersDiff(ctx, tx, id, ids); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
if flagUpdate {
|
||||
if err := s.Repository.SyncFlags(ctx, tx, id, flagValues); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil, fiber.NewError(fiber.StatusNotFound, "Product not found")
|
||||
}
|
||||
s.Log.Errorf("Failed to update product: %+v", err)
|
||||
return nil, err
|
||||
}
|
||||
return s.GetOne(c, id)
|
||||
}
|
||||
|
||||
func (s productService) DeleteOne(c *fiber.Ctx, id uint) error {
|
||||
err := s.Repository.DB().WithContext(c.Context()).Transaction(func(tx *gorm.DB) error {
|
||||
repoTx := s.Repository.WithTx(tx)
|
||||
|
||||
if err := s.Repository.SyncSuppliersDiff(c.Context(), tx, id, nil); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err := s.Repository.DeleteFlags(c.Context(), tx, id); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return repoTx.DeleteOne(c.Context(), id)
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return fiber.NewError(fiber.StatusNotFound, "Product not found")
|
||||
}
|
||||
s.Log.Errorf("Failed to delete product: %+v", err)
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
package validation
|
||||
|
||||
type Create struct {
|
||||
Name string `json:"name" validate:"required_strict,min=3"`
|
||||
Brand string `json:"brand" validate:"required_strict,min=2"`
|
||||
Sku *string `json:"sku,omitempty" validate:"omitempty"`
|
||||
UomID uint `json:"uom_id" validate:"required,gt=0"`
|
||||
ProductCategoryID uint `json:"product_category_id" validate:"required,gt=0"`
|
||||
ProductPrice float64 `json:"product_price" validate:"required"`
|
||||
SellingPrice *float64 `json:"selling_price,omitempty" validate:"omitempty"`
|
||||
Tax *float64 `json:"tax,omitempty" validate:"omitempty"`
|
||||
ExpiryPeriod *int `json:"expiry_period,omitempty" validate:"omitempty,gt=0"`
|
||||
SupplierIDs []uint `json:"supplier_ids,omitempty" validate:"omitempty,dive,gt=0"`
|
||||
Flags []string `json:"flags,omitempty" validate:"omitempty,dive"`
|
||||
}
|
||||
|
||||
type Update struct {
|
||||
Name *string `json:"name,omitempty" validate:"omitempty,min=3"`
|
||||
Brand *string `json:"brand,omitempty" validate:"omitempty,min=2"`
|
||||
Sku *string `json:"sku,omitempty" validate:"omitempty"`
|
||||
UomID *uint `json:"uom_id,omitempty" validate:"omitempty,gt=0"`
|
||||
ProductCategoryID *uint `json:"product_category_id,omitempty" validate:"omitempty,gt=0"`
|
||||
ProductPrice *float64 `json:"product_price,omitempty" validate:"omitempty"`
|
||||
SellingPrice *float64 `json:"selling_price,omitempty" validate:"omitempty"`
|
||||
Tax *float64 `json:"tax,omitempty" validate:"omitempty"`
|
||||
ExpiryPeriod *int `json:"expiry_period,omitempty" validate:"omitempty,gt=0"`
|
||||
SupplierIDs *[]uint `json:"supplier_ids,omitempty" validate:"omitempty,dive,gt=0"`
|
||||
Flags *[]string `json:"flags,omitempty" validate:"omitempty,dive"`
|
||||
}
|
||||
|
||||
type Query struct {
|
||||
Page int `query:"page" validate:"omitempty,number,min=1"`
|
||||
Limit int `query:"limit" validate:"omitempty,number,min=1"`
|
||||
Search string `query:"search" validate:"omitempty,max=50"`
|
||||
}
|
||||
Reference in New Issue
Block a user