mirror of
https://gitlab.com/mbugroup/lti-api.git
synced 2026-05-20 13:31:56 +00:00
FIX[BE]: fix logic on Chickin Laying not convert to layer but still Pullet, and inisiate laying transfer migration and base basic API
This commit is contained in:
@@ -1 +1 @@
|
||||
DROP TABLE IF EXISTS laying_transfers;
|
||||
DROP TABLE IF EXISTS laying_transfers CASCADE;
|
||||
@@ -1,14 +1,15 @@
|
||||
CREATE TABLE IF NOT EXISTS laying_transfers (
|
||||
id BIGSERIAL PRIMARY KEY,
|
||||
transfer_number VARCHAR(50) UNIQUE NOT NULL,
|
||||
from_project_flock_id BIGINT NOT NULL,
|
||||
to_project_flock_id BIGINT NOT NULL,
|
||||
transfer_date DATE NOT NULL,
|
||||
total_qty INTEGER,
|
||||
total_qty NUMERIC(15, 3) NOT NULL,
|
||||
notes TEXT,
|
||||
created_at TIMESTAMPTZ DEFAULT now(),
|
||||
updated_at TIMESTAMPTZ DEFAULT now(),
|
||||
deleted_at TIMESTAMPTZ,
|
||||
created_by BIGINT
|
||||
created_by BIGINT NOT NULL
|
||||
);
|
||||
|
||||
-- FOREIGN KEYS (dijalankan setelah semua tabel parent ada)
|
||||
@@ -37,6 +38,10 @@ BEGIN
|
||||
END $$;
|
||||
|
||||
-- INDEXES
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS idx_laying_transfers_transfer_number ON laying_transfers (transfer_number)
|
||||
WHERE
|
||||
deleted_at IS NULL;
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_laying_transfers_from_project_flock_id ON laying_transfers (from_project_flock_id);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_laying_transfers_to_project_flock_id ON laying_transfers (to_project_flock_id);
|
||||
|
||||
-1
@@ -1 +0,0 @@
|
||||
DROP TABLE IF EXISTS laying_kandang_transfers;
|
||||
-40
@@ -1,40 +0,0 @@
|
||||
CREATE TABLE IF NOT EXISTS laying_kandang_transfers (
|
||||
id BIGSERIAL PRIMARY KEY,
|
||||
kandang_id BIGINT,
|
||||
product_warehouse_id BIGINT,
|
||||
qty NUMERIC(15,3),
|
||||
laying_transfer_id BIGINT NOT NULL
|
||||
);
|
||||
|
||||
-- FOREIGN KEYS (dijalankan setelah semua tabel parent ada)
|
||||
DO $$
|
||||
BEGIN
|
||||
IF EXISTS (SELECT 1 FROM pg_tables WHERE tablename = 'kandangs') THEN
|
||||
ALTER TABLE laying_kandang_transfers
|
||||
ADD CONSTRAINT fk_laying_kandang_transfers_kandang
|
||||
FOREIGN KEY (kandang_id)
|
||||
REFERENCES kandangs(id)
|
||||
ON DELETE RESTRICT ON UPDATE CASCADE;
|
||||
END IF;
|
||||
|
||||
IF EXISTS (SELECT 1 FROM pg_tables WHERE tablename = 'product_warehouses') THEN
|
||||
ALTER TABLE laying_kandang_transfers
|
||||
ADD CONSTRAINT fk_laying_kandang_transfers_product_warehouse
|
||||
FOREIGN KEY (product_warehouse_id)
|
||||
REFERENCES product_warehouses(id)
|
||||
ON DELETE RESTRICT ON UPDATE CASCADE;
|
||||
END IF;
|
||||
|
||||
IF EXISTS (SELECT 1 FROM pg_tables WHERE tablename = 'laying_transfers') THEN
|
||||
ALTER TABLE laying_kandang_transfers
|
||||
ADD CONSTRAINT fk_laying_kandang_transfers_laying_transfer
|
||||
FOREIGN KEY (laying_transfer_id)
|
||||
REFERENCES laying_transfers(id)
|
||||
ON DELETE RESTRICT ON UPDATE CASCADE;
|
||||
END IF;
|
||||
END $$;
|
||||
|
||||
-- INDEXES
|
||||
CREATE INDEX IF NOT EXISTS idx_laying_kandang_transfers_kandang_id ON laying_kandang_transfers(kandang_id);
|
||||
CREATE INDEX IF NOT EXISTS idx_laying_kandang_transfers_product_warehouse_id ON laying_kandang_transfers(product_warehouse_id);
|
||||
CREATE INDEX IF NOT EXISTS idx_laying_kandang_transfers_laying_transfer_id ON laying_kandang_transfers(laying_transfer_id);
|
||||
+5
@@ -0,0 +1,5 @@
|
||||
-- Rollback laying_transfer_sources dan laying_transfer_targets tables
|
||||
|
||||
DROP TABLE IF EXISTS laying_transfer_targets CASCADE;
|
||||
|
||||
DROP TABLE IF EXISTS laying_transfer_sources CASCADE;
|
||||
+93
@@ -0,0 +1,93 @@
|
||||
-- Create laying_transfer_sources dan laying_transfer_targets tables
|
||||
|
||||
-- 1. Create laying_transfer_sources table (detail sumber - kandang asal growing)
|
||||
CREATE TABLE laying_transfer_sources (
|
||||
id BIGSERIAL PRIMARY KEY,
|
||||
laying_transfer_id BIGINT NOT NULL,
|
||||
source_project_flock_kandang_id BIGINT NOT NULL,
|
||||
product_warehouse_id BIGINT,
|
||||
qty NUMERIC(15, 3) NOT NULL,
|
||||
note TEXT,
|
||||
created_at TIMESTAMPTZ DEFAULT NOW(),
|
||||
updated_at TIMESTAMPTZ DEFAULT NOW(),
|
||||
deleted_at TIMESTAMPTZ
|
||||
);
|
||||
|
||||
-- Add foreign keys untuk laying_transfer_sources
|
||||
DO $$
|
||||
BEGIN
|
||||
IF EXISTS (SELECT 1 FROM pg_tables WHERE tablename = 'laying_transfers') THEN
|
||||
ALTER TABLE laying_transfer_sources
|
||||
ADD CONSTRAINT fk_laying_transfer_sources_laying_transfer_id
|
||||
FOREIGN KEY (laying_transfer_id) REFERENCES laying_transfers(id) ON DELETE CASCADE;
|
||||
END IF;
|
||||
|
||||
IF EXISTS (SELECT 1 FROM pg_tables WHERE tablename = 'project_flock_kandangs') THEN
|
||||
ALTER TABLE laying_transfer_sources
|
||||
ADD CONSTRAINT fk_laying_transfer_sources_project_flock_kandang_id
|
||||
FOREIGN KEY (source_project_flock_kandang_id) REFERENCES project_flock_kandangs(id) ON DELETE RESTRICT;
|
||||
END IF;
|
||||
|
||||
IF EXISTS (SELECT 1 FROM pg_tables WHERE tablename = 'product_warehouses') THEN
|
||||
ALTER TABLE laying_transfer_sources
|
||||
ADD CONSTRAINT fk_laying_transfer_sources_product_warehouse_id
|
||||
FOREIGN KEY (product_warehouse_id) REFERENCES product_warehouses(id) ON DELETE SET NULL;
|
||||
END IF;
|
||||
END $$;
|
||||
|
||||
-- 2. Create laying_transfer_targets table (detail tujuan - kandang laying)
|
||||
CREATE TABLE laying_transfer_targets (
|
||||
id BIGSERIAL PRIMARY KEY,
|
||||
laying_transfer_id BIGINT NOT NULL,
|
||||
target_project_flock_kandang_id BIGINT NOT NULL,
|
||||
qty NUMERIC(15, 3) NOT NULL,
|
||||
product_warehouse_id BIGINT,
|
||||
note TEXT,
|
||||
created_at TIMESTAMPTZ DEFAULT NOW(),
|
||||
updated_at TIMESTAMPTZ DEFAULT NOW(),
|
||||
deleted_at TIMESTAMPTZ
|
||||
);
|
||||
|
||||
-- Add foreign keys untuk laying_transfer_targets
|
||||
DO $$
|
||||
BEGIN
|
||||
IF EXISTS (SELECT 1 FROM pg_tables WHERE tablename = 'laying_transfers') THEN
|
||||
ALTER TABLE laying_transfer_targets
|
||||
ADD CONSTRAINT fk_laying_transfer_targets_laying_transfer_id
|
||||
FOREIGN KEY (laying_transfer_id) REFERENCES laying_transfers(id) ON DELETE CASCADE;
|
||||
END IF;
|
||||
|
||||
IF EXISTS (SELECT 1 FROM pg_tables WHERE tablename = 'project_flock_kandangs') THEN
|
||||
ALTER TABLE laying_transfer_targets
|
||||
ADD CONSTRAINT fk_laying_transfer_targets_project_flock_kandang_id
|
||||
FOREIGN KEY (target_project_flock_kandang_id) REFERENCES project_flock_kandangs(id) ON DELETE RESTRICT;
|
||||
END IF;
|
||||
|
||||
IF EXISTS (SELECT 1 FROM pg_tables WHERE tablename = 'product_warehouses') THEN
|
||||
ALTER TABLE laying_transfer_targets
|
||||
ADD CONSTRAINT fk_laying_transfer_targets_product_warehouse_id
|
||||
FOREIGN KEY (product_warehouse_id) REFERENCES product_warehouses(id) ON DELETE SET NULL;
|
||||
END IF;
|
||||
END $$;
|
||||
|
||||
-- 3. Create indexes untuk laying_transfer_sources
|
||||
CREATE INDEX idx_laying_transfer_sources_laying_transfer_id ON laying_transfer_sources (laying_transfer_id);
|
||||
|
||||
CREATE INDEX idx_laying_transfer_sources_source_kandang_id ON laying_transfer_sources (
|
||||
source_project_flock_kandang_id
|
||||
);
|
||||
|
||||
CREATE INDEX idx_laying_transfer_sources_product_warehouse_id ON laying_transfer_sources (product_warehouse_id);
|
||||
|
||||
CREATE INDEX idx_laying_transfer_sources_deleted_at ON laying_transfer_sources (deleted_at);
|
||||
|
||||
-- 4. Create indexes untuk laying_transfer_targets
|
||||
CREATE INDEX idx_laying_transfer_targets_laying_transfer_id ON laying_transfer_targets (laying_transfer_id);
|
||||
|
||||
CREATE INDEX idx_laying_transfer_targets_target_kandang_id ON laying_transfer_targets (
|
||||
target_project_flock_kandang_id
|
||||
);
|
||||
|
||||
CREATE INDEX idx_laying_transfer_targets_product_warehouse_id ON laying_transfer_targets (product_warehouse_id);
|
||||
|
||||
CREATE INDEX idx_laying_transfer_targets_deleted_at ON laying_transfer_targets (deleted_at);
|
||||
@@ -258,7 +258,7 @@ func seedProjectFlocks(tx *gorm.DB, createdBy uint, flocks, areas, fcrs, locatio
|
||||
Flock: "Flock Priangan",
|
||||
Area: "Priangan",
|
||||
Category: utils.ProjectFlockCategoryGrowing,
|
||||
Fcr: "FCR Layer",
|
||||
Fcr: "FCR DOC",
|
||||
Location: "Singaparna",
|
||||
Period: 1,
|
||||
},
|
||||
@@ -267,7 +267,7 @@ func seedProjectFlocks(tx *gorm.DB, createdBy uint, flocks, areas, fcrs, locatio
|
||||
Flock: "Flock Banten",
|
||||
Area: "Banten",
|
||||
Category: utils.ProjectFlockCategoryGrowing,
|
||||
Fcr: "FCR Layer",
|
||||
Fcr: "FCR DOC",
|
||||
Location: "Cikaum",
|
||||
Period: 1,
|
||||
},
|
||||
@@ -574,7 +574,6 @@ func seedProductCategories(tx *gorm.DB, createdBy uint) (map[string]uint, error)
|
||||
{"Bahan Baku", "RAW"},
|
||||
{"Day Old Chick", "DOC"},
|
||||
{"Pullet", "PULLET"},
|
||||
{"Layer", "LAYER"},
|
||||
}
|
||||
|
||||
result := make(map[string]uint, len(seeds))
|
||||
@@ -698,14 +697,25 @@ func seedFcr(tx *gorm.DB, createdBy uint) (map[string]uint, error) {
|
||||
}
|
||||
}{
|
||||
{
|
||||
Name: "FCR Layer",
|
||||
Name: "FCR DOC",
|
||||
Standards: []struct {
|
||||
Weight float64
|
||||
FcrNumber float64
|
||||
Mortality float64
|
||||
}{
|
||||
{Weight: 0.8, FcrNumber: 1.60, Mortality: 2.0},
|
||||
{Weight: 1.5, FcrNumber: 1.75, Mortality: 3.5},
|
||||
{Weight: 0.1, FcrNumber: 1.20, Mortality: 1.0},
|
||||
{Weight: 0.3, FcrNumber: 1.35, Mortality: 1.5},
|
||||
},
|
||||
},
|
||||
{
|
||||
Name: "FCR Pullet",
|
||||
Standards: []struct {
|
||||
Weight float64
|
||||
FcrNumber float64
|
||||
Mortality float64
|
||||
}{
|
||||
{Weight: 0.5, FcrNumber: 1.45, Mortality: 2.0},
|
||||
{Weight: 0.8, FcrNumber: 1.50, Mortality: 2.5},
|
||||
},
|
||||
},
|
||||
}
|
||||
@@ -809,16 +819,6 @@ func seedProducts(tx *gorm.DB, createdBy uint, uoms map[string]uint, categories
|
||||
Suppliers: []string{"PT CHAROEN POKPHAND INDONESIA Tbk"},
|
||||
Flags: []utils.FlagType{utils.FlagPullet},
|
||||
},
|
||||
{
|
||||
Name: "Ayam Layer",
|
||||
Brand: "MBU Layer",
|
||||
Sku: "LAY0001",
|
||||
Uom: "Ekor",
|
||||
Category: "Layer",
|
||||
Price: 20000,
|
||||
Suppliers: []string{"PT CHAROEN POKPHAND INDONESIA Tbk"},
|
||||
Flags: []utils.FlagType{utils.FlagLayer},
|
||||
},
|
||||
}
|
||||
|
||||
for _, seed := range seeds {
|
||||
|
||||
@@ -8,17 +8,21 @@ import (
|
||||
|
||||
type LayingTransfer struct {
|
||||
Id uint `gorm:"primaryKey"`
|
||||
TransferNumber string `gorm:"uniqueIndex;not null"`
|
||||
FromProjectFlockId uint `gorm:"not null"`
|
||||
ToProjectFlockId uint `gorm:"not null"`
|
||||
TotalQty float64 `gorm:"type:numeric(15,3)"`
|
||||
TransferDate time.Time `gorm:"type:date;not null"`
|
||||
TotalQty float64 `gorm:"type:numeric(15,3);not null"`
|
||||
Notes string `gorm:"type:text"`
|
||||
CreatedBy uint `gorm:"not null"`
|
||||
CreatedAt time.Time `gorm:"autoCreateTime"`
|
||||
UpdatedAt time.Time `gorm:"autoUpdateTime"`
|
||||
DeletedAt gorm.DeletedAt `gorm:"index"`
|
||||
|
||||
FromProjectFlock *ProjectFlock `gorm:"foreignKey:FromProjectFlockId;references:Id"`
|
||||
ToProjectFlock *ProjectFlock `gorm:"foreignKey:ToProjectFlockId;references:Id"`
|
||||
CreatedUser *User `gorm:"foreignKey:CreatedBy;references:Id"`
|
||||
FromProjectFlock *ProjectFlock `gorm:"foreignKey:FromProjectFlockId;references:Id"`
|
||||
ToProjectFlock *ProjectFlock `gorm:"foreignKey:ToProjectFlockId;references:Id"`
|
||||
CreatedUser *User `gorm:"foreignKey:CreatedBy;references:Id"`
|
||||
Sources []LayingTransferSource `gorm:"foreignKey:LayingTransferId;constraint:OnDelete:CASCADE"`
|
||||
Targets []LayingTransferTarget `gorm:"foreignKey:LayingTransferId;constraint:OnDelete:CASCADE"`
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
package entities
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type LayingTransferSource struct {
|
||||
Id uint `gorm:"primaryKey"`
|
||||
LayingTransferId uint `gorm:"index;not null"`
|
||||
SourceProjectFlockKandangId uint `gorm:"not null"`
|
||||
ProductWarehouseId *uint `gorm:""`
|
||||
Qty float64 `gorm:"type:numeric(15,3);not null"`
|
||||
Note string `gorm:"type:text"`
|
||||
CreatedAt time.Time `gorm:"autoCreateTime"`
|
||||
UpdatedAt time.Time `gorm:"autoUpdateTime"`
|
||||
DeletedAt gorm.DeletedAt `gorm:"index"`
|
||||
|
||||
LayingTransfer *LayingTransfer `gorm:"foreignKey:LayingTransferId;references:Id"`
|
||||
SourceProjectFlockKandang *ProjectFlockKandang `gorm:"foreignKey:SourceProjectFlockKandangId;references:Id"`
|
||||
ProductWarehouse *ProductWarehouse `gorm:"foreignKey:ProductWarehouseId;references:Id"`
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
package entities
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type LayingTransferTarget struct {
|
||||
Id uint `gorm:"primaryKey"`
|
||||
LayingTransferId uint `gorm:"index;not null"`
|
||||
TargetProjectFlockKandangId uint `gorm:"not null"`
|
||||
Qty float64 `gorm:"type:numeric(15,3);not null"`
|
||||
ProductWarehouseId *uint `gorm:""`
|
||||
Note string `gorm:"type:text"`
|
||||
CreatedAt time.Time `gorm:"autoCreateTime"`
|
||||
UpdatedAt time.Time `gorm:"autoUpdateTime"`
|
||||
DeletedAt gorm.DeletedAt `gorm:"index"`
|
||||
|
||||
LayingTransfer *LayingTransfer `gorm:"foreignKey:LayingTransferId;references:Id"`
|
||||
TargetProjectFlockKandang *ProjectFlockKandang `gorm:"foreignKey:TargetProjectFlockKandangId;references:Id"`
|
||||
ProductWarehouse *ProductWarehouse `gorm:"foreignKey:ProductWarehouseId;references:Id"`
|
||||
}
|
||||
|
||||
@@ -12,6 +12,7 @@ type ProjectChickinRepository interface {
|
||||
repository.BaseRepository[entity.ProjectChickin]
|
||||
GetFirstByProjectFlockID(ctx context.Context, projectFlockID uint) (*entity.ProjectChickin, error)
|
||||
GetByProjectFlockKandangID(ctx context.Context, projectFlockKandangID uint) ([]entity.ProjectChickin, error)
|
||||
GetPendingByProjectFlockKandangID(ctx context.Context, projectFlockKandangID uint) ([]entity.ProjectChickin, error)
|
||||
}
|
||||
|
||||
type ChickinRepositoryImpl struct {
|
||||
@@ -49,3 +50,17 @@ func (r *ChickinRepositoryImpl) GetByProjectFlockKandangID(ctx context.Context,
|
||||
}
|
||||
return chickins, nil
|
||||
}
|
||||
|
||||
func (r *ChickinRepositoryImpl) GetPendingByProjectFlockKandangID(ctx context.Context, projectFlockKandangID uint) ([]entity.ProjectChickin, error) {
|
||||
var chickins []entity.ProjectChickin
|
||||
err := r.db.WithContext(ctx).
|
||||
Where("project_flock_kandang_id = ?", projectFlockKandangID).
|
||||
Where("usage_qty = 0").
|
||||
Where("pending_usage_qty > 0").
|
||||
Order("created_at DESC").
|
||||
Find(&chickins).Error
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return chickins, nil
|
||||
}
|
||||
|
||||
@@ -150,8 +150,12 @@ func (s *chickinService) CreateOne(c *fiber.Ctx, req *validation.Create) ([]enti
|
||||
actorID := uint(1) // todo nanti ambil dari auth context
|
||||
newChikins := make([]*entity.ProjectChickin, 0)
|
||||
for _, productWarehouse := range productWarehouses {
|
||||
availableQty, err := s.calculateAvailableQuantity(c, req.ProjectFlockKandangId, &productWarehouse, category)
|
||||
if err != nil {
|
||||
s.Log.Warnf("Failed to calculate available quantity for product warehouse %d: %v", productWarehouse.Id, err)
|
||||
}
|
||||
|
||||
if productWarehouse.Quantity <= 0 {
|
||||
if availableQty <= 0 {
|
||||
continue
|
||||
}
|
||||
|
||||
@@ -159,7 +163,7 @@ func (s *chickinService) CreateOne(c *fiber.Ctx, req *validation.Create) ([]enti
|
||||
ProjectFlockKandangId: req.ProjectFlockKandangId,
|
||||
ChickInDate: chickinDate,
|
||||
UsageQty: 0,
|
||||
PendingUsageQty: productWarehouse.Quantity,
|
||||
PendingUsageQty: availableQty,
|
||||
ProductWarehouseId: productWarehouse.Id,
|
||||
Notes: req.Note,
|
||||
CreatedBy: actorID,
|
||||
@@ -176,6 +180,7 @@ func (s *chickinService) CreateOne(c *fiber.Ctx, req *validation.Create) ([]enti
|
||||
if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil, fiber.NewError(fiber.StatusInternalServerError, "Failed to check existing chickins")
|
||||
}
|
||||
|
||||
isFirstTime := len(existingChikins) == 0
|
||||
|
||||
err = s.Repository.DB().WithContext(c.Context()).Transaction(func(dbTransaction *gorm.DB) error {
|
||||
@@ -192,17 +197,19 @@ func (s *chickinService) CreateOne(c *fiber.Ctx, req *validation.Create) ([]enti
|
||||
return err
|
||||
}
|
||||
|
||||
for _, chickin := range newChikins {
|
||||
if category == string(utils.ProjectFlockCategoryLaying) {
|
||||
for _, chickin := range newChikins {
|
||||
updates := map[string]any{"quantity": gorm.Expr("quantity - ?", chickin.PendingUsageQty)}
|
||||
|
||||
updates := map[string]any{"quantity": 0}
|
||||
|
||||
if err := productWarehouseTx.PatchOne(c.Context(), chickin.ProductWarehouseId, updates, nil); err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return fiber.NewError(fiber.StatusNotFound, fmt.Sprintf("Product warehouse %d not found", chickin.ProductWarehouseId))
|
||||
if err := productWarehouseTx.PatchOne(c.Context(), chickin.ProductWarehouseId, updates, nil); err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return fiber.NewError(fiber.StatusNotFound, fmt.Sprintf("Product warehouse %d not found", chickin.ProductWarehouseId))
|
||||
}
|
||||
return fiber.NewError(fiber.StatusInternalServerError, "Failed to update product warehouse quantity")
|
||||
}
|
||||
return fiber.NewError(fiber.StatusInternalServerError, "Failed to update product warehouse quantity")
|
||||
}
|
||||
}
|
||||
|
||||
var approvalAction entity.ApprovalAction
|
||||
if isFirstTime {
|
||||
approvalAction = entity.ApprovalActionCreated
|
||||
@@ -287,6 +294,56 @@ func (s chickinService) DeleteOne(c *fiber.Ctx, id uint) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s chickinService) calculateAvailableQuantity(ctx *fiber.Ctx, projectFlockKandangID uint, productWarehouse *entity.ProductWarehouse, category string) (float64, error) {
|
||||
availableQty := productWarehouse.Quantity
|
||||
|
||||
if category == string(utils.ProjectFlockCategoryGrowing) {
|
||||
var totalPendingQty float64
|
||||
|
||||
chickins, err := s.Repository.GetByProjectFlockKandangID(ctx.Context(), projectFlockKandangID)
|
||||
if err == nil {
|
||||
for _, chickin := range chickins {
|
||||
|
||||
if chickin.ProductWarehouseId == productWarehouse.Id && chickin.DeletedAt.Time.IsZero() && chickin.PendingUsageQty > 0 {
|
||||
totalPendingQty += chickin.PendingUsageQty
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
availableQty = productWarehouse.Quantity - totalPendingQty
|
||||
if availableQty < 0 {
|
||||
availableQty = 0
|
||||
}
|
||||
} else if category == string(utils.ProjectFlockCategoryLaying) {
|
||||
var totalPopulation float64
|
||||
var totalPendingQty float64
|
||||
|
||||
populations, err := s.ProjectflockPopulationRepo.GetByProjectFlockKandangIDAndProductWarehouseID(ctx.Context(), projectFlockKandangID, productWarehouse.Id)
|
||||
if err == nil {
|
||||
for _, pop := range populations {
|
||||
totalPopulation += pop.TotalQty
|
||||
}
|
||||
}
|
||||
|
||||
chickins, err := s.Repository.GetByProjectFlockKandangID(ctx.Context(), projectFlockKandangID)
|
||||
if err == nil {
|
||||
for _, chickin := range chickins {
|
||||
|
||||
if chickin.ProductWarehouseId == productWarehouse.Id && chickin.DeletedAt.Time.IsZero() && chickin.PendingUsageQty > 0 {
|
||||
totalPendingQty += chickin.PendingUsageQty
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
availableQty = productWarehouse.Quantity - totalPopulation - totalPendingQty
|
||||
if availableQty < 0 {
|
||||
availableQty = 0
|
||||
}
|
||||
}
|
||||
|
||||
return availableQty, nil
|
||||
}
|
||||
|
||||
func (s chickinService) Approval(c *fiber.Ctx, req *validation.Approve) ([]entity.ProjectChickin, error) {
|
||||
if err := s.Validate.Struct(req); err != nil {
|
||||
return nil, err
|
||||
@@ -356,7 +413,7 @@ func (s chickinService) Approval(c *fiber.Ctx, req *validation.Approve) ([]entit
|
||||
if !(strings.Contains(lower, "duplicate") || strings.Contains(lower, "unique constraint") || strings.Contains(lower, "23505")) {
|
||||
return err
|
||||
}
|
||||
s.Log.Infof("ignored duplicate approval for kandang %d: %v", approvableID, err)
|
||||
|
||||
}
|
||||
|
||||
if action == entity.ApprovalActionApproved {
|
||||
@@ -374,54 +431,76 @@ func (s chickinService) Approval(c *fiber.Ctx, req *validation.Approve) ([]entit
|
||||
return err
|
||||
}
|
||||
|
||||
warehouse, err := s.WarehouseRepo.GetByKandangID(c.Context(), kandangForApproval.KandangId)
|
||||
if err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return fiber.NewError(fiber.StatusNotFound, fmt.Sprintf("Warehouse for kandang %d not found", kandangForApproval.KandangId))
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
category := strings.ToUpper(strings.TrimSpace(kandangForApproval.ProjectFlock.Category))
|
||||
var conversionCategoryCode string
|
||||
|
||||
switch category {
|
||||
case string(utils.ProjectFlockCategoryGrowing):
|
||||
conversionCategoryCode = "PULLET"
|
||||
case string(utils.ProjectFlockCategoryLaying):
|
||||
conversionCategoryCode = "LAYER"
|
||||
default:
|
||||
return fiber.NewError(fiber.StatusBadRequest, fmt.Sprintf("Unknown category for conversion: %s", category))
|
||||
if category == string(utils.ProjectFlockCategoryGrowing) {
|
||||
warehouse, err := s.WarehouseRepo.GetByKandangID(c.Context(), kandangForApproval.KandangId)
|
||||
if err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return fiber.NewError(fiber.StatusNotFound, fmt.Sprintf("Warehouse for kandang %d not found", kandangForApproval.KandangId))
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
targetPW, err := s.getOrCreateProductWarehouse(c, warehouse.Id, "PULLET", dbTransaction, actorID)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to get/create PULLET product warehouse: %w", err)
|
||||
}
|
||||
if err := s.convertChickinsToTarget(c, chickins, targetPW, dbTransaction, actorID); err != nil {
|
||||
return err
|
||||
}
|
||||
} else if category == string(utils.ProjectFlockCategoryLaying) {
|
||||
|
||||
warehouse, err := s.WarehouseRepo.GetByKandangID(c.Context(), kandangForApproval.KandangId)
|
||||
if err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return fiber.NewError(fiber.StatusNotFound, fmt.Sprintf("Warehouse for kandang %d not found", kandangForApproval.KandangId))
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
targetPW, err := s.getOrCreateProductWarehouse(c, warehouse.Id, "PULLET", dbTransaction, actorID)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to get/create PULLET product warehouse: %w", err)
|
||||
}
|
||||
if err := s.convertChickinsToTarget(c, chickins, targetPW, dbTransaction, actorID); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
targetPW, err := s.getOrCreateProductWarehouse(c, warehouse.Id, conversionCategoryCode, dbTransaction, actorID)
|
||||
if action == entity.ApprovalActionRejected {
|
||||
|
||||
chickins, err := chickinRepoTx.GetPendingByProjectFlockKandangID(c.Context(), approvableID)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to get/create %s product warehouse: %w", conversionCategoryCode, err)
|
||||
}
|
||||
if err := s.convertChickinsToTarget(c, chickins, targetPW, dbTransaction, actorID); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
} else if action == entity.ApprovalActionRejected {
|
||||
|
||||
chickins, err := chickinRepoTx.GetByProjectFlockKandangID(c.Context(), approvableID)
|
||||
if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return fmt.Errorf("failed to get chickins for rejection %d: %w", approvableID, err)
|
||||
return fmt.Errorf("failed to get pending chickins for rejection %d: %w", approvableID, err)
|
||||
}
|
||||
|
||||
if len(chickins) == 0 {
|
||||
continue
|
||||
}
|
||||
|
||||
kandangForRejection, err := s.ProjectflockKandangRepo.GetByID(c.Context(), approvableID)
|
||||
if err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return fiber.NewError(fiber.StatusNotFound, fmt.Sprintf("ProjectFlockKandang %d not found", approvableID))
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
categoryForRejection := strings.ToUpper(strings.TrimSpace(kandangForRejection.ProjectFlock.Category))
|
||||
|
||||
for _, chickin := range chickins {
|
||||
|
||||
updates := map[string]any{"quantity": chickin.PendingUsageQty}
|
||||
if categoryForRejection == string(utils.ProjectFlockCategoryGrowing) {
|
||||
updates := map[string]any{"quantity": gorm.Expr("quantity + ?", chickin.PendingUsageQty)}
|
||||
|
||||
if err := productWarehouseTx.PatchOne(c.Context(), chickin.ProductWarehouseId, updates, nil); err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return fiber.NewError(fiber.StatusNotFound, fmt.Sprintf("Product warehouse %d not found during rejection", chickin.ProductWarehouseId))
|
||||
if err := productWarehouseTx.PatchOne(c.Context(), chickin.ProductWarehouseId, updates, nil); err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return fiber.NewError(fiber.StatusNotFound, fmt.Sprintf("Product warehouse %d not found during rejection", chickin.ProductWarehouseId))
|
||||
}
|
||||
return fmt.Errorf("failed to restore product warehouse quantity for chickin %d: %w", chickin.Id, err)
|
||||
}
|
||||
return fmt.Errorf("failed to restore product warehouse quantity for chickin %d: %w", chickin.Id, err)
|
||||
}
|
||||
|
||||
if err := chickinRepoTx.DeleteOne(c.Context(), chickin.Id); err != nil {
|
||||
@@ -518,6 +597,18 @@ func (s *chickinService) convertChickinsToTarget(ctx *fiber.Ctx, chickins []enti
|
||||
return fmt.Errorf("failed to update chickin %d qty: %w", chickin.Id, err)
|
||||
}
|
||||
|
||||
if chickin.ProductWarehouseId != targetPW.Id {
|
||||
if err := productWarehouseTx.PatchOne(ctx.Context(), chickin.ProductWarehouseId, map[string]any{
|
||||
"quantity": gorm.Expr("quantity - ?", quantityToConvert),
|
||||
}, nil); err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return fiber.NewError(fiber.StatusNotFound, fmt.Sprintf("Source product warehouse %d not found", chickin.ProductWarehouseId))
|
||||
}
|
||||
return fmt.Errorf("failed to deduct source warehouse quantity for chickin %d: %w", chickin.Id, err)
|
||||
}
|
||||
}
|
||||
|
||||
// Add to target product warehouse
|
||||
if err := productWarehouseTx.PatchOne(ctx.Context(), targetPW.Id, map[string]any{
|
||||
"quantity": gorm.Expr("quantity + ?", quantityToConvert),
|
||||
}, nil); err != nil {
|
||||
|
||||
@@ -41,12 +41,12 @@ type KandangCustomDTO struct {
|
||||
|
||||
type ProductWarehouseDTO struct {
|
||||
Id uint `json:"id"`
|
||||
Quantity float64 `json:"quantity"`
|
||||
Product *productDTO.ProductBaseDTO `json:"product,omitempty"`
|
||||
Warehouse *warehouseDTO.WarehouseBaseDTO `json:"warehouse,omitempty"`
|
||||
}
|
||||
|
||||
type AvailableQtyDTO struct {
|
||||
AvailableQty float64 `json:"available_qty"`
|
||||
ProductWarehouse *ProductWarehouseDTO `json:"product_warehouse,omitempty"`
|
||||
}
|
||||
|
||||
@@ -171,10 +171,6 @@ func buildProductWarehouseFromMap(pwData map[string]interface{}) *ProductWarehou
|
||||
dto.Id = id
|
||||
}
|
||||
|
||||
if qty, ok := pwData["quantity"].(float64); ok {
|
||||
dto.Quantity = qty
|
||||
}
|
||||
|
||||
if pData, ok := pwData["product"].(map[string]interface{}); ok {
|
||||
dto.Product = buildProductFromMap(pData)
|
||||
}
|
||||
@@ -276,8 +272,7 @@ func buildAvailableQtys(chickins []entity.ProjectChickin) []AvailableQtyDTO {
|
||||
}
|
||||
|
||||
pwDTO := &ProductWarehouseDTO{
|
||||
Id: ch.ProductWarehouse.Id,
|
||||
Quantity: ch.ProductWarehouse.Quantity,
|
||||
Id: ch.ProductWarehouse.Id,
|
||||
}
|
||||
|
||||
if ch.ProductWarehouse.Product.Id != 0 {
|
||||
@@ -324,7 +319,13 @@ func buildAvailableQtysFromRaw(availableQtysRaw []map[string]interface{}) []Avai
|
||||
}
|
||||
|
||||
pwDTO := buildProductWarehouseFromMap(pwData)
|
||||
availableQty := 0.0
|
||||
if qty, ok := v["available_qty"].(float64); ok {
|
||||
availableQty = qty
|
||||
}
|
||||
|
||||
result[i] = AvailableQtyDTO{
|
||||
AvailableQty: availableQty,
|
||||
ProductWarehouse: pwDTO,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -24,6 +24,7 @@ type ProjectFlockKandangModule struct{}
|
||||
|
||||
func (ProjectFlockKandangModule) RegisterRoutes(router fiber.Router, db *gorm.DB, validate *validator.Validate) {
|
||||
projectFlockKandangRepo := rProjectFlockKandang.NewProjectFlockKandangRepository(db)
|
||||
projectFlockPopulationRepo := rProjectFlockKandang.NewProjectFlockPopulationRepository(db)
|
||||
userRepo := rUser.NewUserRepository(db)
|
||||
warehouseRepo := rWarehouse.NewWarehouseRepository(db)
|
||||
productWarehouseRepo := rProductWarehouse.NewProductWarehouseRepository(db)
|
||||
@@ -35,7 +36,7 @@ func (ProjectFlockKandangModule) RegisterRoutes(router fiber.Router, db *gorm.DB
|
||||
panic(fmt.Sprintf("failed to register project flock kandang approval workflow: %v", err))
|
||||
}
|
||||
|
||||
projectFlockKandangService := sProjectFlockKandang.NewProjectFlockKandangService(projectFlockKandangRepo, approvalService, warehouseRepo, productWarehouseRepo, validate)
|
||||
projectFlockKandangService := sProjectFlockKandang.NewProjectFlockKandangService(projectFlockKandangRepo, approvalService, warehouseRepo, productWarehouseRepo, projectFlockPopulationRepo, validate)
|
||||
userService := sUser.NewUserService(userRepo, validate)
|
||||
|
||||
ProjectFlockKandangRoutes(router, userService, projectFlockKandangService)
|
||||
|
||||
+75
-25
@@ -29,9 +29,10 @@ type projectFlockKandangService struct {
|
||||
ApprovalSvc commonSvc.ApprovalService
|
||||
WarehouseRepo rWarehouse.WarehouseRepository
|
||||
ProductWarehouseRepo rProductWarehouse.ProductWarehouseRepository
|
||||
PopulationRepo repository.ProjectFlockPopulationRepository
|
||||
}
|
||||
|
||||
func NewProjectFlockKandangService(repo repository.ProjectFlockKandangRepository, approvalSvc commonSvc.ApprovalService, warehouseRepo rWarehouse.WarehouseRepository, productWarehouseRepo rProductWarehouse.ProductWarehouseRepository, validate *validator.Validate) ProjectFlockKandangService {
|
||||
func NewProjectFlockKandangService(repo repository.ProjectFlockKandangRepository, approvalSvc commonSvc.ApprovalService, warehouseRepo rWarehouse.WarehouseRepository, productWarehouseRepo rProductWarehouse.ProductWarehouseRepository, populationRepo repository.ProjectFlockPopulationRepository, validate *validator.Validate) ProjectFlockKandangService {
|
||||
return &projectFlockKandangService{
|
||||
Log: utils.Log,
|
||||
Validate: validate,
|
||||
@@ -39,6 +40,7 @@ func NewProjectFlockKandangService(repo repository.ProjectFlockKandangRepository
|
||||
ApprovalSvc: approvalSvc,
|
||||
WarehouseRepo: warehouseRepo,
|
||||
ProductWarehouseRepo: productWarehouseRepo,
|
||||
PopulationRepo: populationRepo,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -114,32 +116,80 @@ func (s projectFlockKandangService) getAvailableQuantities(c *fiber.Ctx, project
|
||||
|
||||
var result []map[string]interface{}
|
||||
for _, pw := range products {
|
||||
if pw.Quantity > 0 {
|
||||
|
||||
productData := map[string]interface{}{
|
||||
"id": pw.Product.Id,
|
||||
"name": pw.Product.Name,
|
||||
}
|
||||
|
||||
warehouseData := map[string]interface{}{
|
||||
"id": pw.Warehouse.Id,
|
||||
"name": pw.Warehouse.Name,
|
||||
"type": pw.Warehouse.Type,
|
||||
}
|
||||
|
||||
productWarehouseData := map[string]interface{}{
|
||||
"id": pw.Id,
|
||||
"quantity": pw.Quantity,
|
||||
"product": productData,
|
||||
"warehouse": warehouseData,
|
||||
}
|
||||
|
||||
result = append(result, map[string]interface{}{
|
||||
"available_qty": pw.Quantity,
|
||||
"product_warehouse": productWarehouseData,
|
||||
})
|
||||
availableQty, err := s.calculateAvailableQuantityForProductWarehouse(c, projectFlockKandang, &pw)
|
||||
if err != nil {
|
||||
s.Log.Warnf("Failed to calculate available quantity for product warehouse %d: %v", pw.Id, err)
|
||||
}
|
||||
|
||||
// Only include product warehouse if available_qty > 0
|
||||
if availableQty <= 0 {
|
||||
continue
|
||||
}
|
||||
|
||||
productData := map[string]interface{}{
|
||||
"id": pw.Product.Id,
|
||||
"name": pw.Product.Name,
|
||||
}
|
||||
|
||||
warehouseData := map[string]interface{}{
|
||||
"id": pw.Warehouse.Id,
|
||||
"name": pw.Warehouse.Name,
|
||||
"type": pw.Warehouse.Type,
|
||||
}
|
||||
|
||||
productWarehouseData := map[string]interface{}{
|
||||
"id": pw.Id,
|
||||
"product": productData,
|
||||
"warehouse": warehouseData,
|
||||
}
|
||||
|
||||
result = append(result, map[string]interface{}{
|
||||
"available_qty": availableQty,
|
||||
"product_warehouse": productWarehouseData,
|
||||
})
|
||||
}
|
||||
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func (s projectFlockKandangService) calculateAvailableQuantityForProductWarehouse(c *fiber.Ctx, projectFlockKandang *entity.ProjectFlockKandang, productWarehouse *entity.ProductWarehouse) (float64, error) {
|
||||
availableQty := productWarehouse.Quantity
|
||||
|
||||
if projectFlockKandang.ProjectFlock.Category == string(utils.ProjectFlockCategoryGrowing) {
|
||||
var totalPendingQty float64
|
||||
|
||||
for _, chickin := range projectFlockKandang.Chickins {
|
||||
if chickin.ProductWarehouseId == productWarehouse.Id && chickin.DeletedAt.Time.IsZero() && chickin.PendingUsageQty > 0 {
|
||||
totalPendingQty += chickin.PendingUsageQty
|
||||
}
|
||||
}
|
||||
|
||||
availableQty = productWarehouse.Quantity - totalPendingQty
|
||||
if availableQty < 0 {
|
||||
availableQty = 0
|
||||
}
|
||||
} else if projectFlockKandang.ProjectFlock.Category == string(utils.ProjectFlockCategoryLaying) {
|
||||
var totalPopulation float64
|
||||
var totalPendingQty float64
|
||||
|
||||
populations, err := s.PopulationRepo.GetByProjectFlockKandangIDAndProductWarehouseID(c.Context(), projectFlockKandang.Id, productWarehouse.Id)
|
||||
if err == nil {
|
||||
for _, pop := range populations {
|
||||
totalPopulation += pop.TotalQty
|
||||
}
|
||||
}
|
||||
|
||||
for _, chickin := range projectFlockKandang.Chickins {
|
||||
if chickin.ProductWarehouseId == productWarehouse.Id && chickin.DeletedAt.Time.IsZero() && chickin.PendingUsageQty > 0 {
|
||||
totalPendingQty += chickin.PendingUsageQty
|
||||
}
|
||||
}
|
||||
|
||||
availableQty = productWarehouse.Quantity - totalPopulation - totalPendingQty
|
||||
if availableQty < 0 {
|
||||
availableQty = 0
|
||||
}
|
||||
}
|
||||
|
||||
return availableQty, nil
|
||||
}
|
||||
|
||||
+25
@@ -12,6 +12,8 @@ type ProjectFlockPopulationRepository interface {
|
||||
// domain-specific
|
||||
GetByProjectFlockKandangID(ctx context.Context, projectFlockKandangID uint) (*entity.ProjectFlockPopulation, error)
|
||||
ExistsByProjectChickinID(ctx context.Context, projectChickinID uint) (bool, error)
|
||||
GetByProjectChickinIDAndProductWarehouseID(ctx context.Context, projectChickinID uint, productWarehouseID uint) ([]entity.ProjectFlockPopulation, error)
|
||||
GetByProjectFlockKandangIDAndProductWarehouseID(ctx context.Context, projectFlockKandangID uint, productWarehouseID uint) ([]entity.ProjectFlockPopulation, error)
|
||||
|
||||
// subset of base repository methods used by services
|
||||
CreateOne(ctx context.Context, entity *entity.ProjectFlockPopulation, modifier func(*gorm.DB) *gorm.DB) error
|
||||
@@ -64,3 +66,26 @@ func (r *projectFlockPopulationRepositoryImpl) ExistsByProjectChickinID(ctx cont
|
||||
}
|
||||
return count > 0, nil
|
||||
}
|
||||
|
||||
func (r *projectFlockPopulationRepositoryImpl) GetByProjectChickinIDAndProductWarehouseID(ctx context.Context, projectChickinID uint, productWarehouseID uint) ([]entity.ProjectFlockPopulation, error) {
|
||||
var records []entity.ProjectFlockPopulation
|
||||
err := r.DB().WithContext(ctx).
|
||||
Where("project_chickin_id = ? AND product_warehouse_id = ?", projectChickinID, productWarehouseID).
|
||||
Find(&records).Error
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return records, nil
|
||||
}
|
||||
|
||||
func (r *projectFlockPopulationRepositoryImpl) GetByProjectFlockKandangIDAndProductWarehouseID(ctx context.Context, projectFlockKandangID uint, productWarehouseID uint) ([]entity.ProjectFlockPopulation, error) {
|
||||
var records []entity.ProjectFlockPopulation
|
||||
err := r.DB().WithContext(ctx).
|
||||
Joins("JOIN project_chickins ON project_chickins.id = project_flock_populations.project_chickin_id").
|
||||
Where("project_chickins.project_flock_kandang_id = ? AND project_flock_populations.product_warehouse_id = ?", projectFlockKandangID, productWarehouseID).
|
||||
Find(&records).Error
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return records, nil
|
||||
}
|
||||
|
||||
+6
-3
@@ -24,9 +24,12 @@ func NewTransferLayingController(transferLayingService service.TransferLayingSer
|
||||
|
||||
func (u *TransferLayingController) GetAll(c *fiber.Ctx) error {
|
||||
query := &validation.Query{
|
||||
Page: c.QueryInt("page", 1),
|
||||
Limit: c.QueryInt("limit", 10),
|
||||
Search: c.Query("search", ""),
|
||||
Page: c.QueryInt("page", 1),
|
||||
Limit: c.QueryInt("limit", 10),
|
||||
SourceProjectFlockId: uint(c.QueryInt("source_project_flock_id", 0)),
|
||||
TargetProjectFlockId: uint(c.QueryInt("target_project_flock_id", 0)),
|
||||
TransferDateFrom: c.Query("transfer_date_from", ""),
|
||||
TransferDateTo: c.Query("transfer_date_to", ""),
|
||||
}
|
||||
|
||||
if query.Page < 1 || query.Limit < 1 {
|
||||
|
||||
+17
-1
@@ -1,6 +1,8 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"gitlab.com/mbugroup/lti-api.git/internal/common/repository"
|
||||
entity "gitlab.com/mbugroup/lti-api.git/internal/entities"
|
||||
"gorm.io/gorm"
|
||||
@@ -8,15 +10,29 @@ import (
|
||||
|
||||
type TransferLayingRepository interface {
|
||||
repository.BaseRepository[entity.LayingTransfer]
|
||||
|
||||
GetByTransferNumber(ctx context.Context, transferNumber string) (*entity.LayingTransfer, error)
|
||||
}
|
||||
|
||||
type TransferLayingRepositoryImpl struct {
|
||||
*repository.BaseRepositoryImpl[entity.LayingTransfer]
|
||||
db *gorm.DB
|
||||
}
|
||||
|
||||
func NewTransferLayingRepository(db *gorm.DB) TransferLayingRepository {
|
||||
return &TransferLayingRepositoryImpl{
|
||||
BaseRepositoryImpl: repository.NewBaseRepository[entity.LayingTransfer](db),
|
||||
db: db,
|
||||
}
|
||||
}
|
||||
|
||||
func (r *TransferLayingRepositoryImpl) GetByTransferNumber(ctx context.Context, transferNumber string) (*entity.LayingTransfer, error) {
|
||||
var transfer entity.LayingTransfer
|
||||
err := r.db.WithContext(ctx).
|
||||
Where("transfer_number = ?", transferNumber).
|
||||
Where("deleted_at IS NULL").
|
||||
First(&transfer).Error
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &transfer, nil
|
||||
}
|
||||
|
||||
+38
@@ -0,0 +1,38 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"gitlab.com/mbugroup/lti-api.git/internal/common/repository"
|
||||
entity "gitlab.com/mbugroup/lti-api.git/internal/entities"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type LayingTransferSourceRepository interface {
|
||||
repository.BaseRepository[entity.LayingTransferSource]
|
||||
GetByLayingTransferId(ctx context.Context, layingTransferId uint) ([]entity.LayingTransferSource, error)
|
||||
}
|
||||
|
||||
type LayingTransferSourceRepositoryImpl struct {
|
||||
*repository.BaseRepositoryImpl[entity.LayingTransferSource]
|
||||
db *gorm.DB
|
||||
}
|
||||
|
||||
func NewLayingTransferSourceRepository(db *gorm.DB) LayingTransferSourceRepository {
|
||||
return &LayingTransferSourceRepositoryImpl{
|
||||
BaseRepositoryImpl: repository.NewBaseRepository[entity.LayingTransferSource](db),
|
||||
db: db,
|
||||
}
|
||||
}
|
||||
|
||||
func (r *LayingTransferSourceRepositoryImpl) GetByLayingTransferId(ctx context.Context, layingTransferId uint) ([]entity.LayingTransferSource, error) {
|
||||
var sources []entity.LayingTransferSource
|
||||
err := r.db.WithContext(ctx).
|
||||
Where("laying_transfer_id = ?", layingTransferId).
|
||||
Order("created_at DESC").
|
||||
Find(&sources).Error
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return sources, nil
|
||||
}
|
||||
+38
@@ -0,0 +1,38 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"gitlab.com/mbugroup/lti-api.git/internal/common/repository"
|
||||
entity "gitlab.com/mbugroup/lti-api.git/internal/entities"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type LayingTransferTargetRepository interface {
|
||||
repository.BaseRepository[entity.LayingTransferTarget]
|
||||
GetByLayingTransferId(ctx context.Context, layingTransferId uint) ([]entity.LayingTransferTarget, error)
|
||||
}
|
||||
|
||||
type LayingTransferTargetRepositoryImpl struct {
|
||||
*repository.BaseRepositoryImpl[entity.LayingTransferTarget]
|
||||
db *gorm.DB
|
||||
}
|
||||
|
||||
func NewLayingTransferTargetRepository(db *gorm.DB) LayingTransferTargetRepository {
|
||||
return &LayingTransferTargetRepositoryImpl{
|
||||
BaseRepositoryImpl: repository.NewBaseRepository[entity.LayingTransferTarget](db),
|
||||
db: db,
|
||||
}
|
||||
}
|
||||
|
||||
func (r *LayingTransferTargetRepositoryImpl) GetByLayingTransferId(ctx context.Context, layingTransferId uint) ([]entity.LayingTransferTarget, error) {
|
||||
var targets []entity.LayingTransferTarget
|
||||
err := r.db.WithContext(ctx).
|
||||
Where("laying_transfer_id = ?", layingTransferId).
|
||||
Order("created_at DESC").
|
||||
Find(&targets).Error
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return targets, nil
|
||||
}
|
||||
@@ -55,8 +55,17 @@ func (s transferLayingService) GetAll(c *fiber.Ctx, params *validation.Query) ([
|
||||
|
||||
transferLayings, total, err := s.Repository.GetAll(c.Context(), offset, params.Limit, func(db *gorm.DB) *gorm.DB {
|
||||
db = s.withRelations(db)
|
||||
if params.Search != "" {
|
||||
return db.Where("name LIKE ?", "%"+params.Search+"%")
|
||||
if params.SourceProjectFlockId != 0 {
|
||||
db = db.Where("from_project_flock_id = ?", params.SourceProjectFlockId)
|
||||
}
|
||||
if params.TargetProjectFlockId != 0 {
|
||||
db = db.Where("to_project_flock_id = ?", params.TargetProjectFlockId)
|
||||
}
|
||||
if params.TransferDateFrom != "" {
|
||||
db = db.Where("transfer_date >= ?", params.TransferDateFrom)
|
||||
}
|
||||
if params.TransferDateTo != "" {
|
||||
db = db.Where("transfer_date <= ?", params.TransferDateTo)
|
||||
}
|
||||
return db.Order("created_at DESC").Order("updated_at DESC")
|
||||
})
|
||||
@@ -92,9 +101,19 @@ func (s *transferLayingService) CreateOne(c *fiber.Ctx, req *validation.Create)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
for _, detail := range req.Details {
|
||||
// Validate source kandangs
|
||||
for _, detail := range req.SourceKandangs {
|
||||
if err := common.EnsureRelations(c.Context(),
|
||||
common.RelationCheck{Name: "Project Flock Kandang", ID: &detail.SourceProjectFlockKandangId, Exists: s.ProjectFlockKandangRepo.IdExists},
|
||||
common.RelationCheck{Name: "Source Project Flock Kandang", ID: &detail.ProjectFlockKandangId, Exists: s.ProjectFlockKandangRepo.IdExists},
|
||||
); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
// Validate target kandangs
|
||||
for _, detail := range req.TargetKandangs {
|
||||
if err := common.EnsureRelations(c.Context(),
|
||||
common.RelationCheck{Name: "Target Project Flock Kandang", ID: &detail.ProjectFlockKandangId, Exists: s.ProjectFlockKandangRepo.IdExists},
|
||||
); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -106,7 +125,7 @@ func (s *transferLayingService) CreateOne(c *fiber.Ctx, req *validation.Create)
|
||||
}
|
||||
|
||||
var totalQty float64
|
||||
for _, item := range req.Details {
|
||||
for _, item := range req.SourceKandangs {
|
||||
totalQty += item.Quantity
|
||||
}
|
||||
|
||||
@@ -142,8 +161,12 @@ func (s transferLayingService) UpdateOne(c *fiber.Ctx, req *validation.Update, i
|
||||
|
||||
updateBody := make(map[string]any)
|
||||
|
||||
if req.Name != nil {
|
||||
updateBody["name"] = *req.Name
|
||||
if req.TransferDate != nil {
|
||||
updateBody["transfer_date"] = *req.TransferDate
|
||||
}
|
||||
|
||||
if req.Reason != nil {
|
||||
updateBody["notes"] = *req.Reason
|
||||
}
|
||||
|
||||
if len(updateBody) == 0 {
|
||||
|
||||
+22
-12
@@ -1,24 +1,34 @@
|
||||
package validation
|
||||
|
||||
type CreateDetail struct {
|
||||
SourceProjectFlockKandangId uint `json:"source_project_flock_kandang_id" validate:"required"`
|
||||
Quantity float64 `json:"quantity" validate:"required,gt=0"`
|
||||
type SourceKandangDetail struct {
|
||||
ProjectFlockKandangId uint `json:"project_flock_kandang_id" validate:"required"`
|
||||
Quantity float64 `json:"quantity" validate:"required,gt=0"`
|
||||
}
|
||||
|
||||
type TargetKandangDetail struct {
|
||||
ProjectFlockKandangId uint `json:"project_flock_kandang_id" validate:"required"`
|
||||
Quantity float64 `json:"quantity" validate:"required,gt=0"`
|
||||
}
|
||||
|
||||
type Create struct {
|
||||
TransferDate string `json:"transfer_date" validate:"required,datetime=2006-01-02"`
|
||||
SourceProjectFlockId uint `json:"source_project_flock_id" validate:"required"`
|
||||
TargetProjectFlockId uint `json:"target_project_flock_id" validate:"required"`
|
||||
Details []CreateDetail `json:"details" validate:"required,min=1,dive,required"`
|
||||
Reason string `json:"reason" validate:"omitempty,max=1000"`
|
||||
TransferDate string `json:"transfer_date" validate:"required,datetime=2006-01-02"`
|
||||
SourceProjectFlockId uint `json:"source_project_flock_id" validate:"required"`
|
||||
TargetProjectFlockId uint `json:"target_project_flock_id" validate:"required"`
|
||||
SourceKandangs []SourceKandangDetail `json:"source_kandangs" validate:"required,min=1,dive,required"`
|
||||
TargetKandangs []TargetKandangDetail `json:"target_kandangs" validate:"required,min=1,dive,required"`
|
||||
Reason string `json:"reason" validate:"omitempty,max=1000"`
|
||||
}
|
||||
|
||||
type Update struct {
|
||||
Name *string `json:"name,omitempty" validate:"omitempty"`
|
||||
TransferDate *string `json:"transfer_date,omitempty" validate:"omitempty,datetime=2006-01-02"`
|
||||
Reason *string `json:"reason,omitempty" validate:"omitempty,max=1000"`
|
||||
}
|
||||
|
||||
type Query struct {
|
||||
Page int `query:"page" validate:"omitempty,number,min=1,gt=0"`
|
||||
Limit int `query:"limit" validate:"omitempty,number,min=1,max=100,gt=0"`
|
||||
Search string `query:"search" validate:"omitempty,max=50"`
|
||||
Page int `query:"page" validate:"omitempty,number,min=1,gt=0"`
|
||||
Limit int `query:"limit" validate:"omitempty,number,min=1,max=100,gt=0"`
|
||||
SourceProjectFlockId uint `query:"source_project_flock_id" validate:"omitempty"`
|
||||
TargetProjectFlockId uint `query:"target_project_flock_id" validate:"omitempty"`
|
||||
TransferDateFrom string `query:"transfer_date_from" validate:"omitempty,datetime=2006-01-02"`
|
||||
TransferDateTo string `query:"transfer_date_to" validate:"omitempty,datetime=2006-01-02"`
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user