Feat(BE-36,37,38,39): finish master data management api

This commit is contained in:
Hafizh A. Y
2025-10-03 21:04:21 +07:00
parent e8905be856
commit 2d49ffe4cd
103 changed files with 6974 additions and 117 deletions
@@ -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
}