up
This commit is contained in:
@@ -0,0 +1,27 @@
|
||||
<?php
|
||||
|
||||
namespace App\Models;
|
||||
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
|
||||
class Ajuste extends Model
|
||||
{
|
||||
protected $fillable = [
|
||||
'referencia_type',
|
||||
'referencia_id',
|
||||
'user_id',
|
||||
'tipo',
|
||||
'cantidad',
|
||||
'notas',
|
||||
];
|
||||
|
||||
public function referencia()
|
||||
{
|
||||
return $this->morphTo();
|
||||
}
|
||||
|
||||
public function usuario()
|
||||
{
|
||||
return $this->belongsTo(User::class, 'user_id');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
<?php
|
||||
|
||||
namespace App\Models;
|
||||
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
|
||||
class Cobro extends Model
|
||||
{
|
||||
protected $fillable = [
|
||||
'referencia_type',
|
||||
'referencia_id',
|
||||
'user_id',
|
||||
'cantidad',
|
||||
'valor',
|
||||
'notas',
|
||||
];
|
||||
|
||||
public function referencia()
|
||||
{
|
||||
return $this->morphTo();
|
||||
}
|
||||
|
||||
public function usuario()
|
||||
{
|
||||
return $this->belongsTo(User::class, 'user_id');
|
||||
}
|
||||
}
|
||||
+124
-3
@@ -17,8 +17,19 @@ class Confeccion extends Model
|
||||
'valor_por_prenda',
|
||||
'total_pagar',
|
||||
'estado',
|
||||
'descuentos_cobros',
|
||||
];
|
||||
|
||||
public function cobros()
|
||||
{
|
||||
return $this->morphMany(\App\Models\Cobro::class, 'referencia');
|
||||
}
|
||||
|
||||
public function ajustes()
|
||||
{
|
||||
return $this->morphMany(\App\Models\Ajuste::class, 'referencia');
|
||||
}
|
||||
|
||||
/* Relaciones */
|
||||
public function proveedor()
|
||||
{
|
||||
@@ -52,7 +63,14 @@ class Confeccion extends Model
|
||||
// Total a pagar: usa cantidad_recibida si existe, sino cantidad_enviada
|
||||
$cantidadBase = $confeccion->cantidad_recibida ?? $confeccion->cantidad_enviada ?? 0;
|
||||
$valorUnitario = $confeccion->valor_por_prenda ?? 0;
|
||||
$confeccion->total_pagar = $cantidadBase * $valorUnitario;
|
||||
|
||||
// Aplicar descuentos de cobros si existen (se guarda también en descuentos_cobros para compatibilidad)
|
||||
$descuentos = (float) ($confeccion->getCobrosTotalAttribute() ?? 0);
|
||||
|
||||
$confeccion->total_pagar = max(0, ($cantidadBase * $valorUnitario) - $descuentos);
|
||||
|
||||
// Mantener campo redundante 'descuentos_cobros' sincronizado
|
||||
$confeccion->descuentos_cobros = $descuentos;
|
||||
|
||||
// Estado automático
|
||||
if (! $confeccion->cantidad_recibida) {
|
||||
@@ -81,12 +99,115 @@ class Confeccion extends Model
|
||||
// Total recibido calculado desde recepciones (fuente de la verdad)
|
||||
public function getRecibidoTotalAttribute()
|
||||
{
|
||||
return (int) $this->recepciones()->sum(\DB::raw('cantidad - COALESCE(prendas_defectuosas, 0)'));
|
||||
$recepciones = (int) $this->recepciones()->sum(\DB::raw('cantidad - COALESCE(prendas_defectuosas, 0)'));
|
||||
$ajustes = (int) $this->ajustes()->where('tipo', 'arreglo')->sum('cantidad');
|
||||
|
||||
return max(0, $recepciones - $ajustes);
|
||||
}
|
||||
|
||||
// Cuantas faltan por recibir (usa la suma real de recepciones)
|
||||
// Cuantas faltan por recibir (usa la suma real de recepciones menos ajustes)
|
||||
public function getFaltantesAttribute()
|
||||
{
|
||||
return max(0, (int)($this->cantidad_enviada ?? 0) - $this->recibido_total);
|
||||
}
|
||||
|
||||
// Total de cobros aplicados
|
||||
public function getCobrosTotalAttribute()
|
||||
{
|
||||
return (float) $this->cobros()->sum('valor');
|
||||
}
|
||||
|
||||
/**
|
||||
* Registrar un arreglo como ajuste histórico y crear traslado de reparaciones
|
||||
*/
|
||||
public function registerArreglo(int $cantidad, ?string $notas = null, ?int $userId = null)
|
||||
{
|
||||
if ($cantidad <= 0) {
|
||||
throw \Illuminate\Validation\ValidationException::withMessages(['cantidad' => 'La cantidad debe ser mayor que 0.']);
|
||||
}
|
||||
|
||||
$recibido = $this->recibido_total;
|
||||
if ($cantidad > $recibido) {
|
||||
throw \Illuminate\Validation\ValidationException::withMessages(['cantidad' => 'La cantidad supera lo recibido.']);
|
||||
}
|
||||
|
||||
// Crear ajuste
|
||||
$aj = \App\Models\Ajuste::create([
|
||||
'referencia_type' => self::class,
|
||||
'referencia_id' => $this->id,
|
||||
'user_id' => $userId,
|
||||
'tipo' => 'arreglo',
|
||||
'cantidad' => $cantidad,
|
||||
'notas' => $notas,
|
||||
]);
|
||||
|
||||
// Crear traslado de reparaciones para reflejar la salida
|
||||
\App\Models\TrasladoPrenda::create([
|
||||
'orden_produccion_id' => $this->orden_produccion_id,
|
||||
'referencia_type' => self::class,
|
||||
'referencia_id' => $this->id,
|
||||
'origen' => 'confeccion',
|
||||
'destino' => 'reparaciones',
|
||||
'cantidad_enviada' => $cantidad,
|
||||
'cantidad_recibida' => 0,
|
||||
'prendas_defectuosas' => 0,
|
||||
'reparaciones' => $cantidad,
|
||||
'fecha_envio' => now(),
|
||||
'fecha_recepcion' => now(),
|
||||
'estado' => 'recibido',
|
||||
]);
|
||||
|
||||
// Recalcular cantidad_recibida almacenada para compatibilidad con UI
|
||||
$this->cantidad_recibida = $this->recibido_total;
|
||||
$this->save();
|
||||
|
||||
return $aj;
|
||||
}
|
||||
|
||||
/**
|
||||
* Registrar un cobro: descontar inventario y crear registro de cobro
|
||||
*/
|
||||
public function registerCobro(int $cantidad, float $valor, ?string $notas = null, ?int $userId = null)
|
||||
{
|
||||
if ($cantidad <= 0) {
|
||||
throw \Illuminate\Validation\ValidationException::withMessages(['cantidad' => 'La cantidad debe ser mayor que 0.']);
|
||||
}
|
||||
|
||||
// Buscar inventario disponible
|
||||
$inventario = \App\Models\InventarioPrenda::where('orden_produccion_id', $this->orden_produccion_id)
|
||||
->where('cantidad_disponible', '>=', $cantidad)
|
||||
->first();
|
||||
|
||||
if (! $inventario) {
|
||||
throw \Illuminate\Validation\ValidationException::withMessages(['cantidad' => 'No hay inventario disponible suficiente para descontar.']);
|
||||
}
|
||||
|
||||
// Descontar del inventario
|
||||
$inventario->cantidad_disponible = $inventario->cantidad_disponible - $cantidad;
|
||||
$inventario->save();
|
||||
|
||||
// Si está asociado a producto, decrementar stock
|
||||
if ($inventario->producto_id) {
|
||||
$producto = \App\Models\Producto::find($inventario->producto_id);
|
||||
if ($producto) {
|
||||
$producto->decrement('stock', $cantidad);
|
||||
}
|
||||
}
|
||||
|
||||
// Crear registro de cobro
|
||||
$c = \App\Models\Cobro::create([
|
||||
'referencia_type' => self::class,
|
||||
'referencia_id' => $this->id,
|
||||
'user_id' => $userId,
|
||||
'cantidad' => $cantidad,
|
||||
'valor' => $valor,
|
||||
'notas' => $notas,
|
||||
]);
|
||||
|
||||
// Mantener campo redundante sincronizado
|
||||
$this->descuentos_cobros = $this->getCobrosTotalAttribute();
|
||||
$this->save();
|
||||
|
||||
return $c;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -153,6 +153,7 @@ class InventarioPrenda extends Model
|
||||
'precio_venta' => 0,
|
||||
'unidad_medida' => 'unidad',
|
||||
'codigo_barras' => $codigo,
|
||||
'categoria_id' => \App\Models\Categoria::first()?->id ?? \App\Models\Categoria::create(['nombre' => 'Generica'])->id,
|
||||
]);
|
||||
});
|
||||
}
|
||||
|
||||
@@ -14,6 +14,7 @@ class InventarioPrendaDistribucion extends Model
|
||||
protected $fillable = [
|
||||
'inventario_prenda_id',
|
||||
'bodega_id',
|
||||
'proveedor_id',
|
||||
'color_id',
|
||||
'size_id',
|
||||
'cantidad',
|
||||
@@ -52,8 +53,8 @@ class InventarioPrendaDistribucion extends Model
|
||||
$cantidad = intval($dist->cantidad ?? 0);
|
||||
$sumExistentes = (int) self::where('inventario_prenda_id', $parentId)->sum('cantidad');
|
||||
|
||||
// Validar contra la cantidad disponible actual
|
||||
if (($sumExistentes + $cantidad) > (int) $parent->cantidad_disponible) {
|
||||
// Validar contra la cantidad terminada total (no distribuir más del total entregado)
|
||||
if (($sumExistentes + $cantidad) > (int) $parent->cantidad_terminada) {
|
||||
throw \Illuminate\Validation\ValidationException::withMessages([
|
||||
'cantidad' => 'No se puede añadir más prendas que las disponibles.',
|
||||
]);
|
||||
@@ -72,8 +73,8 @@ class InventarioPrendaDistribucion extends Model
|
||||
->where('id', '<>', $dist->id)
|
||||
->sum('cantidad');
|
||||
|
||||
// Validar contra la cantidad disponible actual (considerando otras distribuciones)
|
||||
if (($othersSum + $newCantidad) > (int) $parent->cantidad_disponible) {
|
||||
// Validar contra la cantidad terminada total (no distribuir más del total entregado)
|
||||
if (($othersSum + $newCantidad) > (int) $parent->cantidad_terminada) {
|
||||
throw \Illuminate\Validation\ValidationException::withMessages([
|
||||
'cantidad' => 'No se puede añadir más prendas que las disponibles.',
|
||||
]);
|
||||
@@ -87,6 +88,18 @@ class InventarioPrendaDistribucion extends Model
|
||||
|
||||
$bodegaId = $dist->bodega_id;
|
||||
|
||||
// If a proveedor_id is present, treat as assignment to a provider/person (no warehouse stock changes)
|
||||
if ($dist->proveedor_id && ! $bodegaId) {
|
||||
// Just decrement disponibilidad on parent
|
||||
$parent = $dist->inventarioPrenda;
|
||||
if ($parent) {
|
||||
$parent->cantidad_disponible = max(0, $parent->cantidad_disponible - $cantidad);
|
||||
$parent->save();
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
if ($dist->color_id && $dist->size_id) {
|
||||
// Variante
|
||||
// Determinar producto: preferir inventario.prenda.producto_id -> op.producto_id
|
||||
@@ -158,6 +171,41 @@ class InventarioPrendaDistribucion extends Model
|
||||
} else {
|
||||
// Producto
|
||||
$productoId = $dist->inventarioPrenda->producto_id ?? ($dist->inventarioPrenda->ordenProduccion->producto_id ?? null);
|
||||
|
||||
// Si no existe producto, intentar crear/inferrir desde la Orden de Producción
|
||||
if (! $productoId && $dist->inventarioPrenda && $dist->inventarioPrenda->ordenProduccion) {
|
||||
$op = $dist->inventarioPrenda->ordenProduccion;
|
||||
$nombre = $op->prenda_modelo ?? $op->referencia ?? ('Producto OP #' . $op->id);
|
||||
|
||||
$codigo = 'AUTOP-' . $op->id . '-' . time();
|
||||
$codigo = substr($codigo, 0, 50);
|
||||
while (\App\Models\Producto::where('codigo_barras', $codigo)->exists()) {
|
||||
$codigo .= '-' . rand(0, 9);
|
||||
$codigo = substr($codigo, 0, 50);
|
||||
}
|
||||
|
||||
$producto = \App\Models\Producto::create([
|
||||
'nombre' => $nombre,
|
||||
'descripcion' => 'Creado automáticamente desde distribución (OP #' . $op->id . ')',
|
||||
'stock' => 0,
|
||||
'estado' => true,
|
||||
'precio_compra' => 0,
|
||||
'precio_venta' => 0,
|
||||
'unidad_medida' => 'unidad',
|
||||
'codigo_barras' => $codigo,
|
||||
'categoria_id' => \App\Models\Categoria::first()?->id ?? \App\Models\Categoria::create(['nombre' => 'Generica'])->id,
|
||||
]);
|
||||
|
||||
$productoId = $producto->id;
|
||||
|
||||
// Guardar producto en el inventario padre para futuras referencias
|
||||
$parent = $dist->inventarioPrenda;
|
||||
if ($parent && ! $parent->producto_id) {
|
||||
$parent->producto_id = $productoId;
|
||||
$parent->save();
|
||||
}
|
||||
}
|
||||
|
||||
if ($productoId) {
|
||||
$existing = \DB::table('producto_bodega')->where('producto_id', $productoId)->where('bodega_id', $bodegaId)->first();
|
||||
if ($existing) {
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
<?php
|
||||
|
||||
namespace App\Models;
|
||||
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
|
||||
class Ojal extends Model
|
||||
{
|
||||
protected $table = 'ojales';
|
||||
|
||||
protected $fillable = [
|
||||
'proveedor_id',
|
||||
'orden_produccion_id',
|
||||
'fecha_envio',
|
||||
'cantidad_enviada',
|
||||
'fecha_recepcion',
|
||||
'cantidad_recibida',
|
||||
'perdidas',
|
||||
];
|
||||
|
||||
public function proveedor()
|
||||
{
|
||||
return $this->belongsTo(Proveedor::class);
|
||||
}
|
||||
|
||||
public function ordenProduccion()
|
||||
{
|
||||
return $this->belongsTo(OrdenProduccion::class);
|
||||
}
|
||||
|
||||
protected static function booted()
|
||||
{
|
||||
static::creating(function ($p) {
|
||||
// Validar disponibilidad desde confecciones
|
||||
$opId = $p->orden_produccion_id;
|
||||
$totalProducido = \App\Models\Confeccion::where('orden_produccion_id', $opId)->sum('cantidad_recibida');
|
||||
$yaAsignado = \App\Models\Prensilla::where('orden_produccion_id', $opId)->sum('cantidad_enviada')
|
||||
+ \App\Models\Ojal::where('orden_produccion_id', $opId)->sum('cantidad_enviada');
|
||||
|
||||
if (($yaAsignado + ($p->cantidad_enviada ?? 0)) > $totalProducido) {
|
||||
throw \Illuminate\Validation\ValidationException::withMessages(['cantidad_enviada' => 'No hay suficientes unidades disponibles desde confecciones para asignar.']);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -53,6 +53,16 @@ class OrdenProduccion extends Model
|
||||
return $this->hasMany(\App\Models\Tintoreria::class);
|
||||
}
|
||||
|
||||
public function prensillas()
|
||||
{
|
||||
return $this->hasMany(\App\Models\Prensilla::class);
|
||||
}
|
||||
|
||||
public function ojales()
|
||||
{
|
||||
return $this->hasMany(\App\Models\Ojal::class);
|
||||
}
|
||||
|
||||
public function procesosAcabado()
|
||||
{
|
||||
return $this->hasMany(\App\Models\ProcesoAcabado::class);
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
<?php
|
||||
|
||||
namespace App\Models;
|
||||
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
|
||||
class Prensilla extends Model
|
||||
{
|
||||
protected $fillable = [
|
||||
'proveedor_id',
|
||||
'orden_produccion_id',
|
||||
'fecha_envio',
|
||||
'cantidad_enviada',
|
||||
'fecha_recepcion',
|
||||
'cantidad_recibida',
|
||||
'perdidas',
|
||||
];
|
||||
|
||||
public function proveedor()
|
||||
{
|
||||
return $this->belongsTo(Proveedor::class);
|
||||
}
|
||||
|
||||
public function ordenProduccion()
|
||||
{
|
||||
return $this->belongsTo(OrdenProduccion::class);
|
||||
}
|
||||
|
||||
protected static function booted()
|
||||
{
|
||||
static::creating(function ($p) {
|
||||
// Validar disponibilidad desde confecciones
|
||||
$opId = $p->orden_produccion_id;
|
||||
$totalProducido = \App\Models\Confeccion::where('orden_produccion_id', $opId)->sum('cantidad_recibida');
|
||||
$yaAsignado = \App\Models\Prensilla::where('orden_produccion_id', $opId)->sum('cantidad_enviada')
|
||||
+ \App\Models\Ojal::where('orden_produccion_id', $opId)->sum('cantidad_enviada');
|
||||
|
||||
if (($yaAsignado + ($p->cantidad_enviada ?? 0)) > $totalProducido) {
|
||||
throw \Illuminate\Validation\ValidationException::withMessages(['cantidad_enviada' => 'No hay suficientes unidades disponibles desde confecciones para asignar.']);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
+115
-2
@@ -63,16 +63,124 @@ class Tintoreria extends Model
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Registrar un reproceso: crear ajuste histórico y traslado de reproceso
|
||||
*/
|
||||
public function registerReproceso(int $cantidad, ?string $notas = null, ?int $userId = null)
|
||||
{
|
||||
if ($cantidad <= 0) {
|
||||
throw \Illuminate\Validation\ValidationException::withMessages(['cantidad' => 'La cantidad debe ser mayor que 0.']);
|
||||
}
|
||||
|
||||
$recibido = $this->recibido_total;
|
||||
if ($cantidad > $recibido) {
|
||||
throw \Illuminate\Validation\ValidationException::withMessages(['cantidad' => 'La cantidad supera lo recibido.']);
|
||||
}
|
||||
|
||||
// Crear ajuste de tipo reproceso
|
||||
$aj = \App\Models\Ajuste::create([
|
||||
'referencia_type' => self::class,
|
||||
'referencia_id' => $this->id,
|
||||
'user_id' => $userId,
|
||||
'tipo' => 'reproceso',
|
||||
'cantidad' => $cantidad,
|
||||
'notas' => $notas,
|
||||
]);
|
||||
|
||||
// Crear traslado de reprocesos para reflejar la operación
|
||||
\App\Models\TrasladoPrenda::create([
|
||||
'orden_produccion_id' => $this->orden_produccion_id,
|
||||
'referencia_type' => self::class,
|
||||
'referencia_id' => $this->id,
|
||||
'origen' => 'tintoreria',
|
||||
'destino' => 'reprocesos',
|
||||
'cantidad_enviada' => $cantidad,
|
||||
'cantidad_recibida' => 0,
|
||||
'prendas_defectuosas' => 0,
|
||||
'reparaciones' => 0,
|
||||
'saldos' => 0,
|
||||
'fecha_envio' => now(),
|
||||
'fecha_recepcion' => now(),
|
||||
'estado' => 'recibido',
|
||||
]);
|
||||
|
||||
// Recalcular cantidad_recibida almacenada para compatibilidad con UI
|
||||
$this->cantidad_recibida = $this->recibido_total;
|
||||
$this->save();
|
||||
|
||||
return $aj;
|
||||
}
|
||||
|
||||
/**
|
||||
* Registrar un cobro: descontar inventario y crear registro de cobro
|
||||
*/
|
||||
public function registerCobro(int $cantidad, float $valor, ?string $notas = null, ?int $userId = null)
|
||||
{
|
||||
if ($cantidad <= 0) {
|
||||
throw \Illuminate\Validation\ValidationException::withMessages(['cantidad' => 'La cantidad debe ser mayor que 0.']);
|
||||
}
|
||||
|
||||
// Buscar inventario disponible
|
||||
$inventario = \App\Models\InventarioPrenda::where('orden_produccion_id', $this->orden_produccion_id)
|
||||
->where('cantidad_disponible', '>=', $cantidad)
|
||||
->first();
|
||||
|
||||
if (! $inventario) {
|
||||
throw \Illuminate\Validation\ValidationException::withMessages(['cantidad' => 'No hay inventario disponible suficiente para descontar.']);
|
||||
}
|
||||
|
||||
// Descontar del inventario
|
||||
$inventario->cantidad_disponible = $inventario->cantidad_disponible - $cantidad;
|
||||
$inventario->save();
|
||||
|
||||
// Si está asociado a producto, decrementar stock
|
||||
if ($inventario->producto_id) {
|
||||
$producto = \App\Models\Producto::find($inventario->producto_id);
|
||||
if ($producto) {
|
||||
$producto->decrement('stock', $cantidad);
|
||||
}
|
||||
}
|
||||
|
||||
// Crear registro de cobro
|
||||
$c = \App\Models\Cobro::create([
|
||||
'referencia_type' => self::class,
|
||||
'referencia_id' => $this->id,
|
||||
'user_id' => $userId,
|
||||
'cantidad' => $cantidad,
|
||||
'valor' => $valor,
|
||||
'notas' => $notas,
|
||||
]);
|
||||
|
||||
// Mantener campo redundante sincronizado
|
||||
$this->descuentos_cobros = $this->getCobrosTotalAttribute();
|
||||
$this->save();
|
||||
|
||||
return $c;
|
||||
}
|
||||
|
||||
/* Recepciones polimórficas */
|
||||
public function recepciones()
|
||||
{
|
||||
return $this->morphMany(\App\Models\Recepcion::class, 'referencia');
|
||||
}
|
||||
|
||||
// Total recibido calculado desde recepciones (fuente de la verdad)
|
||||
public function cobros()
|
||||
{
|
||||
return $this->morphMany(\App\Models\Cobro::class, 'referencia');
|
||||
}
|
||||
|
||||
public function ajustes()
|
||||
{
|
||||
return $this->morphMany(\App\Models\Ajuste::class, 'referencia');
|
||||
}
|
||||
|
||||
// Total recibido calculado desde recepciones (fuente de la verdad) menos reprocesos
|
||||
public function getRecibidoTotalAttribute()
|
||||
{
|
||||
return (int) $this->recepciones()->sum(\DB::raw('cantidad - COALESCE(prendas_defectuosas, 0)'));
|
||||
$recepciones = (int) $this->recepciones()->sum(\DB::raw('cantidad - COALESCE(prendas_defectuosas, 0)'));
|
||||
$reprocesos = (int) $this->ajustes()->where('tipo', 'reproceso')->sum('cantidad');
|
||||
|
||||
return max(0, $recepciones - $reprocesos);
|
||||
}
|
||||
|
||||
// Total de pérdidas registradas en las recepciones
|
||||
@@ -81,6 +189,11 @@ class Tintoreria extends Model
|
||||
return (int) $this->recepciones()->sum('prendas_defectuosas');
|
||||
}
|
||||
|
||||
public function getCobrosTotalAttribute()
|
||||
{
|
||||
return (float) $this->cobros()->sum('valor');
|
||||
}
|
||||
|
||||
// Cuantas faltan por recibir (usa la suma real de recepciones)
|
||||
public function getFaltantesAttribute()
|
||||
{
|
||||
|
||||
Reference in New Issue
Block a user