Skip to content

Commit 9472e31

Browse files
authored
Merge pull request #70 from chechojgb/buttonsLovers
fix: correcion modelo de movimientos
2 parents 89c7ab3 + fede1e1 commit 9472e31

File tree

8 files changed

+182
-125
lines changed

8 files changed

+182
-125
lines changed

app/Http/Controllers/BlProductoController.php

Lines changed: 36 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -49,53 +49,62 @@ public function indexHistorico()
4949
{
5050
$user = Auth::user();
5151
$productos = BlProducto::with(['color', 'empaques.movimientos'])
52-
->get()
53-
->map(function ($producto) {
54-
return [
55-
'id' => $producto->id,
56-
'tipo_producto' => $producto->tipo_producto,
57-
'tamanio' => $producto->tamanio,
58-
'color_nombre' => $producto->color->nombre,
59-
'descripcion' => $producto->descripcion,
60-
'stock_total' => $producto->empaques->sum(function ($empaque) {
61-
return $empaque->movimientos->sum('cantidad') * $empaque->cantidad_por_empaque;
62-
}),
63-
];
64-
});
65-
$entrada = BlMovimiento::with(['empaque.producto', 'usuario'])
66-
->where('tipo', 'entrada')
67-
->whereHas('empaque.producto')
68-
->get()
69-
->map(function ($movimiento) {
52+
->get()
53+
->map(function ($producto) {
54+
return [
55+
'id' => $producto->id,
56+
'tipo_producto' => $producto->tipo_producto,
57+
'tamanio' => $producto->tamanio,
58+
'color_nombre' => $producto->color->nombre,
59+
'descripcion' => $producto->descripcion,
60+
'stock_total' => $producto->empaques->sum(function ($empaque) {
61+
return $empaque->movimientos->sum('cantidad') * $empaque->cantidad_por_empaque;
62+
}),
63+
];
64+
});
65+
$entrada = BlMovimiento::with(['movible.empaque.producto.color', 'usuario'])
66+
->where('tipo', 'entrada')
67+
->get()
68+
->map(function ($movimiento) {
69+
if ($movimiento->movible instanceof \App\Models\BLPedidoItem) {
70+
$item = $movimiento->movible;
71+
$producto = $item->empaque->producto;
72+
7073
return [
7174
'id' => $movimiento->id,
72-
'producto' => $movimiento->empaque->producto->tipo_producto ,
73-
'tamanio' => $movimiento->empaque->producto->tamanio,
74-
'color' => $movimiento->empaque->producto->color->nombre,
75+
'pedido_id' => $item->pedido_id,
76+
'producto' => $producto->tipo_producto,
77+
'tamanio' => $producto->tamanio,
78+
'color' => $producto->color->nombre,
79+
'cantidad_empaques' => $item->cantidad_empaques,
7580
'cantidad' => $movimiento->cantidad,
7681
'motivo' => $movimiento->motivo,
7782
'usuario' => $movimiento->usuario->name,
7883
'fecha' => $movimiento->created_at->format('d-m-Y H:i'),
79-
'tipo'=> $movimiento->tipo,
80-
'codigo_unico' => $movimiento->empaque->codigo_unico,
81-
'cantidad_por_empaque' => $movimiento->empaque->cantidad_por_empaque,
84+
'tipo' => $movimiento->tipo,
8285
];
83-
});
84-
$marcacion = BlMovimiento::with(['empaque.producto', 'usuario'])
86+
}
87+
88+
return null; // si el movible no es un BLPedidoItem
89+
})
90+
->filter();
91+
$marcacion = BlMovimiento::with(['movible', 'usuario'])
8592
->where('tipo', 'pedido')
8693
->whereIn('motivo', [
8794
'Cambio de estado a en proceso',
8895
'Cambio de estado a completado'
8996
])
9097
->get();
9198
// dd($marcacion);
99+
$entrega = BLPedido::with('cliente')->where('estado', 'entregado')->get();
92100

93101
return Inertia::render('BLHistorico', [
94102
'productos' => $productos,
95103
'colores' => BlColor::all(),
96104
'user' => $user,
97105
'marcacion' => $marcacion,
98-
'entrada' => $entrada
106+
'entrada' => $entrada,
107+
'entrega' => $entrega
99108
]);
100109
}
101110

