66 lines
3.0 KiB
PHP
66 lines
3.0 KiB
PHP
<?php
|
|
|
|
namespace App\Filament\Resources\InformeResource\Widgets;
|
|
|
|
use Filament\Widgets\StatsOverviewWidget as BaseWidget;
|
|
use Filament\Widgets\StatsOverviewWidget\Stat;
|
|
use App\Models\DetalleVenta;
|
|
use Illuminate\Support\Facades\DB;
|
|
use Carbon\Carbon;
|
|
|
|
class ResumenPromedioWidget extends BaseWidget
|
|
{
|
|
protected function getStats(): array
|
|
{
|
|
$filtros = request()->get('tableFilters', []);
|
|
$fechaDesde = $filtros['fecha_rango']['fecha_desde'] ?? Carbon::now()->startOfMonth()->format('Y-m-d');
|
|
$fechaHasta = $filtros['fecha_rango']['fecha_hasta'] ?? Carbon::now()->endOfMonth()->format('Y-m-d');
|
|
|
|
$resumen = $this->calcularResumen($fechaDesde, $fechaHasta);
|
|
|
|
return [
|
|
Stat::make('Total Productos Vendidos', number_format($resumen['total_productos']))
|
|
->description('Unidades vendidas en el período')
|
|
->descriptionIcon('heroicon-m-cube')
|
|
->color('primary'),
|
|
|
|
Stat::make('Promedio Ponderado Compra', '$' . number_format($resumen['promedio_compra'], 0))
|
|
->description('Costo promedio por unidad')
|
|
->descriptionIcon('heroicon-m-banknotes')
|
|
->color('warning'),
|
|
|
|
Stat::make('Valor Total Invertido', '$' . number_format($resumen['valor_total_compra'], 0))
|
|
->description('Inversión total en productos vendidos')
|
|
->descriptionIcon('heroicon-m-chart-bar')
|
|
->color('danger'),
|
|
|
|
Stat::make('Margen Promedio', round($resumen['margen_promedio'], 2) . '%')
|
|
->description($resumen['margen_promedio'] >= 0 ? 'Beneficio promedio' : 'Pérdida promedio')
|
|
->descriptionIcon($resumen['margen_promedio'] >= 0 ? 'heroicon-m-arrow-trending-up' : 'heroicon-m-arrow-trending-down')
|
|
->color($resumen['margen_promedio'] >= 0 ? 'success' : 'danger'),
|
|
];
|
|
}
|
|
|
|
protected function calcularResumen(string $fechaDesde, string $fechaHasta): array
|
|
{
|
|
$query = DetalleVenta::query()
|
|
->join('productos', 'detalle_ventas.producto_id', '=', 'productos.id')
|
|
->join('ventas', 'detalle_ventas.venta_id', '=', 'ventas.id')
|
|
->whereDate('ventas.created_at', '>=', $fechaDesde)
|
|
->whereDate('ventas.created_at', '<=', $fechaHasta);
|
|
|
|
$totalProductos = $query->sum('detalle_ventas.cantidad');
|
|
$valorTotalCompra = $query->sum(DB::raw('detalle_ventas.cantidad * CAST(productos.precio_compra AS DECIMAL)'));
|
|
$valorTotalVenta = $query->sum(DB::raw('detalle_ventas.cantidad * detalle_ventas.precio_unitario'));
|
|
|
|
$promedioCompra = $totalProductos > 0 ? $valorTotalCompra / $totalProductos : 0;
|
|
$margenPromedio = $valorTotalCompra > 0 ? (($valorTotalVenta - $valorTotalCompra) / $valorTotalCompra) * 100 : 0;
|
|
|
|
return [
|
|
'total_productos' => $totalProductos,
|
|
'valor_total_compra' => $valorTotalCompra,
|
|
'promedio_compra' => $promedioCompra,
|
|
'margen_promedio' => $margenPromedio,
|
|
];
|
|
}
|
|
} |