fix(BE-48): improve adjustment history filtering and fix pointer conversion

- Add search parameter to adjustment history API
- Fix JOIN query logic to avoid duplicate JOINs
- Use EXISTS subquery for cleaner product/warehouse filtering
- Fix pointer conversion issue in slice iteration
- Improve query performance and code readability
This commit is contained in:
aguhh18
2025-10-10 12:36:11 +07:00
parent 91b320d489
commit 81cbb230f3
6 changed files with 31 additions and 23 deletions
@@ -48,7 +48,6 @@ func (u *AdjustmentController) AdjustmentHistory(c *fiber.Ctx) error {
query := &validation.Query{
Page: c.QueryInt("page", 1),
Limit: c.QueryInt("limit", 10),
Search: c.Query("search", ""),
ProductID: c.QueryInt("product_id", 0),
WarehouseID: c.QueryInt("warehouse_id", 0),
TransactionType: c.Query("transaction_type", ""),
@@ -159,13 +159,24 @@ func (s *adjustmentService) AdjustmentHistory(c *fiber.Ctx, query *validation.Qu
db = db.Where("log_type = ?", entity.LogTypeAdjustment)
if query.Search != "" {
db = db.Where("note ILIKE ?", "%"+query.Search+"%")
}
if query.TransactionType != "" {
db = db.Where("transaction_type = ?", strings.ToUpper(query.TransactionType))
}
if query.ProductID > 0 {
db = db.Joins("JOIN product_warehouses ON product_warehouses.id = stock_logs.product_warehouse_id").
Where("product_warehouses.product_id = ?", query.ProductID)
}
if query.WarehouseID > 0 {
if query.ProductID > 0 {
db = db.Where("product_warehouses.warehouse_id = ?", query.WarehouseID)
} else {
db = db.Joins("JOIN product_warehouses ON product_warehouses.id = stock_logs.product_warehouse_id").
Where("product_warehouses.warehouse_id = ?", query.WarehouseID)
}
}
return db.Order("created_at DESC")
})
@@ -175,7 +186,6 @@ func (s *adjustmentService) AdjustmentHistory(c *fiber.Ctx, query *validation.Qu
return nil, 0, fiber.NewError(fiber.StatusInternalServerError, "Failed to get adjustment history")
}
// Convert to pointer slice
result := make([]*entity.StockLog, len(stockLogs))
for i, v := range stockLogs {
result[i] = &v
@@ -11,7 +11,6 @@ type Create struct {
type Query struct {
Page int `query:"page" validate:"omitempty,min=1"`
Limit int `query:"limit" validate:"omitempty,min=1,max=100"`
Search string `query:"search" validate:"omitempty"`
ProductID int `query:"product_id" validate:"omitempty,min=0"`
WarehouseID int `query:"warehouse_id" validate:"omitempty,min=0"`
TransactionType string `query:"transaction_type" validate:"omitempty,oneof=increase decrease"`
@@ -32,5 +32,5 @@ type Query struct {
Page int `query:"page" validate:"omitempty,number,min=1"`
Limit int `query:"limit" validate:"omitempty,number,min=1"`
Search string `query:"search" validate:"omitempty,max=50"`
ProductCategoryID int `query:"product_category_id" validate:"omitempty,number,min=1"`
ProductCategoryID int `query:"product_category_id" validate:"omitempty,number,min=1"`
}