app/Http/Controllers/DashboardController.php

Lines changed: 52 additions & 49 deletions
Original file line numberDiff line numberDiff line change
@@ -17,22 +17,25 @@ class DashboardController extends Controller
1717
public function index()
1818
{
1919
$user = Auth::user();
20-
$productos = BlProducto::with(['color', 'empaques.movimientos'])
20+
$productos = BlProducto::with('color')
21+
->withSum(['empaques as stock_total' => function ($q) {
22+
$q->where('estado', 'disponible');
23+
}], 'cantidad_por_empaque')
2124
->get()
25+
->filter(function ($producto) {
26+
return $producto->stock_total > 0; // ✅ filtrar en memoria
27+
})
28+
->take(10)
2229
->map(function ($producto) {
2330
return [
2431
'id' => $producto->id,
2532
'tipo_producto' => $producto->tipo_producto,
2633
'tamanio' => $producto->tamanio,
2734
'color_nombre' => $producto->color->codigo,
2835
'descripcion' => $producto->descripcion,
29-
'stock_total' => $producto->empaques->sum(function ($empaque) {
30-
return $empaque->movimientos->sum('cantidad') * $empaque->cantidad_por_empaque;
31-
}),
36+
'stock_total' => $producto->stock_total ?? 0,
3237
];
33-
})
34-
->where('stock_total', '>', 1)
35-
->take(10);
38+
});
3639
// dd($productos->pluck('descripcion'));
3740
$rankingProductos = BLPedido::with(['items.empaque.producto'])
3841
->get()
@@ -63,7 +66,7 @@ public function index()
6366

6467
$pedidosEspera = BLPedido::get()
6568
->where('estado', 'pendiente');
66-
$movimientos = BlMovimiento::with(['empaque.producto'])->orderByDesc('created_at')->take(6)->get();
69+
$movimientos = BlMovimiento::with(['movible'])->orderByDesc('created_at')->take(6)->get();
6770
// dd($movimientos);
6871
$produccion = $this->produccionSemanal();
6972

@@ -78,49 +81,49 @@ public function index()
7881
]);
7982
}
8083

