From 8220e343029bf557a340589f32284111632199d5 Mon Sep 17 00:00:00 2001 From: aguhh18 Date: Tue, 4 Nov 2025 08:24:38 +0700 Subject: [PATCH] FIX[BE]: fix logic on Chickin Laying not convert to layer but still Pullet, and inisiate laying transfer migration and base basic API --- ...825_create_laying_transfers_table.down.sql | 2 +- ...74825_create_laying_transfers_table.up.sql | 9 +- ...te_laying_kandang_transfers_table.down.sql | 1 - ...eate_laying_kandang_transfers_table.up.sql | 40 ---- ...ansfer_sources_and_targets_tables.down.sql | 5 + ...transfer_sources_and_targets_tables.up.sql | 93 +++++++++ internal/database/seed/seeder.go | 32 ++-- internal/entities/laying_transfer.go | 12 +- internal/entities/laying_transfer_source.go | 23 +++ internal/entities/laying_transfer_target.go | 24 +++ .../project_chickin.repository.go | 15 ++ .../chickins/services/chickin.service.go | 177 +++++++++++++----- .../dto/project_flock_kandang.dto.go | 15 +- .../project-flock-kandangs/module.go | 3 +- .../services/project_flock_kandang.service.go | 100 +++++++--- .../project_flock_population_repository.go | 25 +++ .../controllers/transfer_laying.controller.go | 9 +- .../laying_transfer.repository.go | 18 +- .../laying_transfer_source.repository.go | 38 ++++ .../laying_transfer_target.repository.go | 38 ++++ .../services/transfer_laying.service.go | 37 +++- .../validations/transfer_laying.validation.go | 34 ++-- 22 files changed, 587 insertions(+), 163 deletions(-) delete mode 100644 internal/database/migrations/20251029081833_create_laying_kandang_transfers_table.down.sql delete mode 100644 internal/database/migrations/20251029081833_create_laying_kandang_transfers_table.up.sql create mode 100644 internal/database/migrations/20251103054536_add_laying_transfer_sources_and_targets_tables.down.sql create mode 100644 internal/database/migrations/20251103054536_add_laying_transfer_sources_and_targets_tables.up.sql create mode 100644 internal/entities/laying_transfer_source.go create mode 100644 internal/entities/laying_transfer_target.go create mode 100644 internal/modules/production/transfer_layings/repositories/laying_transfer_source.repository.go create mode 100644 internal/modules/production/transfer_layings/repositories/laying_transfer_target.repository.go diff --git a/internal/database/migrations/20251029074825_create_laying_transfers_table.down.sql b/internal/database/migrations/20251029074825_create_laying_transfers_table.down.sql index 6ad77820..29313fe4 100644 --- a/internal/database/migrations/20251029074825_create_laying_transfers_table.down.sql +++ b/internal/database/migrations/20251029074825_create_laying_transfers_table.down.sql @@ -1 +1 @@ -DROP TABLE IF EXISTS laying_transfers; \ No newline at end of file +DROP TABLE IF EXISTS laying_transfers CASCADE; \ No newline at end of file diff --git a/internal/database/migrations/20251029074825_create_laying_transfers_table.up.sql b/internal/database/migrations/20251029074825_create_laying_transfers_table.up.sql index 10ced117..a01f6e02 100644 --- a/internal/database/migrations/20251029074825_create_laying_transfers_table.up.sql +++ b/internal/database/migrations/20251029074825_create_laying_transfers_table.up.sql @@ -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); diff --git a/internal/database/migrations/20251029081833_create_laying_kandang_transfers_table.down.sql b/internal/database/migrations/20251029081833_create_laying_kandang_transfers_table.down.sql deleted file mode 100644 index caf4f52d..00000000 --- a/internal/database/migrations/20251029081833_create_laying_kandang_transfers_table.down.sql +++ /dev/null @@ -1 +0,0 @@ -DROP TABLE IF EXISTS laying_kandang_transfers; \ No newline at end of file diff --git a/internal/database/migrations/20251029081833_create_laying_kandang_transfers_table.up.sql b/internal/database/migrations/20251029081833_create_laying_kandang_transfers_table.up.sql deleted file mode 100644 index 786f8de3..00000000 --- a/internal/database/migrations/20251029081833_create_laying_kandang_transfers_table.up.sql +++ /dev/null @@ -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); \ No newline at end of file diff --git a/internal/database/migrations/20251103054536_add_laying_transfer_sources_and_targets_tables.down.sql b/internal/database/migrations/20251103054536_add_laying_transfer_sources_and_targets_tables.down.sql new file mode 100644 index 00000000..2b890114 --- /dev/null +++ b/internal/database/migrations/20251103054536_add_laying_transfer_sources_and_targets_tables.down.sql @@ -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; \ No newline at end of file diff --git a/internal/database/migrations/20251103054536_add_laying_transfer_sources_and_targets_tables.up.sql b/internal/database/migrations/20251103054536_add_laying_transfer_sources_and_targets_tables.up.sql new file mode 100644 index 00000000..023fc7b4 --- /dev/null +++ b/internal/database/migrations/20251103054536_add_laying_transfer_sources_and_targets_tables.up.sql @@ -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); \ No newline at end of file diff --git a/internal/database/seed/seeder.go b/internal/database/seed/seeder.go index 93c75b29..3e4f1eb9 100644 --- a/internal/database/seed/seeder.go +++ b/internal/database/seed/seeder.go @@ -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 { diff --git a/internal/entities/laying_transfer.go b/internal/entities/laying_transfer.go index 75c5e23a..8c2058df 100644 --- a/internal/entities/laying_transfer.go +++ b/internal/entities/laying_transfer.go @@ -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"` } + diff --git a/internal/entities/laying_transfer_source.go b/internal/entities/laying_transfer_source.go new file mode 100644 index 00000000..6b54bd84 --- /dev/null +++ b/internal/entities/laying_transfer_source.go @@ -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"` +} diff --git a/internal/entities/laying_transfer_target.go b/internal/entities/laying_transfer_target.go new file mode 100644 index 00000000..dec98f1f --- /dev/null +++ b/internal/entities/laying_transfer_target.go @@ -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"` +} + diff --git a/internal/modules/production/chickins/repositories/project_chickin.repository.go b/internal/modules/production/chickins/repositories/project_chickin.repository.go index fa6f13e6..c0f522ad 100644 --- a/internal/modules/production/chickins/repositories/project_chickin.repository.go +++ b/internal/modules/production/chickins/repositories/project_chickin.repository.go @@ -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 +} diff --git a/internal/modules/production/chickins/services/chickin.service.go b/internal/modules/production/chickins/services/chickin.service.go index 243bdf52..1970354a 100644 --- a/internal/modules/production/chickins/services/chickin.service.go +++ b/internal/modules/production/chickins/services/chickin.service.go @@ -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 { diff --git a/internal/modules/production/project-flock-kandangs/dto/project_flock_kandang.dto.go b/internal/modules/production/project-flock-kandangs/dto/project_flock_kandang.dto.go index 888964a7..b7dcdbef 100644 --- a/internal/modules/production/project-flock-kandangs/dto/project_flock_kandang.dto.go +++ b/internal/modules/production/project-flock-kandangs/dto/project_flock_kandang.dto.go @@ -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, } } diff --git a/internal/modules/production/project-flock-kandangs/module.go b/internal/modules/production/project-flock-kandangs/module.go index 2457f691..160cec5e 100644 --- a/internal/modules/production/project-flock-kandangs/module.go +++ b/internal/modules/production/project-flock-kandangs/module.go @@ -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) diff --git a/internal/modules/production/project-flock-kandangs/services/project_flock_kandang.service.go b/internal/modules/production/project-flock-kandangs/services/project_flock_kandang.service.go index 6258e34a..ec292d90 100644 --- a/internal/modules/production/project-flock-kandangs/services/project_flock_kandang.service.go +++ b/internal/modules/production/project-flock-kandangs/services/project_flock_kandang.service.go @@ -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 +} diff --git a/internal/modules/production/project_flocks/repositories/project_flock_population_repository.go b/internal/modules/production/project_flocks/repositories/project_flock_population_repository.go index fdb1249f..2f622656 100644 --- a/internal/modules/production/project_flocks/repositories/project_flock_population_repository.go +++ b/internal/modules/production/project_flocks/repositories/project_flock_population_repository.go @@ -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 +} diff --git a/internal/modules/production/transfer_layings/controllers/transfer_laying.controller.go b/internal/modules/production/transfer_layings/controllers/transfer_laying.controller.go index 01f49867..f962c263 100644 --- a/internal/modules/production/transfer_layings/controllers/transfer_laying.controller.go +++ b/internal/modules/production/transfer_layings/controllers/transfer_laying.controller.go @@ -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 { diff --git a/internal/modules/production/transfer_layings/repositories/laying_transfer.repository.go b/internal/modules/production/transfer_layings/repositories/laying_transfer.repository.go index e92e8f95..2e5437da 100644 --- a/internal/modules/production/transfer_layings/repositories/laying_transfer.repository.go +++ b/internal/modules/production/transfer_layings/repositories/laying_transfer.repository.go @@ -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 +} diff --git a/internal/modules/production/transfer_layings/repositories/laying_transfer_source.repository.go b/internal/modules/production/transfer_layings/repositories/laying_transfer_source.repository.go new file mode 100644 index 00000000..6c52683e --- /dev/null +++ b/internal/modules/production/transfer_layings/repositories/laying_transfer_source.repository.go @@ -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 +} diff --git a/internal/modules/production/transfer_layings/repositories/laying_transfer_target.repository.go b/internal/modules/production/transfer_layings/repositories/laying_transfer_target.repository.go new file mode 100644 index 00000000..486008cc --- /dev/null +++ b/internal/modules/production/transfer_layings/repositories/laying_transfer_target.repository.go @@ -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 +} diff --git a/internal/modules/production/transfer_layings/services/transfer_laying.service.go b/internal/modules/production/transfer_layings/services/transfer_laying.service.go index bc66bd13..0a5b5dd2 100644 --- a/internal/modules/production/transfer_layings/services/transfer_laying.service.go +++ b/internal/modules/production/transfer_layings/services/transfer_laying.service.go @@ -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 { diff --git a/internal/modules/production/transfer_layings/validations/transfer_laying.validation.go b/internal/modules/production/transfer_layings/validations/transfer_laying.validation.go index 3b83132f..1d291ac5 100644 --- a/internal/modules/production/transfer_layings/validations/transfer_laying.validation.go +++ b/internal/modules/production/transfer_layings/validations/transfer_laying.validation.go @@ -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"` }