mirror of
https://gitlab.com/mbugroup/lti-api.git
synced 2026-05-20 13:31:56 +00:00
Merge remote-tracking branch 'origin/dev/fifo-v2' into development
This commit is contained in:
@@ -2,7 +2,6 @@ package chickins
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/go-playground/validator/v10"
|
||||
"github.com/gofiber/fiber/v2"
|
||||
@@ -10,7 +9,6 @@ import (
|
||||
|
||||
commonRepo "gitlab.com/mbugroup/lti-api.git/internal/common/repository"
|
||||
commonSvc "gitlab.com/mbugroup/lti-api.git/internal/common/service"
|
||||
"gitlab.com/mbugroup/lti-api.git/internal/utils/fifo"
|
||||
|
||||
rProductWarehouse "gitlab.com/mbugroup/lti-api.git/internal/modules/inventory/product-warehouses/repositories"
|
||||
rKandang "gitlab.com/mbugroup/lti-api.git/internal/modules/master/kandangs/repositories"
|
||||
@@ -20,6 +18,7 @@ import (
|
||||
sChickin "gitlab.com/mbugroup/lti-api.git/internal/modules/production/chickins/services"
|
||||
|
||||
rProjectFlock "gitlab.com/mbugroup/lti-api.git/internal/modules/production/project_flocks/repositories"
|
||||
rTransferLaying "gitlab.com/mbugroup/lti-api.git/internal/modules/production/transfer_layings/repositories"
|
||||
|
||||
rUser "gitlab.com/mbugroup/lti-api.git/internal/modules/users/repositories"
|
||||
sUser "gitlab.com/mbugroup/lti-api.git/internal/modules/users/services"
|
||||
@@ -38,47 +37,12 @@ func (ChickinModule) RegisterRoutes(router fiber.Router, db *gorm.DB, validate *
|
||||
projectflockkandangrepo := rProjectFlock.NewProjectFlockKandangRepository(db)
|
||||
projectflockpopulationrepo := rProjectFlock.NewProjectFlockPopulationRepository(db)
|
||||
projectFlockRepo := rProjectFlock.NewProjectflockRepository(db)
|
||||
transferLayingRepo := rTransferLaying.NewTransferLayingRepository(db)
|
||||
productWarehouseRepo := rProductWarehouse.NewProductWarehouseRepository(db)
|
||||
productRepo := rProduct.NewProductRepository(db)
|
||||
stockAllocationRepo := commonRepo.NewStockAllocationRepository(db)
|
||||
fifoService := commonSvc.NewFifoService(db, stockAllocationRepo, productWarehouseRepo, utils.Log)
|
||||
fifoStockV2Service := commonSvc.NewFifoStockV2Service(db, utils.Log)
|
||||
userRepo := rUser.NewUserRepository(db)
|
||||
|
||||
if err := fifoService.RegisterUsable(fifo.UsableConfig{
|
||||
Key: fifo.UsableKeyProjectChickin,
|
||||
Table: "project_chickins",
|
||||
Columns: fifo.UsableColumns{
|
||||
ID: "id",
|
||||
ProductWarehouseID: "product_warehouse_id",
|
||||
UsageQuantity: "usage_qty",
|
||||
PendingQuantity: "pending_usage_qty",
|
||||
CreatedAt: "created_at",
|
||||
},
|
||||
|
||||
ExcludedStockables: []fifo.StockableKey{fifo.StockableKeyProjectFlockPopulation},
|
||||
}); err != nil {
|
||||
if !strings.Contains(strings.ToLower(err.Error()), "already registered") {
|
||||
panic(fmt.Sprintf("failed to register chickin usable workflow: %v", err))
|
||||
}
|
||||
}
|
||||
|
||||
if err := fifoService.RegisterStockable(fifo.StockableConfig{
|
||||
Key: fifo.StockableKeyProjectFlockPopulation,
|
||||
Table: "project_flock_populations",
|
||||
Columns: fifo.StockableColumns{
|
||||
ID: "id",
|
||||
ProductWarehouseID: "product_warehouse_id",
|
||||
TotalQuantity: "total_qty",
|
||||
TotalUsedQuantity: "total_used_qty",
|
||||
CreatedAt: "created_at",
|
||||
},
|
||||
OrderBy: []string{"created_at ASC", "id ASC"},
|
||||
}); err != nil {
|
||||
if !strings.Contains(strings.ToLower(err.Error()), "already registered") {
|
||||
panic(fmt.Sprintf("failed to register project flock population stockable workflow: %v", err))
|
||||
}
|
||||
}
|
||||
|
||||
approvalRepo := commonRepo.NewApprovalRepository(db)
|
||||
approvalService := commonSvc.NewApprovalService(approvalRepo)
|
||||
if err := approvalService.RegisterWorkflowSteps(utils.ApprovalWorkflowChickin, utils.ChickinApprovalSteps); err != nil {
|
||||
@@ -95,8 +59,9 @@ func (ChickinModule) RegisterRoutes(router fiber.Router, db *gorm.DB, validate *
|
||||
projectflockkandangrepo,
|
||||
projectflockpopulationrepo,
|
||||
chickinDetailRepo,
|
||||
transferLayingRepo,
|
||||
validate,
|
||||
fifoService)
|
||||
fifoStockV2Service)
|
||||
userService := sUser.NewUserService(userRepo, validate)
|
||||
|
||||
ChickinRoutes(router, userService, chickinService)
|
||||
|
||||
@@ -4,7 +4,9 @@ import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"math"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
commonRepo "gitlab.com/mbugroup/lti-api.git/internal/common/repository"
|
||||
commonSvc "gitlab.com/mbugroup/lti-api.git/internal/common/service"
|
||||
@@ -17,6 +19,7 @@ import (
|
||||
repository "gitlab.com/mbugroup/lti-api.git/internal/modules/production/chickins/repositories"
|
||||
validation "gitlab.com/mbugroup/lti-api.git/internal/modules/production/chickins/validations"
|
||||
rProjectFlock "gitlab.com/mbugroup/lti-api.git/internal/modules/production/project_flocks/repositories"
|
||||
rTransferLaying "gitlab.com/mbugroup/lti-api.git/internal/modules/production/transfer_layings/repositories"
|
||||
rStockLogs "gitlab.com/mbugroup/lti-api.git/internal/modules/shared/repositories"
|
||||
"gitlab.com/mbugroup/lti-api.git/internal/utils"
|
||||
"gitlab.com/mbugroup/lti-api.git/internal/utils/fifo"
|
||||
@@ -25,10 +28,9 @@ import (
|
||||
"github.com/gofiber/fiber/v2"
|
||||
"github.com/sirupsen/logrus"
|
||||
"gorm.io/gorm"
|
||||
"gorm.io/gorm/clause"
|
||||
)
|
||||
|
||||
var chickinUsableKey = fifo.UsableKeyProjectChickin
|
||||
|
||||
type ChickinService interface {
|
||||
GetAll(ctx *fiber.Ctx, params *validation.Query) ([]entity.ProjectChickin, int64, error)
|
||||
GetOne(ctx *fiber.Ctx, id uint) (*entity.ProjectChickin, error)
|
||||
@@ -51,11 +53,12 @@ type chickinService struct {
|
||||
ProjectflockKandangRepo rProjectFlock.ProjectFlockKandangRepository
|
||||
ProjectflockPopulationRepo rProjectFlock.ProjectFlockPopulationRepository
|
||||
ProjectChickinDetailRepo repository.ProjectChickinDetailRepository
|
||||
FifoSvc commonSvc.FifoService
|
||||
TransferLayingRepo rTransferLaying.TransferLayingRepository
|
||||
FifoStockV2Svc commonSvc.FifoStockV2Service
|
||||
StockLogRepo rStockLogs.StockLogRepository
|
||||
}
|
||||
|
||||
func NewChickinService(repo repository.ProjectChickinRepository, kandangRepo KandangRepo.KandangRepository, warehouseRepo rWarehouse.WarehouseRepository, productWarehouseRepo rProductWarehouse.ProductWarehouseRepository, productRepo rProduct.ProductRepository, projectFlockRepo rProjectFlock.ProjectflockRepository, projectflockkandangRepo rProjectFlock.ProjectFlockKandangRepository, projectflockpopulationRepo rProjectFlock.ProjectFlockPopulationRepository, projectChickinDetailRepo repository.ProjectChickinDetailRepository, validate *validator.Validate, fifoSvc commonSvc.FifoService) ChickinService {
|
||||
func NewChickinService(repo repository.ProjectChickinRepository, kandangRepo KandangRepo.KandangRepository, warehouseRepo rWarehouse.WarehouseRepository, productWarehouseRepo rProductWarehouse.ProductWarehouseRepository, productRepo rProduct.ProductRepository, projectFlockRepo rProjectFlock.ProjectflockRepository, projectflockkandangRepo rProjectFlock.ProjectFlockKandangRepository, projectflockpopulationRepo rProjectFlock.ProjectFlockPopulationRepository, projectChickinDetailRepo repository.ProjectChickinDetailRepository, transferLayingRepo rTransferLaying.TransferLayingRepository, validate *validator.Validate, fifoStockV2Svc commonSvc.FifoStockV2Service) ChickinService {
|
||||
return &chickinService{
|
||||
Log: utils.Log,
|
||||
Validate: validate,
|
||||
@@ -68,7 +71,8 @@ func NewChickinService(repo repository.ProjectChickinRepository, kandangRepo Kan
|
||||
ProjectflockKandangRepo: projectflockkandangRepo,
|
||||
ProjectflockPopulationRepo: projectflockpopulationRepo,
|
||||
ProjectChickinDetailRepo: projectChickinDetailRepo,
|
||||
FifoSvc: fifoSvc,
|
||||
TransferLayingRepo: transferLayingRepo,
|
||||
FifoStockV2Svc: fifoStockV2Svc,
|
||||
StockLogRepo: rStockLogs.NewStockLogRepository(repo.DB()),
|
||||
}
|
||||
}
|
||||
@@ -120,11 +124,36 @@ func (s chickinService) GetOne(c *fiber.Ctx, id uint) (*entity.ProjectChickin, e
|
||||
return chickin, nil
|
||||
}
|
||||
|
||||
func (s chickinService) ensureNotTransferred(ctx context.Context, projectFlockKandangID uint) error {
|
||||
if projectFlockKandangID == 0 || s.TransferLayingRepo == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
transfer, err := s.TransferLayingRepo.GetLatestApprovedBySourceKandang(ctx, projectFlockKandangID)
|
||||
if err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil
|
||||
}
|
||||
s.Log.Errorf("Failed to resolve transfer laying by source kandang %d: %+v", projectFlockKandangID, err)
|
||||
return fiber.NewError(fiber.StatusInternalServerError, "Gagal memvalidasi transfer laying")
|
||||
}
|
||||
|
||||
if transfer != nil && transfer.ExecutedAt != nil && !transfer.ExecutedAt.IsZero() {
|
||||
return fiber.NewError(fiber.StatusBadRequest, "Project flock kandang sudah dipindahkan ke laying")
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *chickinService) CreateOne(c *fiber.Ctx, req *validation.Create) ([]entity.ProjectChickin, error) {
|
||||
if err := s.Validate.Struct(req); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if err := s.ensureNotTransferred(c.Context(), req.ProjectFlockKandangId); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
projectFlockKandang, err := s.ProjectflockKandangRepo.GetByID(c.Context(), req.ProjectFlockKandangId)
|
||||
if err != nil {
|
||||
return nil, fiber.NewError(fiber.StatusNotFound, "Project Flock Kandang not found")
|
||||
@@ -160,30 +189,31 @@ func (s *chickinService) CreateOne(c *fiber.Ctx, req *validation.Create) ([]enti
|
||||
return nil, fiber.NewError(fiber.StatusBadRequest, fmt.Sprintf("Product warehouse %d belongs to different flock. Only product warehouses with project_flock_kandang_id = NULL or = %d can be used", chickinReq.ProductWarehouseId, req.ProjectFlockKandangId))
|
||||
}
|
||||
|
||||
if productWarehouse.Product.Id != 0 {
|
||||
if productWarehouse.Product.Id != 0 {
|
||||
category := strings.ToUpper(strings.TrimSpace(projectFlockKandang.ProjectFlock.Category))
|
||||
if category != string(utils.ProjectFlockCategoryGrowing) && category != string(utils.ProjectFlockCategoryLaying) {
|
||||
return nil, fmt.Errorf("invalid flock category for chickin")
|
||||
}
|
||||
|
||||
var requiredFlag utils.FlagType
|
||||
if projectFlockKandang.ProjectFlock.Category == string(utils.ProjectFlockCategoryGrowing) {
|
||||
requiredFlag = utils.FlagDOC
|
||||
} else if projectFlockKandang.ProjectFlock.Category == string(utils.ProjectFlockCategoryLaying) {
|
||||
requiredFlag = utils.FlagPullet
|
||||
} else {
|
||||
return nil, fmt.Errorf("invalid flock category for chickin")
|
||||
}
|
||||
hasAyamFlag := false
|
||||
for _, flag := range productWarehouse.Product.Flags {
|
||||
if utils.CanonicalFlagType(flag.Name) == utils.FlagAyam {
|
||||
hasAyamFlag = true
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
hasRequiredFlag := false
|
||||
for _, flag := range productWarehouse.Product.Flags {
|
||||
if utils.FlagType(flag.Name) == requiredFlag {
|
||||
hasRequiredFlag = true
|
||||
break
|
||||
if !hasAyamFlag {
|
||||
return nil, fmt.Errorf(
|
||||
"product warehouse %d cannot be used for %s chickin. Product must have AYAM flag (or legacy alias DOC/PULLET/LAYER) (product ID: %d, warehouse ID: %d)",
|
||||
chickinReq.ProductWarehouseId,
|
||||
projectFlockKandang.ProjectFlock.Category,
|
||||
productWarehouse.Product.Id,
|
||||
productWarehouse.Id,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
if !hasRequiredFlag {
|
||||
return nil, fmt.Errorf("product warehouse %d cannot be used for %s chickin. Product must have %s flag (product ID: %d, warehouse ID: %d)", chickinReq.ProductWarehouseId, projectFlockKandang.ProjectFlock.Category, requiredFlag, productWarehouse.Product.Id, productWarehouse.Id)
|
||||
}
|
||||
}
|
||||
|
||||
chickinDate, err := utils.ParseDateString(chickinReq.ChickInDate)
|
||||
if err != nil {
|
||||
return nil, fiber.NewError(fiber.StatusBadRequest, fmt.Sprintf("Invalid ChickInDate format for product warehouse %d", chickinReq.ProductWarehouseId))
|
||||
@@ -260,7 +290,7 @@ func (s *chickinService) CreateOne(c *fiber.Ctx, req *validation.Create) ([]enti
|
||||
|
||||
for idx, chickin := range newChikins {
|
||||
desiredQty := chickinQtyMap[uint(idx)]
|
||||
if err := s.ConsumeChickinStocks(c.Context(), dbTransaction, chickin, desiredQty, actorID); err != nil {
|
||||
if err := s.StageChickinStocks(c.Context(), dbTransaction, chickin, desiredQty, actorID); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
@@ -334,6 +364,17 @@ func (s chickinService) UpdateOne(c *fiber.Ctx, req *validation.Update, id uint)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
chickin, err := s.Repository.GetByID(c.Context(), id, nil)
|
||||
if err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil, fiber.NewError(fiber.StatusNotFound, "Chickin not found")
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
if err := s.ensureNotTransferred(c.Context(), chickin.ProjectFlockKandangId); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
updateBody := make(map[string]any)
|
||||
|
||||
if req.ChickInDate != "" {
|
||||
@@ -353,7 +394,18 @@ func (s chickinService) UpdateOne(c *fiber.Ctx, req *validation.Update, id uint)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return s.GetOne(c, id)
|
||||
updated, err := s.GetOne(c, id)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if updated.UsageQty > 0 {
|
||||
if err := s.syncChickinTraceForProductWarehouse(c.Context(), nil, updated.ProductWarehouseId); err != nil {
|
||||
return nil, fiber.NewError(fiber.StatusInternalServerError, "Failed to sync chickin stock trace")
|
||||
}
|
||||
}
|
||||
|
||||
return updated, nil
|
||||
}
|
||||
|
||||
func (s chickinService) DeleteOne(c *fiber.Ctx, id uint) error {
|
||||
@@ -366,29 +418,40 @@ func (s chickinService) DeleteOne(c *fiber.Ctx, id uint) error {
|
||||
return err
|
||||
}
|
||||
|
||||
if err := s.ensureNotTransferred(c.Context(), chickin.ProjectFlockKandangId); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
actorID, err := m.ActorIDFromContext(c)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if chickin.UsageQty > 0 {
|
||||
err = s.Repository.DB().WithContext(c.Context()).Transaction(func(tx *gorm.DB) error {
|
||||
chickinRepoTx := repository.NewChickinRepository(tx)
|
||||
|
||||
currentUsageQty := chickin.UsageQty
|
||||
if chickin.UsageQty > 0 || chickin.PendingUsageQty > 0 {
|
||||
if err := s.ReleaseChickinStocks(c.Context(), tx, chickin, actorID); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
if err := s.ReleaseChickinStocks(c.Context(), s.Repository.DB(), chickin, actorID); err != nil {
|
||||
if err := chickinRepoTx.DeleteOne(c.Context(), id); err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return fiber.NewError(fiber.StatusNotFound, "Chickin not found")
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
warehouseDeltas := make(map[uint]float64)
|
||||
warehouseDeltas[chickin.ProductWarehouseId] += currentUsageQty
|
||||
if err := s.adjustProductWarehouseQuantities(c.Context(), s.Repository.DB(), warehouseDeltas); err != nil {
|
||||
if err := s.syncChickinTraceForProductWarehouse(c.Context(), tx, chickin.ProductWarehouseId); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
if err := s.Repository.DeleteOne(c.Context(), id); err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return fiber.NewError(fiber.StatusNotFound, "Chickin not found")
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
if fiberErr, ok := err.(*fiber.Error); ok {
|
||||
return fiberErr
|
||||
}
|
||||
return err
|
||||
}
|
||||
@@ -428,6 +491,9 @@ func (s chickinService) Approval(c *fiber.Ctx, req *validation.Approve) ([]entit
|
||||
if err := commonSvc.EnsureRelations(c.Context(), commonSvc.RelationCheck{Name: "ProjectFlockKandang", ID: &id, Exists: s.ProjectflockKandangRepo.IdExists}); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := s.ensureNotTransferred(c.Context(), id); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
latestApproval, err := approvalSvc.LatestByTarget(c.Context(), utils.ApprovalWorkflowChickin, id, nil)
|
||||
|
||||
if err != nil {
|
||||
@@ -451,8 +517,24 @@ func (s chickinService) Approval(c *fiber.Ctx, req *validation.Approve) ([]entit
|
||||
approvalSvc := commonSvc.NewApprovalService(commonRepo.NewApprovalRepository(dbTransaction))
|
||||
chickinRepoTx := repository.NewChickinRepository(dbTransaction)
|
||||
ProjectFlockPopulationRepotx := s.ProjectflockPopulationRepo.WithTx(dbTransaction)
|
||||
touchedProductWarehouseIDs := make(map[uint]struct{})
|
||||
|
||||
for _, approvableID := range approvableIDs {
|
||||
// Re-check latest approval inside transaction to prevent double-approve races.
|
||||
var latest entity.Approval
|
||||
if err := dbTransaction.WithContext(c.Context()).
|
||||
Table("approvals").
|
||||
Where("approvable_type = ? AND approvable_id = ?", utils.ApprovalWorkflowChickin.String(), approvableID).
|
||||
Order("id DESC").
|
||||
Limit(1).
|
||||
Clauses(clause.Locking{Strength: "UPDATE"}).
|
||||
Take(&latest).Error; err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return fiber.NewError(fiber.StatusInternalServerError, "Failed to recheck approval status")
|
||||
}
|
||||
if latest.Id != 0 && latest.StepNumber != uint16(utils.ChickinStepPengajuan) {
|
||||
return fiber.NewError(fiber.StatusBadRequest, fmt.Sprintf("ProjectFlockKandang %d sudah tidak berada di tahap PENGAJUAN", approvableID))
|
||||
}
|
||||
|
||||
if _, err := approvalSvc.CreateApproval(
|
||||
c.Context(),
|
||||
utils.ApprovalWorkflowChickin,
|
||||
@@ -491,6 +573,21 @@ func (s chickinService) Approval(c *fiber.Ctx, req *validation.Approve) ([]entit
|
||||
}
|
||||
|
||||
for _, chickin := range chickins {
|
||||
approvedQty := chickin.UsageQty
|
||||
if approvedQty <= 0 {
|
||||
approvedQty = chickin.PendingUsageQty
|
||||
}
|
||||
if approvedQty < 0 {
|
||||
approvedQty = 0
|
||||
}
|
||||
|
||||
if err := s.ConsumeChickinStocks(c.Context(), dbTransaction, &chickin, approvedQty, actorID); err != nil {
|
||||
return fiber.NewError(fiber.StatusInternalServerError, fmt.Sprintf("Failed to finalize usage qty for chickin %d", chickin.Id))
|
||||
}
|
||||
chickin.UsageQty = approvedQty
|
||||
chickin.PendingUsageQty = 0
|
||||
touchedProductWarehouseIDs[chickin.ProductWarehouseId] = struct{}{}
|
||||
|
||||
populationExists, err := ProjectFlockPopulationRepotx.ExistsByProjectChickinID(c.Context(), chickin.Id)
|
||||
if err != nil {
|
||||
return fiber.NewError(fiber.StatusInternalServerError, fmt.Sprintf("Failed to check population for chickin %d", chickin.Id))
|
||||
@@ -522,19 +619,13 @@ func (s chickinService) Approval(c *fiber.Ctx, req *validation.Approve) ([]entit
|
||||
return fiber.NewError(fiber.StatusInternalServerError, fmt.Sprintf("Failed to create population for chickin %d", chickin.Id))
|
||||
}
|
||||
|
||||
if err := chickinRepoTx.PatchOne(c.Context(), chickin.Id, map[string]any{
|
||||
"pending_usage_qty": 0,
|
||||
}, nil); err != nil {
|
||||
return fiber.NewError(fiber.StatusInternalServerError, fmt.Sprintf("Failed to reset pending usage qty for chickin %d", chickin.Id))
|
||||
}
|
||||
|
||||
if err := s.ReplenishChickinStocks(c.Context(), dbTransaction, &chickin, sourcePW, population, actorID); err != nil {
|
||||
return fiber.NewError(fiber.StatusInternalServerError, fmt.Sprintf("Failed to replenish stock for chickin %d", chickin.Id))
|
||||
}
|
||||
}
|
||||
}
|
||||
if action == entity.ApprovalActionRejected {
|
||||
chickins, err := chickinRepoTx.GetPendingByProjectFlockKandangID(c.Context(), approvableID)
|
||||
chickins, err := chickinRepoTx.GetByProjectFlockKandangID(c.Context(), approvableID)
|
||||
if err != nil {
|
||||
return fiber.NewError(fiber.StatusInternalServerError, fmt.Sprintf("Failed to get pending chickins for rejection %d", approvableID))
|
||||
}
|
||||
@@ -544,16 +635,22 @@ func (s chickinService) Approval(c *fiber.Ctx, req *validation.Approve) ([]entit
|
||||
}
|
||||
|
||||
for _, chickin := range chickins {
|
||||
populationExists, err := ProjectFlockPopulationRepotx.ExistsByProjectChickinID(c.Context(), chickin.Id)
|
||||
if err != nil {
|
||||
return fiber.NewError(fiber.StatusInternalServerError, fmt.Sprintf("Failed to check population for chickin %d", chickin.Id))
|
||||
}
|
||||
if populationExists {
|
||||
continue
|
||||
}
|
||||
|
||||
if chickin.UsageQty <= 0 && chickin.PendingUsageQty <= 0 {
|
||||
continue
|
||||
}
|
||||
|
||||
if err := s.ReleaseChickinStocks(c.Context(), dbTransaction, &chickin, actorID); err != nil {
|
||||
return fiber.NewError(fiber.StatusInternalServerError, fmt.Sprintf("Failed to release stock for rejected chickin %d: %v", chickin.Id, err))
|
||||
}
|
||||
|
||||
warehouseDeltas := make(map[uint]float64)
|
||||
warehouseDeltas[chickin.ProductWarehouseId] += chickin.UsageQty
|
||||
if err := s.adjustProductWarehouseQuantities(c.Context(), dbTransaction, warehouseDeltas); err != nil {
|
||||
return err
|
||||
}
|
||||
touchedProductWarehouseIDs[chickin.ProductWarehouseId] = struct{}{}
|
||||
|
||||
if err := chickinRepoTx.DeleteOne(c.Context(), chickin.Id); err != nil {
|
||||
if !errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
@@ -563,6 +660,13 @@ func (s chickinService) Approval(c *fiber.Ctx, req *validation.Approve) ([]entit
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for productWarehouseID := range touchedProductWarehouseIDs {
|
||||
if err := s.syncChickinTraceForProductWarehouse(c.Context(), dbTransaction, productWarehouseID); err != nil {
|
||||
return fiber.NewError(fiber.StatusInternalServerError, fmt.Sprintf("Failed to sync chickin trace for product warehouse %d", productWarehouseID))
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
})
|
||||
|
||||
@@ -617,121 +721,245 @@ func (s *chickinService) autoAddFlagToProduct(ctx context.Context, tx *gorm.DB,
|
||||
}
|
||||
|
||||
func (s *chickinService) ConsumeChickinStocks(ctx context.Context, tx *gorm.DB, chickin *entity.ProjectChickin, desiredQty float64, actorID uint) error {
|
||||
if chickin == nil || s.FifoSvc == nil {
|
||||
if chickin == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
result, err := s.FifoSvc.Consume(ctx, commonSvc.StockConsumeRequest{
|
||||
UsableKey: chickinUsableKey,
|
||||
UsableID: chickin.Id,
|
||||
ProductWarehouseID: chickin.ProductWarehouseId,
|
||||
Quantity: desiredQty,
|
||||
AllowPending: true,
|
||||
Tx: tx,
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
if tx == nil {
|
||||
return errors.New("transaction is required")
|
||||
}
|
||||
if desiredQty < 0 {
|
||||
return errors.New("desired quantity must be zero or greater")
|
||||
}
|
||||
|
||||
if err := s.Repository.UpdateUsageFields(ctx, tx, chickin.Id, result.UsageQuantity, result.PendingQuantity); err != nil {
|
||||
return err
|
||||
return s.Repository.UpdateUsageFields(ctx, tx, chickin.Id, desiredQty, 0)
|
||||
}
|
||||
|
||||
func (s *chickinService) StageChickinStocks(ctx context.Context, tx *gorm.DB, chickin *entity.ProjectChickin, desiredQty float64, actorID uint) error {
|
||||
if chickin == nil {
|
||||
return nil
|
||||
}
|
||||
if tx == nil {
|
||||
return errors.New("transaction is required")
|
||||
}
|
||||
if desiredQty < 0 {
|
||||
return errors.New("desired quantity must be zero or greater")
|
||||
}
|
||||
|
||||
if result.UsageQuantity > 0 {
|
||||
decreaseLog := &entity.StockLog{
|
||||
Decrease: result.UsageQuantity,
|
||||
LoggableType: string(utils.StockLogTypeChikin),
|
||||
LoggableId: chickin.Id,
|
||||
ProductWarehouseId: chickin.ProductWarehouseId,
|
||||
CreatedBy: actorID,
|
||||
Notes: fmt.Sprintf("Chickin #%d", chickin.Id),
|
||||
}
|
||||
stockLogs, err := s.StockLogRepo.GetByProductWarehouse(ctx, chickin.ProductWarehouseId, 1)
|
||||
if err != nil {
|
||||
return fiber.NewError(fiber.StatusInternalServerError, "Failed to get stock logs")
|
||||
}
|
||||
if len(stockLogs) > 0 {
|
||||
latestStockLog := stockLogs[0]
|
||||
decreaseLog.Stock = latestStockLog.Stock
|
||||
decreaseLog.Stock -= decreaseLog.Decrease
|
||||
} else {
|
||||
decreaseLog.Stock -= decreaseLog.Decrease
|
||||
}
|
||||
|
||||
s.StockLogRepo.CreateOne(ctx, decreaseLog, nil)
|
||||
}
|
||||
|
||||
return nil
|
||||
return s.Repository.UpdateUsageFields(ctx, tx, chickin.Id, 0, desiredQty)
|
||||
}
|
||||
|
||||
func (s *chickinService) ReplenishChickinStocks(ctx context.Context, tx *gorm.DB, chickin *entity.ProjectChickin, targetPW *entity.ProductWarehouse, population *entity.ProjectFlockPopulation, actorID uint) error {
|
||||
if chickin == nil || targetPW == nil || population == nil || s.FifoSvc == nil {
|
||||
if chickin == nil || targetPW == nil || population == nil {
|
||||
return nil
|
||||
}
|
||||
if tx == nil {
|
||||
return errors.New("transaction is required")
|
||||
}
|
||||
if s.FifoStockV2Svc == nil {
|
||||
return errors.New("fifo v2 service is not available")
|
||||
}
|
||||
|
||||
_, err := s.FifoSvc.Replenish(ctx, commonSvc.StockReplenishRequest{
|
||||
StockableKey: fifo.StockableKeyProjectFlockPopulation,
|
||||
StockableID: population.Id,
|
||||
ProductWarehouseID: targetPW.Id,
|
||||
Quantity: chickin.UsageQty,
|
||||
Tx: tx,
|
||||
})
|
||||
if err != nil {
|
||||
if err := tx.WithContext(ctx).
|
||||
Model(&entity.ProjectFlockPopulation{}).
|
||||
Where("id = ?", population.Id).
|
||||
Update("total_qty", chickin.UsageQty).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
asOf := chickin.ChickInDate
|
||||
if asOf.IsZero() {
|
||||
asOf = chickin.CreatedAt
|
||||
}
|
||||
return reflowChickinScope(ctx, s.FifoStockV2Svc, tx, targetPW.Id, &asOf)
|
||||
}
|
||||
|
||||
func (s *chickinService) ReleaseChickinStocks(ctx context.Context, tx *gorm.DB, chickin *entity.ProjectChickin, actorID uint) error {
|
||||
if chickin == nil || s.FifoSvc == nil {
|
||||
if chickin == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
var currentUsage float64
|
||||
if err := tx.Model(&entity.ProjectChickin{}).Where("id = ?", chickin.Id).Select("usage_qty").Scan(¤tUsage).Error; err != nil {
|
||||
|
||||
}
|
||||
|
||||
if err := s.FifoSvc.ReleaseUsage(ctx, commonSvc.StockReleaseRequest{
|
||||
UsableKey: chickinUsableKey,
|
||||
UsableID: chickin.Id,
|
||||
Tx: tx,
|
||||
}); err != nil {
|
||||
return err
|
||||
if tx == nil {
|
||||
return errors.New("transaction is required")
|
||||
}
|
||||
|
||||
if err := s.Repository.UpdateUsageFields(ctx, tx, chickin.Id, 0, 0); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if currentUsage > 0 {
|
||||
increaseLog := &entity.StockLog{
|
||||
Increase: currentUsage,
|
||||
LoggableType: string(utils.StockLogTypeChikin),
|
||||
LoggableId: chickin.Id,
|
||||
ProductWarehouseId: chickin.ProductWarehouseId,
|
||||
CreatedBy: actorID,
|
||||
Notes: fmt.Sprintf("Chickin #%d - Stock released", chickin.Id),
|
||||
}
|
||||
stockLogs, err := s.StockLogRepo.GetByProductWarehouse(ctx, chickin.ProductWarehouseId, 1)
|
||||
if err != nil {
|
||||
return fiber.NewError(fiber.StatusInternalServerError, "Failed to get stock logs")
|
||||
}
|
||||
if len(stockLogs) > 0 {
|
||||
latestStockLog := stockLogs[0]
|
||||
increaseLog.Stock = latestStockLog.Stock
|
||||
increaseLog.Stock += increaseLog.Increase
|
||||
} else {
|
||||
increaseLog.Stock += increaseLog.Increase
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *chickinService) syncChickinTraceForProductWarehouse(ctx context.Context, tx *gorm.DB, productWarehouseID uint) error {
|
||||
if productWarehouseID == 0 {
|
||||
return nil
|
||||
}
|
||||
if s.FifoStockV2Svc == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
if tx == nil {
|
||||
return s.Repository.DB().WithContext(ctx).Transaction(func(innerTx *gorm.DB) error {
|
||||
return s.syncChickinTraceForProductWarehouse(ctx, innerTx, productWarehouseID)
|
||||
})
|
||||
}
|
||||
|
||||
flagGroupCode, err := s.resolveFlagGroupByProductWarehouse(ctx, tx, productWarehouseID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if strings.TrimSpace(flagGroupCode) == "" {
|
||||
return nil
|
||||
}
|
||||
|
||||
now := time.Now()
|
||||
if err := tx.WithContext(ctx).
|
||||
Table("stock_allocations").
|
||||
Where("product_warehouse_id = ?", productWarehouseID).
|
||||
Where("usable_type = ?", fifo.UsableKeyProjectChickin.String()).
|
||||
Where("allocation_purpose = ?", entity.StockAllocationPurposeTraceChickin).
|
||||
Where("status = ?", entity.StockAllocationStatusActive).
|
||||
Updates(map[string]any{
|
||||
"status": entity.StockAllocationStatusReleased,
|
||||
"released_at": now,
|
||||
"updated_at": now,
|
||||
"note": "chickin_trace_reflow_reset",
|
||||
}).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
type chickinTraceRow struct {
|
||||
ID uint `gorm:"column:id"`
|
||||
UsageQty float64 `gorm:"column:usage_qty"`
|
||||
ChickIn time.Time `gorm:"column:chick_in_date"`
|
||||
}
|
||||
chickins := make([]chickinTraceRow, 0)
|
||||
if err := tx.WithContext(ctx).
|
||||
Table("project_chickins").
|
||||
Select("id, usage_qty, chick_in_date").
|
||||
Where("product_warehouse_id = ?", productWarehouseID).
|
||||
Where("deleted_at IS NULL").
|
||||
Where("usage_qty > 0").
|
||||
Order("chick_in_date ASC, id ASC").
|
||||
Scan(&chickins).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
if len(chickins) == 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
gatherRows, err := s.FifoStockV2Svc.Gather(ctx, commonSvc.FifoStockV2GatherRequest{
|
||||
FlagGroupCode: flagGroupCode,
|
||||
Lane: "STOCKABLE",
|
||||
ProductWarehouseID: productWarehouseID,
|
||||
Limit: 50000,
|
||||
Tx: tx,
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if len(gatherRows) == 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
type lotKey struct {
|
||||
StockableType string
|
||||
StockableID uint
|
||||
}
|
||||
remainingByLot := make(map[lotKey]float64, len(gatherRows))
|
||||
for _, row := range gatherRows {
|
||||
key := lotKey{StockableType: row.Ref.LegacyTypeKey, StockableID: row.Ref.ID}
|
||||
remainingByLot[key] = row.AvailableQuantity
|
||||
}
|
||||
|
||||
lotIndex := 0
|
||||
traceNow := time.Now()
|
||||
for _, chickin := range chickins {
|
||||
remaining := chickin.UsageQty
|
||||
for remaining > 1e-6 && lotIndex < len(gatherRows) {
|
||||
lot := gatherRows[lotIndex]
|
||||
key := lotKey{StockableType: lot.Ref.LegacyTypeKey, StockableID: lot.Ref.ID}
|
||||
available := remainingByLot[key]
|
||||
if available <= 1e-6 {
|
||||
lotIndex++
|
||||
continue
|
||||
}
|
||||
|
||||
portion := math.Min(remaining, available)
|
||||
if portion <= 1e-6 {
|
||||
lotIndex++
|
||||
continue
|
||||
}
|
||||
|
||||
insert := map[string]any{
|
||||
"product_warehouse_id": productWarehouseID,
|
||||
"stockable_type": lot.Ref.LegacyTypeKey,
|
||||
"stockable_id": lot.Ref.ID,
|
||||
"usable_type": fifo.UsableKeyProjectChickin.String(),
|
||||
"usable_id": chickin.ID,
|
||||
"qty": portion,
|
||||
"status": entity.StockAllocationStatusActive,
|
||||
"allocation_purpose": entity.StockAllocationPurposeTraceChickin,
|
||||
"engine_version": "v2",
|
||||
"flag_group_code": flagGroupCode,
|
||||
"function_code": "CHICKIN_TRACE",
|
||||
"created_at": traceNow,
|
||||
"updated_at": traceNow,
|
||||
}
|
||||
if err := tx.WithContext(ctx).Table("stock_allocations").Create(insert).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
remaining -= portion
|
||||
remainingByLot[key] = available - portion
|
||||
}
|
||||
|
||||
s.StockLogRepo.CreateOne(ctx, increaseLog, nil)
|
||||
if remaining > 1e-6 {
|
||||
s.Log.Warnf(
|
||||
"chickin trace partial allocation for product_warehouse_id=%d chickin_id=%d: remaining=%.3f",
|
||||
productWarehouseID,
|
||||
chickin.ID,
|
||||
remaining,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *chickinService) resolveFlagGroupByProductWarehouse(ctx context.Context, tx *gorm.DB, productWarehouseID uint) (string, error) {
|
||||
type row struct {
|
||||
FlagGroupCode string `gorm:"column:flag_group_code"`
|
||||
}
|
||||
|
||||
selected := row{}
|
||||
err := tx.WithContext(ctx).
|
||||
Table("fifo_stock_v2_route_rules rr").
|
||||
Select("rr.flag_group_code").
|
||||
Joins("JOIN fifo_stock_v2_flag_groups fg ON fg.code = rr.flag_group_code AND fg.is_active = TRUE").
|
||||
Where("rr.is_active = TRUE").
|
||||
Where("rr.lane = 'STOCKABLE'").
|
||||
Where(`
|
||||
EXISTS (
|
||||
SELECT 1
|
||||
FROM product_warehouses pw
|
||||
JOIN flags f ON f.flagable_id = pw.product_id
|
||||
JOIN fifo_stock_v2_flag_members fm ON fm.flag_name = f.name AND fm.is_active = TRUE
|
||||
WHERE pw.id = ?
|
||||
AND f.flagable_type = ?
|
||||
AND fm.flag_group_code = rr.flag_group_code
|
||||
)
|
||||
`, productWarehouseID, entity.FlagableTypeProduct).
|
||||
Order("fg.priority ASC, rr.id ASC").
|
||||
Limit(1).
|
||||
Take(&selected).Error
|
||||
if err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return "", nil
|
||||
}
|
||||
return "", err
|
||||
}
|
||||
return selected.FlagGroupCode, nil
|
||||
}
|
||||
|
||||
func (s chickinService) EnsureChickInExists(ctx context.Context, projectFlockKandangID uint) error {
|
||||
if projectFlockKandangID == 0 {
|
||||
return fiber.NewError(fiber.StatusBadRequest, "Project flock kandang tidak valid")
|
||||
@@ -755,10 +983,3 @@ func (s chickinService) EnsureChickInExists(ctx context.Context, projectFlockKan
|
||||
|
||||
return fiber.NewError(fiber.StatusBadRequest, "Chick in project flock belum disetujui sehingga belum dapat membuat recording")
|
||||
}
|
||||
|
||||
func (s *chickinService) adjustProductWarehouseQuantities(ctx context.Context, tx *gorm.DB, deltas map[uint]float64) error {
|
||||
if len(deltas) == 0 {
|
||||
return nil
|
||||
}
|
||||
return s.ProductWarehouseRepo.AdjustQuantities(ctx, deltas, func(*gorm.DB) *gorm.DB { return tx })
|
||||
}
|
||||
|
||||
@@ -0,0 +1,82 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
commonSvc "gitlab.com/mbugroup/lti-api.git/internal/common/service"
|
||||
entity "gitlab.com/mbugroup/lti-api.git/internal/entities"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
func reflowChickinScope(
|
||||
ctx context.Context,
|
||||
fifoStockV2Svc commonSvc.FifoStockV2Service,
|
||||
tx *gorm.DB,
|
||||
productWarehouseID uint,
|
||||
asOf *time.Time,
|
||||
) error {
|
||||
if fifoStockV2Svc == nil {
|
||||
return fmt.Errorf("FIFO v2 service is not available")
|
||||
}
|
||||
if tx == nil {
|
||||
return fmt.Errorf("transaction is required")
|
||||
}
|
||||
if productWarehouseID == 0 {
|
||||
return fmt.Errorf("product warehouse id is required")
|
||||
}
|
||||
|
||||
flagGroupCode, err := resolveChickinFlagGroupByProductWarehouse(ctx, tx, productWarehouseID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if strings.TrimSpace(flagGroupCode) == "" {
|
||||
return fmt.Errorf("flag group code is not found for product warehouse %d", productWarehouseID)
|
||||
}
|
||||
|
||||
_, err = fifoStockV2Svc.Reflow(ctx, commonSvc.FifoStockV2ReflowRequest{
|
||||
FlagGroupCode: flagGroupCode,
|
||||
ProductWarehouseID: productWarehouseID,
|
||||
AsOf: asOf,
|
||||
Tx: tx,
|
||||
})
|
||||
return err
|
||||
}
|
||||
|
||||
func resolveChickinFlagGroupByProductWarehouse(ctx context.Context, tx *gorm.DB, productWarehouseID uint) (string, error) {
|
||||
type row struct {
|
||||
FlagGroupCode string `gorm:"column:flag_group_code"`
|
||||
}
|
||||
|
||||
var selected row
|
||||
err := tx.WithContext(ctx).
|
||||
Table("fifo_stock_v2_route_rules rr").
|
||||
Select("rr.flag_group_code").
|
||||
Joins("JOIN fifo_stock_v2_flag_groups fg ON fg.code = rr.flag_group_code AND fg.is_active = TRUE").
|
||||
Where("rr.is_active = TRUE").
|
||||
Where(`
|
||||
EXISTS (
|
||||
SELECT 1
|
||||
FROM product_warehouses pw
|
||||
JOIN flags f ON f.flagable_id = pw.product_id
|
||||
JOIN fifo_stock_v2_flag_members fm ON fm.flag_name = f.name AND fm.is_active = TRUE
|
||||
WHERE pw.id = ?
|
||||
AND f.flagable_type = ?
|
||||
AND fm.flag_group_code = rr.flag_group_code
|
||||
)
|
||||
`, productWarehouseID, entity.FlagableTypeProduct).
|
||||
Order("fg.priority ASC, rr.id ASC").
|
||||
Limit(1).
|
||||
Take(&selected).Error
|
||||
if err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return "", nil
|
||||
}
|
||||
return "", err
|
||||
}
|
||||
|
||||
return strings.TrimSpace(selected.FlagGroupCode), nil
|
||||
}
|
||||
@@ -2,7 +2,6 @@ package recordings
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/go-playground/validator/v10"
|
||||
"github.com/gofiber/fiber/v2"
|
||||
@@ -24,9 +23,9 @@ import (
|
||||
sProjectFlock "gitlab.com/mbugroup/lti-api.git/internal/modules/production/project_flocks/services"
|
||||
rRecording "gitlab.com/mbugroup/lti-api.git/internal/modules/production/recordings/repositories"
|
||||
sRecording "gitlab.com/mbugroup/lti-api.git/internal/modules/production/recordings/services"
|
||||
rTransferLaying "gitlab.com/mbugroup/lti-api.git/internal/modules/production/transfer_layings/repositories"
|
||||
rStockLogs "gitlab.com/mbugroup/lti-api.git/internal/modules/shared/repositories"
|
||||
"gitlab.com/mbugroup/lti-api.git/internal/utils"
|
||||
"gitlab.com/mbugroup/lti-api.git/internal/utils/fifo"
|
||||
|
||||
rUser "gitlab.com/mbugroup/lti-api.git/internal/modules/users/repositories"
|
||||
sUser "gitlab.com/mbugroup/lti-api.git/internal/modules/users/services"
|
||||
@@ -48,7 +47,7 @@ func (RecordingModule) RegisterRoutes(router fiber.Router, db *gorm.DB, validate
|
||||
productRepo := rProduct.NewProductRepository(db)
|
||||
chickinRepo := rChickin.NewChickinRepository(db)
|
||||
chickinDetailRepo := rChickin.NewChickinDetailRepository(db)
|
||||
stockAllocationRepo := commonRepo.NewStockAllocationRepository(db)
|
||||
transferLayingRepo := rTransferLaying.NewTransferLayingRepository(db)
|
||||
stockLogRepo := rStockLogs.NewStockLogRepository(db)
|
||||
productionStandardRepo := rProductionStandard.NewProductionStandardRepository(db)
|
||||
productionStandardDetailRepo := rProductionStandard.NewProductionStandardDetailRepository(db)
|
||||
@@ -61,76 +60,7 @@ func (RecordingModule) RegisterRoutes(router fiber.Router, db *gorm.DB, validate
|
||||
validate,
|
||||
)
|
||||
|
||||
fifoService := commonSvc.NewFifoService(db, stockAllocationRepo, productWarehouseRepo, utils.Log)
|
||||
if err := fifoService.RegisterStockable(fifo.StockableConfig{
|
||||
Key: fifo.StockableKeyRecordingEgg,
|
||||
Table: "recording_eggs",
|
||||
Columns: fifo.StockableColumns{
|
||||
ID: "id",
|
||||
ProductWarehouseID: "product_warehouse_id",
|
||||
TotalQuantity: "total_qty",
|
||||
TotalUsedQuantity: "total_used",
|
||||
CreatedAt: "(SELECT r.record_datetime FROM recordings r WHERE r.id = recording_eggs.recording_id)",
|
||||
},
|
||||
OrderBy: []string{"(SELECT r.record_datetime FROM recordings r WHERE r.id = recording_eggs.recording_id) ASC", "id ASC"},
|
||||
}); err != nil {
|
||||
if !strings.Contains(strings.ToLower(err.Error()), "already registered") {
|
||||
panic(fmt.Sprintf("failed to register recording egg stockable workflow: %v", err))
|
||||
}
|
||||
}
|
||||
if err := fifoService.RegisterStockable(fifo.StockableConfig{
|
||||
Key: fifo.StockableKeyRecordingDepletion,
|
||||
Table: "recording_depletions",
|
||||
Columns: fifo.StockableColumns{
|
||||
ID: "id",
|
||||
ProductWarehouseID: "product_warehouse_id",
|
||||
TotalQuantity: "qty",
|
||||
TotalUsedQuantity: "total_used_qty",
|
||||
CreatedAt: "(SELECT r.record_datetime FROM recordings r WHERE r.id = recording_depletions.recording_id)",
|
||||
},
|
||||
OrderBy: []string{"(SELECT r.record_datetime FROM recordings r WHERE r.id = recording_depletions.recording_id) ASC", "id ASC"},
|
||||
}); err != nil {
|
||||
if !strings.Contains(strings.ToLower(err.Error()), "already registered") {
|
||||
panic(fmt.Sprintf("failed to register recording depletion stockable workflow: %v", err))
|
||||
}
|
||||
}
|
||||
if err := fifoService.RegisterUsable(fifo.UsableConfig{
|
||||
Key: fifo.UsableKeyRecordingStock,
|
||||
Table: "recording_stocks",
|
||||
Columns: fifo.UsableColumns{
|
||||
ID: "id",
|
||||
ProductWarehouseID: "product_warehouse_id",
|
||||
UsageQuantity: "usage_qty",
|
||||
PendingQuantity: "pending_qty",
|
||||
CreatedAt: "(SELECT r.record_datetime FROM recordings r WHERE r.id = recording_stocks.recording_id)",
|
||||
},
|
||||
}); err != nil {
|
||||
if !strings.Contains(strings.ToLower(err.Error()), "already registered") {
|
||||
panic(fmt.Sprintf("failed to register recording usable workflow: %v", err))
|
||||
}
|
||||
}
|
||||
if err := fifoService.RegisterUsable(fifo.UsableConfig{
|
||||
Key: fifo.UsableKeyRecordingDepletion,
|
||||
Table: "recording_depletions",
|
||||
Columns: fifo.UsableColumns{
|
||||
ID: "id",
|
||||
ProductWarehouseID: "source_product_warehouse_id",
|
||||
UsageQuantity: "usage_qty",
|
||||
PendingQuantity: "pending_qty",
|
||||
CreatedAt: "(SELECT r.record_datetime FROM recordings r WHERE r.id = recording_depletions.recording_id)",
|
||||
},
|
||||
ExcludedStockables: []fifo.StockableKey{
|
||||
fifo.StockableKeyTransferToLayingIn,
|
||||
fifo.StockableKeyStockTransferIn,
|
||||
fifo.StockableKeyAdjustmentIn,
|
||||
fifo.StockableKeyPurchaseItems,
|
||||
fifo.StockableKeyRecordingEgg,
|
||||
},
|
||||
}); err != nil {
|
||||
if !strings.Contains(strings.ToLower(err.Error()), "already registered") {
|
||||
panic(fmt.Sprintf("failed to register recording depletion usable workflow: %v", err))
|
||||
}
|
||||
}
|
||||
fifoStockV2Service := commonSvc.NewFifoStockV2Service(db, utils.Log)
|
||||
|
||||
approvalRepo := commonRepo.NewApprovalRepository(db)
|
||||
approvalService := commonSvc.NewApprovalService(approvalRepo)
|
||||
@@ -168,8 +98,9 @@ func (RecordingModule) RegisterRoutes(router fiber.Router, db *gorm.DB, validate
|
||||
projectFlockKandangRepo,
|
||||
projectFlockPopulationRepo,
|
||||
chickinDetailRepo,
|
||||
transferLayingRepo,
|
||||
validate,
|
||||
fifoService,
|
||||
fifoStockV2Service,
|
||||
)
|
||||
|
||||
recordingService := sRecording.NewRecordingService(
|
||||
@@ -179,11 +110,12 @@ func (RecordingModule) RegisterRoutes(router fiber.Router, db *gorm.DB, validate
|
||||
projectFlockPopulationRepo,
|
||||
approvalRepo,
|
||||
approvalService,
|
||||
fifoService,
|
||||
fifoStockV2Service,
|
||||
stockLogRepo,
|
||||
productionStandardService,
|
||||
projectFlockService,
|
||||
chickinService,
|
||||
transferLayingRepo,
|
||||
validate,
|
||||
)
|
||||
userService := sUser.NewUserService(userRepo, validate)
|
||||
|
||||
@@ -25,20 +25,27 @@ type RecordingRepository interface {
|
||||
GetLatestByProjectFlockKandangID(ctx context.Context, projectFlockKandangId uint) (*entity.Recording, error)
|
||||
ListByProjectFlockKandangID(ctx context.Context, tx *gorm.DB, projectFlockKandangId uint, from *time.Time) ([]entity.Recording, error)
|
||||
GenerateNextDay(tx *gorm.DB, projectFlockKandangId uint) (int, error)
|
||||
CreateRecording(tx *gorm.DB, recording *entity.Recording) error
|
||||
|
||||
CreateStocks(tx *gorm.DB, stocks []entity.RecordingStock) error
|
||||
CreateStock(tx *gorm.DB, stock *entity.RecordingStock) error
|
||||
DeleteStocks(tx *gorm.DB, recordingID uint) error
|
||||
DeleteStocksByIDs(tx *gorm.DB, ids []uint) error
|
||||
ListStocks(tx *gorm.DB, recordingID uint) ([]entity.RecordingStock, error)
|
||||
GetStockByID(tx *gorm.DB, stockID uint) (*entity.RecordingStock, error)
|
||||
UpdateStockUsage(tx *gorm.DB, stockID uint, usageQty, pendingQty float64) error
|
||||
UpdateDepletionPending(tx *gorm.DB, depletionID uint, pendingQty float64) error
|
||||
UpdateDepletionQuantities(tx *gorm.DB, depletionID uint, qty, usageQty, pendingQty float64) error
|
||||
|
||||
CreateDepletions(tx *gorm.DB, depletions []entity.RecordingDepletion) error
|
||||
DeleteDepletions(tx *gorm.DB, recordingID uint) error
|
||||
ListDepletions(tx *gorm.DB, recordingID uint) ([]entity.RecordingDepletion, error)
|
||||
GetDepletionByID(tx *gorm.DB, depletionID uint) (*entity.RecordingDepletion, error)
|
||||
|
||||
CreateEggs(tx *gorm.DB, eggs []entity.RecordingEgg) error
|
||||
DeleteEggs(tx *gorm.DB, recordingID uint) error
|
||||
ListEggs(tx *gorm.DB, recordingID uint) ([]entity.RecordingEgg, error)
|
||||
UpdateEggTotalQty(tx *gorm.DB, eggID uint, totalQty float64) error
|
||||
GetRecordingEggByID(ctx context.Context, id uint, modifier func(*gorm.DB) *gorm.DB) (*entity.RecordingEgg, error)
|
||||
|
||||
ExistsOnDate(ctx context.Context, projectFlockKandangId uint, recordTime time.Time) (bool, error)
|
||||
@@ -272,6 +279,18 @@ func (r *RecordingRepositoryImpl) GenerateNextDay(tx *gorm.DB, projectFlockKanda
|
||||
return nextRecordingDay(days), nil
|
||||
}
|
||||
|
||||
func (r *RecordingRepositoryImpl) CreateRecording(tx *gorm.DB, recording *entity.Recording) error {
|
||||
if recording == nil {
|
||||
return nil
|
||||
}
|
||||
return tx.Select(
|
||||
"ProjectFlockKandangId",
|
||||
"RecordDatetime",
|
||||
"Day",
|
||||
"CreatedBy",
|
||||
).Create(recording).Error
|
||||
}
|
||||
|
||||
func (r *RecordingRepositoryImpl) CreateStocks(tx *gorm.DB, stocks []entity.RecordingStock) error {
|
||||
if len(stocks) == 0 {
|
||||
return nil
|
||||
@@ -279,10 +298,24 @@ func (r *RecordingRepositoryImpl) CreateStocks(tx *gorm.DB, stocks []entity.Reco
|
||||
return tx.Create(&stocks).Error
|
||||
}
|
||||
|
||||
func (r *RecordingRepositoryImpl) CreateStock(tx *gorm.DB, stock *entity.RecordingStock) error {
|
||||
if stock == nil {
|
||||
return nil
|
||||
}
|
||||
return tx.Create(stock).Error
|
||||
}
|
||||
|
||||
func (r *RecordingRepositoryImpl) DeleteStocks(tx *gorm.DB, recordingID uint) error {
|
||||
return tx.Where("recording_id = ?", recordingID).Delete(&entity.RecordingStock{}).Error
|
||||
}
|
||||
|
||||
func (r *RecordingRepositoryImpl) DeleteStocksByIDs(tx *gorm.DB, ids []uint) error {
|
||||
if len(ids) == 0 {
|
||||
return nil
|
||||
}
|
||||
return tx.Where("id IN ?", ids).Delete(&entity.RecordingStock{}).Error
|
||||
}
|
||||
|
||||
func (r *RecordingRepositoryImpl) ListStocks(tx *gorm.DB, recordingID uint) ([]entity.RecordingStock, error) {
|
||||
var items []entity.RecordingStock
|
||||
if err := tx.Where("recording_id = ?", recordingID).Find(&items).Error; err != nil {
|
||||
@@ -291,6 +324,18 @@ func (r *RecordingRepositoryImpl) ListStocks(tx *gorm.DB, recordingID uint) ([]e
|
||||
return items, nil
|
||||
}
|
||||
|
||||
func (r *RecordingRepositoryImpl) GetStockByID(tx *gorm.DB, stockID uint) (*entity.RecordingStock, error) {
|
||||
if stockID == 0 {
|
||||
return nil, gorm.ErrRecordNotFound
|
||||
}
|
||||
|
||||
var stock entity.RecordingStock
|
||||
if err := tx.Where("id = ?", stockID).Take(&stock).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &stock, nil
|
||||
}
|
||||
|
||||
func (r *RecordingRepositoryImpl) UpdateStockUsage(tx *gorm.DB, stockID uint, usageQty, pendingQty float64) error {
|
||||
return tx.Model(&entity.RecordingStock{}).
|
||||
Where("id = ?", stockID).
|
||||
@@ -306,6 +351,16 @@ func (r *RecordingRepositoryImpl) UpdateDepletionPending(tx *gorm.DB, depletionI
|
||||
Update("pending_qty", pendingQty).Error
|
||||
}
|
||||
|
||||
func (r *RecordingRepositoryImpl) UpdateDepletionQuantities(tx *gorm.DB, depletionID uint, qty, usageQty, pendingQty float64) error {
|
||||
return tx.Model(&entity.RecordingDepletion{}).
|
||||
Where("id = ?", depletionID).
|
||||
Updates(map[string]any{
|
||||
"qty": qty,
|
||||
"usage_qty": usageQty,
|
||||
"pending_qty": pendingQty,
|
||||
}).Error
|
||||
}
|
||||
|
||||
func (r *RecordingRepositoryImpl) CreateDepletions(tx *gorm.DB, depletions []entity.RecordingDepletion) error {
|
||||
if len(depletions) == 0 {
|
||||
return nil
|
||||
@@ -325,6 +380,18 @@ func (r *RecordingRepositoryImpl) ListDepletions(tx *gorm.DB, recordingID uint)
|
||||
return items, nil
|
||||
}
|
||||
|
||||
func (r *RecordingRepositoryImpl) GetDepletionByID(tx *gorm.DB, depletionID uint) (*entity.RecordingDepletion, error) {
|
||||
if depletionID == 0 {
|
||||
return nil, gorm.ErrRecordNotFound
|
||||
}
|
||||
|
||||
var depletion entity.RecordingDepletion
|
||||
if err := tx.Where("id = ?", depletionID).Take(&depletion).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &depletion, nil
|
||||
}
|
||||
|
||||
func (r *RecordingRepositoryImpl) CreateEggs(tx *gorm.DB, eggs []entity.RecordingEgg) error {
|
||||
if len(eggs) == 0 {
|
||||
return nil
|
||||
@@ -344,6 +411,12 @@ func (r *RecordingRepositoryImpl) ListEggs(tx *gorm.DB, recordingID uint) ([]ent
|
||||
return items, nil
|
||||
}
|
||||
|
||||
func (r *RecordingRepositoryImpl) UpdateEggTotalQty(tx *gorm.DB, eggID uint, totalQty float64) error {
|
||||
return tx.Model(&entity.RecordingEgg{}).
|
||||
Where("id = ?", eggID).
|
||||
Update("total_qty", totalQty).Error
|
||||
}
|
||||
|
||||
func (r *RecordingRepositoryImpl) GetRecordingEggByID(
|
||||
ctx context.Context,
|
||||
id uint,
|
||||
@@ -821,6 +894,7 @@ func (r *RecordingRepositoryImpl) ResyncProjectFlockPopulationUsage(ctx context.
|
||||
FROM stock_allocations
|
||||
WHERE stockable_type = 'PROJECT_FLOCK_POPULATION'
|
||||
AND status = 'ACTIVE'
|
||||
AND allocation_purpose = 'CONSUME'
|
||||
GROUP BY stockable_id
|
||||
) a
|
||||
WHERE p.id = a.stockable_id
|
||||
@@ -831,14 +905,15 @@ func (r *RecordingRepositoryImpl) ResyncProjectFlockPopulationUsage(ctx context.
|
||||
UPDATE project_flock_populations p
|
||||
SET total_used_qty = 0
|
||||
WHERE p.id IN (` + idsSubquery + `)
|
||||
AND NOT EXISTS (
|
||||
SELECT 1
|
||||
FROM stock_allocations sa
|
||||
WHERE sa.stockable_type = 'PROJECT_FLOCK_POPULATION'
|
||||
AND sa.status = 'ACTIVE'
|
||||
AND sa.stockable_id = p.id
|
||||
)
|
||||
`
|
||||
AND NOT EXISTS (
|
||||
SELECT 1
|
||||
FROM stock_allocations sa
|
||||
WHERE sa.stockable_type = 'PROJECT_FLOCK_POPULATION'
|
||||
AND sa.status = 'ACTIVE'
|
||||
AND sa.allocation_purpose = 'CONSUME'
|
||||
AND sa.stockable_id = p.id
|
||||
)
|
||||
`
|
||||
|
||||
db := r.DB().WithContext(ctx)
|
||||
if tx != nil {
|
||||
|
||||
@@ -0,0 +1,137 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
commonSvc "gitlab.com/mbugroup/lti-api.git/internal/common/service"
|
||||
entity "gitlab.com/mbugroup/lti-api.git/internal/entities"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
const (
|
||||
recordingLaneUsable = "USABLE"
|
||||
recordingLaneStockable = "STOCKABLE"
|
||||
|
||||
recordingFunctionStockOut = "RECORDING_STOCK_OUT"
|
||||
recordingFunctionDepletionOut = "RECORDING_DEPLETION_OUT"
|
||||
recordingFunctionDepletionIn = "RECORDING_DEPLETION_IN"
|
||||
recordingFunctionEggIn = "RECORDING_EGG_IN"
|
||||
|
||||
recordingSourceStocks = "recording_stocks"
|
||||
recordingSourceDepletions = "recording_depletions"
|
||||
recordingSourceEggs = "recording_eggs"
|
||||
)
|
||||
|
||||
func (s *recordingService) reflowRecordingScope(
|
||||
ctx context.Context,
|
||||
tx *gorm.DB,
|
||||
productWarehouseID uint,
|
||||
recordingID uint,
|
||||
lane string,
|
||||
functionCode string,
|
||||
sourceTable string,
|
||||
) error {
|
||||
if s == nil || s.FifoStockV2Svc == nil {
|
||||
return fmt.Errorf("FIFO v2 service is not available")
|
||||
}
|
||||
if tx == nil {
|
||||
return fmt.Errorf("transaction is required")
|
||||
}
|
||||
if productWarehouseID == 0 {
|
||||
return fmt.Errorf("product warehouse id is required")
|
||||
}
|
||||
|
||||
flagGroupCode, err := resolveRecordingFlagGroupByProductWarehouse(ctx, tx, productWarehouseID, lane, functionCode, sourceTable)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if strings.TrimSpace(flagGroupCode) == "" {
|
||||
return fmt.Errorf("flag group code is not found for product warehouse %d", productWarehouseID)
|
||||
}
|
||||
|
||||
asOf, err := resolveRecordingAsOf(ctx, tx, recordingID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
_, err = s.FifoStockV2Svc.Reflow(ctx, commonSvc.FifoStockV2ReflowRequest{
|
||||
FlagGroupCode: flagGroupCode,
|
||||
ProductWarehouseID: productWarehouseID,
|
||||
AsOf: asOf,
|
||||
Tx: tx,
|
||||
})
|
||||
return err
|
||||
}
|
||||
|
||||
func resolveRecordingFlagGroupByProductWarehouse(
|
||||
ctx context.Context,
|
||||
tx *gorm.DB,
|
||||
productWarehouseID uint,
|
||||
lane string,
|
||||
functionCode string,
|
||||
sourceTable string,
|
||||
) (string, error) {
|
||||
type row struct {
|
||||
FlagGroupCode string `gorm:"column:flag_group_code"`
|
||||
}
|
||||
|
||||
var selected row
|
||||
q := tx.WithContext(ctx).
|
||||
Table("fifo_stock_v2_route_rules rr").
|
||||
Select("rr.flag_group_code").
|
||||
Joins("JOIN fifo_stock_v2_flag_groups fg ON fg.code = rr.flag_group_code AND fg.is_active = TRUE").
|
||||
Where("rr.is_active = TRUE").
|
||||
Where("rr.lane = ?", lane).
|
||||
Where("rr.source_table = ?", sourceTable)
|
||||
|
||||
if strings.TrimSpace(functionCode) != "" {
|
||||
q = q.Where("rr.function_code = ?", functionCode)
|
||||
}
|
||||
|
||||
err := q.
|
||||
Where(`
|
||||
EXISTS (
|
||||
SELECT 1
|
||||
FROM product_warehouses pw
|
||||
JOIN flags f ON f.flagable_id = pw.product_id
|
||||
JOIN fifo_stock_v2_flag_members fm ON fm.flag_name = f.name AND fm.is_active = TRUE
|
||||
WHERE pw.id = ?
|
||||
AND f.flagable_type = ?
|
||||
AND fm.flag_group_code = rr.flag_group_code
|
||||
)
|
||||
`, productWarehouseID, entity.FlagableTypeProduct).
|
||||
Order("rr.id ASC").
|
||||
Limit(1).
|
||||
Take(&selected).Error
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
return strings.TrimSpace(selected.FlagGroupCode), nil
|
||||
}
|
||||
|
||||
func resolveRecordingAsOf(ctx context.Context, tx *gorm.DB, recordingID uint) (*time.Time, error) {
|
||||
if recordingID == 0 {
|
||||
asOf := time.Now().UTC()
|
||||
return &asOf, nil
|
||||
}
|
||||
|
||||
type row struct {
|
||||
RecordDatetime time.Time `gorm:"column:record_datetime"`
|
||||
}
|
||||
var selected row
|
||||
if err := tx.WithContext(ctx).
|
||||
Table("recordings").
|
||||
Select("record_datetime").
|
||||
Where("id = ?", recordingID).
|
||||
Limit(1).
|
||||
Take(&selected).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
asOf := selected.RecordDatetime.UTC()
|
||||
return &asOf, nil
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
+22
@@ -186,6 +186,28 @@ func (u *TransferLayingController) Approval(c *fiber.Ctx) error {
|
||||
})
|
||||
}
|
||||
|
||||
func (u *TransferLayingController) Execute(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.TransferLayingService.Execute(c, uint(id))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return c.Status(fiber.StatusOK).
|
||||
JSON(response.Success{
|
||||
Code: fiber.StatusOK,
|
||||
Status: "success",
|
||||
Message: "Execute transfer laying successfully",
|
||||
Data: dto.ToTransferLayingDetailDTOWithSingleApproval(*result, result.LatestApproval),
|
||||
})
|
||||
}
|
||||
|
||||
func (u *TransferLayingController) GetAvailableQtyPerKandang(c *fiber.Ctx) error {
|
||||
projectFlockID, err := strconv.ParseUint(c.Params("project_flock_id"), 10, 32)
|
||||
if err != nil {
|
||||
|
||||
@@ -14,10 +14,12 @@ import (
|
||||
// === DTO Structs ===
|
||||
|
||||
type TransferLayingRelationDTO struct {
|
||||
Id uint `json:"id"`
|
||||
TransferNumber string `json:"transfer_number"`
|
||||
TransferDate time.Time `json:"transfer_date"`
|
||||
Notes string `json:"notes"`
|
||||
Id uint `json:"id"`
|
||||
TransferNumber string `json:"transfer_number"`
|
||||
TransferDate time.Time `json:"transfer_date"`
|
||||
EffectiveMoveDate *time.Time `json:"effective_move_date,omitempty"`
|
||||
ExecutedAt *time.Time `json:"executed_at,omitempty"`
|
||||
Notes string `json:"notes"`
|
||||
}
|
||||
|
||||
type ProjectFlockKandangWithKandangDTO struct {
|
||||
@@ -47,6 +49,8 @@ type TransferLayingListDTO struct {
|
||||
ToProjectFlock *projectFlockDTO.ProjectFlockRelationDTO `json:"to_project_flock,omitempty"`
|
||||
CreatedBy uint `json:"created_by"`
|
||||
CreatedUser *userDTO.UserRelationDTO `json:"created_user,omitempty"`
|
||||
ExecutedBy *uint `json:"executed_by,omitempty"`
|
||||
ExecutedUser *userDTO.UserRelationDTO `json:"executed_user,omitempty"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
Approval *approvalDTO.ApprovalRelationDTO `json:"approval,omitempty"`
|
||||
}
|
||||
@@ -88,10 +92,12 @@ type MaxTargetQtyForTransferDTO struct {
|
||||
|
||||
func ToTransferLayingRelationDTO(e entity.LayingTransfer) TransferLayingRelationDTO {
|
||||
return TransferLayingRelationDTO{
|
||||
Id: e.Id,
|
||||
TransferNumber: e.TransferNumber,
|
||||
TransferDate: e.TransferDate,
|
||||
Notes: e.Notes,
|
||||
Id: e.Id,
|
||||
TransferNumber: e.TransferNumber,
|
||||
TransferDate: e.TransferDate,
|
||||
EffectiveMoveDate: e.EffectiveMoveDate,
|
||||
ExecutedAt: e.ExecutedAt,
|
||||
Notes: e.Notes,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -190,6 +196,12 @@ func ToTransferLayingListDTO(e entity.LayingTransfer) TransferLayingListDTO {
|
||||
createdUser = &mapped
|
||||
}
|
||||
|
||||
var executedUser *userDTO.UserRelationDTO
|
||||
if e.ExecutedUser != nil && e.ExecutedUser.Id != 0 {
|
||||
mapped := userDTO.ToUserRelationDTO(*e.ExecutedUser)
|
||||
executedUser = &mapped
|
||||
}
|
||||
|
||||
var approval *approvalDTO.ApprovalRelationDTO
|
||||
if e.LatestApproval != nil {
|
||||
mapped := approvalDTO.ToApprovalDTO(*e.LatestApproval)
|
||||
@@ -219,6 +231,8 @@ func ToTransferLayingListDTO(e entity.LayingTransfer) TransferLayingListDTO {
|
||||
ToProjectFlock: toProjectFlock,
|
||||
CreatedBy: e.CreatedBy,
|
||||
CreatedUser: createdUser,
|
||||
ExecutedBy: e.ExecutedBy,
|
||||
ExecutedUser: executedUser,
|
||||
CreatedAt: e.CreatedAt,
|
||||
Approval: approval,
|
||||
}
|
||||
|
||||
@@ -10,11 +10,11 @@ import (
|
||||
|
||||
commonRepo "gitlab.com/mbugroup/lti-api.git/internal/common/repository"
|
||||
commonSvc "gitlab.com/mbugroup/lti-api.git/internal/common/service"
|
||||
"gitlab.com/mbugroup/lti-api.git/internal/utils/fifo"
|
||||
rProjectFlock "gitlab.com/mbugroup/lti-api.git/internal/modules/production/project_flocks/repositories"
|
||||
rTransferLaying "gitlab.com/mbugroup/lti-api.git/internal/modules/production/transfer_layings/repositories"
|
||||
sTransferLaying "gitlab.com/mbugroup/lti-api.git/internal/modules/production/transfer_layings/services"
|
||||
"gitlab.com/mbugroup/lti-api.git/internal/utils"
|
||||
"gitlab.com/mbugroup/lti-api.git/internal/utils/fifo"
|
||||
|
||||
rInventory "gitlab.com/mbugroup/lti-api.git/internal/modules/inventory/product-warehouses/repositories"
|
||||
rWarehouse "gitlab.com/mbugroup/lti-api.git/internal/modules/master/warehouses/repositories"
|
||||
@@ -37,6 +37,7 @@ func (TransferLayingModule) RegisterRoutes(router fiber.Router, db *gorm.DB, val
|
||||
|
||||
stockAllocationRepo := commonRepo.NewStockAllocationRepository(db)
|
||||
fifoService := commonSvc.NewFifoService(db, stockAllocationRepo, productWarehouseRepo, utils.Log)
|
||||
fifoStockV2Service := commonSvc.NewFifoStockV2Service(db, utils.Log)
|
||||
|
||||
// daftarin jadi stockable
|
||||
if err := fifoService.RegisterStockable(fifo.StockableConfig{
|
||||
@@ -91,6 +92,7 @@ func (TransferLayingModule) RegisterRoutes(router fiber.Router, db *gorm.DB, val
|
||||
warehouseRepo,
|
||||
approvalService,
|
||||
fifoService,
|
||||
fifoStockV2Service,
|
||||
validate,
|
||||
)
|
||||
userService := sUser.NewUserService(userRepo, validate)
|
||||
|
||||
+58
@@ -7,6 +7,7 @@ import (
|
||||
|
||||
"gitlab.com/mbugroup/lti-api.git/internal/common/repository"
|
||||
entity "gitlab.com/mbugroup/lti-api.git/internal/entities"
|
||||
"gitlab.com/mbugroup/lti-api.git/internal/utils"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
@@ -14,6 +15,8 @@ type TransferLayingRepository interface {
|
||||
repository.BaseRepository[entity.LayingTransfer]
|
||||
GetByTransferNumber(ctx context.Context, transferNumber string) (*entity.LayingTransfer, error)
|
||||
IdExists(ctx context.Context, id uint) (bool, error)
|
||||
GetLatestApprovedBySourceKandang(ctx context.Context, sourceProjectFlockKandangID uint) (*entity.LayingTransfer, error)
|
||||
GetLatestApprovedByTargetKandang(ctx context.Context, targetProjectFlockKandangID uint) (*entity.LayingTransfer, error)
|
||||
|
||||
// Tambah method baru untuk query dengan filter lengkap
|
||||
GetAllWithFilters(ctx context.Context, offset int, limit int, params *GetAllFilterParams) ([]entity.LayingTransfer, int64, error)
|
||||
@@ -164,6 +167,7 @@ func (r *TransferLayingRepositoryImpl) GetAllWithFilters(ctx context.Context, of
|
||||
Preload("FromProjectFlock").
|
||||
Preload("ToProjectFlock").
|
||||
Preload("CreatedUser").
|
||||
Preload("ExecutedUser").
|
||||
Preload("Sources").
|
||||
Preload("Sources.SourceProjectFlockKandang").
|
||||
Preload("Sources.SourceProjectFlockKandang.Kandang").
|
||||
@@ -180,3 +184,57 @@ func (r *TransferLayingRepositoryImpl) GetAllWithFilters(ctx context.Context, of
|
||||
|
||||
return records, total, nil
|
||||
}
|
||||
|
||||
func (r *TransferLayingRepositoryImpl) GetLatestApprovedBySourceKandang(ctx context.Context, sourceProjectFlockKandangID uint) (*entity.LayingTransfer, error) {
|
||||
if sourceProjectFlockKandangID == 0 {
|
||||
return nil, gorm.ErrRecordNotFound
|
||||
}
|
||||
|
||||
var transfer entity.LayingTransfer
|
||||
err := r.db.WithContext(ctx).
|
||||
Model(&entity.LayingTransfer{}).
|
||||
Joins("JOIN laying_transfer_sources lts ON lts.laying_transfer_id = laying_transfers.id AND lts.deleted_at IS NULL").
|
||||
Where("lts.source_project_flock_kandang_id = ?", sourceProjectFlockKandangID).
|
||||
Where("laying_transfers.deleted_at IS NULL").
|
||||
Where(`(
|
||||
SELECT a.action
|
||||
FROM approvals a
|
||||
WHERE a.approvable_type = ?
|
||||
AND a.approvable_id = laying_transfers.id
|
||||
ORDER BY a.id DESC
|
||||
LIMIT 1
|
||||
) = ?`, string(utils.ApprovalWorkflowTransferToLaying), entity.ApprovalActionApproved).
|
||||
Order("laying_transfers.id DESC").
|
||||
First(&transfer).Error
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &transfer, nil
|
||||
}
|
||||
|
||||
func (r *TransferLayingRepositoryImpl) GetLatestApprovedByTargetKandang(ctx context.Context, targetProjectFlockKandangID uint) (*entity.LayingTransfer, error) {
|
||||
if targetProjectFlockKandangID == 0 {
|
||||
return nil, gorm.ErrRecordNotFound
|
||||
}
|
||||
|
||||
var transfer entity.LayingTransfer
|
||||
err := r.db.WithContext(ctx).
|
||||
Model(&entity.LayingTransfer{}).
|
||||
Joins("JOIN laying_transfer_targets ltt ON ltt.laying_transfer_id = laying_transfers.id AND ltt.deleted_at IS NULL").
|
||||
Where("ltt.target_project_flock_kandang_id = ?", targetProjectFlockKandangID).
|
||||
Where("laying_transfers.deleted_at IS NULL").
|
||||
Where(`(
|
||||
SELECT a.action
|
||||
FROM approvals a
|
||||
WHERE a.approvable_type = ?
|
||||
AND a.approvable_id = laying_transfers.id
|
||||
ORDER BY a.id DESC
|
||||
LIMIT 1
|
||||
) = ?`, string(utils.ApprovalWorkflowTransferToLaying), entity.ApprovalActionApproved).
|
||||
Order("laying_transfers.id DESC").
|
||||
First(&transfer).Error
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &transfer, nil
|
||||
}
|
||||
|
||||
@@ -27,6 +27,7 @@ func TransferLayingRoutes(v1 fiber.Router, u user.UserService, s transferLaying.
|
||||
route.Patch("/:id", m.RequirePermissions(m.P_TransferToLaying_UpdateOne), ctrl.UpdateOne)
|
||||
route.Delete("/:id", m.RequirePermissions(m.P_TransferToLaying_DeleteOne), ctrl.DeleteOne)
|
||||
route.Post("/approvals", m.RequirePermissions(m.P_TransferToLaying_Approval), ctrl.Approval)
|
||||
route.Post("/:id/execute", m.RequirePermissions(m.P_TransferToLaying_Approval), ctrl.Execute)
|
||||
route.Get("/project-flocks/:project_flock_id/available-qty", m.RequirePermissions(m.P_TransferToLaying_GetAvailableQty), ctrl.GetAvailableQtyPerKandang)
|
||||
route.Get("/project-flocks/:project_flock_id/max-target-qty", m.RequirePermissions(m.P_TransferToLaying_CreateOne), ctrl.GetMaxTargetQtyPerKandang)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,87 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
commonSvc "gitlab.com/mbugroup/lti-api.git/internal/common/service"
|
||||
entity "gitlab.com/mbugroup/lti-api.git/internal/entities"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
const (
|
||||
transferLayingInFunctionCode = "TRANSFER_TO_LAYING_IN"
|
||||
transferLayingStockableLane = "STOCKABLE"
|
||||
transferLayingSourceTable = "laying_transfer_targets"
|
||||
)
|
||||
|
||||
func reflowTransferLayingScope(
|
||||
ctx context.Context,
|
||||
fifoStockV2Svc commonSvc.FifoStockV2Service,
|
||||
tx *gorm.DB,
|
||||
productWarehouseID uint,
|
||||
asOf *time.Time,
|
||||
) error {
|
||||
if fifoStockV2Svc == nil {
|
||||
return fmt.Errorf("FIFO v2 service is not available")
|
||||
}
|
||||
if tx == nil {
|
||||
return fmt.Errorf("transaction is required")
|
||||
}
|
||||
if productWarehouseID == 0 {
|
||||
return fmt.Errorf("product warehouse id is required")
|
||||
}
|
||||
|
||||
flagGroupCode, err := resolveTransferLayingFlagGroupByProductWarehouse(ctx, tx, productWarehouseID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if strings.TrimSpace(flagGroupCode) == "" {
|
||||
return fmt.Errorf("flag group code is not found for product warehouse %d", productWarehouseID)
|
||||
}
|
||||
|
||||
_, err = fifoStockV2Svc.Reflow(ctx, commonSvc.FifoStockV2ReflowRequest{
|
||||
FlagGroupCode: flagGroupCode,
|
||||
ProductWarehouseID: productWarehouseID,
|
||||
AsOf: asOf,
|
||||
Tx: tx,
|
||||
})
|
||||
return err
|
||||
}
|
||||
|
||||
func resolveTransferLayingFlagGroupByProductWarehouse(ctx context.Context, tx *gorm.DB, productWarehouseID uint) (string, error) {
|
||||
type row struct {
|
||||
FlagGroupCode string `gorm:"column:flag_group_code"`
|
||||
}
|
||||
|
||||
var selected row
|
||||
err := tx.WithContext(ctx).
|
||||
Table("fifo_stock_v2_route_rules rr").
|
||||
Select("rr.flag_group_code").
|
||||
Joins("JOIN fifo_stock_v2_flag_groups fg ON fg.code = rr.flag_group_code AND fg.is_active = TRUE").
|
||||
Where("rr.is_active = TRUE").
|
||||
Where("rr.lane = ?", transferLayingStockableLane).
|
||||
Where("rr.function_code = ?", transferLayingInFunctionCode).
|
||||
Where("rr.source_table = ?", transferLayingSourceTable).
|
||||
Where(`
|
||||
EXISTS (
|
||||
SELECT 1
|
||||
FROM product_warehouses pw
|
||||
JOIN flags f ON f.flagable_id = pw.product_id
|
||||
JOIN fifo_stock_v2_flag_members fm ON fm.flag_name = f.name AND fm.is_active = TRUE
|
||||
WHERE pw.id = ?
|
||||
AND f.flagable_type = ?
|
||||
AND fm.flag_group_code = rr.flag_group_code
|
||||
)
|
||||
`, productWarehouseID, entity.FlagableTypeProduct).
|
||||
Order("rr.id ASC").
|
||||
Limit(1).
|
||||
Take(&selected).Error
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
return strings.TrimSpace(selected.FlagGroupCode), nil
|
||||
}
|
||||
+411
-139
@@ -10,6 +10,8 @@ import (
|
||||
|
||||
commonRepo "gitlab.com/mbugroup/lti-api.git/internal/common/repository"
|
||||
commonSvc "gitlab.com/mbugroup/lti-api.git/internal/common/service"
|
||||
fifoV2 "gitlab.com/mbugroup/lti-api.git/internal/common/service/fifo_stock_v2"
|
||||
"gitlab.com/mbugroup/lti-api.git/internal/config"
|
||||
entity "gitlab.com/mbugroup/lti-api.git/internal/entities"
|
||||
m "gitlab.com/mbugroup/lti-api.git/internal/middleware"
|
||||
rInventory "gitlab.com/mbugroup/lti-api.git/internal/modules/inventory/product-warehouses/repositories"
|
||||
@@ -34,6 +36,7 @@ type TransferLayingService interface {
|
||||
UpdateOne(ctx *fiber.Ctx, req *validation.Update, id uint) (*entity.LayingTransfer, error)
|
||||
DeleteOne(ctx *fiber.Ctx, id uint) error
|
||||
Approval(ctx *fiber.Ctx, req *validation.Approve) ([]entity.LayingTransfer, error)
|
||||
Execute(ctx *fiber.Ctx, id uint) (*entity.LayingTransfer, error)
|
||||
GetAvailableQtyPerKandang(ctx *fiber.Ctx, projectFlockID uint) (*entity.ProjectFlock, map[uint]float64, error)
|
||||
GetMaxTargetQtyPerKandang(ctx *fiber.Ctx, projectFlockID uint) (map[uint]float64, error)
|
||||
}
|
||||
@@ -52,8 +55,13 @@ type transferLayingService struct {
|
||||
StockLogRepo rStockLogs.StockLogRepository
|
||||
ApprovalService commonSvc.ApprovalService
|
||||
FifoSvc commonSvc.FifoService
|
||||
FifoStockV2Svc commonSvc.FifoStockV2Service
|
||||
}
|
||||
|
||||
const (
|
||||
transferToLayingFlagGroupCode = "AYAM"
|
||||
)
|
||||
|
||||
func NewTransferLayingService(
|
||||
repo repository.TransferLayingRepository,
|
||||
layingTransferSourceRepo repository.LayingTransferSourceRepository,
|
||||
@@ -65,6 +73,7 @@ func NewTransferLayingService(
|
||||
warehouseRepo rWarehouse.WarehouseRepository,
|
||||
approvalService commonSvc.ApprovalService,
|
||||
fifoSvc commonSvc.FifoService,
|
||||
fifoStockV2Svc commonSvc.FifoStockV2Service,
|
||||
validate *validator.Validate,
|
||||
) TransferLayingService {
|
||||
return &transferLayingService{
|
||||
@@ -81,12 +90,14 @@ func NewTransferLayingService(
|
||||
StockLogRepo: rStockLogs.NewStockLogRepository(repo.DB()),
|
||||
ApprovalService: approvalService,
|
||||
FifoSvc: fifoSvc,
|
||||
FifoStockV2Svc: fifoStockV2Svc,
|
||||
}
|
||||
}
|
||||
|
||||
func (s transferLayingService) withRelations(db *gorm.DB) *gorm.DB {
|
||||
return db.
|
||||
Preload("CreatedUser").
|
||||
Preload("ExecutedUser").
|
||||
Preload("FromProjectFlock").
|
||||
Preload("ToProjectFlock").
|
||||
Preload("Sources").
|
||||
@@ -744,13 +755,10 @@ func (s transferLayingService) Approval(c *fiber.Ctx, req *validation.Approve) (
|
||||
err = s.Repository.DB().WithContext(c.Context()).Transaction(func(dbTransaction *gorm.DB) error {
|
||||
repoTx := s.Repository.WithTx(dbTransaction)
|
||||
approvalSvcTx := commonSvc.NewApprovalService(commonRepo.NewApprovalRepository(dbTransaction))
|
||||
stockAllocationRepo := commonRepo.NewStockAllocationRepository(dbTransaction)
|
||||
sourceRepoTx := repository.NewLayingTransferSourceRepository(dbTransaction)
|
||||
targetRepoTx := repository.NewLayingTransferTargetRepository(dbTransaction)
|
||||
stockLogRepoTx := rStockLogs.NewStockLogRepository(dbTransaction)
|
||||
|
||||
for _, approvableID := range approvableIDs {
|
||||
transfer, err := repoTx.GetByID(c.Context(), approvableID, nil)
|
||||
_, err := repoTx.GetByID(c.Context(), approvableID, nil)
|
||||
if err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return fiber.NewError(fiber.StatusNotFound, fmt.Sprintf("TransferLaying %d not found", approvableID))
|
||||
@@ -771,148 +779,21 @@ func (s transferLayingService) Approval(c *fiber.Ctx, req *validation.Approve) (
|
||||
}
|
||||
|
||||
if action == entity.ApprovalActionApproved {
|
||||
|
||||
sources, err := sourceRepoTx.GetByLayingTransferId(c.Context(), approvableID)
|
||||
if err != nil {
|
||||
return fiber.NewError(fiber.StatusInternalServerError, "Gagal mengambil sources transfer")
|
||||
}
|
||||
|
||||
targets, err := targetRepoTx.GetByLayingTransferId(c.Context(), approvableID)
|
||||
effectiveMoveDate, err := s.calculateEffectiveMoveDate(c.Context(), sources)
|
||||
if err != nil {
|
||||
return fiber.NewError(fiber.StatusInternalServerError, "Gagal mengambil targets transfer")
|
||||
return err
|
||||
}
|
||||
|
||||
totalTargetQty := 0.0
|
||||
for _, target := range targets {
|
||||
totalTargetQty += target.TotalQty
|
||||
}
|
||||
|
||||
totalSourceRequested := 0.0
|
||||
for _, source := range sources {
|
||||
totalSourceRequested += source.RequestedQty
|
||||
}
|
||||
|
||||
for _, source := range sources {
|
||||
if source.ProductWarehouseId == nil {
|
||||
return fiber.NewError(fiber.StatusInternalServerError, fmt.Sprintf("Source product warehouse tidak ditemukan untuk transfer %d", approvableID))
|
||||
}
|
||||
|
||||
sourceShare := (source.RequestedQty / totalSourceRequested) * totalTargetQty
|
||||
|
||||
consumeResult, err := s.FifoSvc.Consume(c.Context(), commonSvc.StockConsumeRequest{
|
||||
UsableKey: fifo.UsableKeyTransferToLayingOut,
|
||||
UsableID: source.Id,
|
||||
ProductWarehouseID: *source.ProductWarehouseId,
|
||||
Quantity: sourceShare,
|
||||
AllowPending: false,
|
||||
Tx: dbTransaction,
|
||||
})
|
||||
if err != nil {
|
||||
return fiber.NewError(fiber.StatusInternalServerError, fmt.Sprintf("Gagal consume FIFO stock: %v", err))
|
||||
}
|
||||
|
||||
if err := sourceRepoTx.PatchOne(c.Context(), source.Id, map[string]interface{}{
|
||||
"usage_qty": source.UsageQty + consumeResult.UsageQuantity,
|
||||
"pending_usage_qty": consumeResult.PendingQuantity,
|
||||
}, nil); err != nil {
|
||||
return fiber.NewError(fiber.StatusInternalServerError, "Gagal update source usage qty")
|
||||
}
|
||||
|
||||
targetShares := distributeProportionalWithRounding(targets, totalTargetQty, sourceShare)
|
||||
|
||||
for i, target := range targets {
|
||||
roundedQty := math.Round(targetShares[i])
|
||||
if roundedQty <= 0 {
|
||||
continue
|
||||
}
|
||||
mappingAllocation := &entity.StockAllocation{
|
||||
StockableType: fifo.UsableKeyTransferToLayingOut.String(),
|
||||
StockableId: source.Id,
|
||||
UsableType: fifo.StockableKeyTransferToLayingIn.String(),
|
||||
UsableId: target.Id,
|
||||
ProductWarehouseId: *source.ProductWarehouseId,
|
||||
Qty: roundedQty,
|
||||
Status: entity.StockAllocationStatusActive,
|
||||
}
|
||||
if err := stockAllocationRepo.CreateOne(c.Context(), mappingAllocation, nil); err != nil {
|
||||
return fiber.NewError(fiber.StatusInternalServerError, "Gagal create mapping allocation source→target")
|
||||
}
|
||||
}
|
||||
|
||||
stockLogDecrease := &entity.StockLog{
|
||||
ProductWarehouseId: *source.ProductWarehouseId,
|
||||
CreatedBy: actorID,
|
||||
Increase: 0,
|
||||
Decrease: sourceShare,
|
||||
LoggableType: string(utils.StockLogTypeTransferLaying),
|
||||
LoggableId: approvableID,
|
||||
Notes: fmt.Sprintf("TL #%s", transfer.TransferNumber),
|
||||
}
|
||||
stockLogs, err := stockLogRepoTx.GetByProductWarehouse(c.Context(), *source.ProductWarehouseId, 1)
|
||||
if err != nil {
|
||||
s.Log.Errorf("Failed to get stock logs: %+v", err)
|
||||
return fiber.NewError(fiber.StatusInternalServerError, "Failed to get stock logs")
|
||||
}
|
||||
if len(stockLogs) > 0 {
|
||||
latestStockLog := stockLogs[0]
|
||||
stockLogDecrease.Stock = latestStockLog.Stock - stockLogDecrease.Decrease
|
||||
} else {
|
||||
stockLogDecrease.Stock -= stockLogDecrease.Decrease
|
||||
}
|
||||
|
||||
if err := stockLogRepoTx.CreateOne(c.Context(), stockLogDecrease, nil); err != nil {
|
||||
return fiber.NewError(fiber.StatusInternalServerError, "Gagal membuat log stok keluar")
|
||||
}
|
||||
}
|
||||
|
||||
for _, target := range targets {
|
||||
if target.ProductWarehouseId == nil {
|
||||
return fiber.NewError(fiber.StatusInternalServerError, fmt.Sprintf("Target product warehouse tidak ditemukan untuk transfer %d", approvableID))
|
||||
}
|
||||
|
||||
note := fmt.Sprintf("Transfer to Laying #%s", transfer.TransferNumber)
|
||||
_, err := s.FifoSvc.Replenish(c.Context(), commonSvc.StockReplenishRequest{
|
||||
StockableKey: fifo.StockableKeyTransferToLayingIn,
|
||||
StockableID: target.Id,
|
||||
ProductWarehouseID: *target.ProductWarehouseId,
|
||||
Quantity: target.TotalQty,
|
||||
Note: ¬e,
|
||||
Tx: dbTransaction,
|
||||
})
|
||||
if err != nil {
|
||||
return fiber.NewError(fiber.StatusInternalServerError, fmt.Sprintf("Gagal replenish stock ke target warehouse: %v", err))
|
||||
}
|
||||
|
||||
if err := targetRepoTx.PatchOne(c.Context(), target.Id, map[string]interface{}{
|
||||
"total_qty": target.TotalQty,
|
||||
}, nil); err != nil {
|
||||
return fiber.NewError(fiber.StatusInternalServerError, "Gagal update target total qty")
|
||||
}
|
||||
|
||||
stockLogIncrease := &entity.StockLog{
|
||||
ProductWarehouseId: *target.ProductWarehouseId,
|
||||
CreatedBy: actorID,
|
||||
Increase: target.TotalQty,
|
||||
Decrease: 0,
|
||||
LoggableType: string(utils.StockLogTypeTransferLaying),
|
||||
LoggableId: approvableID,
|
||||
Notes: fmt.Sprintf("TL #%s", transfer.TransferNumber),
|
||||
}
|
||||
stockLogs, err := stockLogRepoTx.GetByProductWarehouse(c.Context(), *target.ProductWarehouseId, 1)
|
||||
if err != nil {
|
||||
s.Log.Errorf("Failed to get stock logs: %+v", err)
|
||||
return fiber.NewError(fiber.StatusInternalServerError, "Failed to get stock logs")
|
||||
}
|
||||
if len(stockLogs) > 0 {
|
||||
latestStockLog := stockLogs[0]
|
||||
stockLogIncrease.Stock = latestStockLog.Stock + stockLogIncrease.Increase
|
||||
} else {
|
||||
stockLogIncrease.Stock += stockLogIncrease.Increase
|
||||
}
|
||||
|
||||
if err := stockLogRepoTx.CreateOne(c.Context(), stockLogIncrease, nil); err != nil {
|
||||
return fiber.NewError(fiber.StatusInternalServerError, "Gagal membuat log stok masuk")
|
||||
}
|
||||
if err := repoTx.PatchOne(c.Context(), approvableID, map[string]any{
|
||||
"effective_move_date": effectiveMoveDate,
|
||||
"executed_at": nil,
|
||||
"executed_by": nil,
|
||||
}, nil); err != nil {
|
||||
return fiber.NewError(fiber.StatusInternalServerError, "Gagal menyimpan tanggal efektif transfer laying")
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -939,6 +820,393 @@ func (s transferLayingService) Approval(c *fiber.Ctx, req *validation.Approve) (
|
||||
return updated, nil
|
||||
}
|
||||
|
||||
func (s transferLayingService) Execute(c *fiber.Ctx, id uint) (*entity.LayingTransfer, error) {
|
||||
if err := m.EnsureLayingTransferAccess(c, s.Repository.DB(), id); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
actorID, err := m.ActorIDFromContext(c)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
err = s.Repository.DB().WithContext(c.Context()).Transaction(func(dbTransaction *gorm.DB) error {
|
||||
repoTx := s.Repository.WithTx(dbTransaction)
|
||||
sourceRepoTx := repository.NewLayingTransferSourceRepository(dbTransaction)
|
||||
targetRepoTx := repository.NewLayingTransferTargetRepository(dbTransaction)
|
||||
approvalRepoTx := commonRepo.NewApprovalRepository(dbTransaction)
|
||||
|
||||
transfer, err := repoTx.GetByID(c.Context(), id, nil)
|
||||
if err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return fiber.NewError(fiber.StatusNotFound, "Transfer laying tidak ditemukan")
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
if transfer.ExecutedAt != nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
latestApproval, err := approvalRepoTx.LatestByTarget(c.Context(), string(utils.ApprovalWorkflowTransferToLaying), transfer.Id, nil)
|
||||
if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return err
|
||||
}
|
||||
if latestApproval == nil || latestApproval.Action == nil || *latestApproval.Action != entity.ApprovalActionApproved {
|
||||
return fiber.NewError(fiber.StatusBadRequest, "Transfer laying harus disetujui sebelum dieksekusi")
|
||||
}
|
||||
|
||||
sources, err := sourceRepoTx.GetByLayingTransferId(c.Context(), transfer.Id)
|
||||
if err != nil {
|
||||
return fiber.NewError(fiber.StatusInternalServerError, "Gagal mengambil sumber transfer laying")
|
||||
}
|
||||
|
||||
targets, err := targetRepoTx.GetByLayingTransferId(c.Context(), transfer.Id)
|
||||
if err != nil {
|
||||
return fiber.NewError(fiber.StatusInternalServerError, "Gagal mengambil target transfer laying")
|
||||
}
|
||||
|
||||
if transfer.EffectiveMoveDate == nil || transfer.EffectiveMoveDate.IsZero() {
|
||||
effectiveMoveDate, calcErr := s.calculateEffectiveMoveDate(c.Context(), sources)
|
||||
if calcErr != nil {
|
||||
return calcErr
|
||||
}
|
||||
if patchErr := repoTx.PatchOne(c.Context(), transfer.Id, map[string]any{
|
||||
"effective_move_date": effectiveMoveDate,
|
||||
}, nil); patchErr != nil {
|
||||
return fiber.NewError(fiber.StatusInternalServerError, "Gagal menyimpan tanggal efektif transfer laying")
|
||||
}
|
||||
transfer.EffectiveMoveDate = &effectiveMoveDate
|
||||
}
|
||||
|
||||
effectiveMoveDate := normalizeDateOnlyUTC(*transfer.EffectiveMoveDate)
|
||||
today := normalizeDateOnlyUTC(time.Now().UTC())
|
||||
if today.Before(effectiveMoveDate) {
|
||||
return fiber.NewError(fiber.StatusBadRequest, fmt.Sprintf("Transfer laying baru bisa dieksekusi mulai tanggal %s", effectiveMoveDate.Format("2006-01-02")))
|
||||
}
|
||||
|
||||
if err := s.executeApprovedTransferMovement(c.Context(), dbTransaction, transfer, actorID, sources, targets); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
executedAt := time.Now().UTC()
|
||||
if err := repoTx.PatchOne(c.Context(), transfer.Id, map[string]any{
|
||||
"executed_at": executedAt,
|
||||
"executed_by": actorID,
|
||||
}, nil); err != nil {
|
||||
return fiber.NewError(fiber.StatusInternalServerError, "Gagal menyimpan status eksekusi transfer laying")
|
||||
}
|
||||
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
if fiberErr, ok := err.(*fiber.Error); ok {
|
||||
return nil, fiberErr
|
||||
}
|
||||
return nil, fiber.NewError(fiber.StatusInternalServerError, "Gagal mengeksekusi transfer laying")
|
||||
}
|
||||
|
||||
transfer, _, err := s.GetOne(c, id)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return transfer, nil
|
||||
}
|
||||
|
||||
func (s *transferLayingService) executeApprovedTransferMovement(
|
||||
ctx context.Context,
|
||||
tx *gorm.DB,
|
||||
transfer *entity.LayingTransfer,
|
||||
actorID uint,
|
||||
sources []entity.LayingTransferSource,
|
||||
targets []entity.LayingTransferTarget,
|
||||
) error {
|
||||
if transfer == nil || transfer.Id == 0 {
|
||||
return fiber.NewError(fiber.StatusBadRequest, "Transfer laying tidak valid")
|
||||
}
|
||||
if len(sources) == 0 {
|
||||
return fiber.NewError(fiber.StatusBadRequest, "Transfer laying belum memiliki sumber")
|
||||
}
|
||||
if len(targets) == 0 {
|
||||
return fiber.NewError(fiber.StatusBadRequest, "Transfer laying belum memiliki target")
|
||||
}
|
||||
if s.FifoStockV2Svc == nil {
|
||||
return fiber.NewError(fiber.StatusInternalServerError, "FIFO v2 service is not available")
|
||||
}
|
||||
if s.FifoSvc == nil {
|
||||
return fiber.NewError(fiber.StatusInternalServerError, "FIFO service is not available")
|
||||
}
|
||||
|
||||
stockAllocationRepo := commonRepo.NewStockAllocationRepository(tx)
|
||||
sourceRepoTx := repository.NewLayingTransferSourceRepository(tx)
|
||||
targetRepoTx := repository.NewLayingTransferTargetRepository(tx)
|
||||
stockLogRepoTx := rStockLogs.NewStockLogRepository(tx)
|
||||
|
||||
totalTargetQty := 0.0
|
||||
for _, target := range targets {
|
||||
totalTargetQty += target.TotalQty
|
||||
}
|
||||
if totalTargetQty <= 0 {
|
||||
return fiber.NewError(fiber.StatusBadRequest, "Total kuantitas target transfer laying harus lebih dari 0")
|
||||
}
|
||||
|
||||
totalSourceRequested := 0.0
|
||||
for _, source := range sources {
|
||||
totalSourceRequested += source.RequestedQty
|
||||
}
|
||||
if totalSourceRequested <= 0 {
|
||||
return fiber.NewError(fiber.StatusBadRequest, "Total kuantitas sumber transfer laying harus lebih dari 0")
|
||||
}
|
||||
|
||||
for _, source := range sources {
|
||||
if source.ProductWarehouseId == nil {
|
||||
return fiber.NewError(fiber.StatusInternalServerError, fmt.Sprintf("Source product warehouse tidak ditemukan untuk transfer %d", transfer.Id))
|
||||
}
|
||||
if source.RequestedQty <= 0 {
|
||||
continue
|
||||
}
|
||||
|
||||
sourceShare := (source.RequestedQty / totalSourceRequested) * totalTargetQty
|
||||
if sourceShare <= 0 {
|
||||
continue
|
||||
}
|
||||
|
||||
if err := sourceRepoTx.PatchOne(ctx, source.Id, map[string]any{
|
||||
"usage_qty": source.UsageQty + sourceShare,
|
||||
"pending_usage_qty": 0,
|
||||
}, nil); err != nil {
|
||||
return fiber.NewError(fiber.StatusInternalServerError, "Gagal update source usage qty")
|
||||
}
|
||||
|
||||
asOf := transfer.TransferDate
|
||||
if transfer.EffectiveMoveDate != nil && !transfer.EffectiveMoveDate.IsZero() {
|
||||
asOf = *transfer.EffectiveMoveDate
|
||||
}
|
||||
if _, err := s.FifoStockV2Svc.Reflow(ctx, commonSvc.FifoStockV2ReflowRequest{
|
||||
FlagGroupCode: transferToLayingFlagGroupCode,
|
||||
ProductWarehouseID: *source.ProductWarehouseId,
|
||||
AsOf: &asOf,
|
||||
Tx: tx,
|
||||
}); err != nil {
|
||||
return fiber.NewError(fiber.StatusBadRequest, fmt.Sprintf("Gagal consume FIFO v2 stock: %v", err))
|
||||
}
|
||||
|
||||
refreshedSource, err := sourceRepoTx.GetByID(ctx, source.Id, nil)
|
||||
if err != nil {
|
||||
return fiber.NewError(fiber.StatusInternalServerError, "Gagal refresh source transfer setelah reflow")
|
||||
}
|
||||
|
||||
usageDelta := refreshedSource.UsageQty - source.UsageQty
|
||||
pendingQty := refreshedSource.PendingUsageQty
|
||||
if pendingQty > 1e-6 || usageDelta < sourceShare-1e-6 {
|
||||
return fiber.NewError(
|
||||
fiber.StatusBadRequest,
|
||||
fmt.Sprintf("Stok sumber tidak mencukupi untuk mengeksekusi transfer laying %s", transfer.TransferNumber),
|
||||
)
|
||||
}
|
||||
|
||||
movedQty := usageDelta
|
||||
if err := s.allocatePopulationForTransfer(ctx, tx, source, movedQty); err != nil {
|
||||
return err
|
||||
}
|
||||
targetShares := distributeProportionalWithRounding(targets, totalTargetQty, movedQty)
|
||||
for i, target := range targets {
|
||||
roundedQty := math.Round(targetShares[i])
|
||||
if roundedQty <= 0 {
|
||||
continue
|
||||
}
|
||||
mappingAllocation := &entity.StockAllocation{
|
||||
StockableType: fifo.UsableKeyTransferToLayingOut.String(),
|
||||
StockableId: source.Id,
|
||||
UsableType: fifo.StockableKeyTransferToLayingIn.String(),
|
||||
UsableId: target.Id,
|
||||
ProductWarehouseId: *source.ProductWarehouseId,
|
||||
Qty: roundedQty,
|
||||
Status: entity.StockAllocationStatusActive,
|
||||
}
|
||||
if err := stockAllocationRepo.CreateOne(ctx, mappingAllocation, nil); err != nil {
|
||||
return fiber.NewError(fiber.StatusInternalServerError, "Gagal create mapping allocation source→target")
|
||||
}
|
||||
}
|
||||
|
||||
stockLogDecrease := &entity.StockLog{
|
||||
ProductWarehouseId: *source.ProductWarehouseId,
|
||||
CreatedBy: actorID,
|
||||
Increase: 0,
|
||||
Decrease: movedQty,
|
||||
LoggableType: string(utils.StockLogTypeTransferLaying),
|
||||
LoggableId: transfer.Id,
|
||||
Notes: fmt.Sprintf("TL #%s", transfer.TransferNumber),
|
||||
}
|
||||
stockLogs, err := stockLogRepoTx.GetByProductWarehouse(ctx, *source.ProductWarehouseId, 1)
|
||||
if err != nil {
|
||||
s.Log.Errorf("Failed to get stock logs: %+v", err)
|
||||
return fiber.NewError(fiber.StatusInternalServerError, "Failed to get stock logs")
|
||||
}
|
||||
if len(stockLogs) > 0 {
|
||||
latestStockLog := stockLogs[0]
|
||||
stockLogDecrease.Stock = latestStockLog.Stock - stockLogDecrease.Decrease
|
||||
} else {
|
||||
stockLogDecrease.Stock -= stockLogDecrease.Decrease
|
||||
}
|
||||
|
||||
if err := stockLogRepoTx.CreateOne(ctx, stockLogDecrease, nil); err != nil {
|
||||
return fiber.NewError(fiber.StatusInternalServerError, "Gagal membuat log stok keluar")
|
||||
}
|
||||
}
|
||||
|
||||
for _, target := range targets {
|
||||
if target.ProductWarehouseId == nil {
|
||||
return fiber.NewError(fiber.StatusInternalServerError, fmt.Sprintf("Target product warehouse tidak ditemukan untuk transfer %d", transfer.Id))
|
||||
}
|
||||
|
||||
note := fmt.Sprintf("Transfer to Laying #%s", transfer.TransferNumber)
|
||||
_, err := s.FifoSvc.Replenish(ctx, commonSvc.StockReplenishRequest{
|
||||
StockableKey: fifo.StockableKeyTransferToLayingIn,
|
||||
StockableID: target.Id,
|
||||
ProductWarehouseID: *target.ProductWarehouseId,
|
||||
Quantity: target.TotalQty,
|
||||
Note: ¬e,
|
||||
Tx: tx,
|
||||
})
|
||||
if err != nil {
|
||||
return fiber.NewError(fiber.StatusInternalServerError, fmt.Sprintf("Gagal replenish stock ke target warehouse: %v", err))
|
||||
}
|
||||
|
||||
if err := targetRepoTx.PatchOne(ctx, target.Id, map[string]any{
|
||||
"total_qty": target.TotalQty,
|
||||
}, nil); err != nil {
|
||||
return fiber.NewError(fiber.StatusInternalServerError, "Gagal update target total qty")
|
||||
}
|
||||
|
||||
stockLogIncrease := &entity.StockLog{
|
||||
ProductWarehouseId: *target.ProductWarehouseId,
|
||||
CreatedBy: actorID,
|
||||
Increase: target.TotalQty,
|
||||
Decrease: 0,
|
||||
LoggableType: string(utils.StockLogTypeTransferLaying),
|
||||
LoggableId: transfer.Id,
|
||||
Notes: fmt.Sprintf("TL #%s", transfer.TransferNumber),
|
||||
}
|
||||
stockLogs, err := stockLogRepoTx.GetByProductWarehouse(ctx, *target.ProductWarehouseId, 1)
|
||||
if err != nil {
|
||||
s.Log.Errorf("Failed to get stock logs: %+v", err)
|
||||
return fiber.NewError(fiber.StatusInternalServerError, "Failed to get stock logs")
|
||||
}
|
||||
if len(stockLogs) > 0 {
|
||||
latestStockLog := stockLogs[0]
|
||||
stockLogIncrease.Stock = latestStockLog.Stock + stockLogIncrease.Increase
|
||||
} else {
|
||||
stockLogIncrease.Stock += stockLogIncrease.Increase
|
||||
}
|
||||
|
||||
if err := stockLogRepoTx.CreateOne(ctx, stockLogIncrease, nil); err != nil {
|
||||
return fiber.NewError(fiber.StatusInternalServerError, "Gagal membuat log stok masuk")
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *transferLayingService) allocatePopulationForTransfer(
|
||||
ctx context.Context,
|
||||
tx *gorm.DB,
|
||||
source entity.LayingTransferSource,
|
||||
consumeQty float64,
|
||||
) error {
|
||||
if consumeQty <= 0 {
|
||||
return nil
|
||||
}
|
||||
if tx == nil {
|
||||
return errors.New("transaction is required")
|
||||
}
|
||||
if source.SourceProjectFlockKandangId == 0 || source.ProductWarehouseId == nil || *source.ProductWarehouseId == 0 {
|
||||
return fiber.NewError(fiber.StatusBadRequest, "Project flock kandang sumber atau product warehouse tidak valid")
|
||||
}
|
||||
|
||||
populations, err := s.ProjectFlockPopulationRepo.GetByProjectFlockKandangIDAndProductWarehouseID(
|
||||
ctx,
|
||||
source.SourceProjectFlockKandangId,
|
||||
*source.ProductWarehouseId,
|
||||
)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if len(populations) == 0 {
|
||||
return fiber.NewError(fiber.StatusBadRequest, "Populasi tidak ditemukan untuk transfer laying")
|
||||
}
|
||||
|
||||
return fifoV2.AllocatePopulationConsumption(
|
||||
ctx,
|
||||
tx,
|
||||
populations,
|
||||
*source.ProductWarehouseId,
|
||||
fifo.UsableKeyTransferToLayingOut.String(),
|
||||
source.Id,
|
||||
consumeQty,
|
||||
)
|
||||
}
|
||||
|
||||
func (s *transferLayingService) calculateEffectiveMoveDate(ctx context.Context, sources []entity.LayingTransferSource) (time.Time, error) {
|
||||
if len(sources) == 0 {
|
||||
return time.Time{}, fiber.NewError(fiber.StatusBadRequest, "Sumber transfer laying tidak ditemukan")
|
||||
}
|
||||
|
||||
maxGrowingWeek := config.TransferToLayingGrowingMaxWeek
|
||||
if maxGrowingWeek <= 0 {
|
||||
maxGrowingWeek = 19
|
||||
}
|
||||
|
||||
var baselineChickInDate time.Time
|
||||
for _, source := range sources {
|
||||
chickInDate, err := s.resolveSourceChickInDate(ctx, source.SourceProjectFlockKandangId)
|
||||
if err != nil {
|
||||
return time.Time{}, err
|
||||
}
|
||||
if baselineChickInDate.IsZero() || chickInDate.Before(baselineChickInDate) {
|
||||
baselineChickInDate = chickInDate
|
||||
}
|
||||
}
|
||||
|
||||
if baselineChickInDate.IsZero() {
|
||||
return time.Time{}, fiber.NewError(fiber.StatusBadRequest, "Tanggal chick in sumber transfer laying tidak ditemukan")
|
||||
}
|
||||
|
||||
effectiveMoveDate := baselineChickInDate.AddDate(0, 0, maxGrowingWeek*7)
|
||||
return normalizeDateOnlyUTC(effectiveMoveDate), nil
|
||||
}
|
||||
|
||||
func (s *transferLayingService) resolveSourceChickInDate(ctx context.Context, sourceProjectFlockKandangID uint) (time.Time, error) {
|
||||
if sourceProjectFlockKandangID == 0 {
|
||||
return time.Time{}, fiber.NewError(fiber.StatusBadRequest, "Project flock kandang sumber tidak valid")
|
||||
}
|
||||
|
||||
populations, err := s.ProjectFlockPopulationRepo.GetByProjectFlockKandangID(ctx, sourceProjectFlockKandangID)
|
||||
if err != nil {
|
||||
return time.Time{}, err
|
||||
}
|
||||
|
||||
var earliestChickInDate time.Time
|
||||
for _, population := range populations {
|
||||
if population.ProjectChickin == nil || population.ProjectChickin.ChickInDate.IsZero() {
|
||||
continue
|
||||
}
|
||||
chickInDate := normalizeDateOnlyUTC(population.ProjectChickin.ChickInDate)
|
||||
if earliestChickInDate.IsZero() || chickInDate.Before(earliestChickInDate) {
|
||||
earliestChickInDate = chickInDate
|
||||
}
|
||||
}
|
||||
|
||||
if earliestChickInDate.IsZero() {
|
||||
return time.Time{}, fiber.NewError(
|
||||
fiber.StatusBadRequest,
|
||||
fmt.Sprintf("Tanggal chick in untuk kandang sumber %d tidak ditemukan", sourceProjectFlockKandangID),
|
||||
)
|
||||
}
|
||||
|
||||
return earliestChickInDate, nil
|
||||
}
|
||||
|
||||
func createApprovalTransferLaying(ctx context.Context, tx *gorm.DB, transferLayingID uint, actorID uint) error {
|
||||
if transferLayingID == 0 || actorID == 0 {
|
||||
return nil
|
||||
@@ -1053,6 +1321,10 @@ func (s transferLayingService) GetMaxTargetQtyPerKandang(c *fiber.Ctx, projectFl
|
||||
return kandangMaxTargetQty, nil
|
||||
}
|
||||
|
||||
func normalizeDateOnlyUTC(value time.Time) time.Time {
|
||||
return time.Date(value.UTC().Year(), value.UTC().Month(), value.UTC().Day(), 0, 0, 0, 0, time.UTC)
|
||||
}
|
||||
|
||||
func distributeProportionalWithRounding(targets []entity.LayingTransferTarget, totalTargetQty, sourceShare float64) []float64 {
|
||||
if len(targets) == 0 {
|
||||
return []float64{}
|
||||
|
||||
Reference in New Issue
Block a user