schema([ Section::make('Datos de Confección') ->schema([ Select::make('proveedor_id') ->label('Tallerista') ->relationship( 'proveedor', 'nombre', fn($query) => $query->where('categoria', 'talleres') ) ->searchable() ->preload() ->required(), Select::make('orden_produccion_id') ->label('Orden de Producción') ->options(fn () => \App\Models\OrdenProduccion::whereRaw('( cantidad_total - ( select coalesce(sum(cantidad_enviada),0) from confeccions where confeccions.orden_produccion_id = orden_produccions.id and confeccions.fecha_recepcion is null ) ) > 0')->pluck('numero_orden', 'id')->toArray()) ->searchable() ->preload() ->reactive() ->required() ->afterStateUpdated(function ($state, $set) { if ($state) { $orden = \App\Models\OrdenProduccion::find($state); $sentInProcess = \App\Models\Confeccion::where('orden_produccion_id', $state) ->whereNull('fecha_recepcion') ->sum('cantidad_enviada'); $pending = max(0, (int)($orden->cantidad_total ?? 0) - (int)$sentInProcess); $set('cantidad_enviada', $pending ?: 0); $set('fecha_envio', now()->toDateString()); $set('prenda_nombre_info', $orden->prenda_modelo ?? 'Sin especificar'); } else { $set('prenda_nombre_info', null); } }), TextInput::make('prenda_nombre_info') ->label('Prenda') ->disabled() ->dehydrated(false) ->visible(fn ($get) => $get('orden_produccion_id') !== null) ->helperText('Nombre de la prenda de la orden de producción seleccionada'), DatePicker::make('fecha_envio') ->required() ->default(now()), TextInput::make('cantidad_enviada') ->numeric() ->required() ->minValue(1) ->maxValue(fn ($get) => $get('orden_produccion_id') ? \App\Models\OrdenProduccion::find($get('orden_produccion_id'))->cantidad_total : null) ->helperText(fn ($get) => $get('orden_produccion_id') ? 'Máximo: ' . \App\Models\OrdenProduccion::find($get('orden_produccion_id'))->cantidad_total : 'Selecciona una Orden de Producción') ->reactive() ->afterStateUpdated(function ($state, $set, $get) { $valor = $get('valor_por_prenda') ?? 0; $cantidad = $get('cantidad_recibida') ?? $state; $set('total_pagar', $cantidad && $valor ? $cantidad * $valor : 0); }), TextInput::make('valor_por_prenda') ->numeric() ->prefix('$') ->required() ->reactive() ->afterStateUpdated(function ($state, $set, $get) { $cantidad = $get('cantidad_recibida') ?? $get('cantidad_enviada'); $set('total_pagar', $cantidad && $state ? $cantidad * $state : 0); }), TextInput::make('total_pagar') ->label('Total a pagar') ->prefix('$') ->numeric() ->readOnly() ->default(0) ->helperText('Se calcula automáticamente: (prendas recibidas × valor por prenda) - descuentos por cobros'), ]) ->columns(2), Section::make('Recepciones') ->description('Resumen de recepciones. Para registrar recepciones múltiples use el botón "Agregar recepción" en la cabecera o la relación "Recepciones" abajo.') ->schema([ Forms\Components\Placeholder::make('recepcion_summary') ->label('Resumen') ->content(function ($get) { $id = $get('id'); if (! $id) return 'Sin recepciones registradas'; $confeccion = \App\Models\Confeccion::find($id); if (!$confeccion) return 'Sin datos'; $enviada = (int) ($confeccion->cantidad_enviada ?? 0); $recepciones = (int) $confeccion->recepciones()->sum(\DB::raw('cantidad - COALESCE(prendas_defectuosas, 0)')); $arreglos = (int) $confeccion->ajustes()->where('tipo', 'arreglo')->sum('cantidad'); $cobros = (int) $confeccion->cobros()->sum('cantidad'); $cobrosValor = (float) $confeccion->cobros()->sum('valor'); $recibidoNeto = $recepciones - $arreglos; $disponibleSiguienteProceso = $recepciones - $arreglos - $cobros; $faltantes = max(0, $enviada - $recepciones + $arreglos); $valorPorPrenda = (float) ($confeccion->valor_por_prenda ?? 0); $cantidadBase = $confeccion->cantidad_recibida ?? $enviada; $valorTotal = $cantidadBase * $valorPorPrenda; $valorAPagar = max(0, $valorTotal - $cobrosValor); return "╯━━━ PRENDAS ━━━ 📦 Enviadas: {$enviada} ✅ Recibidas: {$recepciones} 🔧 En arreglo: {$arreglos} 📊 Neto recibido: {$recibidoNeto} 👉 Disponible siguiente proceso: {$disponibleSiguienteProceso} 💰 Con problemas (cobradas): {$cobros} prendas ⚠️ Pendientes: {$faltantes} ━━━ PAGO ━━━ 💵 Valor total: $" . number_format($valorTotal, 0) . " 💸 Descuento cobros: $" . number_format($cobrosValor, 0) . " ✅ A pagar: $" . number_format($valorAPagar, 0); }), Forms\Components\Placeholder::make('instrucciones') ->label('Acciones') ->content('Use el botón "Agregar recepción" en la cabecera para registrar una recepción rápida. También puede gestionar todas las recepciones en la sección relacionada al final de la página.'), ]) ->columns(1) ->collapsed(), ]); } public static function table(Table $table): Table { return $table ->columns([ TextColumn::make('ordenProduccion.numero_orden') ->label('OP') ->searchable(), TextColumn::make('proveedor.nombre') ->label('Tallerista') ->searchable(), TextColumn::make('cantidad_enviada'), TextColumn::make('recibidas_neto') ->label('Cantidad recibida') ->getStateUsing(function ($record) { $recepciones = (int) $record->recepciones()->sum(\DB::raw('cantidad - COALESCE(prendas_defectuosas, 0)')); $arreglos = (int) $record->ajustes()->where('tipo', 'arreglo')->sum('cantidad'); return $recepciones - $arreglos; }) ->sortable(query: function ($query, $direction) { return $query->withSum('recepciones as recepciones_sum', \DB::raw('cantidad - COALESCE(prendas_defectuosas, 0)')) ->orderBy('recepciones_sum', $direction); }), TextColumn::make('faltantes') ->label('Faltan') ->sortable(), BadgeColumn::make('estado') ->colors([ 'warning' => 'pendiente', 'info' => 'parcial', 'success' => 'completo', ]) ->formatStateUsing(fn($state) => ucfirst($state)), TextColumn::make('total_pagar') ->money('COP'), ]) ->defaultSort('created_at', 'desc') ->filters([ Tables\Filters\SelectFilter::make('orden_produccion_id') ->label('Orden de Producción') ->relationship('ordenProduccion', 'numero_orden') ->searchable() ->preload(), ]) ->actions([ Tables\Actions\EditAction::make(), ]) ->bulkActions([ Tables\Actions\BulkActionGroup::make([ Tables\Actions\DeleteBulkAction::make(), ]), ]); } public static function getRelations(): array { return [ RelationManagers\RecepcionesRelationManager::class, RelationManagers\CobrosRelationManager::class, RelationManagers\AjustesRelationManager::class, ]; } public static function getPages(): array { return [ 'index' => Pages\ListConfeccions::route('/'), 'create' => Pages\CreateConfeccion::route('/create'), 'edit' => Pages\EditConfeccion::route('/{record}/edit'), ]; } }