81-
public function produccionSemanal()
82-
{
83-
$dias = [
84-
'Monday' => 'Lun',
85-
'Tuesday' => 'Mar',
86-
'Wednesday' => 'Mié',
87-
'Thursday' => 'Jue',
88-
'Friday' => 'Vie',
89-
'Saturday' => 'Sáb',
90-
'Sunday' => 'Dom',
91-
];
92-
93-
// Rango de la semana actual (Lunes a Domingo)
94-
$inicioSemana = \Carbon\Carbon::now('America/Bogota')->startOfWeek();
95-
$finSemana = \Carbon\Carbon::now('America/Bogota')->endOfWeek();
96-
97-
// Obtener registros agrupados por fecha usando updated_at
98-
$registros = BLPedidoItem::where('estado', 'completado')
99-
->whereBetween('updated_at', [$inicioSemana, $finSemana])
100-
->get()
101-
->groupBy(function ($item) {
102-
return \Carbon\Carbon::parse($item->updated_at)
103-
->setTimezone('America/Bogota')
104-
->format('Y-m-d');
105-
});
106-
107-
// Crear la estructura de la semana completa
108-
$data = collect();
109-
for ($fecha = $inicioSemana->copy(); $fecha <= $finSemana; $fecha->addDay()) {
110-
$fechaStr = $fecha->format('Y-m-d');
111-
$grupo = $registros->get($fechaStr, collect());
112-
113-
$data->push([
114-
'fecha' => $fechaStr,
115-
'dia' => $dias[$fecha->format('l')],
116-
'produccion' => $grupo->sum('cantidad_empaques'),
117-
'timestamps' => $grupo->pluck('updated_at'),
118-
]);
84+
public function produccionSemanal()
85+
{
86+
$dias = [
87+
'Monday' => 'Lun',
88+
'Tuesday' => 'Mar',
89+
'Wednesday' => 'Mié',
90+
'Thursday' => 'Jue',
91+
'Friday' => 'Vie',
92+
'Saturday' => 'Sáb',
93+
'Sunday' => 'Dom',
94+
];
95+
96+
// Rango de la semana actual (Lunes a Domingo)
97+
$inicioSemana = \Carbon\Carbon::now('America/Bogota')->startOfWeek();
98+
$finSemana = \Carbon\Carbon::now('America/Bogota')->endOfWeek();
99+
100+
// Obtener registros agrupados por fecha usando updated_at
101+
$registros = BLPedidoItem::where('estado', 'completado')
102+
->whereBetween('updated_at', [$inicioSemana, $finSemana])
103+
->get()
104+
->groupBy(function ($item) {
105+
return \Carbon\Carbon::parse($item->updated_at)
106+
->setTimezone('America/Bogota')
107+
->format('Y-m-d');
108+
});
109+
110+
// Crear la estructura de la semana completa
111+
$data = collect();
112+
for ($fecha = $inicioSemana->copy(); $fecha <= $finSemana; $fecha->addDay()) {
113+
$fechaStr = $fecha->format('Y-m-d');
114+
$grupo = $registros->get($fechaStr, collect());
115+
116+
$data->push([
117+
'fecha' => $fechaStr,
118+
'dia' => $dias[$fecha->format('l')],
119+
'produccion' => $grupo->sum('cantidad_empaques'),
120+
'timestamps' => $grupo->pluck('updated_at'),
121+
]);
122+
}
123+
124+
return $data->values();
119125
}
120126

121-
return $data->values();
122-
}
123-
124127

125128

126129

app/Models/BlEmpaque.php

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
use Illuminate\Database\Eloquent\Model;
66
use Illuminate\Database\Eloquent\Relations\BelongsTo;
77
use Illuminate\Database\Eloquent\Relations\HasMany;
8+
use Illuminate\Database\Eloquent\Relations\MorphMany;
89

910
class BlEmpaque extends Model
1011
{
@@ -18,9 +19,9 @@ public function producto(): BelongsTo
1819
}
1920

2021
// Relación: Un empaque puede tener muchos movimientos
21-
public function movimientos(): HasMany
22+
public function movimientos(): MorphMany
2223
{
23-
return $this->hasMany(BlMovimiento::class, 'empaque_id');
24+
return $this->morphMany(BlMovimiento::class, 'movible');
2425
}
2526

2627
// Accesor: Total de unidades en stock para este empaque

app/Models/BlMovimiento.php

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -37,10 +37,10 @@ public function movible()
3737
}
3838

3939
// Relación: Un movimiento pertenece a un empaque
40-
public function empaque(): BelongsTo
41-
{
42-
return $this->belongsTo(BlEmpaque::class, 'empaque_id');
43-
}
40+
// public function empaque(): BelongsTo
41+
// {
42+
// return $this->belongsTo(BlEmpaque::class, 'empaque_id');
43+
// }
4444

4545
// Relación: Un movimiento puede tener un usuario asociado (opcional)
4646
public function usuario(): BelongsTo

resources/js/components/BL/historicoBL.jsx

Lines changed: 65 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,14 @@
11
import { Card, CardContent } from "@/components/ui/card";
22
import { Badge } from "@/components/ui/badge";
3-
import { ArrowDown, ArrowUp } from "lucide-react";
3+
import { ArrowDown, ArrowUp,PackageCheck } from "lucide-react";
44
import { format } from "date-fns";
55

