mirror of
https://gitlab.com/mbugroup/lti-api.git
synced 2026-05-24 15:25:43 +00:00
Merge branch 'fix/BE/US-281-adjustment-recording-egg-mass' into 'development'
[FEAT/BE] fix bug recording and closing counting sapronak See merge request mbugroup/lti-api!296
This commit is contained in:
@@ -147,6 +147,7 @@ type StockReleaseRequest struct {
|
|||||||
Reason *string
|
Reason *string
|
||||||
Tx *gorm.DB
|
Tx *gorm.DB
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *fifoService) AdjustStockableQuantity(ctx context.Context, req StockAdjustRequest) error {
|
func (s *fifoService) AdjustStockableQuantity(ctx context.Context, req StockAdjustRequest) error {
|
||||||
if req.StockableID == 0 || strings.TrimSpace(req.StockableKey.String()) == "" {
|
if req.StockableID == 0 || strings.TrimSpace(req.StockableKey.String()) == "" {
|
||||||
return errors.New("stockable key and id are required")
|
return errors.New("stockable key and id are required")
|
||||||
@@ -308,7 +309,7 @@ func (s *fifoService) Consume(ctx context.Context, req StockConsumeRequest) (*St
|
|||||||
}
|
}
|
||||||
|
|
||||||
if reductionTarget > 0 {
|
if reductionTarget > 0 {
|
||||||
released, err := s.releaseUsagePortion(ctx, tx, req.UsableKey, req.UsableID, reductionTarget)
|
released, err := s.releaseUsagePortion(ctx, tx, req.UsableKey, req.UsableID, reductionTarget, productWarehouseID)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
@@ -355,7 +356,7 @@ func (s *fifoService) ReleaseUsage(ctx context.Context, req StockReleaseRequest)
|
|||||||
}
|
}
|
||||||
var usageDelta, pendingDelta float64
|
var usageDelta, pendingDelta float64
|
||||||
if ctxRow.UsageQty > 0 {
|
if ctxRow.UsageQty > 0 {
|
||||||
if _, err := s.releaseUsagePortion(ctx, tx, req.UsableKey, req.UsableID, ctxRow.UsageQty); err != nil {
|
if _, err := s.releaseUsagePortion(ctx, tx, req.UsableKey, req.UsableID, ctxRow.UsageQty, ctxRow.ProductWarehouseID); err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
usageDelta -= ctxRow.UsageQty
|
usageDelta -= ctxRow.UsageQty
|
||||||
@@ -721,6 +722,7 @@ func (s *fifoService) releaseUsagePortion(
|
|||||||
usableKey fifo.UsableKey,
|
usableKey fifo.UsableKey,
|
||||||
usableID uint,
|
usableID uint,
|
||||||
target float64,
|
target float64,
|
||||||
|
expectedWarehouseID uint,
|
||||||
) (float64, error) {
|
) (float64, error) {
|
||||||
if target <= 0 {
|
if target <= 0 {
|
||||||
return 0, nil
|
return 0, nil
|
||||||
@@ -736,6 +738,20 @@ func (s *fifoService) releaseUsagePortion(
|
|||||||
if len(allocations) == 0 {
|
if len(allocations) == 0 {
|
||||||
return 0, nil
|
return 0, nil
|
||||||
}
|
}
|
||||||
|
for i := range allocations {
|
||||||
|
alloc := &allocations[i]
|
||||||
|
if expectedWarehouseID == 0 || alloc.ProductWarehouseId == expectedWarehouseID {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
fmt.Printf("WARN[FIFO] ALLOC WAREHOUSE MISMATCH usable_key=%s usable_id=%d alloc_id=%d expected_pw=%d actual_pw=%d\n",
|
||||||
|
usableKey.String(), usableID, alloc.Id, expectedWarehouseID, alloc.ProductWarehouseId)
|
||||||
|
if err := tx.Model(&entities.StockAllocation{}).
|
||||||
|
Where("id = ?", alloc.Id).
|
||||||
|
Update("product_warehouse_id", expectedWarehouseID).Error; err != nil {
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
alloc.ProductWarehouseId = expectedWarehouseID
|
||||||
|
}
|
||||||
|
|
||||||
var (
|
var (
|
||||||
remaining = target
|
remaining = target
|
||||||
|
|||||||
@@ -234,14 +234,14 @@ func ToSapronakProjectAggregatedFromReport(report *SapronakReportDTO, flag strin
|
|||||||
row.Notes = "TRANSFER STOCK"
|
row.Notes = "TRANSFER STOCK"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
case "pemakaian", "adjustment keluar":
|
case "pemakaian":
|
||||||
price := row.UnitPrice
|
price := row.UnitPrice
|
||||||
if price == 0 {
|
if price == 0 {
|
||||||
price = item.Harga
|
price = item.Harga
|
||||||
}
|
}
|
||||||
row.QtyUsed += item.QtyKeluar
|
row.QtyUsed += item.QtyKeluar
|
||||||
row.TotalAmount += item.QtyKeluar * price
|
row.TotalAmount += item.QtyKeluar * price
|
||||||
case "mutasi keluar", "penjualan":
|
case "adjustment keluar", "mutasi keluar", "penjualan":
|
||||||
price := row.UnitPrice
|
price := row.UnitPrice
|
||||||
if price == 0 {
|
if price == 0 {
|
||||||
price = item.Harga
|
price = item.Harga
|
||||||
|
|||||||
@@ -36,6 +36,7 @@ type ClosingRepository interface {
|
|||||||
FetchSapronakAdjustments(ctx context.Context, kandangID uint) (map[uint][]SapronakDetailRow, map[uint][]SapronakDetailRow, error)
|
FetchSapronakAdjustments(ctx context.Context, kandangID uint) (map[uint][]SapronakDetailRow, map[uint][]SapronakDetailRow, error)
|
||||||
FetchSapronakTransfers(ctx context.Context, kandangID uint) (map[uint][]SapronakDetailRow, map[uint][]SapronakDetailRow, error)
|
FetchSapronakTransfers(ctx context.Context, kandangID uint) (map[uint][]SapronakDetailRow, map[uint][]SapronakDetailRow, error)
|
||||||
FetchSapronakSales(ctx context.Context, projectFlockKandangID uint) (map[uint][]SapronakDetailRow, error)
|
FetchSapronakSales(ctx context.Context, projectFlockKandangID uint) (map[uint][]SapronakDetailRow, error)
|
||||||
|
FetchSapronakSalesAllocatedDetails(ctx context.Context, projectFlockKandangID uint) (map[uint][]SapronakDetailRow, error)
|
||||||
GetProductsWithFlagsByIDs(ctx context.Context, productIDs []uint) ([]entity.Product, error)
|
GetProductsWithFlagsByIDs(ctx context.Context, productIDs []uint) ([]entity.Product, error)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -939,6 +940,7 @@ func (r *ClosingRepositoryImpl) FetchSapronakUsageAllocatedDetails(ctx context.C
|
|||||||
Joins("LEFT JOIN project_flock_populations pfp ON pfp.id = sa.stockable_id AND sa.stockable_type = ?", fifo.StockableKeyProjectFlockPopulation.String()).
|
Joins("LEFT JOIN project_flock_populations pfp ON pfp.id = sa.stockable_id AND sa.stockable_type = ?", fifo.StockableKeyProjectFlockPopulation.String()).
|
||||||
Joins("LEFT JOIN project_chickins pc ON pc.id = pfp.project_chickin_id").
|
Joins("LEFT JOIN project_chickins pc ON pc.id = pfp.project_chickin_id").
|
||||||
Where("sa.status = ?", entity.StockAllocationStatusActive).
|
Where("sa.status = ?", entity.StockAllocationStatusActive).
|
||||||
|
Where("sa.stockable_type <> ?", fifo.StockableKeyProjectFlockPopulation.String()).
|
||||||
Where("f.name IN ?", sapronakFlagsAll).
|
Where("f.name IN ?", sapronakFlagsAll).
|
||||||
Where(`
|
Where(`
|
||||||
(sa.usable_type = ? AND r.project_flock_kandangs_id = ?)
|
(sa.usable_type = ? AND r.project_flock_kandangs_id = ?)
|
||||||
@@ -1085,12 +1087,75 @@ func splitStockLogs(rows []stockLogSapronakRow, refFn func(stockLogSapronakRow)
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (r *ClosingRepositoryImpl) FetchSapronakAdjustments(ctx context.Context, kandangID uint) (map[uint][]SapronakDetailRow, map[uint][]SapronakDetailRow, error) {
|
func (r *ClosingRepositoryImpl) FetchSapronakAdjustments(ctx context.Context, kandangID uint) (map[uint][]SapronakDetailRow, map[uint][]SapronakDetailRow, error) {
|
||||||
rows, err := r.fetchStockLogs(ctx, kandangID, string(utils.StockLogTypeAdjustment), false)
|
poByWarehouse := r.DB().
|
||||||
|
Table("purchase_items pi").
|
||||||
|
Select("DISTINCT ON (pi.product_warehouse_id) pi.product_warehouse_id, po.po_number, pi.received_date").
|
||||||
|
Joins("JOIN purchases po ON po.id = pi.purchase_id").
|
||||||
|
Where("pi.received_date IS NOT NULL").
|
||||||
|
Order("pi.product_warehouse_id, pi.received_date ASC")
|
||||||
|
|
||||||
|
incomingQuery := r.withCtx(ctx).
|
||||||
|
Table("adjustment_stocks AS ast").
|
||||||
|
Select(`
|
||||||
|
pw.product_id AS product_id,
|
||||||
|
p.name AS product_name,
|
||||||
|
f.name AS flag,
|
||||||
|
ast.created_at AS date,
|
||||||
|
CONCAT('ADJ-', ast.id) AS reference,
|
||||||
|
COALESCE(ast.total_qty, 0) AS qty_in,
|
||||||
|
0 AS qty_out,
|
||||||
|
COALESCE(p.product_price, 0) AS price
|
||||||
|
`).
|
||||||
|
Joins("JOIN product_warehouses pw ON pw.id = ast.product_warehouse_id").
|
||||||
|
Joins("JOIN warehouses w ON w.id = pw.warehouse_id").
|
||||||
|
Joins("JOIN products p ON p.id = pw.product_id").
|
||||||
|
Where("w.kandang_id = ?", kandangID).
|
||||||
|
Where("f.name IN ?", sapronakFlagsAll).
|
||||||
|
Where("COALESCE(ast.total_qty, 0) > 0")
|
||||||
|
incomingQuery = r.joinSapronakProductFlag(incomingQuery, "p")
|
||||||
|
incoming, err := scanAndGroupDetails(incomingQuery)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, nil, err
|
return nil, nil, err
|
||||||
}
|
}
|
||||||
in, out := splitStockLogs(rows, func(row stockLogSapronakRow) string { return fmt.Sprintf("ADJ-%d", row.ID) })
|
|
||||||
return in, out, nil
|
outgoingQuery := r.withCtx(ctx).
|
||||||
|
Table("stock_allocations AS sa").
|
||||||
|
Select(`
|
||||||
|
pw.product_id AS product_id,
|
||||||
|
p.name AS product_name,
|
||||||
|
f.name AS flag,
|
||||||
|
COALESCE(pi.received_date, st.transfer_date, lt.transfer_date, pfp_po.received_date, pc.chick_in_date, ast_in.created_at, ast.created_at) AS date,
|
||||||
|
COALESCE(po.po_number, st.movement_number, lt.transfer_number, pfp_po.po_number, CONCAT('CHICKIN-', pc.id), CONCAT('ADJ-', ast_in.id), CONCAT('ADJ-', ast.id)) AS reference,
|
||||||
|
0 AS qty_in,
|
||||||
|
COALESCE(SUM(sa.qty), 0) AS qty_out,
|
||||||
|
COALESCE(p.product_price, 0) AS price
|
||||||
|
`).
|
||||||
|
Joins("JOIN adjustment_stocks ast ON ast.id = sa.usable_id AND sa.usable_type = ?", fifo.UsableKeyAdjustmentOut.String()).
|
||||||
|
Joins("LEFT JOIN purchase_items pi ON pi.id = sa.stockable_id AND sa.stockable_type = ?", fifo.StockableKeyPurchaseItems.String()).
|
||||||
|
Joins("LEFT JOIN purchases po ON po.id = pi.purchase_id").
|
||||||
|
Joins("LEFT JOIN stock_transfer_details std ON std.id = sa.stockable_id AND sa.stockable_type = ?", fifo.StockableKeyStockTransferIn.String()).
|
||||||
|
Joins("LEFT JOIN stock_transfers st ON st.id = std.stock_transfer_id").
|
||||||
|
Joins("LEFT JOIN laying_transfer_targets ltt ON ltt.id = sa.stockable_id AND sa.stockable_type = ?", fifo.StockableKeyTransferToLayingIn.String()).
|
||||||
|
Joins("LEFT JOIN laying_transfers lt ON lt.id = ltt.laying_transfer_id").
|
||||||
|
Joins("LEFT JOIN adjustment_stocks ast_in ON ast_in.id = sa.stockable_id AND sa.stockable_type = ?", fifo.StockableKeyAdjustmentIn.String()).
|
||||||
|
Joins("LEFT JOIN project_flock_populations pfp ON pfp.id = sa.stockable_id AND sa.stockable_type = ?", fifo.StockableKeyProjectFlockPopulation.String()).
|
||||||
|
Joins("LEFT JOIN project_chickins pc ON pc.id = pfp.project_chickin_id").
|
||||||
|
Joins("LEFT JOIN (?) pfp_po ON pfp_po.product_warehouse_id = pfp.product_warehouse_id", poByWarehouse).
|
||||||
|
Joins("JOIN product_warehouses pw ON pw.id = sa.product_warehouse_id").
|
||||||
|
Joins("JOIN warehouses w ON w.id = pw.warehouse_id").
|
||||||
|
Joins("JOIN products p ON p.id = pw.product_id").
|
||||||
|
Where("sa.status = ?", entity.StockAllocationStatusActive).
|
||||||
|
Where("w.kandang_id = ?", kandangID).
|
||||||
|
Where("f.name IN ?", sapronakFlagsAll).
|
||||||
|
Where("f.name NOT IN ?", sapronakFlags(utils.FlagDOC, utils.FlagPullet)).
|
||||||
|
Group("pw.product_id, p.name, f.name, pi.received_date, st.transfer_date, lt.transfer_date, pfp_po.received_date, pc.chick_in_date, ast_in.created_at, ast.created_at, po.po_number, st.movement_number, lt.transfer_number, pfp_po.po_number, pc.id, ast_in.id, ast.id, p.product_price")
|
||||||
|
outgoingQuery = r.joinSapronakProductFlag(outgoingQuery, "p")
|
||||||
|
outgoing, err := scanAndGroupDetails(outgoingQuery)
|
||||||
|
if err != nil {
|
||||||
|
return nil, nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return incoming, outgoing, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (r *ClosingRepositoryImpl) FetchSapronakTransfers(ctx context.Context, kandangID uint) (map[uint][]SapronakDetailRow, map[uint][]SapronakDetailRow, error) {
|
func (r *ClosingRepositoryImpl) FetchSapronakTransfers(ctx context.Context, kandangID uint) (map[uint][]SapronakDetailRow, map[uint][]SapronakDetailRow, error) {
|
||||||
@@ -1286,6 +1351,59 @@ func (r *ClosingRepositoryImpl) FetchSapronakSales(ctx context.Context, projectF
|
|||||||
return sales, nil
|
return sales, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (r *ClosingRepositoryImpl) FetchSapronakSalesAllocatedDetails(ctx context.Context, projectFlockKandangID uint) (map[uint][]SapronakDetailRow, error) {
|
||||||
|
if projectFlockKandangID == 0 {
|
||||||
|
return map[uint][]SapronakDetailRow{}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
query := r.withCtx(ctx).
|
||||||
|
Table("stock_allocations AS sa").
|
||||||
|
Select(`
|
||||||
|
pw.product_id AS product_id,
|
||||||
|
p.name AS product_name,
|
||||||
|
f.name AS flag,
|
||||||
|
COALESCE(
|
||||||
|
pi.received_date,
|
||||||
|
st.transfer_date,
|
||||||
|
lt.transfer_date,
|
||||||
|
ast.created_at
|
||||||
|
) AS date,
|
||||||
|
COALESCE(
|
||||||
|
po.po_number,
|
||||||
|
st.movement_number,
|
||||||
|
lt.transfer_number,
|
||||||
|
CONCAT('ADJ-', ast.id),
|
||||||
|
''
|
||||||
|
) AS reference,
|
||||||
|
0 AS qty_in,
|
||||||
|
COALESCE(SUM(sa.qty), 0) AS qty_out,
|
||||||
|
COALESCE(pi.price, p.product_price, 0) AS price
|
||||||
|
`).
|
||||||
|
Joins("JOIN product_warehouses pw ON pw.id = sa.product_warehouse_id").
|
||||||
|
Joins("JOIN products p ON p.id = pw.product_id").
|
||||||
|
Joins("JOIN marketing_delivery_products mdp ON mdp.id = sa.usable_id AND sa.usable_type = ?", fifo.UsableKeyMarketingDelivery.String()).
|
||||||
|
Joins("LEFT JOIN purchase_items pi ON pi.id = sa.stockable_id AND sa.stockable_type = ?", fifo.StockableKeyPurchaseItems.String()).
|
||||||
|
Joins("LEFT JOIN purchases po ON po.id = pi.purchase_id").
|
||||||
|
Joins("LEFT JOIN stock_transfer_details std ON std.id = sa.stockable_id AND sa.stockable_type = ?", fifo.StockableKeyStockTransferIn.String()).
|
||||||
|
Joins("LEFT JOIN stock_transfers st ON st.id = std.stock_transfer_id").
|
||||||
|
Joins("LEFT JOIN laying_transfer_targets ltt ON ltt.id = sa.stockable_id AND sa.stockable_type = ?", fifo.StockableKeyTransferToLayingIn.String()).
|
||||||
|
Joins("LEFT JOIN laying_transfers lt ON lt.id = ltt.laying_transfer_id").
|
||||||
|
Joins("LEFT JOIN adjustment_stocks ast ON ast.id = sa.stockable_id AND sa.stockable_type = ?", fifo.StockableKeyAdjustmentIn.String()).
|
||||||
|
Where("sa.status = ?", entity.StockAllocationStatusActive).
|
||||||
|
Where("sa.stockable_type <> ?", fifo.StockableKeyProjectFlockPopulation.String()).
|
||||||
|
Where("pw.project_flock_kandang_id = ?", projectFlockKandangID).
|
||||||
|
Where("f.name IN ?", sapronakFlagsAll).
|
||||||
|
Group(`
|
||||||
|
pw.product_id, p.name, f.name,
|
||||||
|
pi.received_date, st.transfer_date, lt.transfer_date, ast.created_at,
|
||||||
|
po.po_number, st.movement_number, lt.transfer_number, ast.id,
|
||||||
|
pi.price, p.product_price
|
||||||
|
`)
|
||||||
|
|
||||||
|
query = r.joinSapronakProductFlag(query, "p")
|
||||||
|
return scanAndGroupDetails(query)
|
||||||
|
}
|
||||||
|
|
||||||
func (r *ClosingRepositoryImpl) GetProductsWithFlagsByIDs(ctx context.Context, productIDs []uint) ([]entity.Product, error) {
|
func (r *ClosingRepositoryImpl) GetProductsWithFlagsByIDs(ctx context.Context, productIDs []uint) ([]entity.Product, error) {
|
||||||
if len(productIDs) == 0 {
|
if len(productIDs) == 0 {
|
||||||
return []entity.Product{}, nil
|
return []entity.Product{}, nil
|
||||||
|
|||||||
@@ -363,7 +363,7 @@ func (s sapronakService) buildSapronakItems(ctx context.Context, pfk entity.Proj
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, nil, 0, 0, err
|
return nil, nil, 0, 0, err
|
||||||
}
|
}
|
||||||
salesOutRows, err := s.Repository.FetchSapronakSales(ctx, pfk.Id)
|
salesOutRows, err := s.Repository.FetchSapronakSalesAllocatedDetails(ctx, pfk.Id)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, nil, 0, 0, err
|
return nil, nil, 0, 0, err
|
||||||
}
|
}
|
||||||
@@ -570,13 +570,12 @@ func (s sapronakService) buildSapronakItems(ctx context.Context, pfk entity.Proj
|
|||||||
if existing.ProductName == "" {
|
if existing.ProductName == "" {
|
||||||
existing.ProductName = d.ProductName
|
existing.ProductName = d.ProductName
|
||||||
}
|
}
|
||||||
existing.UsageQty += d.QtyKeluar
|
// Adjustment keluar should reduce stock without inflating usage-based HPP.
|
||||||
existing.UsageValue += d.Nilai
|
remaining := existing.IncomingQty - existing.UsageQty - d.QtyKeluar
|
||||||
if existing.IncomingQty >= existing.UsageQty {
|
if remaining < 0 {
|
||||||
existing.RemainingQty = existing.IncomingQty - existing.UsageQty
|
remaining = 0
|
||||||
} else {
|
|
||||||
existing.RemainingQty = 0
|
|
||||||
}
|
}
|
||||||
|
existing.RemainingQty = remaining
|
||||||
itemMap[productID] = existing
|
itemMap[productID] = existing
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -107,16 +107,23 @@ func applyDashboardFilters(db *gorm.DB, filters *validation.DashboardFilter) *go
|
|||||||
func (r *DashboardRepositoryImpl) GetRecordingWeeklyMetrics(ctx context.Context, start, end time.Time, filters *validation.DashboardFilter) ([]RecordingWeeklyMetric, error) {
|
func (r *DashboardRepositoryImpl) GetRecordingWeeklyMetrics(ctx context.Context, start, end time.Time, filters *validation.DashboardFilter) ([]RecordingWeeklyMetric, error) {
|
||||||
var rows []RecordingWeeklyMetric
|
var rows []RecordingWeeklyMetric
|
||||||
|
|
||||||
|
weekExpr := `CASE
|
||||||
|
WHEN r.day IS NULL OR r.day <= 0 THEN 1
|
||||||
|
WHEN UPPER(pf.category) = 'LAYING' THEN ((r.day - 1) / 7 + 1) + 17
|
||||||
|
ELSE ((r.day - 1) / 7 + 1)
|
||||||
|
END`
|
||||||
|
|
||||||
db := r.DB().WithContext(ctx).
|
db := r.DB().WithContext(ctx).
|
||||||
Table("recordings AS r").
|
Table("recordings AS r").
|
||||||
Select(`((r.day - 1) / 7 + 1) AS week,
|
Select(fmt.Sprintf(`%s AS week,
|
||||||
COALESCE(AVG(r.hen_day), 0) AS hen_day,
|
COALESCE(AVG(r.hen_day), 0) AS hen_day,
|
||||||
COALESCE(AVG(r.egg_weight), 0) AS egg_weight,
|
COALESCE(AVG(r.egg_weight), 0) AS egg_weight,
|
||||||
COALESCE(AVG(r.feed_intake), 0) AS feed_intake,
|
COALESCE(AVG(r.feed_intake), 0) AS feed_intake,
|
||||||
COALESCE(AVG(r.fcr_value), 0) AS fcr_value,
|
COALESCE(AVG(r.fcr_value), 0) AS fcr_value,
|
||||||
COALESCE(AVG(r.cum_depletion_rate), 0) AS cum_depletion_rate`).
|
COALESCE(AVG(r.cum_depletion_rate), 0) AS cum_depletion_rate`, weekExpr)).
|
||||||
Joins("JOIN project_flock_kandangs AS pfk ON pfk.id = r.project_flock_kandangs_id").
|
Joins("JOIN project_flock_kandangs AS pfk ON pfk.id = r.project_flock_kandangs_id").
|
||||||
Joins("JOIN kandangs AS k ON k.id = pfk.kandang_id").
|
Joins("JOIN kandangs AS k ON k.id = pfk.kandang_id").
|
||||||
|
Joins("JOIN project_flocks AS pf ON pf.id = pfk.project_flock_id").
|
||||||
Where("r.record_datetime >= ? AND r.record_datetime < ?", start, end).
|
Where("r.record_datetime >= ? AND r.record_datetime < ?", start, end).
|
||||||
Where("r.deleted_at IS NULL").
|
Where("r.deleted_at IS NULL").
|
||||||
Where("r.day IS NOT NULL AND r.day > 0")
|
Where("r.day IS NOT NULL AND r.day > 0")
|
||||||
@@ -188,92 +195,19 @@ func (r *DashboardRepositoryImpl) GetStandardFcrWeekly(ctx context.Context, week
|
|||||||
return nil, nil
|
return nil, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
filterClause := ""
|
standardIDs := r.standardIDSubquery(filters)
|
||||||
filterArgs := make([]interface{}, 0)
|
if standardIDs == nil {
|
||||||
if filters != nil {
|
return nil, nil
|
||||||
if len(filters.FlockIds) > 0 {
|
|
||||||
filterClause += " AND pf.id IN ?"
|
|
||||||
filterArgs = append(filterArgs, filters.FlockIds)
|
|
||||||
}
|
|
||||||
if len(filters.KandangIds) > 0 {
|
|
||||||
filterClause += " AND k.id IN ?"
|
|
||||||
filterArgs = append(filterArgs, filters.KandangIds)
|
|
||||||
}
|
|
||||||
if len(filters.LokasiIds) > 0 {
|
|
||||||
filterClause += " AND k.location_id IN ?"
|
|
||||||
filterArgs = append(filterArgs, filters.LokasiIds)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
query := fmt.Sprintf(`
|
|
||||||
WITH src AS (
|
|
||||||
SELECT DISTINCT pf.production_standard_id, pf.fcr_id
|
|
||||||
FROM project_flocks pf
|
|
||||||
JOIN project_flock_kandangs pfk ON pfk.project_flock_id = pf.id
|
|
||||||
JOIN kandangs k ON k.id = pfk.kandang_id
|
|
||||||
WHERE pf.production_standard_id > 0 AND pf.fcr_id > 0
|
|
||||||
%s
|
|
||||||
),
|
|
||||||
actual AS (
|
|
||||||
SELECT u.week AS week,
|
|
||||||
pf.fcr_id AS fcr_id,
|
|
||||||
AVG((u.chart_data->'statistics'->>'average_weight')::numeric) AS avg_weight
|
|
||||||
FROM project_flock_kandang_uniformity u
|
|
||||||
JOIN project_flock_kandangs pfk ON pfk.id = u.project_flock_kandang_id
|
|
||||||
JOIN project_flocks pf ON pf.id = pfk.project_flock_id
|
|
||||||
JOIN kandangs k ON k.id = pfk.kandang_id
|
|
||||||
WHERE u.week IN ? AND u.uniform_date IS NOT NULL AND pf.fcr_id > 0
|
|
||||||
%s
|
|
||||||
GROUP BY u.week, pf.fcr_id
|
|
||||||
),
|
|
||||||
target AS (
|
|
||||||
SELECT sgd.week AS week,
|
|
||||||
src.fcr_id AS fcr_id,
|
|
||||||
AVG(sgd.target_mean_bw) AS target_mean_bw
|
|
||||||
FROM standard_growth_details sgd
|
|
||||||
JOIN src ON src.production_standard_id = sgd.production_standard_id
|
|
||||||
WHERE sgd.week IN ?
|
|
||||||
GROUP BY sgd.week, src.fcr_id
|
|
||||||
),
|
|
||||||
weights AS (
|
|
||||||
SELECT COALESCE(a.week, t.week) AS week,
|
|
||||||
COALESCE(a.fcr_id, t.fcr_id) AS fcr_id,
|
|
||||||
COALESCE(
|
|
||||||
CASE WHEN a.avg_weight > 10 THEN a.avg_weight / 1000 ELSE a.avg_weight END,
|
|
||||||
CASE WHEN t.target_mean_bw > 10 THEN t.target_mean_bw / 1000 ELSE t.target_mean_bw END
|
|
||||||
) AS weight
|
|
||||||
FROM actual a
|
|
||||||
FULL OUTER JOIN target t ON t.week = a.week AND t.fcr_id = a.fcr_id
|
|
||||||
)
|
|
||||||
SELECT w.week AS week,
|
|
||||||
COALESCE(AVG(
|
|
||||||
COALESCE(
|
|
||||||
(SELECT fs.fcr_number
|
|
||||||
FROM fcr_standards fs
|
|
||||||
WHERE fs.fcr_id = w.fcr_id
|
|
||||||
AND fs.weight >= w.weight
|
|
||||||
ORDER BY fs.weight ASC
|
|
||||||
LIMIT 1),
|
|
||||||
(SELECT fs.fcr_number
|
|
||||||
FROM fcr_standards fs
|
|
||||||
WHERE fs.fcr_id = w.fcr_id
|
|
||||||
ORDER BY fs.weight DESC
|
|
||||||
LIMIT 1)
|
|
||||||
)
|
|
||||||
), 0) AS std_fcr
|
|
||||||
FROM weights w
|
|
||||||
GROUP BY w.week
|
|
||||||
ORDER BY w.week ASC
|
|
||||||
`, filterClause, filterClause)
|
|
||||||
|
|
||||||
args := make([]interface{}, 0, len(filterArgs)*2+2)
|
|
||||||
args = append(args, filterArgs...)
|
|
||||||
args = append(args, weeks)
|
|
||||||
args = append(args, filterArgs...)
|
|
||||||
args = append(args, weeks)
|
|
||||||
|
|
||||||
var rows []StandardWeeklyFcrMetric
|
var rows []StandardWeeklyFcrMetric
|
||||||
if err := r.DB().WithContext(ctx).Raw(query, args...).Scan(&rows).Error; err != nil {
|
db := r.DB().WithContext(ctx).
|
||||||
|
Table("production_standard_details AS psd").
|
||||||
|
Select("psd.week AS week, COALESCE(AVG(psd.standard_fcr), 0) AS std_fcr").
|
||||||
|
Where("psd.week IN ?", weeks).
|
||||||
|
Where("psd.production_standard_id IN (?)", standardIDs)
|
||||||
|
|
||||||
|
if err := db.Group("psd.week").Order("psd.week ASC").Scan(&rows).Error; err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -635,13 +569,19 @@ func (r *DashboardRepositoryImpl) GetComparisonWeeklyUniformityMetrics(ctx conte
|
|||||||
func (r *DashboardRepositoryImpl) GetEggQualityWeeklyMetrics(ctx context.Context, start, end time.Time, filters *validation.DashboardFilter) ([]EggQualityWeeklyMetric, error) {
|
func (r *DashboardRepositoryImpl) GetEggQualityWeeklyMetrics(ctx context.Context, start, end time.Time, filters *validation.DashboardFilter) ([]EggQualityWeeklyMetric, error) {
|
||||||
var rows []EggQualityWeeklyMetric
|
var rows []EggQualityWeeklyMetric
|
||||||
|
|
||||||
|
weekExpr := `CASE
|
||||||
|
WHEN r.day IS NULL OR r.day <= 0 THEN 1
|
||||||
|
WHEN UPPER(pf.category) = 'LAYING' THEN ((r.day - 1) / 7 + 1) + 17
|
||||||
|
ELSE ((r.day - 1) / 7 + 1)
|
||||||
|
END`
|
||||||
|
|
||||||
db := r.DB().WithContext(ctx).
|
db := r.DB().WithContext(ctx).
|
||||||
Table("recording_eggs AS re").
|
Table("recording_eggs AS re").
|
||||||
Select(`
|
Select(fmt.Sprintf(`
|
||||||
((r.day - 1) / 7 + 1) AS week,
|
%s AS week,
|
||||||
COALESCE(SUM(CASE WHEN f.name = ? THEN re.qty ELSE 0 END), 0) AS normal_qty,
|
COALESCE(SUM(CASE WHEN f.name = ? THEN re.qty ELSE 0 END), 0) AS normal_qty,
|
||||||
COALESCE(SUM(CASE WHEN f.name IN (?, ?, ?) THEN re.qty ELSE 0 END), 0) AS abnormal_qty,
|
COALESCE(SUM(CASE WHEN f.name IN (?, ?, ?) THEN re.qty ELSE 0 END), 0) AS abnormal_qty,
|
||||||
COALESCE(SUM(re.qty), 0) AS total_qty`,
|
COALESCE(SUM(re.qty), 0) AS total_qty`, weekExpr),
|
||||||
utils.FlagTelurUtuh,
|
utils.FlagTelurUtuh,
|
||||||
utils.FlagTelurPutih,
|
utils.FlagTelurPutih,
|
||||||
utils.FlagTelurRetak,
|
utils.FlagTelurRetak,
|
||||||
@@ -650,6 +590,7 @@ func (r *DashboardRepositoryImpl) GetEggQualityWeeklyMetrics(ctx context.Context
|
|||||||
Joins("JOIN recordings AS r ON r.id = re.recording_id").
|
Joins("JOIN recordings AS r ON r.id = re.recording_id").
|
||||||
Joins("JOIN project_flock_kandangs AS pfk ON pfk.id = r.project_flock_kandangs_id").
|
Joins("JOIN project_flock_kandangs AS pfk ON pfk.id = r.project_flock_kandangs_id").
|
||||||
Joins("JOIN kandangs AS k ON k.id = pfk.kandang_id").
|
Joins("JOIN kandangs AS k ON k.id = pfk.kandang_id").
|
||||||
|
Joins("JOIN project_flocks AS pf ON pf.id = pfk.project_flock_id").
|
||||||
Joins("JOIN product_warehouses AS pw ON pw.id = re.product_warehouse_id").
|
Joins("JOIN product_warehouses AS pw ON pw.id = re.product_warehouse_id").
|
||||||
Joins("JOIN products AS p ON p.id = pw.product_id").
|
Joins("JOIN products AS p ON p.id = pw.product_id").
|
||||||
Joins("JOIN flags AS f ON f.flagable_id = p.id AND f.flagable_type = ?", entity.FlagableTypeProduct).
|
Joins("JOIN flags AS f ON f.flagable_id = p.id AND f.flagable_type = ?", entity.FlagableTypeProduct).
|
||||||
@@ -670,14 +611,21 @@ func (r *DashboardRepositoryImpl) GetEggQualityWeeklyMetrics(ctx context.Context
|
|||||||
func (r *DashboardRepositoryImpl) GetEggWeightWeeklyGrams(ctx context.Context, start, end time.Time, filters *validation.DashboardFilter) ([]WeeklyEggWeightMetric, error) {
|
func (r *DashboardRepositoryImpl) GetEggWeightWeeklyGrams(ctx context.Context, start, end time.Time, filters *validation.DashboardFilter) ([]WeeklyEggWeightMetric, error) {
|
||||||
var rows []WeeklyEggWeightMetric
|
var rows []WeeklyEggWeightMetric
|
||||||
|
|
||||||
|
weekExpr := `CASE
|
||||||
|
WHEN r.day IS NULL OR r.day <= 0 THEN 1
|
||||||
|
WHEN UPPER(pf.category) = 'LAYING' THEN ((r.day - 1) / 7 + 1) + 17
|
||||||
|
ELSE ((r.day - 1) / 7 + 1)
|
||||||
|
END`
|
||||||
|
|
||||||
db := r.DB().WithContext(ctx).
|
db := r.DB().WithContext(ctx).
|
||||||
Table("recording_eggs AS re").
|
Table("recording_eggs AS re").
|
||||||
Select(`
|
Select(fmt.Sprintf(`
|
||||||
((r.day - 1) / 7 + 1) AS week,
|
%s AS week,
|
||||||
COALESCE(SUM(re.weight * 1000), 0) AS egg_weight_grams`).
|
COALESCE(SUM(re.weight * 1000), 0) AS egg_weight_grams`, weekExpr)).
|
||||||
Joins("JOIN recordings AS r ON r.id = re.recording_id").
|
Joins("JOIN recordings AS r ON r.id = re.recording_id").
|
||||||
Joins("JOIN project_flock_kandangs AS pfk ON pfk.id = r.project_flock_kandangs_id").
|
Joins("JOIN project_flock_kandangs AS pfk ON pfk.id = r.project_flock_kandangs_id").
|
||||||
Joins("JOIN kandangs AS k ON k.id = pfk.kandang_id").
|
Joins("JOIN kandangs AS k ON k.id = pfk.kandang_id").
|
||||||
|
Joins("JOIN project_flocks AS pf ON pf.id = pfk.project_flock_id").
|
||||||
Where("r.record_datetime >= ? AND r.record_datetime < ?", start, end).
|
Where("r.record_datetime >= ? AND r.record_datetime < ?", start, end).
|
||||||
Where("r.deleted_at IS NULL").
|
Where("r.deleted_at IS NULL").
|
||||||
Where("r.day IS NOT NULL AND r.day > 0")
|
Where("r.day IS NOT NULL AND r.day > 0")
|
||||||
@@ -694,15 +642,22 @@ func (r *DashboardRepositoryImpl) GetEggWeightWeeklyGrams(ctx context.Context, s
|
|||||||
func (r *DashboardRepositoryImpl) GetFeedUsageWeeklyByUom(ctx context.Context, start, end time.Time, filters *validation.DashboardFilter) ([]WeeklyFeedUsageMetric, error) {
|
func (r *DashboardRepositoryImpl) GetFeedUsageWeeklyByUom(ctx context.Context, start, end time.Time, filters *validation.DashboardFilter) ([]WeeklyFeedUsageMetric, error) {
|
||||||
var rows []WeeklyFeedUsageMetric
|
var rows []WeeklyFeedUsageMetric
|
||||||
|
|
||||||
|
weekExpr := `CASE
|
||||||
|
WHEN r.day IS NULL OR r.day <= 0 THEN 1
|
||||||
|
WHEN UPPER(pf.category) = 'LAYING' THEN ((r.day - 1) / 7 + 1) + 17
|
||||||
|
ELSE ((r.day - 1) / 7 + 1)
|
||||||
|
END`
|
||||||
|
|
||||||
db := r.DB().WithContext(ctx).
|
db := r.DB().WithContext(ctx).
|
||||||
Table("recording_stocks AS rs").
|
Table("recording_stocks AS rs").
|
||||||
Select(`
|
Select(fmt.Sprintf(`
|
||||||
((r.day - 1) / 7 + 1) AS week,
|
%s AS week,
|
||||||
COALESCE(SUM(rs.usage_qty), 0) + COALESCE(SUM(rs.pending_qty), 0) AS total_qty,
|
COALESCE(SUM(rs.usage_qty), 0) + COALESCE(SUM(rs.pending_qty), 0) AS total_qty,
|
||||||
LOWER(uoms.name) AS uom_name`).
|
LOWER(uoms.name) AS uom_name`, weekExpr)).
|
||||||
Joins("JOIN recordings AS r ON r.id = rs.recording_id").
|
Joins("JOIN recordings AS r ON r.id = rs.recording_id").
|
||||||
Joins("JOIN project_flock_kandangs AS pfk ON pfk.id = r.project_flock_kandangs_id").
|
Joins("JOIN project_flock_kandangs AS pfk ON pfk.id = r.project_flock_kandangs_id").
|
||||||
Joins("JOIN kandangs AS k ON k.id = pfk.kandang_id").
|
Joins("JOIN kandangs AS k ON k.id = pfk.kandang_id").
|
||||||
|
Joins("JOIN project_flocks AS pf ON pf.id = pfk.project_flock_id").
|
||||||
Joins("JOIN product_warehouses AS pw ON pw.id = rs.product_warehouse_id").
|
Joins("JOIN product_warehouses AS pw ON pw.id = rs.product_warehouse_id").
|
||||||
Joins("JOIN products AS p ON p.id = pw.product_id").
|
Joins("JOIN products AS p ON p.id = pw.product_id").
|
||||||
Joins("JOIN uoms ON uoms.id = p.uom_id").
|
Joins("JOIN uoms ON uoms.id = p.uom_id").
|
||||||
|
|||||||
@@ -21,7 +21,6 @@ import (
|
|||||||
rStockLogs "gitlab.com/mbugroup/lti-api.git/internal/modules/shared/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"
|
||||||
approvalutils "gitlab.com/mbugroup/lti-api.git/internal/utils/approvals"
|
approvalutils "gitlab.com/mbugroup/lti-api.git/internal/utils/approvals"
|
||||||
"gitlab.com/mbugroup/lti-api.git/internal/utils/fifo"
|
|
||||||
recordingutil "gitlab.com/mbugroup/lti-api.git/internal/utils/recording"
|
recordingutil "gitlab.com/mbugroup/lti-api.git/internal/utils/recording"
|
||||||
|
|
||||||
"github.com/go-playground/validator/v10"
|
"github.com/go-playground/validator/v10"
|
||||||
@@ -40,14 +39,6 @@ type RecordingService interface {
|
|||||||
Approval(ctx *fiber.Ctx, req *validation.Approve) ([]entity.Recording, error)
|
Approval(ctx *fiber.Ctx, req *validation.Approve) ([]entity.Recording, error)
|
||||||
}
|
}
|
||||||
|
|
||||||
type RecordingFIFOIntegrationService interface {
|
|
||||||
ConsumeRecordingStocks(ctx context.Context, tx *gorm.DB, stocks []entity.RecordingStock, note string, actorID uint) error
|
|
||||||
ReleaseRecordingStocks(ctx context.Context, tx *gorm.DB, stocks []entity.RecordingStock, note string, actorID uint) error
|
|
||||||
}
|
|
||||||
|
|
||||||
var recordingStockUsableKey = fifo.UsableKeyRecordingStock
|
|
||||||
var recordingDepletionUsableKey = fifo.UsableKeyRecordingDepletion
|
|
||||||
|
|
||||||
type recordingService struct {
|
type recordingService struct {
|
||||||
Log *logrus.Logger
|
Log *logrus.Logger
|
||||||
Validate *validator.Validate
|
Validate *validator.Validate
|
||||||
@@ -89,21 +80,6 @@ func NewRecordingService(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewRecordingFIFOIntegrationService(
|
|
||||||
repo repository.RecordingRepository,
|
|
||||||
productWarehouseRepo rProductWarehouse.ProductWarehouseRepository,
|
|
||||||
fifoSvc commonSvc.FifoService,
|
|
||||||
stockLogRepo rStockLogs.StockLogRepository,
|
|
||||||
) RecordingFIFOIntegrationService {
|
|
||||||
return &recordingService{
|
|
||||||
Log: utils.Log,
|
|
||||||
Repository: repo,
|
|
||||||
ProductWarehouseRepo: productWarehouseRepo,
|
|
||||||
FifoSvc: fifoSvc,
|
|
||||||
StockLogRepo: stockLogRepo,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s recordingService) GetAll(c *fiber.Ctx, params *validation.Query) ([]entity.Recording, int64, error) {
|
func (s recordingService) GetAll(c *fiber.Ctx, params *validation.Query) ([]entity.Recording, int64, error) {
|
||||||
if err := s.Validate.Struct(params); err != nil {
|
if err := s.Validate.Struct(params); err != nil {
|
||||||
return nil, 0, err
|
return nil, 0, err
|
||||||
@@ -347,7 +323,12 @@ func (s *recordingService) CreateOne(c *fiber.Ctx, req *validation.Create) (*ent
|
|||||||
}
|
}
|
||||||
|
|
||||||
var warehouseDeltas map[uint]float64
|
var warehouseDeltas map[uint]float64
|
||||||
warehouseDeltas = buildWarehouseDeltas(nil, mappedDepletions, nil, mappedEggs)
|
if s.FifoSvc != nil {
|
||||||
|
// FIFO replenish already adjusts egg warehouse quantities.
|
||||||
|
warehouseDeltas = buildWarehouseDeltas(nil, mappedDepletions, nil, nil)
|
||||||
|
} else {
|
||||||
|
warehouseDeltas = buildWarehouseDeltas(nil, mappedDepletions, nil, mappedEggs)
|
||||||
|
}
|
||||||
if err := s.adjustProductWarehouseQuantities(ctx, tx, warehouseDeltas); err != nil {
|
if err := s.adjustProductWarehouseQuantities(ctx, tx, warehouseDeltas); err != nil {
|
||||||
s.Log.Errorf("Failed to adjust product warehouses: %+v", err)
|
s.Log.Errorf("Failed to adjust product warehouses: %+v", err)
|
||||||
return err
|
return err
|
||||||
@@ -529,39 +510,9 @@ func (s recordingService) UpdateOne(c *fiber.Ctx, req *validation.Update, id uin
|
|||||||
if err := ensureRecordingEggsUnused(existingEggs); err != nil {
|
if err := ensureRecordingEggsUnused(existingEggs); err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
if s.StockLogRepo != nil {
|
note := fmt.Sprintf("Recording-Edit#%d", recordingEntity.Id)
|
||||||
note := fmt.Sprintf("Recording-Edit#%d", recordingEntity.Id)
|
if err := s.logRecordingEggUsage(ctx, tx, existingEggs, note, actorID); err != nil {
|
||||||
logs := make([]*entity.StockLog, 0, len(existingEggs))
|
return err
|
||||||
for _, egg := range existingEggs {
|
|
||||||
if egg.ProductWarehouseId == 0 || egg.Qty <= 0 {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
stockLogs, err := s.StockLogRepo.GetByProductWarehouse(ctx, egg.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")
|
|
||||||
}
|
|
||||||
latestStockLog := &entity.StockLog{}
|
|
||||||
if len(stockLogs) > 0 {
|
|
||||||
latestStockLog = stockLogs[0]
|
|
||||||
} else {
|
|
||||||
latestStockLog.Stock = 0
|
|
||||||
}
|
|
||||||
logs = append(logs, &entity.StockLog{
|
|
||||||
ProductWarehouseId: egg.ProductWarehouseId,
|
|
||||||
CreatedBy: actorID,
|
|
||||||
Decrease: float64(egg.Qty),
|
|
||||||
LoggableType: string(utils.StockLogTypeRecording),
|
|
||||||
LoggableId: recordingEntity.Id,
|
|
||||||
Notes: note,
|
|
||||||
Stock: latestStockLog.Stock - float64(egg.Qty),
|
|
||||||
})
|
|
||||||
}
|
|
||||||
if len(logs) > 0 {
|
|
||||||
if err := s.StockLogRepo.WithTx(tx).CreateMany(ctx, logs, nil); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
if err := s.adjustProductWarehouseQuantities(ctx, tx, buildWarehouseDeltas(nil, nil, existingEggs, nil)); err != nil {
|
if err := s.adjustProductWarehouseQuantities(ctx, tx, buildWarehouseDeltas(nil, nil, existingEggs, nil)); err != nil {
|
||||||
s.Log.Errorf("Failed to adjust product warehouses for eggs: %+v", err)
|
s.Log.Errorf("Failed to adjust product warehouses for eggs: %+v", err)
|
||||||
@@ -818,40 +769,6 @@ func (s recordingService) DeleteOne(c *fiber.Ctx, id uint) error {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *recordingService) logRecordingEggRollback(
|
|
||||||
ctx context.Context,
|
|
||||||
tx *gorm.DB,
|
|
||||||
eggs []entity.RecordingEgg,
|
|
||||||
note string,
|
|
||||||
actorID uint,
|
|
||||||
) error {
|
|
||||||
if len(eggs) == 0 || s.StockLogRepo == nil {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
if strings.TrimSpace(note) == "" || actorID == 0 {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
for _, egg := range eggs {
|
|
||||||
if egg.ProductWarehouseId == 0 || egg.Qty <= 0 {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
log := &entity.StockLog{
|
|
||||||
ProductWarehouseId: egg.ProductWarehouseId,
|
|
||||||
CreatedBy: actorID,
|
|
||||||
Decrease: float64(egg.Qty),
|
|
||||||
LoggableType: string(utils.StockLogTypeRecording),
|
|
||||||
LoggableId: egg.RecordingId,
|
|
||||||
Notes: note,
|
|
||||||
}
|
|
||||||
if err := s.StockLogRepo.WithTx(tx).CreateOne(ctx, log, nil); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// === Persistence Helpers ===
|
// === Persistence Helpers ===
|
||||||
|
|
||||||
func (s *recordingService) ensureProductWarehousesExist(c *fiber.Ctx, stocks []validation.Stock, depletions []validation.Depletion, eggs []validation.Egg) error {
|
func (s *recordingService) ensureProductWarehousesExist(c *fiber.Ctx, stocks []validation.Stock, depletions []validation.Depletion, eggs []validation.Egg) error {
|
||||||
@@ -891,381 +808,6 @@ func (s *recordingService) ensureProductWarehousesExist(c *fiber.Ctx, stocks []v
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *recordingService) consumeRecordingStocks(
|
|
||||||
ctx context.Context,
|
|
||||||
tx *gorm.DB,
|
|
||||||
stocks []entity.RecordingStock,
|
|
||||||
note string,
|
|
||||||
actorID uint,
|
|
||||||
) error {
|
|
||||||
if len(stocks) == 0 || s.FifoSvc == nil {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
if strings.TrimSpace(note) != "" && s.StockLogRepo == nil {
|
|
||||||
return errors.New("stock log repository is not available")
|
|
||||||
}
|
|
||||||
|
|
||||||
for _, stock := range stocks {
|
|
||||||
if stock.Id == 0 {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
|
|
||||||
var desired float64
|
|
||||||
if stock.UsageQty != nil {
|
|
||||||
desired = *stock.UsageQty
|
|
||||||
}
|
|
||||||
var pending float64
|
|
||||||
if stock.PendingQty != nil {
|
|
||||||
pending = *stock.PendingQty
|
|
||||||
}
|
|
||||||
desiredTotal := desired + pending
|
|
||||||
|
|
||||||
result, err := s.FifoSvc.Consume(ctx, commonSvc.StockConsumeRequest{
|
|
||||||
UsableKey: recordingStockUsableKey,
|
|
||||||
UsableID: stock.Id,
|
|
||||||
ProductWarehouseID: stock.ProductWarehouseId,
|
|
||||||
Quantity: desiredTotal,
|
|
||||||
AllowPending: true,
|
|
||||||
Tx: tx,
|
|
||||||
})
|
|
||||||
if err != nil {
|
|
||||||
s.Log.Errorf("Failed to consume FIFO stock for recording stock %d: %+v", stock.Id, err)
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
if err := s.Repository.UpdateStockUsage(tx, stock.Id, result.UsageQuantity, result.PendingQuantity); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
logDecrease := result.UsageQuantity
|
|
||||||
if result.PendingQuantity > 0 {
|
|
||||||
logDecrease += result.PendingQuantity
|
|
||||||
}
|
|
||||||
if logDecrease > 0 && strings.TrimSpace(note) != "" && actorID != 0 {
|
|
||||||
log := &entity.StockLog{
|
|
||||||
ProductWarehouseId: stock.ProductWarehouseId,
|
|
||||||
CreatedBy: actorID,
|
|
||||||
Decrease: logDecrease,
|
|
||||||
LoggableType: string(utils.StockLogTypeRecording),
|
|
||||||
LoggableId: stock.RecordingId,
|
|
||||||
Notes: note,
|
|
||||||
}
|
|
||||||
stockLogs, err := s.StockLogRepo.GetByProductWarehouse(ctx, stock.ProductWarehouseId, 1)
|
|
||||||
if err != nil {
|
|
||||||
return fiber.NewError(fiber.StatusInternalServerError, "Failed to get stock logs")
|
|
||||||
}
|
|
||||||
if len(stockLogs) > 0 {
|
|
||||||
latestStockLog := stockLogs[0]
|
|
||||||
log.Stock = latestStockLog.Stock
|
|
||||||
log.Stock -= log.Decrease
|
|
||||||
} else {
|
|
||||||
log.Stock -= log.Decrease
|
|
||||||
}
|
|
||||||
|
|
||||||
if err := s.StockLogRepo.WithTx(tx).CreateOne(ctx, log, nil); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *recordingService) consumeRecordingDepletions(
|
|
||||||
ctx context.Context,
|
|
||||||
tx *gorm.DB,
|
|
||||||
depletions []entity.RecordingDepletion,
|
|
||||||
note string,
|
|
||||||
actorID uint,
|
|
||||||
) error {
|
|
||||||
if len(depletions) == 0 || s.FifoSvc == nil {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
if strings.TrimSpace(note) != "" && s.StockLogRepo == nil {
|
|
||||||
return errors.New("stock log repository is not available")
|
|
||||||
}
|
|
||||||
|
|
||||||
for _, depletion := range depletions {
|
|
||||||
if depletion.Id == 0 {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
|
|
||||||
sourceWarehouseID := uint(0)
|
|
||||||
if depletion.SourceProductWarehouseId != nil {
|
|
||||||
sourceWarehouseID = *depletion.SourceProductWarehouseId
|
|
||||||
}
|
|
||||||
if sourceWarehouseID == 0 {
|
|
||||||
return fiber.NewError(fiber.StatusBadRequest, "Source product warehouse tidak ditemukan untuk depletion")
|
|
||||||
}
|
|
||||||
|
|
||||||
desired := depletion.Qty + depletion.PendingQty
|
|
||||||
result, err := s.FifoSvc.Consume(ctx, commonSvc.StockConsumeRequest{
|
|
||||||
UsableKey: recordingDepletionUsableKey,
|
|
||||||
UsableID: depletion.Id,
|
|
||||||
ProductWarehouseID: sourceWarehouseID,
|
|
||||||
Quantity: desired,
|
|
||||||
AllowPending: false,
|
|
||||||
Tx: tx,
|
|
||||||
})
|
|
||||||
if err != nil {
|
|
||||||
s.Log.Errorf("Failed to consume FIFO stock for recording depletion %d: %+v", depletion.Id, err)
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
if err := s.Repository.UpdateDepletionPending(tx, depletion.Id, result.PendingQuantity); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
logDecrease := result.UsageQuantity
|
|
||||||
if result.PendingQuantity > 0 {
|
|
||||||
logDecrease += result.PendingQuantity
|
|
||||||
}
|
|
||||||
if logDecrease > 0 && strings.TrimSpace(note) != "" && actorID != 0 {
|
|
||||||
log := &entity.StockLog{
|
|
||||||
ProductWarehouseId: sourceWarehouseID,
|
|
||||||
CreatedBy: actorID,
|
|
||||||
Decrease: logDecrease,
|
|
||||||
LoggableType: string(utils.StockLogTypeRecording),
|
|
||||||
LoggableId: depletion.RecordingId,
|
|
||||||
Notes: note,
|
|
||||||
}
|
|
||||||
stockLogs, err := s.StockLogRepo.GetByProductWarehouse(ctx, sourceWarehouseID, 1)
|
|
||||||
if err != nil {
|
|
||||||
return fiber.NewError(fiber.StatusInternalServerError, "Failed to get stock logs")
|
|
||||||
}
|
|
||||||
if len(stockLogs) > 0 {
|
|
||||||
latestStockLog := stockLogs[0]
|
|
||||||
log.Stock = latestStockLog.Stock
|
|
||||||
log.Stock -= log.Decrease
|
|
||||||
} else {
|
|
||||||
log.Stock -= log.Decrease
|
|
||||||
}
|
|
||||||
|
|
||||||
if err := s.StockLogRepo.WithTx(tx).CreateOne(ctx, log, nil); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
destDelta := depletion.Qty + depletion.PendingQty
|
|
||||||
if depletion.ProductWarehouseId != 0 && destDelta > 0 && strings.TrimSpace(note) != "" && actorID != 0 {
|
|
||||||
if depletion.ProductWarehouseId == sourceWarehouseID {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
log := &entity.StockLog{
|
|
||||||
ProductWarehouseId: depletion.ProductWarehouseId,
|
|
||||||
CreatedBy: actorID,
|
|
||||||
Increase: destDelta,
|
|
||||||
LoggableType: string(utils.StockLogTypeRecording),
|
|
||||||
LoggableId: depletion.RecordingId,
|
|
||||||
Notes: note,
|
|
||||||
}
|
|
||||||
stockLogs, err := s.StockLogRepo.GetByProductWarehouse(ctx, depletion.ProductWarehouseId, 1)
|
|
||||||
if err != nil {
|
|
||||||
return fiber.NewError(fiber.StatusInternalServerError, "Failed to get stock logs")
|
|
||||||
}
|
|
||||||
if len(stockLogs) > 0 {
|
|
||||||
latestStockLog := stockLogs[0]
|
|
||||||
log.Stock = latestStockLog.Stock
|
|
||||||
log.Stock += log.Increase
|
|
||||||
} else {
|
|
||||||
log.Stock += log.Increase
|
|
||||||
}
|
|
||||||
|
|
||||||
if err := s.StockLogRepo.WithTx(tx).CreateOne(ctx, log, nil); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *recordingService) ConsumeRecordingStocks(
|
|
||||||
ctx context.Context,
|
|
||||||
tx *gorm.DB,
|
|
||||||
stocks []entity.RecordingStock,
|
|
||||||
note string,
|
|
||||||
actorID uint,
|
|
||||||
) error {
|
|
||||||
return s.consumeRecordingStocks(ctx, tx, stocks, note, actorID)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *recordingService) releaseRecordingStocks(
|
|
||||||
ctx context.Context,
|
|
||||||
tx *gorm.DB,
|
|
||||||
stocks []entity.RecordingStock,
|
|
||||||
note string,
|
|
||||||
actorID uint,
|
|
||||||
) error {
|
|
||||||
if len(stocks) == 0 || s.FifoSvc == nil {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
if strings.TrimSpace(note) != "" && s.StockLogRepo == nil {
|
|
||||||
return errors.New("stock log repository is not available")
|
|
||||||
}
|
|
||||||
|
|
||||||
for _, stock := range stocks {
|
|
||||||
if stock.Id == 0 {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
|
|
||||||
if err := s.FifoSvc.ReleaseUsage(ctx, commonSvc.StockReleaseRequest{
|
|
||||||
UsableKey: recordingStockUsableKey,
|
|
||||||
UsableID: stock.Id,
|
|
||||||
Tx: tx,
|
|
||||||
}); err != nil {
|
|
||||||
s.Log.Errorf("Failed to release FIFO stock for recording stock %d: %+v", stock.Id, err)
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
if err := s.Repository.UpdateStockUsage(tx, stock.Id, 0, 0); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
if stock.UsageQty != nil && *stock.UsageQty > 0 && strings.TrimSpace(note) != "" && actorID != 0 {
|
|
||||||
log := &entity.StockLog{
|
|
||||||
ProductWarehouseId: stock.ProductWarehouseId,
|
|
||||||
CreatedBy: actorID,
|
|
||||||
Increase: *stock.UsageQty,
|
|
||||||
LoggableType: string(utils.StockLogTypeRecording),
|
|
||||||
LoggableId: stock.RecordingId,
|
|
||||||
Notes: note,
|
|
||||||
}
|
|
||||||
stockLogs, err := s.StockLogRepo.GetByProductWarehouse(ctx, stock.ProductWarehouseId, 1)
|
|
||||||
if err != nil {
|
|
||||||
return fiber.NewError(fiber.StatusInternalServerError, "Failed to get stock logs")
|
|
||||||
}
|
|
||||||
if len(stockLogs) > 0 {
|
|
||||||
latestStockLog := stockLogs[0]
|
|
||||||
log.Stock = latestStockLog.Stock
|
|
||||||
log.Stock += log.Increase
|
|
||||||
} else {
|
|
||||||
log.Stock += log.Increase
|
|
||||||
}
|
|
||||||
|
|
||||||
if err := s.StockLogRepo.WithTx(tx).CreateOne(ctx, log, nil); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *recordingService) releaseRecordingDepletions(
|
|
||||||
ctx context.Context,
|
|
||||||
tx *gorm.DB,
|
|
||||||
depletions []entity.RecordingDepletion,
|
|
||||||
note string,
|
|
||||||
actorID uint,
|
|
||||||
) error {
|
|
||||||
if len(depletions) == 0 || s.FifoSvc == nil {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
if strings.TrimSpace(note) != "" && s.StockLogRepo == nil {
|
|
||||||
return errors.New("stock log repository is not available")
|
|
||||||
}
|
|
||||||
|
|
||||||
for _, depletion := range depletions {
|
|
||||||
if depletion.Id == 0 {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
|
|
||||||
sourceWarehouseID := uint(0)
|
|
||||||
if depletion.SourceProductWarehouseId != nil {
|
|
||||||
sourceWarehouseID = *depletion.SourceProductWarehouseId
|
|
||||||
}
|
|
||||||
if sourceWarehouseID == 0 {
|
|
||||||
return fiber.NewError(fiber.StatusBadRequest, "Source product warehouse tidak ditemukan untuk depletion")
|
|
||||||
}
|
|
||||||
|
|
||||||
if err := s.FifoSvc.ReleaseUsage(ctx, commonSvc.StockReleaseRequest{
|
|
||||||
UsableKey: recordingDepletionUsableKey,
|
|
||||||
UsableID: depletion.Id,
|
|
||||||
Tx: tx,
|
|
||||||
}); err != nil {
|
|
||||||
s.Log.Errorf("Failed to release FIFO stock for recording depletion %d: %+v", depletion.Id, err)
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
if err := s.Repository.UpdateDepletionPending(tx, depletion.Id, 0); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
logIncrease := depletion.Qty
|
|
||||||
if depletion.PendingQty > 0 {
|
|
||||||
logIncrease += depletion.PendingQty
|
|
||||||
}
|
|
||||||
if logIncrease > 0 && strings.TrimSpace(note) != "" && actorID != 0 {
|
|
||||||
log := &entity.StockLog{
|
|
||||||
ProductWarehouseId: sourceWarehouseID,
|
|
||||||
CreatedBy: actorID,
|
|
||||||
Increase: logIncrease,
|
|
||||||
LoggableType: string(utils.StockLogTypeRecording),
|
|
||||||
LoggableId: depletion.RecordingId,
|
|
||||||
Notes: note,
|
|
||||||
}
|
|
||||||
stockLogs, err := s.StockLogRepo.GetByProductWarehouse(ctx, sourceWarehouseID, 1)
|
|
||||||
if err != nil {
|
|
||||||
return fiber.NewError(fiber.StatusInternalServerError, "Failed to get stock logs")
|
|
||||||
}
|
|
||||||
if len(stockLogs) > 0 {
|
|
||||||
latestStockLog := stockLogs[0]
|
|
||||||
log.Stock = latestStockLog.Stock
|
|
||||||
log.Stock += log.Increase
|
|
||||||
} else {
|
|
||||||
log.Stock += log.Increase
|
|
||||||
}
|
|
||||||
|
|
||||||
if err := s.StockLogRepo.WithTx(tx).CreateOne(ctx, log, nil); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
destDelta := depletion.Qty + depletion.PendingQty
|
|
||||||
if depletion.ProductWarehouseId != 0 && destDelta > 0 && strings.TrimSpace(note) != "" && actorID != 0 {
|
|
||||||
if depletion.ProductWarehouseId == sourceWarehouseID {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
log := &entity.StockLog{
|
|
||||||
ProductWarehouseId: depletion.ProductWarehouseId,
|
|
||||||
CreatedBy: actorID,
|
|
||||||
Decrease: destDelta,
|
|
||||||
LoggableType: string(utils.StockLogTypeRecording),
|
|
||||||
LoggableId: depletion.RecordingId,
|
|
||||||
Notes: note,
|
|
||||||
}
|
|
||||||
stockLogs, err := s.StockLogRepo.GetByProductWarehouse(ctx, depletion.ProductWarehouseId, 1)
|
|
||||||
if err != nil {
|
|
||||||
return fiber.NewError(fiber.StatusInternalServerError, "Failed to get stock logs")
|
|
||||||
}
|
|
||||||
if len(stockLogs) > 0 {
|
|
||||||
latestStockLog := stockLogs[0]
|
|
||||||
log.Stock = latestStockLog.Stock
|
|
||||||
log.Stock -= log.Decrease
|
|
||||||
} else {
|
|
||||||
log.Stock -= log.Decrease
|
|
||||||
}
|
|
||||||
|
|
||||||
if err := s.StockLogRepo.WithTx(tx).CreateOne(ctx, log, nil); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *recordingService) ReleaseRecordingStocks(
|
|
||||||
ctx context.Context,
|
|
||||||
tx *gorm.DB,
|
|
||||||
stocks []entity.RecordingStock,
|
|
||||||
note string,
|
|
||||||
actorID uint,
|
|
||||||
) error {
|
|
||||||
return s.releaseRecordingStocks(ctx, tx, stocks, note, actorID)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *recordingService) resolvePopulationWarehouseID(ctx context.Context, projectFlockKandangID uint) (uint, error) {
|
func (s *recordingService) resolvePopulationWarehouseID(ctx context.Context, projectFlockKandangID uint) (uint, error) {
|
||||||
if projectFlockKandangID == 0 {
|
if projectFlockKandangID == 0 {
|
||||||
return 0, fiber.NewError(fiber.StatusBadRequest, "Project flock kandang tidak valid")
|
return 0, fiber.NewError(fiber.StatusBadRequest, "Project flock kandang tidak valid")
|
||||||
@@ -1356,212 +898,6 @@ func (s *recordingService) adjustProductWarehouseQuantities(ctx context.Context,
|
|||||||
return s.ProductWarehouseRepo.AdjustQuantities(ctx, deltas, func(*gorm.DB) *gorm.DB { return tx })
|
return s.ProductWarehouseRepo.AdjustQuantities(ctx, deltas, func(*gorm.DB) *gorm.DB { return tx })
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *recordingService) replenishRecordingEggs(
|
|
||||||
ctx context.Context,
|
|
||||||
tx *gorm.DB,
|
|
||||||
eggs []entity.RecordingEgg,
|
|
||||||
note string,
|
|
||||||
actorID uint,
|
|
||||||
) error {
|
|
||||||
if len(eggs) == 0 || s.FifoSvc == nil {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
if strings.TrimSpace(note) != "" && s.StockLogRepo == nil {
|
|
||||||
return errors.New("stock log repository is not available")
|
|
||||||
}
|
|
||||||
|
|
||||||
for _, egg := range eggs {
|
|
||||||
if egg.Id == 0 || egg.ProductWarehouseId == 0 || egg.Qty <= 0 {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
if _, err := s.FifoSvc.Replenish(ctx, commonSvc.StockReplenishRequest{
|
|
||||||
StockableKey: fifo.StockableKeyRecordingEgg,
|
|
||||||
StockableID: egg.Id,
|
|
||||||
ProductWarehouseID: egg.ProductWarehouseId,
|
|
||||||
Quantity: float64(egg.Qty),
|
|
||||||
Tx: tx,
|
|
||||||
}); err != nil {
|
|
||||||
s.Log.Errorf("Failed to replenish FIFO stock for recording egg %d: %+v", egg.Id, err)
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
if strings.TrimSpace(note) != "" && actorID != 0 {
|
|
||||||
log := &entity.StockLog{
|
|
||||||
ProductWarehouseId: egg.ProductWarehouseId,
|
|
||||||
CreatedBy: actorID,
|
|
||||||
Increase: float64(egg.Qty),
|
|
||||||
LoggableType: string(utils.StockLogTypeRecording),
|
|
||||||
LoggableId: egg.RecordingId,
|
|
||||||
Notes: note,
|
|
||||||
}
|
|
||||||
stockLogs, err := s.StockLogRepo.GetByProductWarehouse(ctx, egg.ProductWarehouseId, 1)
|
|
||||||
if err != nil {
|
|
||||||
return fiber.NewError(fiber.StatusInternalServerError, "Failed to get stock logs")
|
|
||||||
}
|
|
||||||
if len(stockLogs) > 0 {
|
|
||||||
latestStockLog := stockLogs[0]
|
|
||||||
log.Stock = latestStockLog.Stock
|
|
||||||
log.Stock += log.Increase
|
|
||||||
} else {
|
|
||||||
log.Stock += log.Increase
|
|
||||||
}
|
|
||||||
|
|
||||||
if err := s.StockLogRepo.WithTx(tx).CreateOne(ctx, log, nil); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
type desiredStock struct {
|
|
||||||
Usage float64
|
|
||||||
Pending float64
|
|
||||||
}
|
|
||||||
|
|
||||||
type desiredDepletion struct {
|
|
||||||
Qty float64
|
|
||||||
Pending float64
|
|
||||||
}
|
|
||||||
|
|
||||||
func resetStockQuantitiesForFIFO(stocks []entity.RecordingStock, enabled bool) []desiredStock {
|
|
||||||
desired := make([]desiredStock, len(stocks))
|
|
||||||
for i := range stocks {
|
|
||||||
if stocks[i].UsageQty != nil {
|
|
||||||
desired[i].Usage = *stocks[i].UsageQty
|
|
||||||
}
|
|
||||||
if stocks[i].PendingQty != nil {
|
|
||||||
desired[i].Pending = *stocks[i].PendingQty
|
|
||||||
}
|
|
||||||
if !enabled {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
zero := 0.0
|
|
||||||
stocks[i].UsageQty = &zero
|
|
||||||
stocks[i].PendingQty = &zero
|
|
||||||
}
|
|
||||||
return desired
|
|
||||||
}
|
|
||||||
|
|
||||||
func applyStockDesiredQuantities(stocks []entity.RecordingStock, desired []desiredStock, enabled bool) {
|
|
||||||
if !enabled {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
for i := range stocks {
|
|
||||||
if i >= len(desired) {
|
|
||||||
break
|
|
||||||
}
|
|
||||||
usage := desired[i].Usage
|
|
||||||
pending := desired[i].Pending
|
|
||||||
stocks[i].UsageQty = &usage
|
|
||||||
stocks[i].PendingQty = &pending
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func resetDepletionQuantitiesForFIFO(depletions []entity.RecordingDepletion, enabled bool) []desiredDepletion {
|
|
||||||
desired := make([]desiredDepletion, len(depletions))
|
|
||||||
for i := range depletions {
|
|
||||||
desired[i].Qty = depletions[i].Qty
|
|
||||||
desired[i].Pending = depletions[i].PendingQty
|
|
||||||
if !enabled {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
depletions[i].Qty = 0
|
|
||||||
depletions[i].PendingQty = 0
|
|
||||||
}
|
|
||||||
return desired
|
|
||||||
}
|
|
||||||
|
|
||||||
func applyDepletionDesiredQuantities(depletions []entity.RecordingDepletion, desired []desiredDepletion, enabled bool) {
|
|
||||||
if !enabled {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
for i := range depletions {
|
|
||||||
if i >= len(desired) {
|
|
||||||
break
|
|
||||||
}
|
|
||||||
depletions[i].Qty = desired[i].Qty
|
|
||||||
depletions[i].PendingQty = desired[i].Pending
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *recordingService) syncRecordingStocks(
|
|
||||||
ctx context.Context,
|
|
||||||
tx *gorm.DB,
|
|
||||||
recordingID uint,
|
|
||||||
existing []entity.RecordingStock,
|
|
||||||
incoming []validation.Stock,
|
|
||||||
note string,
|
|
||||||
actorID uint,
|
|
||||||
) error {
|
|
||||||
if s.FifoSvc == nil {
|
|
||||||
if err := s.Repository.DeleteStocks(tx, recordingID); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
mapped := recordingutil.MapStocks(recordingID, incoming)
|
|
||||||
return s.Repository.CreateStocks(tx, mapped)
|
|
||||||
}
|
|
||||||
|
|
||||||
existingByWarehouse := make(map[uint][]entity.RecordingStock)
|
|
||||||
for _, stock := range existing {
|
|
||||||
existingByWarehouse[stock.ProductWarehouseId] = append(existingByWarehouse[stock.ProductWarehouseId], stock)
|
|
||||||
}
|
|
||||||
|
|
||||||
stocksToConsume := make([]entity.RecordingStock, 0, len(incoming))
|
|
||||||
for _, item := range incoming {
|
|
||||||
list := existingByWarehouse[item.ProductWarehouseId]
|
|
||||||
var stock entity.RecordingStock
|
|
||||||
if len(list) > 0 {
|
|
||||||
stock = list[0]
|
|
||||||
existingByWarehouse[item.ProductWarehouseId] = list[1:]
|
|
||||||
} else {
|
|
||||||
zero := 0.0
|
|
||||||
stock = entity.RecordingStock{
|
|
||||||
RecordingId: recordingID,
|
|
||||||
ProductWarehouseId: item.ProductWarehouseId,
|
|
||||||
UsageQty: &zero,
|
|
||||||
PendingQty: &zero,
|
|
||||||
}
|
|
||||||
if err := tx.Create(&stock).Error; err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
desired := item.Qty
|
|
||||||
stock.UsageQty = &desired
|
|
||||||
zero := 0.0
|
|
||||||
stock.PendingQty = &zero
|
|
||||||
stocksToConsume = append(stocksToConsume, stock)
|
|
||||||
}
|
|
||||||
|
|
||||||
var leftovers []entity.RecordingStock
|
|
||||||
for _, list := range existingByWarehouse {
|
|
||||||
leftovers = append(leftovers, list...)
|
|
||||||
}
|
|
||||||
if len(leftovers) > 0 {
|
|
||||||
if err := s.releaseRecordingStocks(ctx, tx, leftovers, note, actorID); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
ids := make([]uint, 0, len(leftovers))
|
|
||||||
for _, stock := range leftovers {
|
|
||||||
if stock.Id != 0 {
|
|
||||||
ids = append(ids, stock.Id)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if len(ids) > 0 {
|
|
||||||
if err := tx.Where("id IN ?", ids).Delete(&entity.RecordingStock{}).Error; err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if len(stocksToConsume) == 0 {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
return s.consumeRecordingStocks(ctx, tx, stocksToConsume, note, actorID)
|
|
||||||
}
|
|
||||||
|
|
||||||
type eggTotals struct {
|
type eggTotals struct {
|
||||||
Qty int
|
Qty int
|
||||||
Weight float64
|
Weight float64
|
||||||
@@ -1999,16 +1335,17 @@ func (s *recordingService) attachProductionStandard(ctx context.Context, item *e
|
|||||||
|
|
||||||
var standard productionStandardValues
|
var standard productionStandardValues
|
||||||
var standardFcr *float64
|
var standardFcr *float64
|
||||||
if category == string(utils.ProjectFlockCategoryLaying) {
|
detail, err := standardDetailRepo.GetByStandardIDAndWeek(ctx, standardID, week)
|
||||||
detail, err := standardDetailRepo.GetByStandardIDAndWeek(ctx, standardID, week)
|
if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
|
||||||
if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
|
return err
|
||||||
return err
|
}
|
||||||
}
|
if detail != nil {
|
||||||
if detail != nil {
|
standard.HenDay = detail.TargetHenDayProduction
|
||||||
standard.HenDay = detail.TargetHenDayProduction
|
standard.HenHouse = detail.TargetHenHouseProduction
|
||||||
standard.HenHouse = detail.TargetHenHouseProduction
|
standard.EggWeight = detail.TargetEggWeight
|
||||||
standard.EggWeight = detail.TargetEggWeight
|
standard.EggMass = detail.TargetEggMass
|
||||||
standard.EggMass = detail.TargetEggMass
|
if detail.StandardFCR != nil {
|
||||||
|
standardFcr = detail.StandardFCR
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -2019,21 +1356,6 @@ func (s *recordingService) attachProductionStandard(ctx context.Context, item *e
|
|||||||
if growthDetail != nil {
|
if growthDetail != nil {
|
||||||
standard.FeedIntake = growthDetail.FeedIntake
|
standard.FeedIntake = growthDetail.FeedIntake
|
||||||
standard.MaxDepletion = growthDetail.MaxDepletion
|
standard.MaxDepletion = growthDetail.MaxDepletion
|
||||||
if category == string(utils.ProjectFlockCategoryLaying) && growthDetail.TargetMeanBw != nil && item.ProjectFlockKandang.ProjectFlock.FcrId > 0 {
|
|
||||||
targetWeight := *growthDetail.TargetMeanBw
|
|
||||||
if targetWeight > 10 {
|
|
||||||
targetWeight = targetWeight / 1000
|
|
||||||
}
|
|
||||||
if targetWeight > 0 {
|
|
||||||
fcrStd, ok, err := s.Repository.GetFcrStandardNumber(db, item.ProjectFlockKandang.ProjectFlock.FcrId, targetWeight)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
if ok {
|
|
||||||
standardFcr = &fcrStd
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
item.StandardHenDay = standard.HenDay
|
item.StandardHenDay = standard.HenDay
|
||||||
|
|||||||
@@ -0,0 +1,703 @@
|
|||||||
|
package service
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
commonSvc "gitlab.com/mbugroup/lti-api.git/internal/common/service"
|
||||||
|
entity "gitlab.com/mbugroup/lti-api.git/internal/entities"
|
||||||
|
rProductWarehouse "gitlab.com/mbugroup/lti-api.git/internal/modules/inventory/product-warehouses/repositories"
|
||||||
|
repository "gitlab.com/mbugroup/lti-api.git/internal/modules/production/recordings/repositories"
|
||||||
|
validation "gitlab.com/mbugroup/lti-api.git/internal/modules/production/recordings/validations"
|
||||||
|
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"
|
||||||
|
recordingutil "gitlab.com/mbugroup/lti-api.git/internal/utils/recording"
|
||||||
|
|
||||||
|
"github.com/gofiber/fiber/v2"
|
||||||
|
"gorm.io/gorm"
|
||||||
|
)
|
||||||
|
|
||||||
|
type RecordingFIFOIntegrationService interface {
|
||||||
|
ConsumeRecordingStocks(ctx context.Context, tx *gorm.DB, stocks []entity.RecordingStock, note string, actorID uint) error
|
||||||
|
ReleaseRecordingStocks(ctx context.Context, tx *gorm.DB, stocks []entity.RecordingStock, note string, actorID uint) error
|
||||||
|
}
|
||||||
|
|
||||||
|
var recordingStockUsableKey = fifo.UsableKeyRecordingStock
|
||||||
|
var recordingDepletionUsableKey = fifo.UsableKeyRecordingDepletion
|
||||||
|
|
||||||
|
func NewRecordingFIFOIntegrationService(
|
||||||
|
repo repository.RecordingRepository,
|
||||||
|
productWarehouseRepo rProductWarehouse.ProductWarehouseRepository,
|
||||||
|
fifoSvc commonSvc.FifoService,
|
||||||
|
stockLogRepo rStockLogs.StockLogRepository,
|
||||||
|
) RecordingFIFOIntegrationService {
|
||||||
|
return &recordingService{
|
||||||
|
Log: utils.Log,
|
||||||
|
Repository: repo,
|
||||||
|
ProductWarehouseRepo: productWarehouseRepo,
|
||||||
|
FifoSvc: fifoSvc,
|
||||||
|
StockLogRepo: stockLogRepo,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *recordingService) consumeRecordingStocks(
|
||||||
|
ctx context.Context,
|
||||||
|
tx *gorm.DB,
|
||||||
|
stocks []entity.RecordingStock,
|
||||||
|
note string,
|
||||||
|
actorID uint,
|
||||||
|
) error {
|
||||||
|
if len(stocks) == 0 || s.FifoSvc == nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
if strings.TrimSpace(note) != "" && s.StockLogRepo == nil {
|
||||||
|
return errors.New("stock log repository is not available")
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, stock := range stocks {
|
||||||
|
if stock.Id == 0 {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
var desired float64
|
||||||
|
if stock.UsageQty != nil {
|
||||||
|
desired = *stock.UsageQty
|
||||||
|
}
|
||||||
|
var pending float64
|
||||||
|
if stock.PendingQty != nil {
|
||||||
|
pending = *stock.PendingQty
|
||||||
|
}
|
||||||
|
desiredTotal := desired + pending
|
||||||
|
|
||||||
|
result, err := s.FifoSvc.Consume(ctx, commonSvc.StockConsumeRequest{
|
||||||
|
UsableKey: recordingStockUsableKey,
|
||||||
|
UsableID: stock.Id,
|
||||||
|
ProductWarehouseID: stock.ProductWarehouseId,
|
||||||
|
Quantity: desiredTotal,
|
||||||
|
AllowPending: true,
|
||||||
|
Tx: tx,
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
s.Log.Errorf("Failed to consume FIFO stock for recording stock %d: %+v", stock.Id, err)
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := s.Repository.UpdateStockUsage(tx, stock.Id, result.UsageQuantity, result.PendingQuantity); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
logDecrease := result.UsageQuantity
|
||||||
|
if result.PendingQuantity > 0 {
|
||||||
|
logDecrease += result.PendingQuantity
|
||||||
|
}
|
||||||
|
if logDecrease > 0 && strings.TrimSpace(note) != "" && actorID != 0 {
|
||||||
|
log := &entity.StockLog{
|
||||||
|
ProductWarehouseId: stock.ProductWarehouseId,
|
||||||
|
CreatedBy: actorID,
|
||||||
|
Decrease: logDecrease,
|
||||||
|
LoggableType: string(utils.StockLogTypeRecording),
|
||||||
|
LoggableId: stock.RecordingId,
|
||||||
|
Notes: note,
|
||||||
|
}
|
||||||
|
stockLogs, err := s.StockLogRepo.GetByProductWarehouse(ctx, stock.ProductWarehouseId, 1)
|
||||||
|
if err != nil {
|
||||||
|
return fiber.NewError(fiber.StatusInternalServerError, "Failed to get stock logs")
|
||||||
|
}
|
||||||
|
if len(stockLogs) > 0 {
|
||||||
|
latestStockLog := stockLogs[0]
|
||||||
|
log.Stock = latestStockLog.Stock
|
||||||
|
log.Stock -= log.Decrease
|
||||||
|
} else {
|
||||||
|
log.Stock -= log.Decrease
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := s.StockLogRepo.WithTx(tx).CreateOne(ctx, log, nil); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *recordingService) consumeRecordingDepletions(
|
||||||
|
ctx context.Context,
|
||||||
|
tx *gorm.DB,
|
||||||
|
depletions []entity.RecordingDepletion,
|
||||||
|
note string,
|
||||||
|
actorID uint,
|
||||||
|
) error {
|
||||||
|
if len(depletions) == 0 || s.FifoSvc == nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
if strings.TrimSpace(note) != "" && s.StockLogRepo == nil {
|
||||||
|
return errors.New("stock log repository is not available")
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, depletion := range depletions {
|
||||||
|
if depletion.Id == 0 {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
sourceWarehouseID := uint(0)
|
||||||
|
if depletion.SourceProductWarehouseId != nil {
|
||||||
|
sourceWarehouseID = *depletion.SourceProductWarehouseId
|
||||||
|
}
|
||||||
|
if sourceWarehouseID == 0 {
|
||||||
|
return fiber.NewError(fiber.StatusBadRequest, "Source product warehouse tidak ditemukan untuk depletion")
|
||||||
|
}
|
||||||
|
|
||||||
|
desired := depletion.Qty + depletion.PendingQty
|
||||||
|
result, err := s.FifoSvc.Consume(ctx, commonSvc.StockConsumeRequest{
|
||||||
|
UsableKey: recordingDepletionUsableKey,
|
||||||
|
UsableID: depletion.Id,
|
||||||
|
ProductWarehouseID: sourceWarehouseID,
|
||||||
|
Quantity: desired,
|
||||||
|
AllowPending: false,
|
||||||
|
Tx: tx,
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
s.Log.Errorf("Failed to consume FIFO stock for recording depletion %d: %+v", depletion.Id, err)
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := s.Repository.UpdateDepletionPending(tx, depletion.Id, result.PendingQuantity); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
logDecrease := result.UsageQuantity
|
||||||
|
if result.PendingQuantity > 0 {
|
||||||
|
logDecrease += result.PendingQuantity
|
||||||
|
}
|
||||||
|
if logDecrease > 0 && strings.TrimSpace(note) != "" && actorID != 0 {
|
||||||
|
log := &entity.StockLog{
|
||||||
|
ProductWarehouseId: sourceWarehouseID,
|
||||||
|
CreatedBy: actorID,
|
||||||
|
Decrease: logDecrease,
|
||||||
|
LoggableType: string(utils.StockLogTypeRecording),
|
||||||
|
LoggableId: depletion.RecordingId,
|
||||||
|
Notes: note,
|
||||||
|
}
|
||||||
|
stockLogs, err := s.StockLogRepo.GetByProductWarehouse(ctx, sourceWarehouseID, 1)
|
||||||
|
if err != nil {
|
||||||
|
return fiber.NewError(fiber.StatusInternalServerError, "Failed to get stock logs")
|
||||||
|
}
|
||||||
|
if len(stockLogs) > 0 {
|
||||||
|
latestStockLog := stockLogs[0]
|
||||||
|
log.Stock = latestStockLog.Stock
|
||||||
|
log.Stock -= log.Decrease
|
||||||
|
} else {
|
||||||
|
log.Stock -= log.Decrease
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := s.StockLogRepo.WithTx(tx).CreateOne(ctx, log, nil); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
destDelta := depletion.Qty + depletion.PendingQty
|
||||||
|
if depletion.ProductWarehouseId != 0 && destDelta > 0 && strings.TrimSpace(note) != "" && actorID != 0 {
|
||||||
|
if depletion.ProductWarehouseId == sourceWarehouseID {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
log := &entity.StockLog{
|
||||||
|
ProductWarehouseId: depletion.ProductWarehouseId,
|
||||||
|
CreatedBy: actorID,
|
||||||
|
Increase: destDelta,
|
||||||
|
LoggableType: string(utils.StockLogTypeRecording),
|
||||||
|
LoggableId: depletion.RecordingId,
|
||||||
|
Notes: note,
|
||||||
|
}
|
||||||
|
stockLogs, err := s.StockLogRepo.GetByProductWarehouse(ctx, depletion.ProductWarehouseId, 1)
|
||||||
|
if err != nil {
|
||||||
|
return fiber.NewError(fiber.StatusInternalServerError, "Failed to get stock logs")
|
||||||
|
}
|
||||||
|
if len(stockLogs) > 0 {
|
||||||
|
latestStockLog := stockLogs[0]
|
||||||
|
log.Stock = latestStockLog.Stock
|
||||||
|
log.Stock += log.Increase
|
||||||
|
} else {
|
||||||
|
log.Stock += log.Increase
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := s.StockLogRepo.WithTx(tx).CreateOne(ctx, log, nil); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *recordingService) ConsumeRecordingStocks(
|
||||||
|
ctx context.Context,
|
||||||
|
tx *gorm.DB,
|
||||||
|
stocks []entity.RecordingStock,
|
||||||
|
note string,
|
||||||
|
actorID uint,
|
||||||
|
) error {
|
||||||
|
return s.consumeRecordingStocks(ctx, tx, stocks, note, actorID)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *recordingService) releaseRecordingStocks(
|
||||||
|
ctx context.Context,
|
||||||
|
tx *gorm.DB,
|
||||||
|
stocks []entity.RecordingStock,
|
||||||
|
note string,
|
||||||
|
actorID uint,
|
||||||
|
) error {
|
||||||
|
if len(stocks) == 0 || s.FifoSvc == nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
if strings.TrimSpace(note) != "" && s.StockLogRepo == nil {
|
||||||
|
return errors.New("stock log repository is not available")
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, stock := range stocks {
|
||||||
|
if stock.Id == 0 {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if err := s.FifoSvc.ReleaseUsage(ctx, commonSvc.StockReleaseRequest{
|
||||||
|
UsableKey: recordingStockUsableKey,
|
||||||
|
UsableID: stock.Id,
|
||||||
|
Tx: tx,
|
||||||
|
}); err != nil {
|
||||||
|
s.Log.Errorf("Failed to release FIFO stock for recording stock %d: %+v", stock.Id, err)
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := s.Repository.UpdateStockUsage(tx, stock.Id, 0, 0); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
if stock.UsageQty != nil && *stock.UsageQty > 0 && strings.TrimSpace(note) != "" && actorID != 0 {
|
||||||
|
log := &entity.StockLog{
|
||||||
|
ProductWarehouseId: stock.ProductWarehouseId,
|
||||||
|
CreatedBy: actorID,
|
||||||
|
Increase: *stock.UsageQty,
|
||||||
|
LoggableType: string(utils.StockLogTypeRecording),
|
||||||
|
LoggableId: stock.RecordingId,
|
||||||
|
Notes: note,
|
||||||
|
}
|
||||||
|
stockLogs, err := s.StockLogRepo.GetByProductWarehouse(ctx, stock.ProductWarehouseId, 1)
|
||||||
|
if err != nil {
|
||||||
|
return fiber.NewError(fiber.StatusInternalServerError, "Failed to get stock logs")
|
||||||
|
}
|
||||||
|
if len(stockLogs) > 0 {
|
||||||
|
latestStockLog := stockLogs[0]
|
||||||
|
log.Stock = latestStockLog.Stock
|
||||||
|
log.Stock += log.Increase
|
||||||
|
} else {
|
||||||
|
log.Stock += log.Increase
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := s.StockLogRepo.WithTx(tx).CreateOne(ctx, log, nil); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *recordingService) releaseRecordingDepletions(
|
||||||
|
ctx context.Context,
|
||||||
|
tx *gorm.DB,
|
||||||
|
depletions []entity.RecordingDepletion,
|
||||||
|
note string,
|
||||||
|
actorID uint,
|
||||||
|
) error {
|
||||||
|
if len(depletions) == 0 || s.FifoSvc == nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
if strings.TrimSpace(note) != "" && s.StockLogRepo == nil {
|
||||||
|
return errors.New("stock log repository is not available")
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, depletion := range depletions {
|
||||||
|
if depletion.Id == 0 {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
sourceWarehouseID := uint(0)
|
||||||
|
if depletion.SourceProductWarehouseId != nil {
|
||||||
|
sourceWarehouseID = *depletion.SourceProductWarehouseId
|
||||||
|
}
|
||||||
|
if sourceWarehouseID == 0 {
|
||||||
|
return fiber.NewError(fiber.StatusBadRequest, "Source product warehouse tidak ditemukan untuk depletion")
|
||||||
|
}
|
||||||
|
if err := s.FifoSvc.ReleaseUsage(ctx, commonSvc.StockReleaseRequest{
|
||||||
|
UsableKey: recordingDepletionUsableKey,
|
||||||
|
UsableID: depletion.Id,
|
||||||
|
Tx: tx,
|
||||||
|
}); err != nil {
|
||||||
|
s.Log.Errorf("Failed to release FIFO stock for recording depletion %d: %+v", depletion.Id, err)
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := s.Repository.UpdateDepletionPending(tx, depletion.Id, 0); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
logIncrease := depletion.Qty
|
||||||
|
if depletion.PendingQty > 0 {
|
||||||
|
logIncrease += depletion.PendingQty
|
||||||
|
}
|
||||||
|
if logIncrease > 0 && strings.TrimSpace(note) != "" && actorID != 0 {
|
||||||
|
log := &entity.StockLog{
|
||||||
|
ProductWarehouseId: sourceWarehouseID,
|
||||||
|
CreatedBy: actorID,
|
||||||
|
Increase: logIncrease,
|
||||||
|
LoggableType: string(utils.StockLogTypeRecording),
|
||||||
|
LoggableId: depletion.RecordingId,
|
||||||
|
Notes: note,
|
||||||
|
}
|
||||||
|
stockLogs, err := s.StockLogRepo.GetByProductWarehouse(ctx, sourceWarehouseID, 1)
|
||||||
|
if err != nil {
|
||||||
|
return fiber.NewError(fiber.StatusInternalServerError, "Failed to get stock logs")
|
||||||
|
}
|
||||||
|
if len(stockLogs) > 0 {
|
||||||
|
latestStockLog := stockLogs[0]
|
||||||
|
log.Stock = latestStockLog.Stock
|
||||||
|
log.Stock += log.Increase
|
||||||
|
} else {
|
||||||
|
log.Stock += log.Increase
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := s.StockLogRepo.WithTx(tx).CreateOne(ctx, log, nil); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
destDelta := depletion.Qty + depletion.PendingQty
|
||||||
|
if depletion.ProductWarehouseId != 0 && destDelta > 0 && strings.TrimSpace(note) != "" && actorID != 0 {
|
||||||
|
if depletion.ProductWarehouseId == sourceWarehouseID {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
log := &entity.StockLog{
|
||||||
|
ProductWarehouseId: depletion.ProductWarehouseId,
|
||||||
|
CreatedBy: actorID,
|
||||||
|
Decrease: destDelta,
|
||||||
|
LoggableType: string(utils.StockLogTypeRecording),
|
||||||
|
LoggableId: depletion.RecordingId,
|
||||||
|
Notes: note,
|
||||||
|
}
|
||||||
|
stockLogs, err := s.StockLogRepo.GetByProductWarehouse(ctx, depletion.ProductWarehouseId, 1)
|
||||||
|
if err != nil {
|
||||||
|
return fiber.NewError(fiber.StatusInternalServerError, "Failed to get stock logs")
|
||||||
|
}
|
||||||
|
if len(stockLogs) > 0 {
|
||||||
|
latestStockLog := stockLogs[0]
|
||||||
|
log.Stock = latestStockLog.Stock
|
||||||
|
log.Stock -= log.Decrease
|
||||||
|
} else {
|
||||||
|
log.Stock -= log.Decrease
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := s.StockLogRepo.WithTx(tx).CreateOne(ctx, log, nil); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *recordingService) ReleaseRecordingStocks(
|
||||||
|
ctx context.Context,
|
||||||
|
tx *gorm.DB,
|
||||||
|
stocks []entity.RecordingStock,
|
||||||
|
note string,
|
||||||
|
actorID uint,
|
||||||
|
) error {
|
||||||
|
return s.releaseRecordingStocks(ctx, tx, stocks, note, actorID)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *recordingService) logRecordingEggUsage(
|
||||||
|
ctx context.Context,
|
||||||
|
tx *gorm.DB,
|
||||||
|
eggs []entity.RecordingEgg,
|
||||||
|
note string,
|
||||||
|
actorID uint,
|
||||||
|
) error {
|
||||||
|
if len(eggs) == 0 || s.StockLogRepo == nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
if strings.TrimSpace(note) == "" || actorID == 0 {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
logs := make([]*entity.StockLog, 0, len(eggs))
|
||||||
|
for _, egg := range eggs {
|
||||||
|
if egg.ProductWarehouseId == 0 || egg.Qty <= 0 {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
stockLogs, err := s.StockLogRepo.GetByProductWarehouse(ctx, egg.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")
|
||||||
|
}
|
||||||
|
latestStockLog := &entity.StockLog{}
|
||||||
|
if len(stockLogs) > 0 {
|
||||||
|
latestStockLog = stockLogs[0]
|
||||||
|
} else {
|
||||||
|
latestStockLog.Stock = 0
|
||||||
|
}
|
||||||
|
logs = append(logs, &entity.StockLog{
|
||||||
|
ProductWarehouseId: egg.ProductWarehouseId,
|
||||||
|
CreatedBy: actorID,
|
||||||
|
Decrease: float64(egg.Qty),
|
||||||
|
LoggableType: string(utils.StockLogTypeRecording),
|
||||||
|
LoggableId: egg.RecordingId,
|
||||||
|
Notes: note,
|
||||||
|
Stock: latestStockLog.Stock - float64(egg.Qty),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
if len(logs) == 0 {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
return s.StockLogRepo.WithTx(tx).CreateMany(ctx, logs, nil)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *recordingService) logRecordingEggRollback(
|
||||||
|
ctx context.Context,
|
||||||
|
tx *gorm.DB,
|
||||||
|
eggs []entity.RecordingEgg,
|
||||||
|
note string,
|
||||||
|
actorID uint,
|
||||||
|
) error {
|
||||||
|
if len(eggs) == 0 || s.StockLogRepo == nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
if strings.TrimSpace(note) == "" || actorID == 0 {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, egg := range eggs {
|
||||||
|
if egg.ProductWarehouseId == 0 || egg.Qty <= 0 {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
log := &entity.StockLog{
|
||||||
|
ProductWarehouseId: egg.ProductWarehouseId,
|
||||||
|
CreatedBy: actorID,
|
||||||
|
Decrease: float64(egg.Qty),
|
||||||
|
LoggableType: string(utils.StockLogTypeRecording),
|
||||||
|
LoggableId: egg.RecordingId,
|
||||||
|
Notes: note,
|
||||||
|
}
|
||||||
|
if err := s.StockLogRepo.WithTx(tx).CreateOne(ctx, log, nil); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *recordingService) replenishRecordingEggs(
|
||||||
|
ctx context.Context,
|
||||||
|
tx *gorm.DB,
|
||||||
|
eggs []entity.RecordingEgg,
|
||||||
|
note string,
|
||||||
|
actorID uint,
|
||||||
|
) error {
|
||||||
|
if len(eggs) == 0 || s.FifoSvc == nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
if strings.TrimSpace(note) != "" && s.StockLogRepo == nil {
|
||||||
|
return errors.New("stock log repository is not available")
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, egg := range eggs {
|
||||||
|
if egg.Id == 0 || egg.ProductWarehouseId == 0 || egg.Qty <= 0 {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if _, err := s.FifoSvc.Replenish(ctx, commonSvc.StockReplenishRequest{
|
||||||
|
StockableKey: fifo.StockableKeyRecordingEgg,
|
||||||
|
StockableID: egg.Id,
|
||||||
|
ProductWarehouseID: egg.ProductWarehouseId,
|
||||||
|
Quantity: float64(egg.Qty),
|
||||||
|
Tx: tx,
|
||||||
|
}); err != nil {
|
||||||
|
s.Log.Errorf("Failed to replenish FIFO stock for recording egg %d: %+v", egg.Id, err)
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
if strings.TrimSpace(note) != "" && actorID != 0 {
|
||||||
|
log := &entity.StockLog{
|
||||||
|
ProductWarehouseId: egg.ProductWarehouseId,
|
||||||
|
CreatedBy: actorID,
|
||||||
|
Increase: float64(egg.Qty),
|
||||||
|
LoggableType: string(utils.StockLogTypeRecording),
|
||||||
|
LoggableId: egg.RecordingId,
|
||||||
|
Notes: note,
|
||||||
|
}
|
||||||
|
stockLogs, err := s.StockLogRepo.GetByProductWarehouse(ctx, egg.ProductWarehouseId, 1)
|
||||||
|
if err != nil {
|
||||||
|
return fiber.NewError(fiber.StatusInternalServerError, "Failed to get stock logs")
|
||||||
|
}
|
||||||
|
if len(stockLogs) > 0 {
|
||||||
|
latestStockLog := stockLogs[0]
|
||||||
|
log.Stock = latestStockLog.Stock
|
||||||
|
log.Stock += log.Increase
|
||||||
|
} else {
|
||||||
|
log.Stock += log.Increase
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := s.StockLogRepo.WithTx(tx).CreateOne(ctx, log, nil); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
type desiredStock struct {
|
||||||
|
Usage float64
|
||||||
|
Pending float64
|
||||||
|
}
|
||||||
|
|
||||||
|
type desiredDepletion struct {
|
||||||
|
Qty float64
|
||||||
|
Pending float64
|
||||||
|
}
|
||||||
|
|
||||||
|
func resetStockQuantitiesForFIFO(stocks []entity.RecordingStock, enabled bool) []desiredStock {
|
||||||
|
desired := make([]desiredStock, len(stocks))
|
||||||
|
for i := range stocks {
|
||||||
|
if stocks[i].UsageQty != nil {
|
||||||
|
desired[i].Usage = *stocks[i].UsageQty
|
||||||
|
}
|
||||||
|
if stocks[i].PendingQty != nil {
|
||||||
|
desired[i].Pending = *stocks[i].PendingQty
|
||||||
|
}
|
||||||
|
if !enabled {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
zero := 0.0
|
||||||
|
stocks[i].UsageQty = &zero
|
||||||
|
stocks[i].PendingQty = &zero
|
||||||
|
}
|
||||||
|
return desired
|
||||||
|
}
|
||||||
|
|
||||||
|
func applyStockDesiredQuantities(stocks []entity.RecordingStock, desired []desiredStock, enabled bool) {
|
||||||
|
if !enabled {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
for i := range stocks {
|
||||||
|
if i >= len(desired) {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
usage := desired[i].Usage
|
||||||
|
pending := desired[i].Pending
|
||||||
|
stocks[i].UsageQty = &usage
|
||||||
|
stocks[i].PendingQty = &pending
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func resetDepletionQuantitiesForFIFO(depletions []entity.RecordingDepletion, enabled bool) []desiredDepletion {
|
||||||
|
desired := make([]desiredDepletion, len(depletions))
|
||||||
|
for i := range depletions {
|
||||||
|
desired[i].Qty = depletions[i].Qty
|
||||||
|
desired[i].Pending = depletions[i].PendingQty
|
||||||
|
if !enabled {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
depletions[i].Qty = 0
|
||||||
|
depletions[i].PendingQty = 0
|
||||||
|
}
|
||||||
|
return desired
|
||||||
|
}
|
||||||
|
|
||||||
|
func applyDepletionDesiredQuantities(depletions []entity.RecordingDepletion, desired []desiredDepletion, enabled bool) {
|
||||||
|
if !enabled {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
for i := range depletions {
|
||||||
|
if i >= len(desired) {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
depletions[i].Qty = desired[i].Qty
|
||||||
|
depletions[i].PendingQty = desired[i].Pending
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *recordingService) syncRecordingStocks(
|
||||||
|
ctx context.Context,
|
||||||
|
tx *gorm.DB,
|
||||||
|
recordingID uint,
|
||||||
|
existing []entity.RecordingStock,
|
||||||
|
incoming []validation.Stock,
|
||||||
|
note string,
|
||||||
|
actorID uint,
|
||||||
|
) error {
|
||||||
|
if s.FifoSvc == nil {
|
||||||
|
if err := s.Repository.DeleteStocks(tx, recordingID); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
mapped := recordingutil.MapStocks(recordingID, incoming)
|
||||||
|
return s.Repository.CreateStocks(tx, mapped)
|
||||||
|
}
|
||||||
|
|
||||||
|
existingByWarehouse := make(map[uint][]entity.RecordingStock)
|
||||||
|
for _, stock := range existing {
|
||||||
|
existingByWarehouse[stock.ProductWarehouseId] = append(existingByWarehouse[stock.ProductWarehouseId], stock)
|
||||||
|
}
|
||||||
|
|
||||||
|
stocksToConsume := make([]entity.RecordingStock, 0, len(incoming))
|
||||||
|
for _, item := range incoming {
|
||||||
|
list := existingByWarehouse[item.ProductWarehouseId]
|
||||||
|
var stock entity.RecordingStock
|
||||||
|
if len(list) > 0 {
|
||||||
|
stock = list[0]
|
||||||
|
existingByWarehouse[item.ProductWarehouseId] = list[1:]
|
||||||
|
} else {
|
||||||
|
zero := 0.0
|
||||||
|
stock = entity.RecordingStock{
|
||||||
|
RecordingId: recordingID,
|
||||||
|
ProductWarehouseId: item.ProductWarehouseId,
|
||||||
|
UsageQty: &zero,
|
||||||
|
PendingQty: &zero,
|
||||||
|
}
|
||||||
|
if err := tx.Create(&stock).Error; err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
desired := item.Qty
|
||||||
|
stock.UsageQty = &desired
|
||||||
|
zero := 0.0
|
||||||
|
stock.PendingQty = &zero
|
||||||
|
stocksToConsume = append(stocksToConsume, stock)
|
||||||
|
}
|
||||||
|
|
||||||
|
var leftovers []entity.RecordingStock
|
||||||
|
for _, list := range existingByWarehouse {
|
||||||
|
leftovers = append(leftovers, list...)
|
||||||
|
}
|
||||||
|
if len(leftovers) > 0 {
|
||||||
|
if err := s.releaseRecordingStocks(ctx, tx, leftovers, note, actorID); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
ids := make([]uint, 0, len(leftovers))
|
||||||
|
for _, stock := range leftovers {
|
||||||
|
if stock.Id != 0 {
|
||||||
|
ids = append(ids, stock.Id)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if len(ids) > 0 {
|
||||||
|
if err := tx.Where("id IN ?", ids).Delete(&entity.RecordingStock{}).Error; err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(stocksToConsume) == 0 {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return s.consumeRecordingStocks(ctx, tx, stocksToConsume, note, actorID)
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user