Derive stock and availability from the ledger, not stored fields
Stock shown in the console did not match the productstocks ledger, and two product endpoints were failing outright. Every cause was on the read side or in how the availability flag was maintained; the ledger writes themselves (CreateOrder's "out" entry, cancellation's "in" entry) were already correct. Read fixes, repositories/productRepository.go: - GetProductStocks returned SQLSTATE 42803 on every call: bare a.tenantid / a.stocktype / a.status under GROUP BY a.productid. The per-ledger-row columns are now aggregated and the grouping covers the identity columns. - FetchFilteredProducts filtered on an alias `e` that no query defines, so every /getallproducts call carrying a locationid failed with SQLSTATE 42P01 instead of returning products. - FetchFilteredProducts joined productlocations on productid alone and joined a (productid, locationid)-grouped stock subquery on productid alone, so a product carried by three outlets came back three times, each row showing another outlet's quantity and status. Both are now tenant-scoped subqueries collapsed to one row per product and scoped to the outlet when one is given. - GetProductStocks and FetchFilteredProducts compared stocktype = 'in' case-sensitively. Production holds 'in' and 'IN' both, so uppercase receipts were silently dropped from the balance: one outlet reported 0 for a product holding 50, another reported 0 for twelve products holding 200-840. - GetStockStatement summed opening over stockdate <= CURRENT_DATE, making it arithmetically identical to closing. The Inventory ledger showed the same number in both columns on every row, which reads as stock never moving. Availability flag: productlocations.status was maintained by two different rules — the order path derived it from the balance, the receiving path set 'available' on any "in" entry regardless of the resulting balance. A partial restock that left the balance at or below zero marked a product sellable, and a flag set by an old order never cleared for stock that arrived by a route the API did not own. Both paths now derive the flag from the live balance through one rule: SyncProductLocationStatus (receiving side) and syncProductLocationStatus (order side, inside the caller's transaction). ReactivateProductLocations is replaced by the former; the service no longer filters refs by stocktype, since the direction of the movement is no longer what decides the flag. A row that has already drifted now repairs itself on its next ledger entry. Verified against the live database: all four stock endpoints return matching balances, /getallproducts no longer duplicates rows, and the flag sync was exercised in both directions inside a rolled-back transaction. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -1007,6 +1007,36 @@ func (r *orderRepository) GetOrderDetails(orderHeaderID int) ([]models.OrderDeta
|
||||
return details, nil
|
||||
}
|
||||
|
||||
// syncProductLocationStatus re-derives productlocations.status for one
|
||||
// product at one outlet from the live productstocks balance — "available"
|
||||
// above zero, "outofstock" at or below it. It runs inside the caller's
|
||||
// transaction so the flag is committed together with the ledger entry that
|
||||
// moved it, and it is the same rule productRepository.SyncProductLocationStatus
|
||||
// applies on the receiving side; both paths agreeing is what stops the flag
|
||||
// drifting away from the ledger over time.
|
||||
//
|
||||
// Status errors are deliberately swallowed: an order must not fail because a
|
||||
// display flag could not be refreshed, and the next ledger entry re-derives it.
|
||||
func syncProductLocationStatus(tx *gorm.DB, tenantid, locationid, productid int) {
|
||||
if tenantid <= 0 || locationid <= 0 || productid <= 0 {
|
||||
return
|
||||
}
|
||||
if err := tx.Exec(`
|
||||
UPDATE productlocations
|
||||
SET status = CASE WHEN (
|
||||
SELECT COALESCE(
|
||||
SUM(CASE WHEN LOWER(stocktype) = 'in' THEN quantity ELSE 0 END) -
|
||||
SUM(CASE WHEN LOWER(stocktype) = 'out' THEN quantity ELSE 0 END), 0)
|
||||
FROM productstocks
|
||||
WHERE productid = ? AND tenantid = ? AND locationid = ?
|
||||
) > 0 THEN 'available' ELSE 'outofstock' END
|
||||
WHERE tenantid = ? AND locationid = ? AND productid = ?`,
|
||||
productid, tenantid, locationid,
|
||||
tenantid, locationid, productid).Error; err != nil {
|
||||
log.Println("syncProductLocationStatus:", err)
|
||||
}
|
||||
}
|
||||
|
||||
func (r *orderRepository) UpdateOrder(order *models.Orders) error {
|
||||
tx := r.db.Begin()
|
||||
|
||||
@@ -1043,10 +1073,11 @@ func (r *orderRepository) UpdateOrder(order *models.Orders) error {
|
||||
return err
|
||||
}
|
||||
|
||||
// Update productlocation status back to available if stock is restored
|
||||
tx.Table("productlocations").
|
||||
Where("productid = ? AND tenantid = ? AND locationid = ?", item.Productid, existingOrder.Tenantid, itemLocID).
|
||||
Update("status", "available")
|
||||
// Re-derive availability from the restored balance rather
|
||||
// than assuming "available": cancelling one line of a
|
||||
// heavily oversold product can leave it still at or below
|
||||
// zero, in which case it must stay flagged outofstock.
|
||||
syncProductLocationStatus(tx, existingOrder.Tenantid, itemLocID, item.Productid)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1254,24 +1285,9 @@ func (r *orderRepository) CreateOrder(data models.Orders) (models.Orders, error)
|
||||
return models.Orders{}, err
|
||||
}
|
||||
|
||||
// Update productlocation status to 'outofstock' if remaining stock drops to 0 or below
|
||||
var remainingStock int
|
||||
remStockQuery := `
|
||||
SELECT COALESCE(
|
||||
SUM(CASE WHEN LOWER(stocktype) = 'in' THEN quantity ELSE 0 END) -
|
||||
SUM(CASE WHEN LOWER(stocktype) = 'out' THEN quantity ELSE 0 END),
|
||||
0
|
||||
)
|
||||
FROM productstocks
|
||||
WHERE productid = ? AND tenantid = ? AND locationid = ?
|
||||
`
|
||||
if err := tx.Raw(remStockQuery, item.Productid, data.Tenantid, itemLocID).Scan(&remainingStock).Error; err == nil {
|
||||
if remainingStock <= 0 {
|
||||
tx.Table("productlocations").
|
||||
Where("productid = ? AND tenantid = ? AND locationid = ?", item.Productid, data.Tenantid, itemLocID).
|
||||
Update("status", "outofstock")
|
||||
}
|
||||
}
|
||||
// Re-derive the location's availability flag from the ledger balance
|
||||
// this "out" entry just produced.
|
||||
syncProductLocationStatus(tx, data.Tenantid, itemLocID, item.Productid)
|
||||
}
|
||||
|
||||
if err := r.updateSeqno(data.Tenantid, "ORD"); err != nil {
|
||||
|
||||
Reference in New Issue
Block a user