Files
pos_heidiver/tests/Feature/InventarioDistribucionTest.php
2026-01-28 23:38:21 -05:00

282 lines
15 KiB
PHP

<?php
namespace Tests\Feature;
use Tests\TestCase;
use Illuminate\Foundation\Testing\RefreshDatabase;
use App\Models\Bodega;
use App\Models\Color;
use App\Models\Size;
use App\Models\Producto;
use App\Models\OrdenProduccion;
use App\Models\InventarioPrenda;
use App\Models\InventarioPrendaDistribucion;
use App\Models\ProductVariant;
class InventarioDistribucionTest extends TestCase
{
use RefreshDatabase;
public function test_distribution_create_updates_variant_and_bodega_stock()
{
$bodega = Bodega::create(['nombre' => 'Bodega A']);
$color = Color::create(['name' => 'Rojo', 'hex_code' => '#ff0000']);
$size = Size::create(['name' => 'M']);
$categoria = \App\Models\Categoria::create(['nombre' => 'Ropa']);
$producto = Producto::create(['nombre' => 'Camiseta', 'descripcion' => '', 'stock' => 0, 'estado' => true, 'precio_compra' => 0, 'precio_venta' => 0, 'unidad_medida' => 'unidad', 'codigo_barras' => '', 'categoria_id' => $categoria->id, 'imagen' => '']);
$op = OrdenProduccion::create(['numero_orden' => 'OP-0001', 'prenda_modelo' => 'Camiseta', 'referencia' => 'C-01', 'cantidad_total' => 10, 'metros_requeridos' => 0, 'fecha_inicio' => now(), 'fecha_entrega_estimada' => now()->addDays(7)]);
\App\Models\ProcesoAcabado::create(['orden_produccion_id' => $op->id, 'tipo_proceso' => 'Acabado', 'cantidad_enviada' => 0, 'cantidad_recibida' => 5, 'fecha_recepcion' => now()]);
$inv = InventarioPrenda::create(['orden_produccion_id' => $op->id, 'cantidad_terminada' => 5, 'cantidad_disponible' => 5, 'fecha_ingreso' => now(), 'estado' => 'en_bodega', 'producto_id' => $producto->id]);
// Crear distribución
$dist = InventarioPrendaDistribucion::create([
'inventario_prenda_id' => $inv->id,
'bodega_id' => $bodega->id,
'color_id' => $color->id,
'size_id' => $size->id,
'cantidad' => 3,
]);
// El evento debe haber creado la variante
$variant = ProductVariant::where('producto_id', $producto->id)->where('color_id', $color->id)->where('size_id', $size->id)->first();
$this->assertNotNull($variant, 'Variant should be created');
$this->assertEquals(3, $variant->stock);
// Revisar pivot variante_bodega
$pivot = \DB::table('variante_bodega')->where('variante_id', $variant->id)->where('bodega_id', $bodega->id)->first();
$this->assertNotNull($pivot);
$this->assertEquals(3, $pivot->stock);
// El inventario padre debe quedar ligado al producto si se creó automáticamente
$inv->refresh();
$this->assertNotNull($inv->producto_id);
$this->assertEquals($variant->producto_id, $inv->producto_id);
}
public function test_distribution_creates_and_links_product_when_missing()
{
$categoria = \App\Models\Categoria::create(['nombre' => 'Ropa']);
$op = OrdenProduccion::create(['numero_orden' => 'OP-0100', 'prenda_modelo' => 'PrendaX', 'referencia' => 'PX-01', 'cantidad_total' => 10, 'metros_requeridos' => 0, 'fecha_inicio' => now(), 'fecha_entrega_estimada' => now()->addDays(7)]);
\App\Models\ProcesoAcabado::create(['orden_produccion_id' => $op->id, 'tipo_proceso' => 'Acabado', 'cantidad_enviada' => 0, 'cantidad_recibida' => 5, 'fecha_recepcion' => now()]);
$inv = InventarioPrenda::create(['orden_produccion_id' => $op->id, 'cantidad_terminada' => 5, 'cantidad_disponible' => 5, 'fecha_ingreso' => now(), 'estado' => 'en_bodega', 'producto_id' => null]);
// Crear distribución sin producto previo
$dist = InventarioPrendaDistribucion::create([
'inventario_prenda_id' => $inv->id,
'bodega_id' => 1,
'color_id' => null,
'size_id' => null,
'cantidad' => 2,
]);
// Verificar que se creó un producto y que el inventario padre quedó ligado
$inv->refresh();
$this->assertNotNull($inv->producto_id);
$producto = \App\Models\Producto::find($inv->producto_id);
$this->assertNotNull($producto);
// Y que la distribución llevó stock al producto en la bodega
$pivot = \DB::table('producto_bodega')->where('producto_id', $producto->id)->where('bodega_id', 1)->first();
$this->assertNotNull($pivot);
$this->assertEquals(2, $pivot->stock);
}
public function test_distribution_does_not_double_increment_product_stock()
{
$categoria = \App\Models\Categoria::create(['nombre' => 'Ropa']);
$producto = Producto::create(['nombre' => 'Doblez', 'descripcion' => '', 'stock' => 0, 'estado' => true, 'precio_compra' => 0, 'precio_venta' => 0, 'unidad_medida' => 'unidad', 'codigo_barras' => '', 'categoria_id' => $categoria->id, 'imagen' => '']);
$op = OrdenProduccion::create(['numero_orden' => 'OP-0200', 'prenda_modelo' => 'Doblez', 'referencia' => 'D-01', 'cantidad_total' => 10, 'metros_requeridos' => 0, 'fecha_inicio' => now(), 'fecha_entrega_estimada' => now()->addDays(7)]);
// Crear inventario: esto incrementa el stock global del producto en +5
\App\Models\ProcesoAcabado::create(['orden_produccion_id' => $op->id, 'tipo_proceso' => 'Acabado', 'cantidad_enviada' => 0, 'cantidad_recibida' => 5, 'fecha_recepcion' => now()]);
$inv = InventarioPrenda::create(['orden_produccion_id' => $op->id, 'cantidad_terminada' => 5, 'cantidad_disponible' => 5, 'fecha_ingreso' => now(), 'estado' => 'en_bodega', 'producto_id' => $producto->id]);
$producto->refresh();
$this->assertEquals(5, $producto->stock, 'Stock should be increased by inventario creation');
// Crear distribución: no debe aumentar nuevamente el stock global del producto
InventarioPrendaDistribucion::create([
'inventario_prenda_id' => $inv->id,
'bodega_id' => 1,
'color_id' => null,
'size_id' => null,
'cantidad' => 2,
]);
$producto->refresh();
$this->assertEquals(5, $producto->stock, 'Stock should NOT be increased by distribution creator (no double count)');
$pivot = \DB::table('producto_bodega')->where('producto_id', $producto->id)->where('bodega_id', 1)->first();
$this->assertNotNull($pivot);
$this->assertEquals(2, $pivot->stock);
}
public function test_creating_inventario_with_excessive_distributions_throws_validation_exception()
{
$categoria = \App\Models\Categoria::create(['nombre' => 'Ropa']);
$producto = Producto::create(['nombre' => 'Polo', 'descripcion' => '', 'stock' => 0, 'estado' => true, 'precio_compra' => 0, 'precio_venta' => 0, 'unidad_medida' => 'unidad', 'codigo_barras' => '', 'categoria_id' => $categoria->id, 'imagen' => '']);
$op = OrdenProduccion::create(['numero_orden' => 'OP-0002', 'prenda_modelo' => 'Polo', 'referencia' => 'P-01', 'cantidad_total' => 10, 'metros_requeridos' => 0, 'fecha_inicio' => now(), 'fecha_entrega_estimada' => now()->addDays(7)]);
\App\Models\ProcesoAcabado::create(['orden_produccion_id' => $op->id, 'tipo_proceso' => 'Acabado', 'cantidad_enviada' => 0, 'cantidad_recibida' => 5, 'fecha_recepcion' => now()]);
$data = [
'orden_produccion_id' => $op->id,
'cantidad_terminada' => 5,
'cantidad_disponible' => 5,
'fecha_ingreso' => now()->toDateString(),
'producto_id' => $producto->id,
'estado' => 'en_bodega',
'distribuciones' => [
['bodega_id' => 1, 'cantidad' => 3],
['bodega_id' => 1, 'cantidad' => 3],
],
];
$this->expectException(\Illuminate\Validation\ValidationException::class);
$page = new \App\Filament\Resources\InventarioPrendaResource\Pages\CreateInventarioPrenda();
$ref = new \ReflectionClass($page);
$method = $ref->getMethod('handleRecordCreation');
$method->setAccessible(true);
$method->invoke($page, $data);
}
public function test_creating_distribution_directly_exceeding_throws_validation_exception()
{
$categoria = \App\Models\Categoria::create(['nombre' => 'Ropa']);
$producto = Producto::create(['nombre' => 'Camisa', 'descripcion' => '', 'stock' => 0, 'estado' => true, 'precio_compra' => 0, 'precio_venta' => 0, 'unidad_medida' => 'unidad', 'codigo_barras' => '', 'categoria_id' => $categoria->id, 'imagen' => '']);
$op = OrdenProduccion::create(['numero_orden' => 'OP-0003', 'prenda_modelo' => 'Camisa', 'referencia' => 'C-02', 'cantidad_total' => 10, 'metros_requeridos' => 0, 'fecha_inicio' => now(), 'fecha_entrega_estimada' => now()->addDays(7)]);
\App\Models\ProcesoAcabado::create(['orden_produccion_id' => $op->id, 'tipo_proceso' => 'Acabado', 'cantidad_enviada' => 0, 'cantidad_recibida' => 5, 'fecha_recepcion' => now()]);
$inv = InventarioPrenda::create(['orden_produccion_id' => $op->id, 'cantidad_terminada' => 5, 'cantidad_disponible' => 5, 'fecha_ingreso' => now(), 'estado' => 'en_bodega', 'producto_id' => $producto->id]);
// Crear primera distribución 2
InventarioPrendaDistribucion::create([
'inventario_prenda_id' => $inv->id,
'bodega_id' => 1,
'cantidad' => 2,
]);
$this->expectException(\Illuminate\Validation\ValidationException::class);
// Intentar crear una segunda distribución que exceda (4) => 2 + 4 = 6 > 5
InventarioPrendaDistribucion::create([
'inventario_prenda_id' => $inv->id,
'bodega_id' => 1,
'cantidad' => 4,
]);
}
public function test_updating_distribution_exceeding_throws_validation_exception()
{
$categoria = \App\Models\Categoria::create(['nombre' => 'Ropa']);
$producto = Producto::create(['nombre' => 'Saco', 'descripcion' => '', 'stock' => 0, 'estado' => true, 'precio_compra' => 0, 'precio_venta' => 0, 'unidad_medida' => 'unidad', 'codigo_barras' => '', 'categoria_id' => $categoria->id, 'imagen' => '']);
$op = OrdenProduccion::create(['numero_orden' => 'OP-0004', 'prenda_modelo' => 'Saco', 'referencia' => 'S-01', 'cantidad_total' => 10, 'metros_requeridos' => 0, 'fecha_inicio' => now(), 'fecha_entrega_estimada' => now()->addDays(7)]);
\App\Models\ProcesoAcabado::create(['orden_produccion_id' => $op->id, 'tipo_proceso' => 'Acabado', 'cantidad_enviada' => 0, 'cantidad_recibida' => 5, 'fecha_recepcion' => now()]);
$inv = InventarioPrenda::create(['orden_produccion_id' => $op->id, 'cantidad_terminada' => 5, 'cantidad_disponible' => 5, 'fecha_ingreso' => now(), 'estado' => 'en_bodega', 'producto_id' => $producto->id]);
// Crear dos distribuciones 2 y 2
$d1 = InventarioPrendaDistribucion::create([
'inventario_prenda_id' => $inv->id,
'bodega_id' => 1,
'cantidad' => 2,
]);
$d2 = InventarioPrendaDistribucion::create([
'inventario_prenda_id' => $inv->id,
'bodega_id' => 1,
'cantidad' => 2,
]);
$this->expectException(\Illuminate\Validation\ValidationException::class);
// Intentar actualizar d1 a 4 => 4 + 2 = 6 > 5
$d1->cantidad = 4;
$d1->save();
}
public function test_distribution_to_providers_decreases_disponible_and_does_not_create_bodega_stock()
{
$categoria = \App\Models\Categoria::create(['nombre' => 'Ropa']);
$producto = Producto::create(['nombre' => 'Equipo', 'descripcion' => '', 'stock' => 0, 'estado' => true, 'precio_compra' => 0, 'precio_venta' => 0, 'unidad_medida' => 'unidad', 'codigo_barras' => '', 'categoria_id' => $categoria->id, 'imagen' => '']);
$op = OrdenProduccion::create(['numero_orden' => 'OP-1000', 'prenda_modelo' => 'Equipo', 'referencia' => 'E-01', 'cantidad_total' => 10, 'metros_requeridos' => 0, 'fecha_inicio' => now(), 'fecha_entrega_estimada' => now()->addDays(7)]);
\App\Models\ProcesoAcabado::create(['orden_produccion_id' => $op->id, 'tipo_proceso' => 'Acabado', 'cantidad_enviada' => 0, 'cantidad_recibida' => 10, 'fecha_recepcion' => now()]);
// La creación del ProcesoAcabado puede crear automáticamente el inventario al finalizar la OP.
$inv = \App\Models\InventarioPrenda::where('orden_produccion_id', $op->id)->first();
$this->assertNotNull($inv);
$p1 = \App\Models\Proveedor::create(['nombre' => 'Proveedor 1']);
$p2 = \App\Models\Proveedor::create(['nombre' => 'Proveedor 2']);
// Crear distribuciones a proveedores
InventarioPrendaDistribucion::create([
'inventario_prenda_id' => $inv->id,
'proveedor_id' => $p1->id,
'cantidad' => 4,
]);
InventarioPrendaDistribucion::create([
'inventario_prenda_id' => $inv->id,
'proveedor_id' => $p2->id,
'cantidad' => 5,
]);
// No deben crearse filas en producto_bodega / variante_bodega
$this->assertEquals(0, \DB::table('producto_bodega')->count());
$this->assertEquals(0, \DB::table('variante_bodega')->count());
$inv->refresh();
$this->assertEquals(1, $inv->cantidad_disponible);
}
public function test_provider_distributions_exceeding_throws_validation_exception()
{
$categoria = \App\Models\Categoria::create(['nombre' => 'Ropa']);
$producto = Producto::create(['nombre' => 'Surtido', 'descripcion' => '', 'stock' => 0, 'estado' => true, 'precio_compra' => 0, 'precio_venta' => 0, 'unidad_medida' => 'unidad', 'codigo_barras' => '', 'categoria_id' => $categoria->id, 'imagen' => '']);
$op = OrdenProduccion::create(['numero_orden' => 'OP-2000', 'prenda_modelo' => 'Surtido', 'referencia' => 'S-02', 'cantidad_total' => 10, 'metros_requeridos' => 0, 'fecha_inicio' => now(), 'fecha_entrega_estimada' => now()->addDays(7)]);
\App\Models\ProcesoAcabado::create(['orden_produccion_id' => $op->id, 'tipo_proceso' => 'Acabado', 'cantidad_enviada' => 0, 'cantidad_recibida' => 5, 'fecha_recepcion' => now()]);
$inv = InventarioPrenda::create(['orden_produccion_id' => $op->id, 'cantidad_terminada' => 5, 'cantidad_disponible' => 5, 'fecha_ingreso' => now(), 'estado' => 'en_bodega', 'producto_id' => $producto->id]);
$p = \App\Models\Proveedor::create(['nombre' => 'Proveedor X']);
// Primera distribución 3
InventarioPrendaDistribucion::create([
'inventario_prenda_id' => $inv->id,
'proveedor_id' => $p->id,
'cantidad' => 3,
]);
$this->expectException(\Illuminate\Validation\ValidationException::class);
// Intentar crear 3 nuevamente => 3 + 3 = 6 > 5
InventarioPrendaDistribucion::create([
'inventario_prenda_id' => $inv->id,
'proveedor_id' => $p->id,
'cantidad' => 3,
]);
}
}