mirror of
https://gitlab.com/mbugroup/lti-api.git
synced 2026-05-23 23:05:44 +00:00
FIX[BE]: fix logic on Chickin Laying not convert to layer but still Pullet, and inisiate laying transfer migration and base basic API
This commit is contained in:
@@ -12,6 +12,7 @@ type ProjectChickinRepository interface {
|
||||
repository.BaseRepository[entity.ProjectChickin]
|
||||
GetFirstByProjectFlockID(ctx context.Context, projectFlockID uint) (*entity.ProjectChickin, error)
|
||||
GetByProjectFlockKandangID(ctx context.Context, projectFlockKandangID uint) ([]entity.ProjectChickin, error)
|
||||
GetPendingByProjectFlockKandangID(ctx context.Context, projectFlockKandangID uint) ([]entity.ProjectChickin, error)
|
||||
}
|
||||
|
||||
type ChickinRepositoryImpl struct {
|
||||
@@ -49,3 +50,17 @@ func (r *ChickinRepositoryImpl) GetByProjectFlockKandangID(ctx context.Context,
|
||||
}
|
||||
return chickins, nil
|
||||
}
|
||||
|
||||
func (r *ChickinRepositoryImpl) GetPendingByProjectFlockKandangID(ctx context.Context, projectFlockKandangID uint) ([]entity.ProjectChickin, error) {
|
||||
var chickins []entity.ProjectChickin
|
||||
err := r.db.WithContext(ctx).
|
||||
Where("project_flock_kandang_id = ?", projectFlockKandangID).
|
||||
Where("usage_qty = 0").
|
||||
Where("pending_usage_qty > 0").
|
||||
Order("created_at DESC").
|
||||
Find(&chickins).Error
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return chickins, nil
|
||||
}
|
||||
|
||||
@@ -150,8 +150,12 @@ func (s *chickinService) CreateOne(c *fiber.Ctx, req *validation.Create) ([]enti
|
||||
actorID := uint(1) // todo nanti ambil dari auth context
|
||||
newChikins := make([]*entity.ProjectChickin, 0)
|
||||
for _, productWarehouse := range productWarehouses {
|
||||
availableQty, err := s.calculateAvailableQuantity(c, req.ProjectFlockKandangId, &productWarehouse, category)
|
||||
if err != nil {
|
||||
s.Log.Warnf("Failed to calculate available quantity for product warehouse %d: %v", productWarehouse.Id, err)
|
||||
}
|
||||
|
||||
if productWarehouse.Quantity <= 0 {
|
||||
if availableQty <= 0 {
|
||||
continue
|
||||
}
|
||||
|
||||
@@ -159,7 +163,7 @@ func (s *chickinService) CreateOne(c *fiber.Ctx, req *validation.Create) ([]enti
|
||||
ProjectFlockKandangId: req.ProjectFlockKandangId,
|
||||
ChickInDate: chickinDate,
|
||||
UsageQty: 0,
|
||||
PendingUsageQty: productWarehouse.Quantity,
|
||||
PendingUsageQty: availableQty,
|
||||
ProductWarehouseId: productWarehouse.Id,
|
||||
Notes: req.Note,
|
||||
CreatedBy: actorID,
|
||||
@@ -176,6 +180,7 @@ func (s *chickinService) CreateOne(c *fiber.Ctx, req *validation.Create) ([]enti
|
||||
if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil, fiber.NewError(fiber.StatusInternalServerError, "Failed to check existing chickins")
|
||||
}
|
||||
|
||||
isFirstTime := len(existingChikins) == 0
|
||||
|
||||
err = s.Repository.DB().WithContext(c.Context()).Transaction(func(dbTransaction *gorm.DB) error {
|
||||
@@ -192,17 +197,19 @@ func (s *chickinService) CreateOne(c *fiber.Ctx, req *validation.Create) ([]enti
|
||||
return err
|
||||
}
|
||||
|
||||
for _, chickin := range newChikins {
|
||||
if category == string(utils.ProjectFlockCategoryLaying) {
|
||||
for _, chickin := range newChikins {
|
||||
updates := map[string]any{"quantity": gorm.Expr("quantity - ?", chickin.PendingUsageQty)}
|
||||
|
||||
updates := map[string]any{"quantity": 0}
|
||||
|
||||
if err := productWarehouseTx.PatchOne(c.Context(), chickin.ProductWarehouseId, updates, nil); err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return fiber.NewError(fiber.StatusNotFound, fmt.Sprintf("Product warehouse %d not found", chickin.ProductWarehouseId))
|
||||
if err := productWarehouseTx.PatchOne(c.Context(), chickin.ProductWarehouseId, updates, nil); err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return fiber.NewError(fiber.StatusNotFound, fmt.Sprintf("Product warehouse %d not found", chickin.ProductWarehouseId))
|
||||
}
|
||||
return fiber.NewError(fiber.StatusInternalServerError, "Failed to update product warehouse quantity")
|
||||
}
|
||||
return fiber.NewError(fiber.StatusInternalServerError, "Failed to update product warehouse quantity")
|
||||
}
|
||||
}
|
||||
|
||||
var approvalAction entity.ApprovalAction
|
||||
if isFirstTime {
|
||||
approvalAction = entity.ApprovalActionCreated
|
||||
@@ -287,6 +294,56 @@ func (s chickinService) DeleteOne(c *fiber.Ctx, id uint) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s chickinService) calculateAvailableQuantity(ctx *fiber.Ctx, projectFlockKandangID uint, productWarehouse *entity.ProductWarehouse, category string) (float64, error) {
|
||||
availableQty := productWarehouse.Quantity
|
||||
|
||||
if category == string(utils.ProjectFlockCategoryGrowing) {
|
||||
var totalPendingQty float64
|
||||
|
||||
chickins, err := s.Repository.GetByProjectFlockKandangID(ctx.Context(), projectFlockKandangID)
|
||||
if err == nil {
|
||||
for _, chickin := range chickins {
|
||||
|
||||
if chickin.ProductWarehouseId == productWarehouse.Id && chickin.DeletedAt.Time.IsZero() && chickin.PendingUsageQty > 0 {
|
||||
totalPendingQty += chickin.PendingUsageQty
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
availableQty = productWarehouse.Quantity - totalPendingQty
|
||||
if availableQty < 0 {
|
||||
availableQty = 0
|
||||
}
|
||||
} else if category == string(utils.ProjectFlockCategoryLaying) {
|
||||
var totalPopulation float64
|
||||
var totalPendingQty float64
|
||||
|
||||
populations, err := s.ProjectflockPopulationRepo.GetByProjectFlockKandangIDAndProductWarehouseID(ctx.Context(), projectFlockKandangID, productWarehouse.Id)
|
||||
if err == nil {
|
||||
for _, pop := range populations {
|
||||
totalPopulation += pop.TotalQty
|
||||
}
|
||||
}
|
||||
|
||||
chickins, err := s.Repository.GetByProjectFlockKandangID(ctx.Context(), projectFlockKandangID)
|
||||
if err == nil {
|
||||
for _, chickin := range chickins {
|
||||
|
||||
if chickin.ProductWarehouseId == productWarehouse.Id && chickin.DeletedAt.Time.IsZero() && chickin.PendingUsageQty > 0 {
|
||||
totalPendingQty += chickin.PendingUsageQty
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
availableQty = productWarehouse.Quantity - totalPopulation - totalPendingQty
|
||||
if availableQty < 0 {
|
||||
availableQty = 0
|
||||
}
|
||||
}
|
||||
|
||||
return availableQty, nil
|
||||
}
|
||||
|
||||
func (s chickinService) Approval(c *fiber.Ctx, req *validation.Approve) ([]entity.ProjectChickin, error) {
|
||||
if err := s.Validate.Struct(req); err != nil {
|
||||
return nil, err
|
||||
@@ -356,7 +413,7 @@ func (s chickinService) Approval(c *fiber.Ctx, req *validation.Approve) ([]entit
|
||||
if !(strings.Contains(lower, "duplicate") || strings.Contains(lower, "unique constraint") || strings.Contains(lower, "23505")) {
|
||||
return err
|
||||
}
|
||||
s.Log.Infof("ignored duplicate approval for kandang %d: %v", approvableID, err)
|
||||
|
||||
}
|
||||
|
||||
if action == entity.ApprovalActionApproved {
|
||||
@@ -374,54 +431,76 @@ func (s chickinService) Approval(c *fiber.Ctx, req *validation.Approve) ([]entit
|
||||
return err
|
||||
}
|
||||
|
||||
warehouse, err := s.WarehouseRepo.GetByKandangID(c.Context(), kandangForApproval.KandangId)
|
||||
if err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return fiber.NewError(fiber.StatusNotFound, fmt.Sprintf("Warehouse for kandang %d not found", kandangForApproval.KandangId))
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
category := strings.ToUpper(strings.TrimSpace(kandangForApproval.ProjectFlock.Category))
|
||||
var conversionCategoryCode string
|
||||
|
||||
switch category {
|
||||
case string(utils.ProjectFlockCategoryGrowing):
|
||||
conversionCategoryCode = "PULLET"
|
||||
case string(utils.ProjectFlockCategoryLaying):
|
||||
conversionCategoryCode = "LAYER"
|
||||
default:
|
||||
return fiber.NewError(fiber.StatusBadRequest, fmt.Sprintf("Unknown category for conversion: %s", category))
|
||||
if category == string(utils.ProjectFlockCategoryGrowing) {
|
||||
warehouse, err := s.WarehouseRepo.GetByKandangID(c.Context(), kandangForApproval.KandangId)
|
||||
if err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return fiber.NewError(fiber.StatusNotFound, fmt.Sprintf("Warehouse for kandang %d not found", kandangForApproval.KandangId))
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
targetPW, err := s.getOrCreateProductWarehouse(c, warehouse.Id, "PULLET", dbTransaction, actorID)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to get/create PULLET product warehouse: %w", err)
|
||||
}
|
||||
if err := s.convertChickinsToTarget(c, chickins, targetPW, dbTransaction, actorID); err != nil {
|
||||
return err
|
||||
}
|
||||
} else if category == string(utils.ProjectFlockCategoryLaying) {
|
||||
|
||||
warehouse, err := s.WarehouseRepo.GetByKandangID(c.Context(), kandangForApproval.KandangId)
|
||||
if err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return fiber.NewError(fiber.StatusNotFound, fmt.Sprintf("Warehouse for kandang %d not found", kandangForApproval.KandangId))
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
targetPW, err := s.getOrCreateProductWarehouse(c, warehouse.Id, "PULLET", dbTransaction, actorID)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to get/create PULLET product warehouse: %w", err)
|
||||
}
|
||||
if err := s.convertChickinsToTarget(c, chickins, targetPW, dbTransaction, actorID); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
targetPW, err := s.getOrCreateProductWarehouse(c, warehouse.Id, conversionCategoryCode, dbTransaction, actorID)
|
||||
if action == entity.ApprovalActionRejected {
|
||||
|
||||
chickins, err := chickinRepoTx.GetPendingByProjectFlockKandangID(c.Context(), approvableID)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to get/create %s product warehouse: %w", conversionCategoryCode, err)
|
||||
}
|
||||
if err := s.convertChickinsToTarget(c, chickins, targetPW, dbTransaction, actorID); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
} else if action == entity.ApprovalActionRejected {
|
||||
|
||||
chickins, err := chickinRepoTx.GetByProjectFlockKandangID(c.Context(), approvableID)
|
||||
if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return fmt.Errorf("failed to get chickins for rejection %d: %w", approvableID, err)
|
||||
return fmt.Errorf("failed to get pending chickins for rejection %d: %w", approvableID, err)
|
||||
}
|
||||
|
||||
if len(chickins) == 0 {
|
||||
continue
|
||||
}
|
||||
|
||||
kandangForRejection, err := s.ProjectflockKandangRepo.GetByID(c.Context(), approvableID)
|
||||
if err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return fiber.NewError(fiber.StatusNotFound, fmt.Sprintf("ProjectFlockKandang %d not found", approvableID))
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
categoryForRejection := strings.ToUpper(strings.TrimSpace(kandangForRejection.ProjectFlock.Category))
|
||||
|
||||
for _, chickin := range chickins {
|
||||
|
||||
updates := map[string]any{"quantity": chickin.PendingUsageQty}
|
||||
if categoryForRejection == string(utils.ProjectFlockCategoryGrowing) {
|
||||
updates := map[string]any{"quantity": gorm.Expr("quantity + ?", chickin.PendingUsageQty)}
|
||||
|
||||
if err := productWarehouseTx.PatchOne(c.Context(), chickin.ProductWarehouseId, updates, nil); err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return fiber.NewError(fiber.StatusNotFound, fmt.Sprintf("Product warehouse %d not found during rejection", chickin.ProductWarehouseId))
|
||||
if err := productWarehouseTx.PatchOne(c.Context(), chickin.ProductWarehouseId, updates, nil); err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return fiber.NewError(fiber.StatusNotFound, fmt.Sprintf("Product warehouse %d not found during rejection", chickin.ProductWarehouseId))
|
||||
}
|
||||
return fmt.Errorf("failed to restore product warehouse quantity for chickin %d: %w", chickin.Id, err)
|
||||
}
|
||||
return fmt.Errorf("failed to restore product warehouse quantity for chickin %d: %w", chickin.Id, err)
|
||||
}
|
||||
|
||||
if err := chickinRepoTx.DeleteOne(c.Context(), chickin.Id); err != nil {
|
||||
@@ -518,6 +597,18 @@ func (s *chickinService) convertChickinsToTarget(ctx *fiber.Ctx, chickins []enti
|
||||
return fmt.Errorf("failed to update chickin %d qty: %w", chickin.Id, err)
|
||||
}
|
||||
|
||||
if chickin.ProductWarehouseId != targetPW.Id {
|
||||
if err := productWarehouseTx.PatchOne(ctx.Context(), chickin.ProductWarehouseId, map[string]any{
|
||||
"quantity": gorm.Expr("quantity - ?", quantityToConvert),
|
||||
}, nil); err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return fiber.NewError(fiber.StatusNotFound, fmt.Sprintf("Source product warehouse %d not found", chickin.ProductWarehouseId))
|
||||
}
|
||||
return fmt.Errorf("failed to deduct source warehouse quantity for chickin %d: %w", chickin.Id, err)
|
||||
}
|
||||
}
|
||||
|
||||
// Add to target product warehouse
|
||||
if err := productWarehouseTx.PatchOne(ctx.Context(), targetPW.Id, map[string]any{
|
||||
"quantity": gorm.Expr("quantity + ?", quantityToConvert),
|
||||
}, nil); err != nil {
|
||||
|
||||
@@ -41,12 +41,12 @@ type KandangCustomDTO struct {
|
||||
|
||||
type ProductWarehouseDTO struct {
|
||||
Id uint `json:"id"`
|
||||
Quantity float64 `json:"quantity"`
|
||||
Product *productDTO.ProductBaseDTO `json:"product,omitempty"`
|
||||
Warehouse *warehouseDTO.WarehouseBaseDTO `json:"warehouse,omitempty"`
|
||||
}
|
||||
|
||||
type AvailableQtyDTO struct {
|
||||
AvailableQty float64 `json:"available_qty"`
|
||||
ProductWarehouse *ProductWarehouseDTO `json:"product_warehouse,omitempty"`
|
||||
}
|
||||
|
||||
@@ -171,10 +171,6 @@ func buildProductWarehouseFromMap(pwData map[string]interface{}) *ProductWarehou
|
||||
dto.Id = id
|
||||
}
|
||||
|
||||
if qty, ok := pwData["quantity"].(float64); ok {
|
||||
dto.Quantity = qty
|
||||
}
|
||||
|
||||
if pData, ok := pwData["product"].(map[string]interface{}); ok {
|
||||
dto.Product = buildProductFromMap(pData)
|
||||
}
|
||||
@@ -276,8 +272,7 @@ func buildAvailableQtys(chickins []entity.ProjectChickin) []AvailableQtyDTO {
|
||||
}
|
||||
|
||||
pwDTO := &ProductWarehouseDTO{
|
||||
Id: ch.ProductWarehouse.Id,
|
||||
Quantity: ch.ProductWarehouse.Quantity,
|
||||
Id: ch.ProductWarehouse.Id,
|
||||
}
|
||||
|
||||
if ch.ProductWarehouse.Product.Id != 0 {
|
||||
@@ -324,7 +319,13 @@ func buildAvailableQtysFromRaw(availableQtysRaw []map[string]interface{}) []Avai
|
||||
}
|
||||
|
||||
pwDTO := buildProductWarehouseFromMap(pwData)
|
||||
availableQty := 0.0
|
||||
if qty, ok := v["available_qty"].(float64); ok {
|
||||
availableQty = qty
|
||||
}
|
||||
|
||||
result[i] = AvailableQtyDTO{
|
||||
AvailableQty: availableQty,
|
||||
ProductWarehouse: pwDTO,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -24,6 +24,7 @@ type ProjectFlockKandangModule struct{}
|
||||
|
||||
func (ProjectFlockKandangModule) RegisterRoutes(router fiber.Router, db *gorm.DB, validate *validator.Validate) {
|
||||
projectFlockKandangRepo := rProjectFlockKandang.NewProjectFlockKandangRepository(db)
|
||||
projectFlockPopulationRepo := rProjectFlockKandang.NewProjectFlockPopulationRepository(db)
|
||||
userRepo := rUser.NewUserRepository(db)
|
||||
warehouseRepo := rWarehouse.NewWarehouseRepository(db)
|
||||
productWarehouseRepo := rProductWarehouse.NewProductWarehouseRepository(db)
|
||||
@@ -35,7 +36,7 @@ func (ProjectFlockKandangModule) RegisterRoutes(router fiber.Router, db *gorm.DB
|
||||
panic(fmt.Sprintf("failed to register project flock kandang approval workflow: %v", err))
|
||||
}
|
||||
|
||||
projectFlockKandangService := sProjectFlockKandang.NewProjectFlockKandangService(projectFlockKandangRepo, approvalService, warehouseRepo, productWarehouseRepo, validate)
|
||||
projectFlockKandangService := sProjectFlockKandang.NewProjectFlockKandangService(projectFlockKandangRepo, approvalService, warehouseRepo, productWarehouseRepo, projectFlockPopulationRepo, validate)
|
||||
userService := sUser.NewUserService(userRepo, validate)
|
||||
|
||||
ProjectFlockKandangRoutes(router, userService, projectFlockKandangService)
|
||||
|
||||
+75
-25
@@ -29,9 +29,10 @@ type projectFlockKandangService struct {
|
||||
ApprovalSvc commonSvc.ApprovalService
|
||||
WarehouseRepo rWarehouse.WarehouseRepository
|
||||
ProductWarehouseRepo rProductWarehouse.ProductWarehouseRepository
|
||||
PopulationRepo repository.ProjectFlockPopulationRepository
|
||||
}
|
||||
|
||||
func NewProjectFlockKandangService(repo repository.ProjectFlockKandangRepository, approvalSvc commonSvc.ApprovalService, warehouseRepo rWarehouse.WarehouseRepository, productWarehouseRepo rProductWarehouse.ProductWarehouseRepository, validate *validator.Validate) ProjectFlockKandangService {
|
||||
func NewProjectFlockKandangService(repo repository.ProjectFlockKandangRepository, approvalSvc commonSvc.ApprovalService, warehouseRepo rWarehouse.WarehouseRepository, productWarehouseRepo rProductWarehouse.ProductWarehouseRepository, populationRepo repository.ProjectFlockPopulationRepository, validate *validator.Validate) ProjectFlockKandangService {
|
||||
return &projectFlockKandangService{
|
||||
Log: utils.Log,
|
||||
Validate: validate,
|
||||
@@ -39,6 +40,7 @@ func NewProjectFlockKandangService(repo repository.ProjectFlockKandangRepository
|
||||
ApprovalSvc: approvalSvc,
|
||||
WarehouseRepo: warehouseRepo,
|
||||
ProductWarehouseRepo: productWarehouseRepo,
|
||||
PopulationRepo: populationRepo,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -114,32 +116,80 @@ func (s projectFlockKandangService) getAvailableQuantities(c *fiber.Ctx, project
|
||||
|
||||
var result []map[string]interface{}
|
||||
for _, pw := range products {
|
||||
if pw.Quantity > 0 {
|
||||
|
||||
productData := map[string]interface{}{
|
||||
"id": pw.Product.Id,
|
||||
"name": pw.Product.Name,
|
||||
}
|
||||
|
||||
warehouseData := map[string]interface{}{
|
||||
"id": pw.Warehouse.Id,
|
||||
"name": pw.Warehouse.Name,
|
||||
"type": pw.Warehouse.Type,
|
||||
}
|
||||
|
||||
productWarehouseData := map[string]interface{}{
|
||||
"id": pw.Id,
|
||||
"quantity": pw.Quantity,
|
||||
"product": productData,
|
||||
"warehouse": warehouseData,
|
||||
}
|
||||
|
||||
result = append(result, map[string]interface{}{
|
||||
"available_qty": pw.Quantity,
|
||||
"product_warehouse": productWarehouseData,
|
||||
})
|
||||
availableQty, err := s.calculateAvailableQuantityForProductWarehouse(c, projectFlockKandang, &pw)
|
||||
if err != nil {
|
||||
s.Log.Warnf("Failed to calculate available quantity for product warehouse %d: %v", pw.Id, err)
|
||||
}
|
||||
|
||||
// Only include product warehouse if available_qty > 0
|
||||
if availableQty <= 0 {
|
||||
continue
|
||||
}
|
||||
|
||||
productData := map[string]interface{}{
|
||||
"id": pw.Product.Id,
|
||||
"name": pw.Product.Name,
|
||||
}
|
||||
|
||||
warehouseData := map[string]interface{}{
|
||||
"id": pw.Warehouse.Id,
|
||||
"name": pw.Warehouse.Name,
|
||||
"type": pw.Warehouse.Type,
|
||||
}
|
||||
|
||||
productWarehouseData := map[string]interface{}{
|
||||
"id": pw.Id,
|
||||
"product": productData,
|
||||
"warehouse": warehouseData,
|
||||
}
|
||||
|
||||
result = append(result, map[string]interface{}{
|
||||
"available_qty": availableQty,
|
||||
"product_warehouse": productWarehouseData,
|
||||
})
|
||||
}
|
||||
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func (s projectFlockKandangService) calculateAvailableQuantityForProductWarehouse(c *fiber.Ctx, projectFlockKandang *entity.ProjectFlockKandang, productWarehouse *entity.ProductWarehouse) (float64, error) {
|
||||
availableQty := productWarehouse.Quantity
|
||||
|
||||
if projectFlockKandang.ProjectFlock.Category == string(utils.ProjectFlockCategoryGrowing) {
|
||||
var totalPendingQty float64
|
||||
|
||||
for _, chickin := range projectFlockKandang.Chickins {
|
||||
if chickin.ProductWarehouseId == productWarehouse.Id && chickin.DeletedAt.Time.IsZero() && chickin.PendingUsageQty > 0 {
|
||||
totalPendingQty += chickin.PendingUsageQty
|
||||
}
|
||||
}
|
||||
|
||||
availableQty = productWarehouse.Quantity - totalPendingQty
|
||||
if availableQty < 0 {
|
||||
availableQty = 0
|
||||
}
|
||||
} else if projectFlockKandang.ProjectFlock.Category == string(utils.ProjectFlockCategoryLaying) {
|
||||
var totalPopulation float64
|
||||
var totalPendingQty float64
|
||||
|
||||
populations, err := s.PopulationRepo.GetByProjectFlockKandangIDAndProductWarehouseID(c.Context(), projectFlockKandang.Id, productWarehouse.Id)
|
||||
if err == nil {
|
||||
for _, pop := range populations {
|
||||
totalPopulation += pop.TotalQty
|
||||
}
|
||||
}
|
||||
|
||||
for _, chickin := range projectFlockKandang.Chickins {
|
||||
if chickin.ProductWarehouseId == productWarehouse.Id && chickin.DeletedAt.Time.IsZero() && chickin.PendingUsageQty > 0 {
|
||||
totalPendingQty += chickin.PendingUsageQty
|
||||
}
|
||||
}
|
||||
|
||||
availableQty = productWarehouse.Quantity - totalPopulation - totalPendingQty
|
||||
if availableQty < 0 {
|
||||
availableQty = 0
|
||||
}
|
||||
}
|
||||
|
||||
return availableQty, nil
|
||||
}
|
||||
|
||||
+25
@@ -12,6 +12,8 @@ type ProjectFlockPopulationRepository interface {
|
||||
// domain-specific
|
||||
GetByProjectFlockKandangID(ctx context.Context, projectFlockKandangID uint) (*entity.ProjectFlockPopulation, error)
|
||||
ExistsByProjectChickinID(ctx context.Context, projectChickinID uint) (bool, error)
|
||||
GetByProjectChickinIDAndProductWarehouseID(ctx context.Context, projectChickinID uint, productWarehouseID uint) ([]entity.ProjectFlockPopulation, error)
|
||||
GetByProjectFlockKandangIDAndProductWarehouseID(ctx context.Context, projectFlockKandangID uint, productWarehouseID uint) ([]entity.ProjectFlockPopulation, error)
|
||||
|
||||
// subset of base repository methods used by services
|
||||
CreateOne(ctx context.Context, entity *entity.ProjectFlockPopulation, modifier func(*gorm.DB) *gorm.DB) error
|
||||
@@ -64,3 +66,26 @@ func (r *projectFlockPopulationRepositoryImpl) ExistsByProjectChickinID(ctx cont
|
||||
}
|
||||
return count > 0, nil
|
||||
}
|
||||
|
||||
func (r *projectFlockPopulationRepositoryImpl) GetByProjectChickinIDAndProductWarehouseID(ctx context.Context, projectChickinID uint, productWarehouseID uint) ([]entity.ProjectFlockPopulation, error) {
|
||||
var records []entity.ProjectFlockPopulation
|
||||
err := r.DB().WithContext(ctx).
|
||||
Where("project_chickin_id = ? AND product_warehouse_id = ?", projectChickinID, productWarehouseID).
|
||||
Find(&records).Error
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return records, nil
|
||||
}
|
||||
|
||||
func (r *projectFlockPopulationRepositoryImpl) GetByProjectFlockKandangIDAndProductWarehouseID(ctx context.Context, projectFlockKandangID uint, productWarehouseID uint) ([]entity.ProjectFlockPopulation, error) {
|
||||
var records []entity.ProjectFlockPopulation
|
||||
err := r.DB().WithContext(ctx).
|
||||
Joins("JOIN project_chickins ON project_chickins.id = project_flock_populations.project_chickin_id").
|
||||
Where("project_chickins.project_flock_kandang_id = ? AND project_flock_populations.product_warehouse_id = ?", projectFlockKandangID, productWarehouseID).
|
||||
Find(&records).Error
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return records, nil
|
||||
}
|
||||
|
||||
+6
-3
@@ -24,9 +24,12 @@ func NewTransferLayingController(transferLayingService service.TransferLayingSer
|
||||
|
||||
func (u *TransferLayingController) GetAll(c *fiber.Ctx) error {
|
||||
query := &validation.Query{
|
||||
Page: c.QueryInt("page", 1),
|
||||
Limit: c.QueryInt("limit", 10),
|
||||
Search: c.Query("search", ""),
|
||||
Page: c.QueryInt("page", 1),
|
||||
Limit: c.QueryInt("limit", 10),
|
||||
SourceProjectFlockId: uint(c.QueryInt("source_project_flock_id", 0)),
|
||||
TargetProjectFlockId: uint(c.QueryInt("target_project_flock_id", 0)),
|
||||
TransferDateFrom: c.Query("transfer_date_from", ""),
|
||||
TransferDateTo: c.Query("transfer_date_to", ""),
|
||||
}
|
||||
|
||||
if query.Page < 1 || query.Limit < 1 {
|
||||
|
||||
+17
-1
@@ -1,6 +1,8 @@
|
||||
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"
|
||||
@@ -8,15 +10,29 @@ import (
|
||||
|
||||
type TransferLayingRepository interface {
|
||||
repository.BaseRepository[entity.LayingTransfer]
|
||||
|
||||
GetByTransferNumber(ctx context.Context, transferNumber string) (*entity.LayingTransfer, error)
|
||||
}
|
||||
|
||||
type TransferLayingRepositoryImpl struct {
|
||||
*repository.BaseRepositoryImpl[entity.LayingTransfer]
|
||||
db *gorm.DB
|
||||
}
|
||||
|
||||
func NewTransferLayingRepository(db *gorm.DB) TransferLayingRepository {
|
||||
return &TransferLayingRepositoryImpl{
|
||||
BaseRepositoryImpl: repository.NewBaseRepository[entity.LayingTransfer](db),
|
||||
db: db,
|
||||
}
|
||||
}
|
||||
|
||||
func (r *TransferLayingRepositoryImpl) GetByTransferNumber(ctx context.Context, transferNumber string) (*entity.LayingTransfer, error) {
|
||||
var transfer entity.LayingTransfer
|
||||
err := r.db.WithContext(ctx).
|
||||
Where("transfer_number = ?", transferNumber).
|
||||
Where("deleted_at IS NULL").
|
||||
First(&transfer).Error
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &transfer, nil
|
||||
}
|
||||
|
||||
+38
@@ -0,0 +1,38 @@
|
||||
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 LayingTransferSourceRepository interface {
|
||||
repository.BaseRepository[entity.LayingTransferSource]
|
||||
GetByLayingTransferId(ctx context.Context, layingTransferId uint) ([]entity.LayingTransferSource, error)
|
||||
}
|
||||
|
||||
type LayingTransferSourceRepositoryImpl struct {
|
||||
*repository.BaseRepositoryImpl[entity.LayingTransferSource]
|
||||
db *gorm.DB
|
||||
}
|
||||
|
||||
func NewLayingTransferSourceRepository(db *gorm.DB) LayingTransferSourceRepository {
|
||||
return &LayingTransferSourceRepositoryImpl{
|
||||
BaseRepositoryImpl: repository.NewBaseRepository[entity.LayingTransferSource](db),
|
||||
db: db,
|
||||
}
|
||||
}
|
||||
|
||||
func (r *LayingTransferSourceRepositoryImpl) GetByLayingTransferId(ctx context.Context, layingTransferId uint) ([]entity.LayingTransferSource, error) {
|
||||
var sources []entity.LayingTransferSource
|
||||
err := r.db.WithContext(ctx).
|
||||
Where("laying_transfer_id = ?", layingTransferId).
|
||||
Order("created_at DESC").
|
||||
Find(&sources).Error
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return sources, nil
|
||||
}
|
||||
+38
@@ -0,0 +1,38 @@
|
||||
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 LayingTransferTargetRepository interface {
|
||||
repository.BaseRepository[entity.LayingTransferTarget]
|
||||
GetByLayingTransferId(ctx context.Context, layingTransferId uint) ([]entity.LayingTransferTarget, error)
|
||||
}
|
||||
|
||||
type LayingTransferTargetRepositoryImpl struct {
|
||||
*repository.BaseRepositoryImpl[entity.LayingTransferTarget]
|
||||
db *gorm.DB
|
||||
}
|
||||
|
||||
func NewLayingTransferTargetRepository(db *gorm.DB) LayingTransferTargetRepository {
|
||||
return &LayingTransferTargetRepositoryImpl{
|
||||
BaseRepositoryImpl: repository.NewBaseRepository[entity.LayingTransferTarget](db),
|
||||
db: db,
|
||||
}
|
||||
}
|
||||
|
||||
func (r *LayingTransferTargetRepositoryImpl) GetByLayingTransferId(ctx context.Context, layingTransferId uint) ([]entity.LayingTransferTarget, error) {
|
||||
var targets []entity.LayingTransferTarget
|
||||
err := r.db.WithContext(ctx).
|
||||
Where("laying_transfer_id = ?", layingTransferId).
|
||||
Order("created_at DESC").
|
||||
Find(&targets).Error
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return targets, nil
|
||||
}
|
||||
@@ -55,8 +55,17 @@ func (s transferLayingService) GetAll(c *fiber.Ctx, params *validation.Query) ([
|
||||
|
||||
transferLayings, 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+"%")
|
||||
if params.SourceProjectFlockId != 0 {
|
||||
db = db.Where("from_project_flock_id = ?", params.SourceProjectFlockId)
|
||||
}
|
||||
if params.TargetProjectFlockId != 0 {
|
||||
db = db.Where("to_project_flock_id = ?", params.TargetProjectFlockId)
|
||||
}
|
||||
if params.TransferDateFrom != "" {
|
||||
db = db.Where("transfer_date >= ?", params.TransferDateFrom)
|
||||
}
|
||||
if params.TransferDateTo != "" {
|
||||
db = db.Where("transfer_date <= ?", params.TransferDateTo)
|
||||
}
|
||||
return db.Order("created_at DESC").Order("updated_at DESC")
|
||||
})
|
||||
@@ -92,9 +101,19 @@ func (s *transferLayingService) CreateOne(c *fiber.Ctx, req *validation.Create)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
for _, detail := range req.Details {
|
||||
// Validate source kandangs
|
||||
for _, detail := range req.SourceKandangs {
|
||||
if err := common.EnsureRelations(c.Context(),
|
||||
common.RelationCheck{Name: "Project Flock Kandang", ID: &detail.SourceProjectFlockKandangId, Exists: s.ProjectFlockKandangRepo.IdExists},
|
||||
common.RelationCheck{Name: "Source Project Flock Kandang", ID: &detail.ProjectFlockKandangId, Exists: s.ProjectFlockKandangRepo.IdExists},
|
||||
); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
// Validate target kandangs
|
||||
for _, detail := range req.TargetKandangs {
|
||||
if err := common.EnsureRelations(c.Context(),
|
||||
common.RelationCheck{Name: "Target Project Flock Kandang", ID: &detail.ProjectFlockKandangId, Exists: s.ProjectFlockKandangRepo.IdExists},
|
||||
); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -106,7 +125,7 @@ func (s *transferLayingService) CreateOne(c *fiber.Ctx, req *validation.Create)
|
||||
}
|
||||
|
||||
var totalQty float64
|
||||
for _, item := range req.Details {
|
||||
for _, item := range req.SourceKandangs {
|
||||
totalQty += item.Quantity
|
||||
}
|
||||
|
||||
@@ -142,8 +161,12 @@ func (s transferLayingService) UpdateOne(c *fiber.Ctx, req *validation.Update, i
|
||||
|
||||
updateBody := make(map[string]any)
|
||||
|
||||
if req.Name != nil {
|
||||
updateBody["name"] = *req.Name
|
||||
if req.TransferDate != nil {
|
||||
updateBody["transfer_date"] = *req.TransferDate
|
||||
}
|
||||
|
||||
if req.Reason != nil {
|
||||
updateBody["notes"] = *req.Reason
|
||||
}
|
||||
|
||||
if len(updateBody) == 0 {
|
||||
|
||||
+22
-12
@@ -1,24 +1,34 @@
|
||||
package validation
|
||||
|
||||
type CreateDetail struct {
|
||||
SourceProjectFlockKandangId uint `json:"source_project_flock_kandang_id" validate:"required"`
|
||||
Quantity float64 `json:"quantity" validate:"required,gt=0"`
|
||||
type SourceKandangDetail struct {
|
||||
ProjectFlockKandangId uint `json:"project_flock_kandang_id" validate:"required"`
|
||||
Quantity float64 `json:"quantity" validate:"required,gt=0"`
|
||||
}
|
||||
|
||||
type TargetKandangDetail struct {
|
||||
ProjectFlockKandangId uint `json:"project_flock_kandang_id" validate:"required"`
|
||||
Quantity float64 `json:"quantity" validate:"required,gt=0"`
|
||||
}
|
||||
|
||||
type Create struct {
|
||||
TransferDate string `json:"transfer_date" validate:"required,datetime=2006-01-02"`
|
||||
SourceProjectFlockId uint `json:"source_project_flock_id" validate:"required"`
|
||||
TargetProjectFlockId uint `json:"target_project_flock_id" validate:"required"`
|
||||
Details []CreateDetail `json:"details" validate:"required,min=1,dive,required"`
|
||||
Reason string `json:"reason" validate:"omitempty,max=1000"`
|
||||
TransferDate string `json:"transfer_date" validate:"required,datetime=2006-01-02"`
|
||||
SourceProjectFlockId uint `json:"source_project_flock_id" validate:"required"`
|
||||
TargetProjectFlockId uint `json:"target_project_flock_id" validate:"required"`
|
||||
SourceKandangs []SourceKandangDetail `json:"source_kandangs" validate:"required,min=1,dive,required"`
|
||||
TargetKandangs []TargetKandangDetail `json:"target_kandangs" validate:"required,min=1,dive,required"`
|
||||
Reason string `json:"reason" validate:"omitempty,max=1000"`
|
||||
}
|
||||
|
||||
type Update struct {
|
||||
Name *string `json:"name,omitempty" validate:"omitempty"`
|
||||
TransferDate *string `json:"transfer_date,omitempty" validate:"omitempty,datetime=2006-01-02"`
|
||||
Reason *string `json:"reason,omitempty" validate:"omitempty,max=1000"`
|
||||
}
|
||||
|
||||
type Query struct {
|
||||
Page int `query:"page" validate:"omitempty,number,min=1,gt=0"`
|
||||
Limit int `query:"limit" validate:"omitempty,number,min=1,max=100,gt=0"`
|
||||
Search string `query:"search" validate:"omitempty,max=50"`
|
||||
Page int `query:"page" validate:"omitempty,number,min=1,gt=0"`
|
||||
Limit int `query:"limit" validate:"omitempty,number,min=1,max=100,gt=0"`
|
||||
SourceProjectFlockId uint `query:"source_project_flock_id" validate:"omitempty"`
|
||||
TargetProjectFlockId uint `query:"target_project_flock_id" validate:"omitempty"`
|
||||
TransferDateFrom string `query:"transfer_date_from" validate:"omitempty,datetime=2006-01-02"`
|
||||
TransferDateTo string `query:"transfer_date_to" validate:"omitempty,datetime=2006-01-02"`
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user