refactor(inventory): enhance error reporting for negative stock validation
This commit is contained in:
@@ -52,8 +52,38 @@ return new class extends Migration
|
||||
|
||||
private function assertNonNegative(string $expression, string $reason): void
|
||||
{
|
||||
if (DB::table('inventories')->whereRaw("({$expression}) < 0")->exists()) {
|
||||
throw new RuntimeException("Hay inventarios inconsistentes: {$reason}.");
|
||||
$invalidInventories = DB::table('inventories')
|
||||
->select([
|
||||
'id',
|
||||
'real_stock',
|
||||
'sold_units',
|
||||
'refunded_units',
|
||||
'reserved_stock',
|
||||
'entry_reserved_stock',
|
||||
])
|
||||
->selectRaw("({$expression}) as calculated_stock")
|
||||
->whereRaw("({$expression}) < 0")
|
||||
->orderBy('id')
|
||||
->limit(20)
|
||||
->get();
|
||||
|
||||
if ($invalidInventories->isNotEmpty()) {
|
||||
$details = $invalidInventories
|
||||
->map(static fn (object $inventory): string => sprintf(
|
||||
'id=%d [real=%d, vendidas=%d, reintegradas=%d, reservadas=%d, reservas_entradas=%d, resultado=%d]',
|
||||
$inventory->id,
|
||||
$inventory->real_stock,
|
||||
$inventory->sold_units,
|
||||
$inventory->refunded_units,
|
||||
$inventory->reserved_stock,
|
||||
$inventory->entry_reserved_stock,
|
||||
$inventory->calculated_stock,
|
||||
))
|
||||
->implode('; ');
|
||||
|
||||
throw new RuntimeException(
|
||||
"Hay inventarios inconsistentes: {$reason}. Inventarios detectados (máximo 20): {$details}."
|
||||
);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user