66
export default function EntradaBL({ historico }) {
7+
// Convertir el objeto en array
8+
const historicoArray = Object.values(historico || {});
9+
710
// Filtrar solo las entradas
8-
const entradas = historico?.filter((item) => item.tipo === "entrada") || [];
11+
const entradas = historicoArray.filter((item) => item.tipo === "entrada");
912

1013
return (
1114
<Card className="h-[350px] overflow-hidden shadow-md border ">
@@ -21,7 +24,9 @@ export default function EntradaBL({ historico }) {
2124

2225
<div className="overflow-y-auto pr-2 h-full space-y-3 scrollbar-thin scrollbar-thumb-gray-300 scrollbar-track-transparent">
2326
{entradas.length === 0 ? (
24-
<p className="text-sm text-gray-500">Sin datos de entrada disponibles.</p>
27+
<p className="text-sm text-gray-500">
28+
Sin datos de entrada disponibles.
29+
</p>
2530
) : (
2631
entradas.map((item) => (
2732
<div
@@ -30,14 +35,17 @@ export default function EntradaBL({ historico }) {
3035
>
3136
<div className="space-y-1">
3237
<p className="font-semibold ">
33-
{item.producto || 'No existe'} - {item.tamanio} - {item.color}
38+
{item.producto || "No existe"} - {item.tamanio} - {item.color}
3439
</p>
3540
<p className="text-xs ">
3641
{item.fecha}{item.tipo || "sin tipo"}{" "}
3742
<span className="font-medium">{item.usuario}</span>
3843
</p>
3944
</div>
40-
<Badge variant="outline" className="text-sm border-green-300 text-green-600">
45+
<Badge
46+
variant="outline"
47+
className="text-sm border-green-300 text-green-600"
48+
>
4149
{item.cantidad_por_empaque} und
4250
</Badge>
4351
</div>
@@ -50,6 +58,7 @@ export default function EntradaBL({ historico }) {
5058
}
5159

5260

61+
5362
export function MarcacionBL({ marcacion }) {
5463
// Filtrar solo los pedidos
5564
const marcaciones = marcacion?.filter((item) => item.tipo === "pedido") || [];
@@ -151,3 +160,54 @@ export function MarcacionBL({ marcacion }) {
151160
</Card>
152161
);
153162
}
163+
164+
export function EntregaBL({ entrega }) {
165+
// Filtrar solo los pedidos
166+
const entregado = entrega?.filter((item) => item.estado === "entregado") || [];
167+
168+
169+
return (
170+
<Card className="h-[350px] overflow-hidden shadow-md border">
171+
<CardContent className="p-4 flex flex-col gap-4 h-full">
172+
<div>
173+
<div className="flex items-center gap-3 mb-4">
174+
<div className="bg-blue-50 p-2 rounded-full dark:bg-blue-200">
175+
<PackageCheck className="w-5 h-5 text-blue-400 dark:text-blue-700" />
176+
</div>
177+
<h2 className="text-lg font-bold text-blue-700 tracking-tight">
178+
Pedidos entregados
179+
</h2>
180+
</div>
181+
182+
{/* entregados */}
183+
<div className="overflow-y-auto pr-2 h-full space-y-3 scrollbar-thin scrollbar-thumb-gray-300 scrollbar-track-transparent">
184+
{entregado.length === 0 ? (
185+
<p className="text-xs text-gray-500">
186+
No hay pedidos entregados.
187+
</p>
188+
) : (
189+
entregado.map((item) => (
190+
<div
191+
key={item.id}
192+
className="flex justify-between items-start border p-3 rounded-lg transition hover:shadow-md"
193+
>
194+
<div className="space-y-1">
195+
<p className="font-semibold">PED #{item?.id}</p>
196+
<p className="text-xs">fecha entrega:
197+
{format(new Date(item.updated_at), "dd-MM-yyyy HH:mm")}{" "}
198+
{item.tipo || "sin tipo"}{" "}
199+
<span className="font-medium">
200+
{item?.cliente?.nombre || "Sin cliente"}
201+
</span>
202+
</p>
203+
</div>
204+
205+
</div>
206+
))
207+
)}
208+
</div>
209+
</div>
210+
</CardContent>
211+
</Card>
212+
);
213+
}

0 commit comments

Comments
 (0)