mirror of
https://gitlab.com/mbugroup/lti-api.git
synced 2026-05-20 21:41:55 +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/nonstocks/dto"
|
||||
service "gitlab.com/mbugroup/lti-api.git/internal/modules/master/nonstocks/services"
|
||||
validation "gitlab.com/mbugroup/lti-api.git/internal/modules/master/nonstocks/validations"
|
||||
"gitlab.com/mbugroup/lti-api.git/internal/response"
|
||||
|
||||
"github.com/gofiber/fiber/v2"
|
||||
)
|
||||
|
||||
type NonstockController struct {
|
||||
NonstockService service.NonstockService
|
||||
}
|
||||
|
||||
func NewNonstockController(nonstockService service.NonstockService) *NonstockController {
|
||||
return &NonstockController{
|
||||
NonstockService: nonstockService,
|
||||
}
|
||||
}
|
||||
|
||||
func (u *NonstockController) 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.NonstockService.GetAll(c, query)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return c.Status(fiber.StatusOK).
|
||||
JSON(response.SuccessWithPaginate[dto.NonstockListDTO]{
|
||||
Code: fiber.StatusOK,
|
||||
Status: "success",
|
||||
Message: "Get all nonstocks successfully",
|
||||
Meta: response.Meta{
|
||||
Page: query.Page,
|
||||
Limit: query.Limit,
|
||||
TotalPages: int64(math.Ceil(float64(totalResults) / float64(query.Limit))),
|
||||
TotalResults: totalResults,
|
||||
},
|
||||
Data: dto.ToNonstockListDTOs(result),
|
||||
})
|
||||
}
|
||||
|
||||
func (u *NonstockController) 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.NonstockService.GetOne(c, uint(id))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return c.Status(fiber.StatusOK).
|
||||
JSON(response.Success{
|
||||
Code: fiber.StatusOK,
|
||||
Status: "success",
|
||||
Message: "Get nonstock successfully",
|
||||
Data: dto.ToNonstockDetailDTO(*result),
|
||||
})
|
||||
}
|
||||
|
||||
func (u *NonstockController) 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.NonstockService.CreateOne(c, req)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return c.Status(fiber.StatusCreated).
|
||||
JSON(response.Success{
|
||||
Code: fiber.StatusCreated,
|
||||
Status: "success",
|
||||
Message: "Create nonstock successfully",
|
||||
Data: dto.ToNonstockDetailDTO(*result),
|
||||
})
|
||||
}
|
||||
|
||||
func (u *NonstockController) 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.NonstockService.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 nonstock successfully",
|
||||
Data: dto.ToNonstockDetailDTO(*result),
|
||||
})
|
||||
}
|
||||
|
||||
func (u *NonstockController) 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.NonstockService.DeleteOne(c, uint(id)); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return c.Status(fiber.StatusOK).
|
||||
JSON(response.Common{
|
||||
Code: fiber.StatusOK,
|
||||
Status: "success",
|
||||
Message: "Delete nonstock successfully",
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
package dto
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
entity "gitlab.com/mbugroup/lti-api.git/internal/entities"
|
||||
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 NonstockBaseDTO struct {
|
||||
Id uint `json:"id"`
|
||||
Name string `json:"name"`
|
||||
UomID uint `json:"uom_id"`
|
||||
}
|
||||
|
||||
type NonstockListDTO struct {
|
||||
NonstockBaseDTO
|
||||
Uom *uomDTO.UomBaseDTO `json:"uom,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 NonstockDetailDTO struct {
|
||||
NonstockListDTO
|
||||
Flags []string `json:"flags"`
|
||||
}
|
||||
|
||||
// === Mapper Functions ===
|
||||
|
||||
func ToNonstockBaseDTO(e entity.Nonstock) NonstockBaseDTO {
|
||||
return NonstockBaseDTO{
|
||||
Id: e.Id,
|
||||
Name: e.Name,
|
||||
UomID: e.UomId,
|
||||
}
|
||||
}
|
||||
|
||||
func ToNonstockListDTO(e entity.Nonstock) NonstockListDTO {
|
||||
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
|
||||
}
|
||||
|
||||
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 NonstockListDTO{
|
||||
NonstockBaseDTO: ToNonstockBaseDTO(e),
|
||||
CreatedAt: e.CreatedAt,
|
||||
UpdatedAt: e.UpdatedAt,
|
||||
CreatedUser: createdUser,
|
||||
Uom: uomRef,
|
||||
Suppliers: suppliers,
|
||||
Flags: flags,
|
||||
}
|
||||
}
|
||||
|
||||
func ToNonstockListDTOs(e []entity.Nonstock) []NonstockListDTO {
|
||||
result := make([]NonstockListDTO, len(e))
|
||||
for i, r := range e {
|
||||
result[i] = ToNonstockListDTO(r)
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
func ToNonstockDetailDTO(e entity.Nonstock) NonstockDetailDTO {
|
||||
flags := make([]string, len(e.Flags))
|
||||
for i, f := range e.Flags {
|
||||
flags[i] = f.Name
|
||||
}
|
||||
|
||||
return NonstockDetailDTO{
|
||||
NonstockListDTO: ToNonstockListDTO(e),
|
||||
Flags: flags,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
package nonstocks
|
||||
|
||||
import (
|
||||
"github.com/go-playground/validator/v10"
|
||||
"github.com/gofiber/fiber/v2"
|
||||
"gorm.io/gorm"
|
||||
|
||||
rNonstock "gitlab.com/mbugroup/lti-api.git/internal/modules/master/nonstocks/repositories"
|
||||
sNonstock "gitlab.com/mbugroup/lti-api.git/internal/modules/master/nonstocks/services"
|
||||
|
||||
rUser "gitlab.com/mbugroup/lti-api.git/internal/modules/users/repositories"
|
||||
sUser "gitlab.com/mbugroup/lti-api.git/internal/modules/users/services"
|
||||
)
|
||||
|
||||
type NonstockModule struct{}
|
||||
|
||||
func (NonstockModule) RegisterRoutes(router fiber.Router, db *gorm.DB, validate *validator.Validate) {
|
||||
nonstockRepo := rNonstock.NewNonstockRepository(db)
|
||||
userRepo := rUser.NewUserRepository(db)
|
||||
|
||||
nonstockService := sNonstock.NewNonstockService(nonstockRepo, validate)
|
||||
userService := sUser.NewUserService(userRepo, validate)
|
||||
|
||||
NonstockRoutes(router, userService, nonstockService)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,172 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
|
||||
"gitlab.com/mbugroup/lti-api.git/internal/common/repository"
|
||||
entity "gitlab.com/mbugroup/lti-api.git/internal/entities"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type NonstockRepository interface {
|
||||
repository.BaseRepository[entity.Nonstock]
|
||||
NameExists(ctx context.Context, name string, excludeID *uint) (bool, error)
|
||||
SyncSuppliersDiff(ctx context.Context, tx *gorm.DB, nonstockID uint, supplierIDs []uint) error
|
||||
UomExists(ctx context.Context, uomID uint) (bool, error)
|
||||
GetSuppliersByIDs(ctx context.Context, supplierIDs []uint) ([]entity.Supplier, error)
|
||||
SyncFlags(ctx context.Context, tx *gorm.DB, nonstockID uint, flags []string) error
|
||||
DeleteFlags(ctx context.Context, tx *gorm.DB, nonstockID uint) error
|
||||
GetFlags(ctx context.Context, nonstockID uint) ([]entity.Flag, error)
|
||||
}
|
||||
|
||||
type NonstockRepositoryImpl struct {
|
||||
*repository.BaseRepositoryImpl[entity.Nonstock]
|
||||
}
|
||||
|
||||
func NewNonstockRepository(db *gorm.DB) NonstockRepository {
|
||||
return &NonstockRepositoryImpl{
|
||||
BaseRepositoryImpl: repository.NewBaseRepository[entity.Nonstock](db),
|
||||
}
|
||||
}
|
||||
|
||||
func (r *NonstockRepositoryImpl) NameExists(ctx context.Context, name string, excludeID *uint) (bool, error) {
|
||||
return repository.ExistsByName[entity.Nonstock](ctx, r.DB(), name, excludeID)
|
||||
}
|
||||
|
||||
func (r *NonstockRepositoryImpl) SyncSuppliersDiff(ctx context.Context, tx *gorm.DB, nonstockID uint, supplierIDs []uint) error {
|
||||
db := tx
|
||||
if db == nil {
|
||||
db = r.DB()
|
||||
}
|
||||
|
||||
if supplierIDs == nil {
|
||||
return db.WithContext(ctx).
|
||||
Where("nonstock_id = ?", nonstockID).
|
||||
Delete(&entity.NonstockSupplier{}).
|
||||
Error
|
||||
}
|
||||
|
||||
var existing []entity.NonstockSupplier
|
||||
if err := db.WithContext(ctx).
|
||||
Where("nonstock_id = ?", nonstockID).
|
||||
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.NonstockSupplier{NonstockID: nonstockID, 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("nonstock_id = ? AND supplier_id = ?", nonstockID, rel.SupplierID).
|
||||
Delete(&entity.NonstockSupplier{}).
|
||||
Error; err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
continue
|
||||
}
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *NonstockRepositoryImpl) 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 *NonstockRepositoryImpl) 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 *NonstockRepositoryImpl) SyncFlags(ctx context.Context, tx *gorm.DB, nonstockID 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 = ?", nonstockID, entity.FlagableTypeNonstock).
|
||||
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: nonstockID,
|
||||
FlagableType: entity.FlagableTypeNonstock,
|
||||
}
|
||||
}
|
||||
if err := db.WithContext(ctx).Create(&newFlags).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *NonstockRepositoryImpl) DeleteFlags(ctx context.Context, tx *gorm.DB, nonstockID uint) error {
|
||||
db := tx
|
||||
if db == nil {
|
||||
db = r.DB()
|
||||
}
|
||||
return db.WithContext(ctx).
|
||||
Where("flagable_id = ? AND flagable_type = ?", nonstockID, entity.FlagableTypeNonstock).
|
||||
Delete(&entity.Flag{}).
|
||||
Error
|
||||
}
|
||||
|
||||
func (r *NonstockRepositoryImpl) GetFlags(ctx context.Context, nonstockID uint) ([]entity.Flag, error) {
|
||||
var flags []entity.Flag
|
||||
if err := r.DB().WithContext(ctx).
|
||||
Where("flagable_id = ? AND flagable_type = ?", nonstockID, entity.FlagableTypeNonstock).
|
||||
Find(&flags).
|
||||
Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return flags, nil
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
package nonstocks
|
||||
|
||||
import (
|
||||
// m "gitlab.com/mbugroup/lti-api.git/internal/middleware"
|
||||
controller "gitlab.com/mbugroup/lti-api.git/internal/modules/master/nonstocks/controllers"
|
||||
nonstock "gitlab.com/mbugroup/lti-api.git/internal/modules/master/nonstocks/services"
|
||||
user "gitlab.com/mbugroup/lti-api.git/internal/modules/users/services"
|
||||
|
||||
"github.com/gofiber/fiber/v2"
|
||||
)
|
||||
|
||||
func NonstockRoutes(v1 fiber.Router, u user.UserService, s nonstock.NonstockService) {
|
||||
ctrl := controller.NewNonstockController(s)
|
||||
|
||||
route := v1.Group("/nonstocks")
|
||||
|
||||
// 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,308 @@
|
||||
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/nonstocks/repositories"
|
||||
validation "gitlab.com/mbugroup/lti-api.git/internal/modules/master/nonstocks/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 NonstockService interface {
|
||||
GetAll(ctx *fiber.Ctx, params *validation.Query) ([]entity.Nonstock, int64, error)
|
||||
GetOne(ctx *fiber.Ctx, id uint) (*entity.Nonstock, error)
|
||||
CreateOne(ctx *fiber.Ctx, req *validation.Create) (*entity.Nonstock, error)
|
||||
UpdateOne(ctx *fiber.Ctx, req *validation.Update, id uint) (*entity.Nonstock, error)
|
||||
DeleteOne(ctx *fiber.Ctx, id uint) error
|
||||
}
|
||||
|
||||
type nonstockService struct {
|
||||
Log *logrus.Logger
|
||||
Validate *validator.Validate
|
||||
Repository repository.NonstockRepository
|
||||
}
|
||||
|
||||
func NewNonstockService(repo repository.NonstockRepository, validate *validator.Validate) NonstockService {
|
||||
return &nonstockService{
|
||||
Log: utils.Log,
|
||||
Validate: validate,
|
||||
Repository: repo,
|
||||
}
|
||||
}
|
||||
|
||||
func (s nonstockService) withRelations(db *gorm.DB) *gorm.DB {
|
||||
return db.
|
||||
Preload("CreatedUser").
|
||||
Preload("Uom").
|
||||
Preload("Flags").
|
||||
Preload("Suppliers", func(db *gorm.DB) *gorm.DB {
|
||||
return db.Order("suppliers.name ASC")
|
||||
})
|
||||
}
|
||||
|
||||
func (s nonstockService) GetAll(c *fiber.Ctx, params *validation.Query) ([]entity.Nonstock, int64, error) {
|
||||
if err := s.Validate.Struct(params); err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
|
||||
offset := (params.Page - 1) * params.Limit
|
||||
|
||||
nonstocks, 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 nonstocks: %+v", err)
|
||||
return nil, 0, err
|
||||
}
|
||||
return nonstocks, total, nil
|
||||
}
|
||||
|
||||
func (s nonstockService) GetOne(c *fiber.Ctx, id uint) (*entity.Nonstock, error) {
|
||||
nonstock, err := s.Repository.GetByID(c.Context(), id, s.withRelations)
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil, fiber.NewError(fiber.StatusNotFound, "Nonstock not found")
|
||||
}
|
||||
if err != nil {
|
||||
s.Log.Errorf("Failed get nonstock by id: %+v", err)
|
||||
return nil, err
|
||||
}
|
||||
return nonstock, nil
|
||||
}
|
||||
|
||||
func (s *nonstockService) CreateOne(c *fiber.Ctx, req *validation.Create) (*entity.Nonstock, error) {
|
||||
if err := s.Validate.Struct(req); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
ctx := c.Context()
|
||||
name := strings.TrimSpace(req.Name)
|
||||
|
||||
if exists, err := s.Repository.NameExists(ctx, name, nil); err != nil {
|
||||
s.Log.Errorf("Failed to check nonstock name: %+v", err)
|
||||
return nil, fiber.NewError(fiber.StatusInternalServerError, "Failed to check nonstock name")
|
||||
} else if exists {
|
||||
return nil, fiber.NewError(fiber.StatusConflict, fmt.Sprintf("Nonstock with name %s already exists", name))
|
||||
}
|
||||
|
||||
if err := common.EnsureRelations(ctx, common.RelationCheck{Name: "Uom", ID: &req.UomID, Exists: s.Repository.UomExists}); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
supplierIDs := utils.UniqueUintSlice(req.SupplierIDs)
|
||||
if len(supplierIDs) > 0 {
|
||||
supplierList, supplierErr := s.Repository.GetSuppliersByIDs(ctx, supplierIDs)
|
||||
if supplierErr != nil {
|
||||
s.Log.Errorf("Failed to validate suppliers: %+v", supplierErr)
|
||||
return nil, fiber.NewError(fiber.StatusInternalServerError, "Failed to validate suppliers")
|
||||
}
|
||||
if len(supplierList) != len(supplierIDs) {
|
||||
actualIDs := make([]uint, len(supplierList))
|
||||
for i, supplier := range supplierList {
|
||||
actualIDs[i] = supplier.Id
|
||||
}
|
||||
missing := utils.MissingUintIDs(supplierIDs, actualIDs)
|
||||
return nil, fiber.NewError(fiber.StatusNotFound, fmt.Sprintf("Suppliers with ids %v not found", missing))
|
||||
}
|
||||
for _, sup := range supplierList {
|
||||
if strings.ToUpper(sup.Category) != string(utils.SupplierCategoryBOP) {
|
||||
return nil, fiber.NewError(fiber.StatusBadRequest, fmt.Sprintf("Supplier with id %d is not category BOP", sup.Id))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
nonstockFlags, flagErr := normalizeNonstockFlags(req.Flags)
|
||||
if flagErr != nil {
|
||||
return nil, flagErr
|
||||
}
|
||||
|
||||
createBody := &entity.Nonstock{
|
||||
Name: req.Name,
|
||||
UomId: req.UomID,
|
||||
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, nonstockFlags); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return s.Repository.SyncSuppliersDiff(ctx, tx, createBody.Id, supplierIDs)
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
s.Log.Errorf("Failed to create nonstock: %+v", err)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return s.GetOne(c, createBody.Id)
|
||||
}
|
||||
|
||||
func (s nonstockService) UpdateOne(c *fiber.Ctx, req *validation.Update, id uint) (*entity.Nonstock, error) {
|
||||
if err := s.Validate.Struct(req); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
updateBody := make(map[string]any)
|
||||
|
||||
ctx := c.Context()
|
||||
|
||||
if err := common.EnsureRelations(ctx, common.RelationCheck{Name: "Uom", ID: req.UomID, Exists: s.Repository.UomExists}); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if req.Name != nil {
|
||||
if exists, err := s.Repository.NameExists(ctx, *req.Name, &id); err != nil {
|
||||
s.Log.Errorf("Failed to check nonstock name: %+v", err)
|
||||
return nil, fiber.NewError(fiber.StatusInternalServerError, "Failed to check nonstock name")
|
||||
} else if exists {
|
||||
return nil, fiber.NewError(fiber.StatusConflict, fmt.Sprintf("Nonstock with name %s already exists", *req.Name))
|
||||
}
|
||||
|
||||
updateBody["name"] = *req.Name
|
||||
}
|
||||
if req.UomID != nil {
|
||||
updateBody["uom_id"] = *req.UomID
|
||||
}
|
||||
|
||||
var supplierIDs []uint
|
||||
var supplierUpdate bool
|
||||
if req.SupplierIDs != nil {
|
||||
supplierUpdate = true
|
||||
supplierIDs = utils.UniqueUintSlice(*req.SupplierIDs)
|
||||
if len(supplierIDs) > 0 {
|
||||
var supplierList []entity.Supplier
|
||||
var supplierErr error
|
||||
supplierList, supplierErr = s.Repository.GetSuppliersByIDs(ctx, supplierIDs)
|
||||
if supplierErr != nil {
|
||||
s.Log.Errorf("Failed to validate suppliers: %+v", supplierErr)
|
||||
return nil, fiber.NewError(fiber.StatusInternalServerError, "Failed to validate suppliers")
|
||||
}
|
||||
if len(supplierList) != len(supplierIDs) {
|
||||
actualIDs := make([]uint, len(supplierList))
|
||||
for i, supplier := range supplierList {
|
||||
actualIDs[i] = supplier.Id
|
||||
}
|
||||
missing := utils.MissingUintIDs(supplierIDs, actualIDs)
|
||||
return nil, fiber.NewError(fiber.StatusNotFound, fmt.Sprintf("Suppliers with ids %v not found", missing))
|
||||
}
|
||||
for _, sup := range supplierList {
|
||||
if strings.ToUpper(sup.Category) != string(utils.SupplierCategoryBOP) {
|
||||
return nil, fiber.NewError(fiber.StatusBadRequest, fmt.Sprintf("Supplier with id %d is not category BOP", sup.Id))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
var (
|
||||
flagUpdate bool
|
||||
flagValues []string
|
||||
)
|
||||
if req.Flags != nil {
|
||||
flagUpdate = true
|
||||
var flagErr error
|
||||
flagValues, flagErr = normalizeNonstockFlags(*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, "Nonstock not found")
|
||||
}
|
||||
s.Log.Errorf("Failed to update nonstock: %+v", err)
|
||||
return nil, err
|
||||
}
|
||||
return s.GetOne(c, id)
|
||||
}
|
||||
|
||||
func (s nonstockService) 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, "Nonstock not found")
|
||||
}
|
||||
s.Log.Errorf("Failed to delete nonstock: %+v", err)
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func normalizeNonstockFlags(raw []string) ([]string, error) {
|
||||
normalized, invalid := utils.NormalizeFlagsForGroup(raw, utils.FlagGroupNonstock)
|
||||
if len(invalid) > 0 {
|
||||
invalidStr := strings.Join(utils.FlagTypesToStrings(invalid), ", ")
|
||||
allowedStr := strings.Join(utils.FlagTypesToStrings(utils.AllowedFlagTypes(utils.FlagGroupNonstock)), ", ")
|
||||
return nil, fiber.NewError(fiber.StatusBadRequest, fmt.Sprintf("Invalid nonstock flags: %s. Allowed flags: %s", invalidStr, allowedStr))
|
||||
}
|
||||
return utils.FlagTypesToStrings(normalized), nil
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
package validation
|
||||
|
||||
type Create struct {
|
||||
Name string `json:"name" validate:"required_strict,min=3"`
|
||||
UomID uint `json:"uom_id" validate:"required,gt=0"`
|
||||
SupplierIDs []uint `json:"supplier_ids,omitempty" validate:"omitempty,dive,gt=0"`
|
||||
Flags []string `json:"flags,omitempty" validate:"omitempty,dive,max=50"`
|
||||
}
|
||||
|
||||
type Update struct {
|
||||
Name *string `json:"name,omitempty" validate:"omitempty,min=3"`
|
||||
UomID *uint `json:"uom_id,omitempty" validate:"omitempty,gt=0"`
|
||||
SupplierIDs *[]uint `json:"supplier_ids,omitempty" validate:"omitempty,dive,gt=0"`
|
||||
Flags *[]string `json:"flags,omitempty" validate:"omitempty,dive,max=50"`
|
||||
}
|
||||
|
||||
type Query struct {
|
||||
Page int `query:"page" validate:"omitempty,number,min=1"`
|
||||
Limit int `query:"limit" validate:"omitempty,number,min=1,max=100"`
|
||||
Search string `query:"search" validate:"omitempty,max=50"`
|
||||
}
|
||||
Reference in New Issue
Block a user