codex/fix: inconsistent stock options and availability

This commit is contained in:
Adnan Zahir
2026-04-04 09:52:59 +07:00
parent 7b4bf94329
commit 34a3fc44a8
5 changed files with 68 additions and 7 deletions
@@ -71,6 +71,13 @@ func applyWarehouseSelectionFilter(db *gorm.DB, kandangID, locationID uint) *gor
}
}
func applyAvailableOnlyFilter(db *gorm.DB, availableOnly bool) *gorm.DB {
if !availableOnly {
return db
}
return db.Where("COALESCE(product_warehouses.qty, 0) > 0")
}
func (s productWarehouseService) GetAll(c *fiber.Ctx, params *validation.Query) ([]entity.ProductWarehouse, int64, error) {
if err := s.Validate.Struct(params); err != nil {
return nil, 0, err
@@ -151,12 +158,31 @@ func (s productWarehouseService) GetAll(c *fiber.Ctx, params *validation.Query)
db = db.Where("product_id = ?", params.ProductId)
}
db = applyAvailableOnlyFilter(db, params.AvailableOnly)
db = applyWarehouseSelectionFilter(db, params.KandangId, params.LocationId)
if params.WarehouseId != 0 {
db = db.Where("warehouse_id = ?", params.WarehouseId)
}
if strings.TrimSpace(params.Search) != "" {
searchPattern := "%" + strings.TrimSpace(params.Search) + "%"
db = db.Where(
`(
EXISTS (
SELECT 1
FROM products p_search
WHERE p_search.id = product_warehouses.product_id
AND p_search.name ILIKE ?
)
OR w_scope.name ILIKE ?
)`,
searchPattern,
searchPattern,
)
}
if len(marketingTypes) > 0 {
flagSet := make(map[string]struct{})
for _, t := range marketingTypes {
@@ -49,6 +49,20 @@ func TestApplyWarehouseSelectionFilterSupportsLocationOnlyQuery(t *testing.T) {
assertUintIDs(t, ids, []uint{1, 2, 3})
}
func TestApplyAvailableOnlyFilterRemovesZeroQtyRows(t *testing.T) {
db := setupProductWarehouseServiceTestDB(t)
var ids []uint
err := applyAvailableOnlyFilter(baseProductWarehouseSelectionQuery(db), true).
Order("product_warehouses.id").
Pluck("product_warehouses.id", &ids).Error
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
assertUintIDs(t, ids, []uint{1, 2, 4})
}
func setupProductWarehouseServiceTestDB(t *testing.T) *gorm.DB {
t.Helper()
@@ -67,18 +81,19 @@ func setupProductWarehouseServiceTestDB(t *testing.T) *gorm.DB {
)`,
`CREATE TABLE product_warehouses (
id INTEGER PRIMARY KEY,
warehouse_id INTEGER NOT NULL
warehouse_id INTEGER NOT NULL,
qty NUMERIC NULL
)`,
`INSERT INTO warehouses (id, type, location_id, kandang_id, deleted_at) VALUES
(1, 'KANDANG', 101, 11, NULL),
(2, 'LOKASI', 101, NULL, NULL),
(3, 'KANDANG', 101, 12, NULL),
(4, 'LOKASI', 102, NULL, NULL)`,
`INSERT INTO product_warehouses (id, warehouse_id) VALUES
(1, 1),
(2, 2),
(3, 3),
(4, 4)`,
`INSERT INTO product_warehouses (id, warehouse_id, qty) VALUES
(1, 1, 10),
(2, 2, 20),
(3, 3, 0),
(4, 4, 15)`,
}
for _, stmt := range statements {