up
This commit is contained in:
@@ -41,6 +41,43 @@ class InventarioPrendaDistribucion extends Model
|
||||
|
||||
protected static function booted()
|
||||
{
|
||||
// Validaciones: impedir que la suma de distribuciones supere la cantidad terminada
|
||||
static::creating(function ($dist) {
|
||||
$parentId = $dist->inventario_prenda_id ?? null;
|
||||
if (! $parentId) return;
|
||||
|
||||
$parent = \App\Models\InventarioPrenda::find($parentId);
|
||||
if (! $parent) return;
|
||||
|
||||
$cantidad = intval($dist->cantidad ?? 0);
|
||||
$sumExistentes = (int) self::where('inventario_prenda_id', $parentId)->sum('cantidad');
|
||||
|
||||
if (($sumExistentes + $cantidad) > (int) $parent->cantidad_terminada) {
|
||||
throw \Illuminate\Validation\ValidationException::withMessages([
|
||||
'cantidad' => 'La suma de las distribuciones excede la cantidad terminada disponible (' . $parent->cantidad_terminada . ').',
|
||||
]);
|
||||
}
|
||||
});
|
||||
|
||||
static::updating(function ($dist) {
|
||||
$parentId = $dist->inventario_prenda_id ?? null;
|
||||
if (! $parentId) return;
|
||||
|
||||
$parent = \App\Models\InventarioPrenda::find($parentId);
|
||||
if (! $parent) return;
|
||||
|
||||
$newCantidad = intval($dist->cantidad ?? 0);
|
||||
$othersSum = (int) self::where('inventario_prenda_id', $parentId)
|
||||
->where('id', '<>', $dist->id)
|
||||
->sum('cantidad');
|
||||
|
||||
if (($othersSum + $newCantidad) > (int) $parent->cantidad_terminada) {
|
||||
throw \Illuminate\Validation\ValidationException::withMessages([
|
||||
'cantidad' => 'La suma de las distribuciones excede la cantidad terminada disponible (' . $parent->cantidad_terminada . ').',
|
||||
]);
|
||||
}
|
||||
});
|
||||
|
||||
// Al crear una distribución, incrementar stock
|
||||
static::created(function ($dist) {
|
||||
$cantidad = $dist->cantidad ?? 0;
|
||||
|
||||
Reference in New Issue
Block a user