This commit is contained in:
Lizandro Guarnizo
2026-01-06 15:35:59 -05:00
commit a768146f65
602 changed files with 42505 additions and 0 deletions
@@ -0,0 +1,152 @@
<?php
namespace App\Filament\Resources\CompraResource\Pages;
use App\Filament\Resources\CompraResource;
use Filament\Actions;
use Filament\Resources\Pages\CreateRecord;
use App\Models\Producto;
use App\Models\ProductVariant;
use App\Imports\CompraDetallesImport;
use App\Exports\PlantillaCompraExport;
use Maatwebsite\Excel\Facades\Excel;
use Filament\Forms\Components\FileUpload;
use Filament\Notifications\Notification;
use Illuminate\Support\Facades\Storage;
class CreateCompra extends CreateRecord
{
protected static string $resource = CompraResource::class;
protected function getHeaderActions(): array
{
return [
Actions\Action::make('descargar_plantilla')
->label('Descargar Plantilla Excel')
->icon('heroicon-o-document-arrow-down')
->color('info')
->action(function () {
return Excel::download(
new PlantillaCompraExport(),
'plantilla_compras.xlsx'
);
}),
Actions\Action::make('importar_excel')
->label('Importar desde Excel')
->icon('heroicon-o-arrow-down-tray')
->color('success')
->form([
FileUpload::make('archivo')
->label('Archivo Excel')
->acceptedFileTypes([
'application/vnd.ms-excel',
'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
'text/csv',
])
->required()
->helperText('Formato: Código de Barras, Producto, Cantidad, Precio Unitario, Bodega (opcional), Observaciones (opcional)')
->disk('local')
->directory('temp-imports'),
])
->action(function (array $data) {
try {
$filePath = Storage::disk('local')->path($data['archivo']);
$import = new CompraDetallesImport();
Excel::import($import, $filePath);
$previewData = $import->getPreviewData();
$stats = $import->getStats();
// Mostrar vista preliminar en notificación
$message = "Total de filas: {$stats['total']}\n";
$message .= "Válidas: {$stats['valid']}\n";
$message .= "Con errores: {$stats['invalid']}\n";
if ($stats['productos_creados'] > 0) {
$message .= "✨ Productos nuevos creados: {$stats['productos_creados']}\n";
}
$message .= "Total estimado: $" . number_format($stats['total_amount'], 2);
// Si hay errores, mostrarlos
if ($stats['invalid'] > 0) {
$errorMessages = collect($previewData)
->filter(fn($item) => !$item['valid'])
->map(fn($item) => "Fila {$item['row_number']}: " . implode(', ', $item['errors']))
->take(5)
->implode("\n");
Notification::make()
->warning()
->title("Vista preliminar: {$stats['invalid']} filas con errores")
->body($errorMessages . "\n\n" . $message)
->persistent()
->send();
} else {
Notification::make()
->success()
->title('Vista preliminar de importación')
->body($message)
->persistent()
->send();
}
// Cargar los datos directamente en el formulario
$detallesParaFormulario = $import->getDetallesForSave();
// Actualizar el formulario con los datos importados
$currentData = $this->data;
$currentData['detalles'] = array_merge(
$currentData['detalles'] ?? [],
$detallesParaFormulario
);
// Calcular el total
$currentData['total'] = collect($currentData['detalles'])->sum('subtotal');
$this->form->fill($currentData);
// Limpiar archivo temporal
Storage::disk('local')->delete($data['archivo']);
} catch (\Exception $e) {
Notification::make()
->danger()
->title('Error en la importación')
->body($e->getMessage())
->send();
}
}),
];
}
protected function mutateFormDataBeforeCreate(array $data): array
{
// Calcular el total basado en los detalles
if (isset($data['detalles']) && is_array($data['detalles'])) {
$total = collect($data['detalles'])->sum('subtotal');
$data['total'] = $total;
// Agregar snapshots para cada detalle
foreach ($data['detalles'] as &$detalle) {
if (isset($detalle['producto_id'])) {
$producto = Producto::find($detalle['producto_id']);
$detalle['producto_nombre_snapshot'] = $producto?->nombre;
}
if (isset($detalle['variante_id'])) {
$variante = ProductVariant::find($detalle['variante_id']);
if ($variante) {
$colorName = $variante->color?->name ?? 'Sin color';
$sizeName = $variante->size?->name ?? 'Sin talla';
$detalle['variante_info_snapshot'] = "$colorName / $sizeName";
}
}
}
} else {
$data['total'] = 0;
}
return $data;
}
}
@@ -0,0 +1,186 @@
<?php
namespace App\Filament\Resources\CompraResource\Pages;
use App\Filament\Resources\CompraResource;
use Filament\Actions;
use Filament\Resources\Pages\EditRecord;
use App\Models\Producto;
use App\Models\ProductVariant;
use App\Imports\CompraDetallesImport;
use App\Exports\PlantillaCompraExport;
use Maatwebsite\Excel\Facades\Excel;
use Filament\Forms\Components\FileUpload;
use Filament\Notifications\Notification;
use Illuminate\Support\Facades\Storage;
class EditCompra extends EditRecord
{
protected static string $resource = CompraResource::class;
protected function getHeaderActions(): array
{
return [
Actions\Action::make('marcar_recibida')
->label('Marcar como Recibida')
->icon('heroicon-o-check-circle')
->color('success')
->visible(fn() => $this->record->estado === 'Pendiente')
->requiresConfirmation()
->modalHeading('Marcar compra como recibida')
->modalDescription('Esto actualizará el stock en las bodegas según los productos de esta compra.')
->action(function () {
$this->record->update(['estado' => 'Recibida']);
Notification::make()
->success()
->title('Compra recibida')
->body('El stock ha sido actualizado en las bodegas.')
->send();
$this->redirect(static::getResource()::getUrl('edit', ['record' => $this->record]));
}),
Actions\Action::make('descargar_plantilla')
->label('Descargar Plantilla Excel')
->icon('heroicon-o-document-arrow-down')
->color('info')
->action(function () {
return Excel::download(
new PlantillaCompraExport(),
'plantilla_compras.xlsx'
);
}),
Actions\Action::make('importar_excel')
->label('Importar desde Excel')
->icon('heroicon-o-arrow-down-tray')
->color('success')
->form([
FileUpload::make('archivo')
->label('Archivo Excel')
->acceptedFileTypes([
'application/vnd.ms-excel',
'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
'text/csv',
])
->required()
->helperText('Formato: Código de Barras, Producto, Cantidad, Precio Unitario, Bodega (opcional), Observaciones (opcional)')
->disk('local')
->directory('temp-imports'),
])
->action(function (array $data) {
try {
$filePath = Storage::disk('local')->path($data['archivo']);
$import = new CompraDetallesImport();
Excel::import($import, $filePath);
$previewData = $import->getPreviewData();
$stats = $import->getStats();
// Si hay errores, mostrarlos
if ($stats['invalid'] > 0) {
$errorMessages = collect($previewData)
->filter(fn($item) => !$item['valid'])
->map(fn($item) => "Fila {$item['row_number']}: " . implode(', ', $item['errors']))
->take(10)
->implode("\n");
Notification::make()
->warning()
->title("Se encontraron {$stats['invalid']} filas con errores")
->body($errorMessages)
->persistent()
->send();
}
// Obtener detalles válidos para agregar
$detallesValidos = $import->getDetallesForSave();
if (count($detallesValidos) > 0) {
// Agregar los detalles a la compra
foreach ($detallesValidos as $detalle) {
$this->record->detalles()->create($detalle);
}
// Recalcular el total
$nuevoTotal = $this->record->detalles()->sum('subtotal');
$this->record->update(['total' => $nuevoTotal]);
$mensaje = "{$stats['valid']} productos agregados. Total: $" . number_format($stats['total_amount'], 2);
if ($stats['productos_creados'] > 0) {
$mensaje .= "\n{$stats['productos_creados']} productos nuevos creados automáticamente";
}
Notification::make()
->success()
->title('Importación exitosa')
->body($mensaje)
->send();
// Si la compra está en estado Pendiente, preguntar si desea recibirla
if ($this->record->estado === 'Pendiente') {
Notification::make()
->info()
->title('Actualizar stock')
->body('⚠️ La compra está en estado "Pendiente". Cambia el estado a "Recibida" para actualizar el stock en las bodegas.')
->persistent()
->send();
}
// Refrescar la página
$this->redirect(static::getResource()::getUrl('edit', ['record' => $this->record]));
} else {
Notification::make()
->warning()
->title('No hay datos válidos para importar')
->send();
}
// Limpiar archivo temporal
Storage::disk('local')->delete($data['archivo']);
} catch (\Exception $e) {
Notification::make()
->danger()
->title('Error en la importación')
->body($e->getMessage())
->send();
}
}),
Actions\DeleteAction::make(),
];
}
protected function mutateFormDataBeforeSave(array $data): array
{
// Calcular el total basado en los detalles
if (isset($data['detalles']) && is_array($data['detalles'])) {
$total = collect($data['detalles'])->sum('subtotal');
$data['total'] = $total;
// Agregar snapshots para cada detalle
foreach ($data['detalles'] as &$detalle) {
if (isset($detalle['producto_id'])) {
$producto = Producto::find($detalle['producto_id']);
$detalle['producto_nombre_snapshot'] = $producto?->nombre;
}
if (isset($detalle['variante_id'])) {
$variante = ProductVariant::find($detalle['variante_id']);
if ($variante) {
$colorName = $variante->color?->name ?? 'Sin color';
$sizeName = $variante->size?->name ?? 'Sin talla';
$detalle['variante_info_snapshot'] = "$colorName / $sizeName";
}
}
}
} else {
$data['total'] = 0;
}
return $data;
}
}
@@ -0,0 +1,31 @@
<?php
namespace App\Filament\Resources\CompraResource\Pages;
use App\Filament\Resources\CompraResource;
use App\Exports\PlantillaCompraExport;
use Filament\Actions;
use Filament\Resources\Pages\ListRecords;
use Maatwebsite\Excel\Facades\Excel;
class ListCompras extends ListRecords
{
protected static string $resource = CompraResource::class;
protected function getHeaderActions(): array
{
return [
Actions\Action::make('descargar_plantilla')
->label('Descargar Plantilla Excel')
->icon('heroicon-o-document-arrow-down')
->color('info')
->action(function () {
return Excel::download(
new PlantillaCompraExport(),
'plantilla_compras.xlsx'
);
}),
Actions\CreateAction::make(),
];
}
}
@@ -0,0 +1,275 @@
<?php
namespace App\Filament\Resources\CompraResource\RelationManagers;
use App\Models\Producto;
use App\Models\ProductVariant;
use App\Models\Bodega;
use Filament\Forms;
use Filament\Forms\Form;
use Filament\Resources\RelationManagers\RelationManager;
use Filament\Tables;
use Filament\Tables\Table;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\SoftDeletingScope;
use Filament\Forms\Components\TextInput;
use Filament\Forms\Components\Select;
use Filament\Notifications\Notification;
use Illuminate\Support\Facades\DB;
class DetallesRelationManagerRelationManager extends RelationManager
{
protected static string $relationship = 'detalles';
public function form(Form $form): Form
{
return $form
->schema([
TextInput::make('codigo_escaneado')
->label('Escanear código de barras')
->live()
->afterStateUpdated(function (callable $set, $state) {
// Buscar en ProductVariant
$variant = ProductVariant::where('barcode', $state)->first();
if ($variant) {
$set('producto_id', $variant->producto_id);
$set('variante_id', $variant->id);
// Validación defensiva para evitar error "name" on null
$colorName = $variant->color ? $variant->color->name : 'Sin color';
$sizeName = $variant->size ? $variant->size->name : 'Sin talla';
Notification::make()
->success()
->title('Variante encontrada')
->body("Producto: {$variant->producto->nombre} - Variante: {$colorName}/{$sizeName}")
->send();
return;
}
// Buscar en Producto
$producto = Producto::where('codigo_barras', $state)->first();
if ($producto) {
$set('producto_id', $producto->id);
$set('variante_id', null);
if ($producto->variants()->exists()) {
Notification::make()
->warning()
->title('Producto con variantes')
->body('Este producto tiene variantes. Por favor selecciona una variante específica.')
->send();
} else {
Notification::make()
->success()
->title('Producto encontrado')
->body("Producto: {$producto->nombre}")
->send();
}
} else {
Notification::make()
->warning()
->title('Código no encontrado')
->body('No se encontró ningún producto o variante con este código.')
->send();
}
}),
Select::make('bodega_id')
->label('Bodega de Destino')
->relationship('bodega', 'nombre')
->searchable()
->required()
->default(function () {
// Buscar bodega "Principal" como default
$bodegaPrincipal = Bodega::where('nombre', 'Principal')->first();
return $bodegaPrincipal ? $bodegaPrincipal->id : null;
})
->helperText('Selecciona la bodega donde se almacenará este producto'),
Select::make('producto_id')
->label('Producto')
->relationship('producto', 'nombre')
->searchable()
->required()
->live()
->afterStateUpdated(function (callable $set, $state) {
// Limpiar variante cuando cambia el producto
$set('variante_id', null);
if ($state) {
$producto = Producto::find($state);
if ($producto && $producto->variants()->exists()) {
Notification::make()
->info()
->title('Producto con variantes')
->body('Este producto tiene variantes disponibles. Por favor selecciona una.')
->send();
}
}
}),
Select::make('variante_id')
->label('Variante')
->options(function (callable $get) {
$productoId = $get('producto_id');
if (!$productoId) {
return [];
}
$producto = Producto::find($productoId);
if (!$producto || !$producto->variants()->exists()) {
return [];
}
return ProductVariant::where('producto_id', $productoId)
->with(['color', 'size'])
->get()
->mapWithKeys(function ($variant) {
// Validación defensiva para evitar error "name" on null
$colorName = $variant->color ? $variant->color->name : 'Sin color';
$sizeName = $variant->size ? $variant->size->name : 'Sin talla';
return [
$variant->id => "{$colorName} / {$sizeName}",
];
});
})
->searchable()
->live()
->visible(function (callable $get) {
$productoId = $get('producto_id');
if (!$productoId) return false;
$producto = Producto::find($productoId);
return $producto && $producto->variants()->exists();
})
->required(function (callable $get) {
$productoId = $get('producto_id');
if (!$productoId) return false;
$producto = Producto::find($productoId);
return $producto && $producto->variants()->exists();
})
->helperText(function (callable $get) {
$productoId = $get('producto_id');
if (!$productoId) return null;
$producto = Producto::find($productoId);
if (!$producto || !$producto->variants()->exists()) {
return null;
}
return 'Este producto requiere seleccionar una variante específica.';
}),
TextInput::make('cantidad')
->required()
->numeric()
->live()
->helperText('Cantidad en unidades individuales')
->afterStateUpdated(function (callable $set, callable $get) {
$cantidad = (float) $get('cantidad');
$precio = (float) $get('precio_unitario');
$set('subtotal', $cantidad * $precio);
}),
TextInput::make('precio_unitario')
->required()
->numeric()
->prefix('$')
->live()
->helperText('Precio por unidad individual')
->afterStateUpdated(function (callable $set, callable $get) {
$cantidad = (float) $get('cantidad');
$precio = (float) $get('precio_unitario');
$set('subtotal', $cantidad * $precio);
}),
TextInput::make('subtotal')
->numeric()
->prefix('$')
->disabled()
->dehydrated(true), // guarda el valor aunque esté deshabilitado
TextInput::make('DetalleCompra')
->label('Detalle/Observaciones')
->maxLength(255)
->helperText('Información adicional sobre esta compra (opcional)'),
]);
}
public function table(Table $table): Table
{
return $table
->recordTitleAttribute('DetalleCompra')
->columns([
Tables\Columns\TextColumn::make('bodega.nombre')
->label('Bodega')
->badge()
->color('primary'),
Tables\Columns\TextColumn::make('producto_nombre')
->label('Producto')
->searchable()
->sortable()
->color(fn($record) => $record->producto_id ? 'primary' : 'warning')
->icon(fn($record) => $record->producto_id ? null : 'heroicon-o-archive-box-x-mark')
->tooltip(fn($record) => $record->producto_id ? null : 'Producto eliminado - información histórica'),
Tables\Columns\TextColumn::make('variante_info')
->label('Variante')
->badge()
->color(function ($record) {
if ($record->variante_id) return 'success';
if ($record->variante_info_snapshot) return 'warning';
return 'gray';
})
->formatStateUsing(fn($record) => $record->variante_info ?: '—')
->tooltip(function ($record) {
if ($record->variante_id) return null;
if ($record->variante_info_snapshot) return 'Variante eliminada - información histórica';
return 'Sin variante';
}),
Tables\Columns\TextColumn::make('cantidad')
->label('Cantidad')
->alignEnd(),
Tables\Columns\TextColumn::make('precio_unitario')
->label('Precio Unitario')
->money('cop')
->alignEnd(),
Tables\Columns\TextColumn::make('subtotal')
->label('Subtotal')
->money('cop')
->alignEnd()
->weight('bold')
->color('primary'),
Tables\Columns\TextColumn::make('DetalleCompra')
->label('Detalle')
->limit(30)
->toggleable(isToggledHiddenByDefault: true),
])
->filters([
//
])
->headerActions([
Tables\Actions\CreateAction::make(),
])
->actions([
Tables\Actions\EditAction::make(),
Tables\Actions\DeleteAction::make(),
])
->bulkActions([
Tables\Actions\BulkActionGroup::make([
Tables\Actions\DeleteBulkAction::make(),
]),
]);
}
}