80 lines
2.4 KiB
Go
80 lines
2.4 KiB
Go
package repository
|
|
|
|
import (
|
|
"regexp"
|
|
"testing"
|
|
|
|
"github.com/DATA-DOG/go-sqlmock"
|
|
"github.com/wmms/wmms/pkg/database"
|
|
)
|
|
|
|
const stockByMaterialSQL = `SELECT m.id, m.material_code, m.name, m.spec, m.category, m.unit,
|
|
COALESCE(SUM(ib.on_hand), 0), COALESCE(MAX(swr.minimum_available), 0)
|
|
FROM materials m
|
|
LEFT JOIN inventory_balances ib ON ib.material_id = m.id
|
|
LEFT JOIN stock_warning_rules swr ON swr.organization_id = ib.organization_id
|
|
AND swr.warehouse_id = ib.warehouse_id AND swr.material_id = m.id AND swr.enabled = TRUE
|
|
WHERE m.id = ?
|
|
GROUP BY m.id, m.material_code, m.name, m.spec, m.category, m.unit`
|
|
|
|
func TestStockRepoGetByMaterialIDReadsInventoryTables(t *testing.T) {
|
|
db, mock, err := sqlmock.New()
|
|
if err != nil {
|
|
t.Fatalf("open sql mock: %v", err)
|
|
}
|
|
t.Cleanup(func() {
|
|
database.DB = nil
|
|
db.Close()
|
|
})
|
|
database.DB = db
|
|
|
|
mock.ExpectQuery(regexp.QuoteMeta(stockByMaterialSQL)).WithArgs(int64(9)).WillReturnRows(
|
|
sqlmock.NewRows([]string{"id", "material_code", "name", "spec", "category", "unit", "on_hand", "minimum_available"}).
|
|
AddRow(9, "MAT-009", "电机", "80W", "A03", "台", 12, 3),
|
|
)
|
|
|
|
stock, err := NewStockRepo().GetByMaterialID(9)
|
|
if err != nil {
|
|
t.Fatalf("get stock: %v", err)
|
|
}
|
|
if stock.CurrentStock != 12 || stock.WarningStock != 3 {
|
|
t.Fatalf("unexpected stock quantities: %+v", stock)
|
|
}
|
|
if err := mock.ExpectationsWereMet(); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
}
|
|
|
|
func TestStockRepoUpdateStockTxWritesDefaultInventoryBalance(t *testing.T) {
|
|
db, mock, err := sqlmock.New()
|
|
if err != nil {
|
|
t.Fatalf("open sql mock: %v", err)
|
|
}
|
|
t.Cleanup(func() {
|
|
database.DB = nil
|
|
db.Close()
|
|
})
|
|
database.DB = db
|
|
|
|
mock.ExpectBegin()
|
|
tx, err := db.Begin()
|
|
if err != nil {
|
|
t.Fatalf("begin: %v", err)
|
|
}
|
|
query := `INSERT INTO inventory_balances (organization_id, warehouse_id, location_id, material_id, on_hand)
|
|
SELECT o.id, w.id, l.id, ?, ?
|
|
FROM organizations o
|
|
JOIN warehouses w ON w.organization_id = o.id AND w.code = 'DEFAULT'
|
|
JOIN warehouse_locations l ON l.warehouse_id = w.id AND l.code = 'MAIN'
|
|
WHERE o.code = 'DEFAULT'
|
|
ON DUPLICATE KEY UPDATE on_hand = on_hand + VALUES(on_hand), version = version + 1`
|
|
mock.ExpectExec(regexp.QuoteMeta(query)).WithArgs(int64(11), 5).WillReturnResult(sqlmock.NewResult(1, 1))
|
|
|
|
if err := NewStockRepo().UpdateStockTx(tx, 11, 5); err != nil {
|
|
t.Fatalf("update inventory balance: %v", err)
|
|
}
|
|
if err := mock.ExpectationsWereMet(); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
}
|