98 lines
3.2 KiB
PHP
98 lines
3.2 KiB
PHP
<?php
|
|
|
|
namespace App\Models;
|
|
|
|
use Illuminate\Database\Eloquent\Model;
|
|
|
|
class InventarioPrenda extends Model
|
|
{
|
|
protected $fillable = [
|
|
'orden_produccion_id',
|
|
'cantidad_terminada',
|
|
'cantidad_disponible',
|
|
'fecha_ingreso',
|
|
'estado',
|
|
'producto_id',
|
|
];
|
|
|
|
public function ordenProduccion()
|
|
{
|
|
return $this->belongsTo(OrdenProduccion::class);
|
|
}
|
|
|
|
public function producto()
|
|
{
|
|
return $this->belongsTo(\App\Models\Producto::class, 'producto_id');
|
|
}
|
|
|
|
public function distribuciones()
|
|
{
|
|
return $this->hasMany(\App\Models\InventarioPrendaDistribucion::class, 'inventario_prenda_id');
|
|
}
|
|
|
|
protected static function booted()
|
|
{
|
|
static::creating(function ($inventario) {
|
|
// Al ingresar al inventario, todo está disponible
|
|
$inventario->cantidad_disponible = $inventario->cantidad_terminada;
|
|
|
|
// Estado automático inicial
|
|
$inventario->estado = 'en_bodega';
|
|
});
|
|
|
|
// Al crear inventario de prenda, alimentar (incrementar o crear) el stock de Producto
|
|
static::created(function ($inventario) {
|
|
if (! $inventario->cantidad_terminada || $inventario->cantidad_terminada <= 0) {
|
|
return;
|
|
}
|
|
|
|
$op = $inventario->ordenProduccion;
|
|
|
|
// Priorizar producto explícito si fue seleccionado
|
|
if ($inventario->producto_id) {
|
|
$producto = \App\Models\Producto::find($inventario->producto_id);
|
|
if ($producto && ! $producto->variants()->exists()) {
|
|
$producto->increment('stock', $inventario->cantidad_terminada);
|
|
}
|
|
return;
|
|
}
|
|
|
|
if (! $op) {
|
|
return;
|
|
}
|
|
|
|
// Intentar emparejar producto por nombre de prenda_modelo o referencia
|
|
$nombre = $op->prenda_modelo ?? $op->referencia ?? null;
|
|
if (! $nombre) {
|
|
return;
|
|
}
|
|
|
|
$producto = \App\Models\Producto::where('nombre', $nombre)->first();
|
|
|
|
// Si existe y no tiene variantes, incrementar stock
|
|
if ($producto) {
|
|
if (! $producto->variants()->exists()) {
|
|
// Si el producto usa bodegas, sumar al stock directo (simplificado)
|
|
$producto->increment('stock', $inventario->cantidad_terminada);
|
|
} else {
|
|
// Tiene variantes: no hacemos cambios automáticos aquí (se requiere asignación manual)
|
|
// Podríamos implementar reglas adicionales si se definieran las variantes en la OP
|
|
}
|
|
|
|
return;
|
|
}
|
|
|
|
// Si no existe el producto, crearlo automáticamente con stock inicial
|
|
\App\Models\Producto::create([
|
|
'nombre' => $nombre,
|
|
'descripcion' => 'Creado automáticamente desde InventarioPrenda (OP #' . $op->id . ')',
|
|
'stock' => $inventario->cantidad_terminada,
|
|
'estado' => true,
|
|
'precio_compra' => 0,
|
|
'precio_venta' => 0,
|
|
'unidad_medida' => 'unidad',
|
|
]);
|
|
});
|
|
}
|
|
}
|