Merge branch 'giane' of https://github.com/BryamE/ProyectoLauck into bryam

This commit is contained in:
BryamE
2026-01-08 21:16:11 -03:00
10 changed files with 595 additions and 274 deletions
+60 -15
View File
@@ -3,15 +3,28 @@
namespace App\Http\Controllers; namespace App\Http\Controllers;
use Illuminate\Http\Request; use Illuminate\Http\Request;
use App\Models\Client;
class ClientController extends Controller class ClientController extends Controller
{ {
/** /**
* Display a listing of the resource. * Display a listing of the resource.
*/ */
public function index() public function index(Request $request)
{ {
// $query = $request->input('search');
$clients = Client::query()
->when($query, function ($q) use ($query) {
// Si hay búsqueda, filtra por nombre o SKU
return $q->where('name', 'like', "%{$query}%");
})
->orderBy('name', 'asc')
//->orderBy('create_at', 'asc')
->paginate(10) // Paginamos de a 10
->withQueryString(); // Mantiene el filtro de búsqueda al cambiar de página
return view('clients.index', compact('clients'));
} }
/** /**
@@ -27,7 +40,28 @@ class ClientController extends Controller
*/ */
public function store(Request $request) public function store(Request $request)
{ {
// $validated = $request->validate([
'name' => 'required|string|max:255',
'phone' => 'nullable|string|max:50',
'email' => 'nullable|email|max:255|unique:clients,email',
'address' => 'nullable|string|max:255',
]);
// 1. Guardamos el cliente en una variable para tener su ID
$client = Client::create($validated);
// 2. Verificamos el origen
if ($request->input('origin') === 'sales') {
// Si vino de ventas, volvemos a ventas
// Y pasamos el ID del nuevo cliente para auto-seleccionarlo
return redirect()->route('sales.create', ['new_client_id' => $client->id])
->with('success', 'Cliente creado. Ya puedes seleccionarlo.');
}
// 3. Si no, comportamiento normal (volver al index de clientes)
return redirect()->route('clients.index')
->with('success', 'Cliente creado correctamente.');
} }
/** /**
@@ -38,27 +72,38 @@ class ClientController extends Controller
// //
} }
/** public function edit(Client $client)
* Show the form for editing the specified resource.
*/
public function edit(string $id)
{ {
// // Reutilizamos la vista de create, o creamos una edit.blade.php similar
return view('clients.edit', compact('client'));
} }
/** public function update(Request $request, Client $client)
* Update the specified resource in storage.
*/
public function update(Request $request, string $id)
{ {
// $validated = $request->validate([
'name' => 'required|string|max:255',
'phone' => 'nullable|string|max:50',
'email' => 'nullable|email|max:255|unique:clients,email,' . $client->id, // Ignorar email propio
'address' => 'nullable|string|max:255',
]);
$client->update($validated);
return redirect()->route('clients.index')->with('success', 'Cliente actualizado correctamente.');
} }
/** /**
* Remove the specified resource from storage. * Remove the specified resource from storage.
*/ */
public function destroy(string $id) public function destroy(Client $client)
{ {
// try {
$client->delete();
return redirect()->route('clients.index')->with('success', 'Cliente eliminado correctamente.');
} catch (\Illuminate\Database\QueryException $e) {
return back()->with('error', 'No se puede eliminar el cliente porque tiene ventas registradas.');
}
} }
} }
+13 -14
View File
@@ -4,10 +4,10 @@ namespace App\Http\Controllers;
use Illuminate\Http\Request; use Illuminate\Http\Request;
use App\Models\Product; use App\Models\Product;
use App\Models\Client;
use App\Models\Sale; use App\Models\Sale;
use App\Models\SaleDetail; use App\Models\SaleDetail;
use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\DB;
use App\Models\Client;
class SaleController extends Controller class SaleController extends Controller
{ {
@@ -22,9 +22,8 @@ class SaleController extends Controller
public function create() public function create()
{ {
// Buscamos productos que tengan stock mayor a 0 para mostrar en el selector // Traemos productos con stock y clientes para los selectores
$products = Product::where('stock_quantity', '>', 0)->get(); $products = Product::where('stock_quantity', '>', 0)->get();
$clients = Client::orderBy('name')->get(); $clients = Client::orderBy('name')->get();
return view('sales.create', compact('products', 'clients')); return view('sales.create', compact('products', 'clients'));
@@ -32,9 +31,10 @@ class SaleController extends Controller
public function store(Request $request) public function store(Request $request)
{ {
// Validación estricta
$request->validate([ $request->validate([
'payment_method' => 'required|string',
'client_id' => 'nullable|exists:clients,id', 'client_id' => 'nullable|exists:clients,id',
'payment_method' => 'required|string',
'items' => 'required|array', 'items' => 'required|array',
'items.*.product_id' => 'required|exists:products,id', 'items.*.product_id' => 'required|exists:products,id',
'items.*.quantity' => 'required|integer|min:1', 'items.*.quantity' => 'required|integer|min:1',
@@ -52,6 +52,7 @@ class SaleController extends Controller
if ($product->stock_quantity < $item['quantity']) { if ($product->stock_quantity < $item['quantity']) {
throw new \Exception("No hay suficiente stock de " . $product->name); throw new \Exception("No hay suficiente stock de " . $product->name);
} }
} }
//cabecera //cabecera
@@ -62,29 +63,27 @@ class SaleController extends Controller
'payment_method' => $request->payment_method, 'payment_method' => $request->payment_method,
]); ]);
foreach ($request->items as $item) { // 3. Guardar Detalle y Restar Stock
$product = Product::find($item['product_id']); foreach ($request->items as $itemData) {
$product = Product::findOrFail($itemData['product_id']);
SaleDetail::create([ SaleDetail::create([
'sale_id' => $newSale->id, 'sale_id' => $newSale->id,
'product_id' => $product->id, 'product_id' => $product->id,
'quantity' => $item['quantity'], 'quantity' => $itemData['quantity'],
'price' => $product->price, 'price' => $product->price,
]); ]);
$nuevoStock = $product->stock_quantity - $item['quantity'];
$product->stock_quantity = $nuevoStock; $product->decrement('stock_quantity', $itemData['quantity']);
$product->save();
} }
return $newSale; // Retornamos la venta creada fuera de la transacción return $newSale; // Retornamos la venta creada fuera de la transacción
}); });
// 4. REDIRECCIÓN AL DETALLE (FACTURA) // 4. REDIRECCIÓN AL DETALLE
// Usamos la variable $sale que nos devolvió la transacción
return redirect()->route('sales.show', $sale)->with('success', '¡Venta registrada exitosamente!'); return redirect()->route('sales.show', $sale)->with('success', '¡Venta registrada exitosamente!');
} catch (\Exception $e) { } catch (\Exception $e) {
// Si algo falló (ej: falta stock), volvemos atrás con el error return back()->with('error', $e->getMessage())->withInput();
return back()->with('error', 'Error en la venta: ' . $e->getMessage());
} }
} }
+8 -1
View File
@@ -6,7 +6,8 @@
"": { "": {
"dependencies": { "dependencies": {
"@tailwindcss/postcss": "^4.1.18", "@tailwindcss/postcss": "^4.1.18",
"jquery": "^3.7.1" "jquery": "^3.7.1",
"select2": "^4.1.0-rc.0"
}, },
"devDependencies": { "devDependencies": {
"@tailwindcss/vite": "^4.1.18", "@tailwindcss/vite": "^4.1.18",
@@ -2243,6 +2244,12 @@
"tslib": "^2.1.0" "tslib": "^2.1.0"
} }
}, },
"node_modules/select2": {
"version": "4.1.0-rc.0",
"resolved": "https://registry.npmjs.org/select2/-/select2-4.1.0-rc.0.tgz",
"integrity": "sha512-Hr9TdhyHCZUtwznEH2CBf7967mEM0idtJ5nMtjvk3Up5tPukOLXbHUNmh10oRfeNIhj+3GD3niu+g6sVK+gK0A==",
"license": "MIT"
},
"node_modules/shell-quote": { "node_modules/shell-quote": {
"version": "1.8.3", "version": "1.8.3",
"resolved": "https://registry.npmjs.org/shell-quote/-/shell-quote-1.8.3.tgz", "resolved": "https://registry.npmjs.org/shell-quote/-/shell-quote-1.8.3.tgz",
+2 -1
View File
@@ -18,6 +18,7 @@
}, },
"dependencies": { "dependencies": {
"@tailwindcss/postcss": "^4.1.18", "@tailwindcss/postcss": "^4.1.18",
"jquery": "^3.7.1" "jquery": "^3.7.1",
"select2": "^4.1.0-rc.0"
} }
} }
+12
View File
@@ -1 +1,13 @@
import './bootstrap'; import './bootstrap';
// 1. Importar jQuery
import jQuery from 'jquery';
// 2. Hacerlo global (IMPORTANTE para que funcione $(document).ready en Blade)
window.$ = window.jQuery = jQuery;
// 3. Importar Select2
import select2 from 'select2';
select2(); // Inicializar el plugin
// 4. Importar los estilos de Select2 (Opcional aquí, o en CSS)
import 'select2/dist/css/select2.css';
+48 -2
View File
@@ -1,3 +1,49 @@
<x-layout> <x-layout title="Lauck - Nuevo Cliente">
<h1>formulario de crear cliente</h1>
<x-section-header subtitle="Gestión de Clientes" title="Nuevo " highlight="Cliente" />
<div class="w-full max-w-4xl mx-auto bg-panel-bg border border-neutral-800 rounded-xl p-8 shadow-lg">
<form action="{{ route('clients.store') }}" method="POST">
@csrf
<input type="hidden" name="origin" value="{{ request('origin') }}">
<div class="grid grid-cols-1 md:grid-cols-4 gap-6 mb-6">
<div class="md:col-span-4">
<x-forms.label for="name" value="Nombre Completo" />
<x-forms.input id="name" name="name" type="text" :value="old('name')" required autofocus placeholder="Ej: Sergio Lauck" :error="$errors->first('name')" />
</div>
<div class="md:col-span-2">
<x-forms.label for="phone" value="Teléfono / WhatsApp" />
<x-forms.input id="phone" name="phone" type="text" :value="old('phone')" placeholder="Ej: 343 154..." :error="$errors->first('phone')" />
</div>
<div class="md:col-span-2">
<x-forms.label for="email" value="Correo Electrónico" />
<x-forms.input id="email" name="email" type="email" :value="old('email')" placeholder="cliente@ejemplo.com" :error="$errors->first('email')" />
</div>
<div class="md:col-span-4">
<x-forms.label for="address" value="Dirección / Domicilio" />
<textarea id="address" name="address" rows="3" class="bg-neutral-800 border-neutral-700 text-white text-sm rounded-lg focus:ring-neon-lime focus:border-neon-lime block w-full p-2.5 placeholder-gray-500" placeholder="Calle, número, piso...">{{ old('address') }}</textarea>
@error('address')
<span class="text-red-500 text-xs mt-1">{{ $message }}</span>
@enderror
</div>
</div>
<div class="flex items-center justify-between md:justify-end space-x-4 border-t border-neutral-800 pt-6">
<a href="{{ route('clients.index') }}" class="text-gray-400 hover:text-white font-medium text-sm transition-colors">Cancelar</a>
<button type="submit" class="px-6 py-2.5 bg-neon-lime text-neutral-900 font-bold rounded-lg hover:bg-[#b3e600] transition-colors shadow-lg shadow-neon-lime/20">
Guardar Cliente
</button>
</div>
</form>
</div>
</x-layout> </x-layout>
+79
View File
@@ -0,0 +1,79 @@
<x-layout title="Lauck - Editar Cliente">
<x-section-header subtitle="Gestión de Clientes" title="Editar " highlight="Cliente" />
<div class="w-full max-w-4xl mx-auto bg-panel-bg border border-neutral-800 rounded-xl p-8 shadow-lg">
<form action="{{ route('clients.update', $client) }}" method="POST">
@csrf
@method('PUT') <div class="grid grid-cols-1 md:grid-cols-4 gap-6 mb-6">
<div class="md:col-span-4">
<x-forms.label for="name" value="Nombre Completo" />
<x-forms.input
id="name"
name="name"
type="text"
:value="old('name', $client->name)"
required
autofocus
placeholder="Ej: Sergio Lauck"
:error="$errors->first('name')"
/>
</div>
<div class="md:col-span-2">
<x-forms.label for="phone" value="Teléfono / WhatsApp" />
<x-forms.input
id="phone"
name="phone"
type="text"
:value="old('phone', $client->phone)"
placeholder="Ej: 343 154..."
:error="$errors->first('phone')"
/>
</div>
<div class="md:col-span-2">
<x-forms.label for="email" value="Correo Electrónico" />
<x-forms.input
id="email"
name="email"
type="email"
:value="old('email', $client->email)"
placeholder="cliente@ejemplo.com"
:error="$errors->first('email')"
/>
</div>
<div class="md:col-span-4">
<x-forms.label for="address" value="Dirección / Domicilio" />
<textarea
id="address"
name="address"
rows="3"
class="bg-neutral-800 border-neutral-700 text-white text-sm rounded-lg focus:ring-neon-lime focus:border-neon-lime block w-full p-2.5 placeholder-gray-500"
placeholder="Calle, número, piso..."
>{{ old('address', $client->address) }}</textarea>
@error('address')
<span class="text-red-500 text-xs mt-1">{{ $message }}</span>
@enderror
</div>
</div>
<div class="flex items-center justify-between md:justify-end space-x-4 border-t border-neutral-800 pt-6">
<a href="{{ route('clients.index') }}" class="text-gray-400 hover:text-white font-medium text-sm transition-colors">
Cancelar
</a>
<button type="submit" class="px-6 py-2.5 bg-neon-lime text-neutral-900 font-bold rounded-lg hover:bg-[#b3e600] transition-colors shadow-lg shadow-neon-lime/20">
Actualizar Cliente
</button>
</div>
</form>
</div>
</x-layout>
+105
View File
@@ -0,0 +1,105 @@
<x-layout title="Lauck - Clientes">
<x-section-header subtitle="Gestión de Clientes" title="Cartera de " highlight="Clientes" />
@if(session('success'))
<div class="bg-green-900/50 border border-green-500 text-green-300 px-4 py-3 rounded-lg mb-6 shadow-sm">
{{ session('success') }}
</div>
@endif
<div class="w-full flex flex-col md:flex-row justify-between items-center gap-4 mb-6">
<form action="{{ route('clients.index') }}" method="GET" class="w-full md:w-1/2">
<div class="relative">
<div class="absolute inset-y-0 start-0 flex items-center ps-3 pointer-events-none">
<svg class="w-4 h-4 text-gray-500" aria-hidden="true" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 20 20">
<path stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="m19 19-4-4m0-7A7 7 0 1 1 1 8a7 7 0 0 1 14 0Z"/>
</svg>
</div>
<input type="text" name="search" value="{{ request('search') }}"
class="block w-full p-3 ps-10 text-sm text-white border border-neutral-700 rounded-lg bg-neutral-800 focus:ring-neon-lime focus:border-neon-lime placeholder-gray-500"
placeholder="Buscar por nombre, teléfono o email...">
</div>
</form>
<a href="{{ route('clients.create') }}" class="w-full md:w-auto text-center px-5 py-3 text-sm font-bold text-neutral-900 bg-neon-lime rounded-lg hover:bg-[#b3e600] transition-colors uppercase tracking-wide shadow-lg shadow-neon-lime/20">
+ Nuevo Cliente
</a>
</div>
<div class="relative overflow-x-auto shadow-md sm:rounded-lg border border-neutral-800 w-full">
<table class="w-full text-sm text-left rtl:text-right text-gray-400">
<thead class="text-xs text-gray-300 uppercase bg-neutral-800 border-b border-neutral-700">
<tr>
<th scope="col" class="px-6 py-3">Cliente / Email</th>
<th scope="col" class="px-6 py-3">Teléfono / WhatsApp</th>
<th scope="col" class="px-6 py-3">Dirección</th>
<th scope="col" class="px-6 py-3 text-right">Acciones</th>
</tr>
</thead>
<tbody>
@forelse($clients as $client)
<tr class="bg-neutral-900/50 border-b border-neutral-800 hover:bg-neutral-800 transition-colors group">
<td class="px-6 py-4 whitespace-nowrap">
<div class="text-base font-bold text-white">{{ $client->name }}</div>
<div class="text-xs text-gray-500 font-mono">
{{ $client->email ?? 'Sin email registrado' }}
</div>
</td>
<td class="px-6 py-4">
@if($client->phone)
<div class="flex items-center gap-2">
<span class="font-mono text-gray-300">{{ $client->phone }}</span>
<span class="text-green-500 text-xs bg-green-900/30 px-1.5 py-0.5 rounded">WA</span>
</div>
@else
<span class="text-gray-600 italic">No registrado</span>
@endif
</td>
<td class="px-6 py-4">
<span class="text-gray-400 truncate max-w-xs block" title="{{ $client->address }}">
{{ $client->address ?? '-' }}
</span>
</td>
<td class="px-6 py-4 text-right flex items-center justify-end gap-3">
<a href="{{ route('clients.edit', $client) }}" class="font-medium text-blue-400 hover:text-blue-300 hover:underline transition-colors">
Editar
</a>
<form action="{{ route('clients.destroy', $client) }}" method="POST" class="inline-block" onsubmit="return confirm('¿Estás seguro de que deseas eliminar este cliente? Esta acción no se puede deshacer.');">
@csrf
@method('DELETE')
<button type="submit" class="font-medium text-red-500 hover:text-red-400 hover:underline transition-colors cursor-pointer bg-transparent border-0 p-0">
Eliminar
</button>
</form>
</td>
</tr>
@empty
<tr>
<td colspan="4" class="px-6 py-10 text-center text-gray-500">
<div class="flex flex-col items-center justify-center">
<svg xmlns="http://www.w3.org/2000/svg" class="h-10 w-10 mb-2 opacity-50" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4.354a4 4 0 110 5.292M15 21H3v-1a6 6 0 0112 0v1zm0 0h6v-1a6 6 0 00-9-5.197M13 7a4 4 0 11-8 0 4 4 0 018 0z" />
</svg>
<p>No se encontraron clientes.</p>
</div>
</td>
</tr>
@endforelse
</tbody>
</table>
</div>
<div class="mt-4 w-full">
{{ $clients->links() }}
</div>
</x-layout>
+1 -1
View File
@@ -21,7 +21,7 @@
</x-ui.card> </x-ui.card>
<!-- Tarjeta Clientes --> <!-- Tarjeta Clientes -->
<x-ui.card href="#" title="Clientes" description="Base de datos de ciclistas." linkText="Buscar usuario"> <x-ui.card href="{{ url('/clients') }}" title="Clientes" description="Base de datos de ciclistas." linkText="Buscar usuario">
<svg class="w-12 h-12 text-neon-lime" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" d="M17 20h5v-2a3 3 0 00-5.356-1.857M17 20H7m10 0v-2c0-.656-.126-1.283-.356-1.857M7 20H2v-2a3 3 0 015.356-1.857M7 20v-2c0-.656.126-1.283.356-1.857m0 0a5.002 5.002 0 019.288 0M15 7a3 3 0 11-6 0 3 3 0 016 0zm6 3a2 2 0 11-4 0 2 2 0 014 0zM7 10a2 2 0 11-4 0 2 2 0 014 0z" /></svg> <svg class="w-12 h-12 text-neon-lime" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" d="M17 20h5v-2a3 3 0 00-5.356-1.857M17 20H7m10 0v-2c0-.656-.126-1.283-.356-1.857M7 20H2v-2a3 3 0 015.356-1.857M7 20v-2c0-.656.126-1.283.356-1.857m0 0a5.002 5.002 0 019.288 0M15 7a3 3 0 11-6 0 3 3 0 016 0zm6 3a2 2 0 11-4 0 2 2 0 014 0zM7 10a2 2 0 11-4 0 2 2 0 014 0z" /></svg>
</x-ui.card> </x-ui.card>
+241 -214
View File
@@ -1,262 +1,289 @@
<x-layout title="Nueva Venta"> <x-layout title="Lauck - Nueva Venta">
@push('styles')
<style>
/* Select2 adaptado al Tema 'Lauck' (Neutral + Neon Lime) */
.select2-container--default .select2-selection--single {
background-color: #262626 !important; /* neutral-800 */
border-color: #404040 !important; /* neutral-700 */
color: white !important;
height: 42px;
display: flex;
align-items: center;
border-radius: 0.5rem; /* rounded-lg */
}
.select2-container--default .select2-selection--single .select2-selection__rendered {
color: white !important;
line-height: 42px;
padding-left: 12px;
}
.select2-dropdown {
background-color: #262626 !important; /* neutral-800 */
border-color: #404040 !important; /* neutral-700 */
color: white !important;
}
/* Color de resalto al pasar el mouse u opción seleccionada */
.select2-container--default .select2-results__option--highlighted.select2-results__option--selectable {
background-color: #ccff00 !important; /* neon-lime */
color: #171717 !important; /* neutral-900 */
font-weight: bold;
}
/* Ajuste del placeholder */
.select2-container--default .select2-selection--single .select2-selection__placeholder {
color: #9ca3af !important; /* gray-400 */
}
</style>
@endpush
<x-section-header subtitle="Punto de Venta" title="Registrar " highlight="Venta" /> <x-section-header subtitle="Punto de Venta" title="Nueva " highlight="Venta" />
<!-- Mensajes de Alerta --> <div class="w-full max-w-5xl mx-auto bg-panel-bg border border-neutral-800 rounded-xl p-8 shadow-lg">
<x-ui.alert />
<form action="{{ route('sales.store') }}" method="POST" id="sale-form" class="pb-20"> @if(session('success'))
<div class="bg-green-900/50 border border-green-500 text-green-300 px-4 py-3 rounded-lg mb-6 shadow-sm">
{{ session('success') }}
</div>
@endif
@if(session('error'))
<div class="bg-red-900/50 border border-red-500 text-red-300 px-4 py-3 rounded-lg mb-6 shadow-sm">
{{ session('error') }}
</div>
@endif
@if($errors->any())
<div class="bg-red-900/50 border border-red-500 text-red-300 px-4 py-3 rounded-lg mb-6 shadow-sm">
<ul class="list-disc list-inside">
@foreach($errors->all() as $error)
<li>{{ $error }}</li>
@endforeach
</ul>
</div>
@endif
<form action="{{ route('sales.store') }}" method="POST">
@csrf @csrf
<div class="grid grid-cols-1 lg:grid-cols-3 gap-6"> <div class="grid grid-cols-1 md:grid-cols-12 gap-6 mb-8 border-b border-neutral-800 pb-8">
<div class="md:col-span-10">
<!-- COLUMNA IZQUIERDA: DATOS GENERALES --> <x-forms.label for="client_id" value="Cliente" />
<div class="lg:col-span-1 space-y-6"> <div class="relative">
<!-- Tarjeta Cliente --> <select name="client_id" class="w-full select2-basic">
<div class="bg-panel-bg border border-neutral-800 rounded-xl p-6 shadow-lg"> <option value="">-- Consumidor Final (Anónimo) --</option>
<h3 class="text-white font-bold mb-4 uppercase tracking-wider text-sm border-b border-neutral-700 pb-2">
1. Datos del Cliente
</h3>
<div class="space-y-4">
<div>
<label class="block text-xs font-bold text-gray-400 uppercase mb-2">Seleccionar Cliente</label>
<!-- Select Nativo Simple -->
<select name="client_id" class="w-full bg-neutral-900 border border-neutral-700 text-white rounded-lg p-2.5 focus:ring-neon-lime focus:border-neon-lime">
<option value="">-- Consumidor Final --</option>
@foreach($clients as $client) @foreach($clients as $client)
<option value="{{ $client->id }}">{{ $client->name }}</option> <option value="{{ $client->id }}">{{ $client->name }}</option>
@endforeach @endforeach
</select> </select>
</div> </div>
</div>
<div class="md:col-span-2 flex items-end">
<a href="{{ route('clients.create', ['origin' => 'sales']) }}" target="_blank" class="bg-indigo-100 text-indigo-700 hover:bg-indigo-200 px-4 py-2 rounded-md font-bold flex items-center border border-indigo-200" title="Crear nuevo cliente">
+
</a>
</div>
</div>
<div class="mb-8">
<div class="flex justify-between items-end mb-4">
<x-forms.label value="Detalle de Productos" />
<div class="text-sm text-gray-400">
Total Items: <span class="text-white font-mono" id="item-count">1</span>
</div>
</div>
<div id="items-container" class="space-y-3">
<div class="item-row grid grid-cols-1 md:grid-cols-12 gap-4 items-start bg-neutral-800/50 p-4 rounded-xl border border-neutral-800">
<div class="md:col-span-6">
<label class="block text-gray-400 text-xs mb-1.5 uppercase tracking-wider font-semibold">Producto</label>
<select name="items[0][product_id]" class="w-full select2-product product-select">
<option value="" data-price="0" selected disabled>Buscar producto...</option>
@foreach($products as $product)
<option value="{{ $product->id }}" data-price="{{ $product->price }}">
{{ $product->sku }} - {{ $product->name }} (Stock: {{ $product->stock_quantity }})
</option>
@endforeach
</select>
</div>
<div class="md:col-span-2">
<label class="block text-gray-400 text-xs mb-1.5 uppercase tracking-wider font-semibold">Cant.</label>
<input type="number" name="items[0][quantity]" value="1" min="1"
class="quantity-input bg-neutral-800 border-neutral-700 text-white text-sm rounded-lg focus:ring-neon-lime focus:border-neon-lime block w-full p-2.5 h-[42px]">
</div>
<div class="md:col-span-3 text-right flex flex-col justify-center h-[42px] mt-6">
<span class="text-xs text-gray-500">Subtotal</span>
<span class="row-total text-lg font-bold text-neon-lime">$0.00</span>
</div>
<div class="md:col-span-1 flex items-end justify-end h-[42px] mt-6">
<button type="button" class="btn-remove text-neutral-500 hover:text-red-500 transition-colors p-2" title="Quitar item">
<svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
</svg>
</button>
</div>
</div>
</div>
<div class="mt-4">
<button type="button" id="btn-add-row" class="inline-flex items-center text-neon-lime hover:text-[#b3e600] font-bold text-sm transition-colors">
<svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5 mr-1" viewBox="0 0 20 20" fill="currentColor">
<path fill-rule="evenodd" d="M10 3a1 1 0 011 1v5h5a1 1 0 110 2h-5v5a1 1 0 11-2 0v-5H4a1 1 0 110-2h5V4a1 1 0 011-1z" clip-rule="evenodd" />
</svg>
Agregar otro producto
</button>
</div>
<div class="mt-5 flex justify-end items-center border-t border-neutral-700 pt-6">
<div class="text-right">
<span class="block text-gray-400 text-sm mb-1">Monto Total a Pagar</span>
<span id="grand-total" class="text-3xl font-bold text-white">$0.00</span>
</div>
</div>
</div>
<div class="grid grid-cols-1 md:grid-cols-2 gap-6 items-end border-t border-neutral-800 pt-6">
<div> <div>
<label class="block text-xs font-bold text-gray-400 uppercase mb-2">Método de Pago</label> <x-forms.label for="payment_method" value="Método de Pago" />
<select name="payment_method" class="w-full bg-neutral-900 border border-neutral-700 text-white rounded-lg p-2.5 focus:ring-neon-lime focus:border-neon-lime"> <select name="payment_method" class="bg-neutral-800 border-neutral-700 text-white text-sm rounded-lg focus:ring-neon-lime focus:border-neon-lime block w-full p-2.5">
<option value="Efectivo">Efectivo</option> <option value="Efectivo">Efectivo</option>
<option value="Tarjeta de Débito">Tarjeta de Débito</option> <option value="Tarjeta de Débito">Tarjeta de Débito</option>
<option value="Tarjeta de Crédito">Tarjeta de Crédito</option> <option value="Tarjeta de Crédito">Tarjeta de Crédito</option>
<option value="Transferencia">Transferencia</option> <option value="Transferencia">Transferencia</option>
</select> </select>
</div> </div>
</div>
</div>
</div>
<!-- COLUMNA DERECHA: CARRITO -->
<div class="lg:col-span-2">
<div class="bg-panel-bg border border-neutral-800 rounded-xl shadow-lg overflow-hidden flex flex-col min-h-[500px]">
<div class="p-4 border-b border-neutral-800 bg-neutral-900/50 flex justify-between items-center">
<h3 class="text-white font-bold uppercase tracking-wider text-sm">2. Detalle de Venta</h3>
<button type="button" onclick="agregarFila()" class="text-xs bg-neutral-800 hover:bg-neutral-700 text-neon-lime border border-neon-lime/30 px-3 py-1.5 rounded uppercase font-bold transition-colors">
+ Agregar Producto
</button>
</div>
<!-- Tabla de Ítems -->
<div class="flex-grow overflow-x-auto">
<table class="w-full text-sm text-left text-gray-400">
<thead class="text-xs text-gray-300 uppercase bg-neutral-800 border-b border-neutral-700">
<tr>
<th class="px-4 py-3 w-[40%]">Producto</th>
<th class="px-4 py-3 text-center w-[15%]">Cant.</th>
<th class="px-4 py-3 text-right w-[20%]">Precio</th>
<th class="px-4 py-3 text-right w-[20%]">Subtotal</th>
<th class="px-4 py-3 text-center w-[5%]"></th>
</tr>
</thead>
<tbody id="items-container">
<!-- Las filas se generan con JS -->
</tbody>
</table>
<!-- Mensaje vacío -->
<div id="empty-message" class="flex flex-col items-center justify-center h-40 text-gray-600">
<p>El carrito está vacío</p>
<p class="text-xs mt-1">Presiona "Agregar Producto" para comenzar</p>
</div>
</div>
<!-- Footer Totales -->
<div class="bg-neutral-900 border-t border-neutral-800 p-6">
<div class="flex justify-between items-center mb-6">
<span class="text-xl font-bold text-white uppercase">Total a Pagar</span>
<span class="text-3xl font-black text-neon-lime">$<span id="total-display">0.00</span></span>
</div>
<div class="flex justify-end gap-4"> <div class="flex justify-end gap-4">
<a href="{{ route('sales.index') }}" class="px-6 py-3 text-gray-400 hover:text-white transition-colors font-medium">Cancelar</a> <a href="{{ route('sales.create') }}" class="px-6 py-2.5 text-gray-400 hover:text-white font-medium text-sm transition-colors flex items-center">
<button type="submit" class="px-8 py-3 bg-neon-lime text-neutral-900 font-black uppercase tracking-wide rounded-lg hover:bg-[#b3e600] shadow-lg shadow-neon-lime/20 transition-transform hover:-translate-y-1"> Cancelar
</a>
<button type="submit" class="px-8 py-2.5 bg-neon-lime text-neutral-900 font-bold rounded-lg hover:bg-[#b3e600] transition-colors shadow-lg shadow-neon-lime/20 transform hover:scale-105">
Confirmar Venta Confirmar Venta
</button> </button>
</div> </div>
</div> </div>
</div>
</div>
</div>
</form> </form>
</div>
@push('scripts')
{{-- SCRIPTS --}}
<script type="module"> <script type="module">
// 1. Base de datos de productos en JS (Para búsqueda rápida) let rowCount = 0;
const productsDB = @json($products);
let rowIndex = 0;
$(document).ready(function() { $(document).ready(function() {
// Agregamos una fila inicial initSelect2();
agregarFila(); actualizarBloqueos(); // Bloqueo inicial
// --- AGREGAR FILA ---
$('#btn-add-row').click(function() {
rowCount++;
const container = $('#items-container');
const firstRow = container.find('.item-row').first();
$('.select2-product').select2('destroy'); // Destruir
const newRow = firstRow.clone(); // Clonar
initSelect2(); // Reactivar originales
// Limpiar nueva fila
newRow.find('input').val(1);
newRow.find('.row-total').text('$0.00');
// Actualizar atributos
newRow.find('select').attr('name', `items[${rowCount}][product_id]`).val('');
newRow.find('input').attr('name', `items[${rowCount}][quantity]`);
// Desbloquear opciones en la nueva fila (vital)
newRow.find('option').prop('disabled', false);
container.append(newRow);
initSelect2(); // Activar nueva
actualizarBloqueos(); // Recalcular bloqueos
actualizarContadorItems();
}); });
// Función para agregar nueva fila // --- ELIMINAR FILA ---
window.agregarFila = function() { $(document).on('click', '.btn-remove', function() {
$('#empty-message').hide(); if ($('.item-row').length > 1) {
$(this).closest('.item-row').remove();
const rowId = `row-${rowIndex}`; recalcularTodo();
actualizarBloqueos();
const html = ` actualizarContadorItems();
<tr class="item-row border-b border-neutral-800 hover:bg-neutral-800/30 transition-colors" id="${rowId}">
<td class="px-4 py-3 relative">
<!-- Input Oculto para ID del producto -->
<input type="hidden" name="items[${rowIndex}][product_id]" class="product-id">
<!-- Buscador Visual -->
<input type="text"
class="product-search w-full bg-neutral-900 border border-neutral-700 text-white rounded p-2 text-xs focus:ring-neon-lime focus:border-neon-lime placeholder-gray-600"
placeholder="Buscar por nombre o SKU..."
autocomplete="off">
<!-- Lista de sugerencias (Dropdown) -->
<div class="suggestions absolute left-4 right-4 z-50 bg-neutral-800 border border-neutral-600 rounded-b-lg shadow-xl max-h-48 overflow-y-auto hidden mt-1"></div>
</td>
<td class="px-4 py-3 text-center">
<input type="number" name="items[${rowIndex}][quantity]" value="1" min="1"
class="quantity-input w-16 bg-neutral-900 border border-neutral-700 text-white text-center rounded p-1 text-xs focus:ring-neon-lime focus:border-neon-lime"
readonly> <!-- Readonly hasta que seleccione producto -->
</td>
<td class="px-4 py-3 text-right font-mono text-gray-300 price-display">$0.00</td>
<td class="px-4 py-3 text-right font-mono font-bold text-white subtotal-display">$0.00</td>
<td class="px-4 py-3 text-center">
<button type="button" class="text-red-500 hover:text-red-400 p-1" onclick="eliminarFila('${rowId}')">
&times;
</button>
</td>
</tr>
`;
$('#items-container').append(html);
rowIndex++;
}
// Función para eliminar fila
window.eliminarFila = function(id) {
$(`#${id}`).remove();
if($('#items-container').children().length === 0) {
$('#empty-message').show();
}
calcularTotalGeneral();
}
// --- LÓGICA DE BÚSQUEDA Y CÁLCULOS (Delegación de eventos) ---
// 1. Al escribir en el buscador
$(document).on('keyup focus', '.product-search', function() {
let input = $(this);
let term = input.val().toLowerCase();
let suggestionsBox = input.siblings('.suggestions');
// Si está vacío, ocultar
if(term.length === 0) {
suggestionsBox.addClass('hidden').empty();
return;
}
// Filtrar productos
let matches = productsDB.filter(p =>
p.name.toLowerCase().includes(term) ||
(p.sku && p.sku.toLowerCase().includes(term))
);
// Renderizar resultados
let html = '';
if(matches.length > 0) {
matches.forEach(p => {
html += `
<div class="p-2 hover:bg-neutral-700 cursor-pointer text-xs text-white border-b border-neutral-700 last:border-0 suggestion-item flex justify-between"
data-id="${p.id}"
data-name="${p.name}"
data-price="${p.price}"
data-stock="${p.stock_quantity}">
<span>${p.name} <span class="text-gray-500">(${p.sku || 'N/A'})</span></span>
<span class="text-neon-lime font-mono">$${p.price}</span>
</div>
`;
});
} else { } else {
html = '<div class="p-2 text-xs text-gray-500 italic">No encontrado</div>'; alert("Debe haber al menos un producto.");
}
suggestionsBox.html(html).removeClass('hidden');
});
// 2. Al hacer click en una sugerencia
$(document).on('click', '.suggestion-item', function() {
let item = $(this);
let row = item.closest('tr');
// Llenar datos en la fila
row.find('.product-id').val(item.data('id'));
row.find('.product-search').val(item.data('name')); // Mostrar nombre en el input
row.find('.price-display').text('$' + parseFloat(item.data('price')).toFixed(2));
row.find('.price-display').data('price', item.data('price')); // Guardar precio crudo
// Activar cantidad
let qtyInput = row.find('.quantity-input');
qtyInput.prop('readonly', false).attr('max', item.data('stock')).val(1).focus();
// Esconder sugerencias
item.closest('.suggestions').addClass('hidden');
// Calcular
calcularFila(row);
});
// 3. Cerrar sugerencias al hacer click fuera
$(document).click(function(e) {
if(!$(e.target).closest('.product-search-container').length) {
$('.suggestions').addClass('hidden');
} }
}); });
// 4. Al cambiar cantidad // --- EVENTOS ---
$(document).on('input', '.quantity-input', function() { $(document).on('select2:select input', '.product-select, .quantity-input', function() {
let row = $(this).closest('tr'); let row = $(this).closest('.item-row');
calcularFila(row); calcularFila(row);
recalcularTodo();
if ($(this).hasClass('product-select')) {
actualizarBloqueos();
}
});
}); });
// Funciones de Cálculo // --- FUNCIONES ---
function initSelect2() {
$('.select2-basic').select2({ width: '100%' });
$('.select2-product').select2({
width: '100%',
placeholder: "Buscar producto...",
language: { noResults: () => "Sin resultados" }
});
}
function calcularFila(row) { function calcularFila(row) {
let price = parseFloat(row.find('.price-display').data('price')) || 0; let select = row.find('.product-select');
let qty = parseInt(row.find('.quantity-input').val()) || 0; let input = row.find('.quantity-input');
let option = select.find(':selected');
let price = parseFloat(option.data('price')) || 0;
let qty = parseInt(input.val()) || 0;
let subtotal = price * qty; let subtotal = price * qty;
row.find('.row-total').text('$' + subtotal.toFixed(2));
row.find('.subtotal-display').text('$' + subtotal.toFixed(2));
row.find('.subtotal-display').data('subtotal', subtotal);
calcularTotalGeneral();
} }
function calcularTotalGeneral() { function recalcularTodo() {
let total = 0; let grandTotal = 0;
$('.subtotal-display').each(function() { $('.item-row').each(function() {
total += $(this).data('subtotal') || 0; let row = $(this);
let price = parseFloat(row.find('.product-select').find(':selected').data('price')) || 0;
let qty = parseInt(row.find('.quantity-input').val()) || 0;
grandTotal += (price * qty);
}); });
$('#total-display').text(total.toFixed(2)); $('#grand-total').text('$' + grandTotal.toFixed(2));
} }
function actualizarContadorItems() {
$('#item-count').text($('.item-row').length);
}
function actualizarBloqueos() {
let seleccionados = [];
$('.product-select').each(function() {
let valor = $(this).val();
if (valor) seleccionados.push(valor);
});
$('.product-select').each(function() {
let selectActual = $(this);
let miValor = selectActual.val();
selectActual.find('option').each(function() {
let opcion = $(this);
let valorOpcion = opcion.val();
if (!valorOpcion) return;
if (seleccionados.includes(valorOpcion) && valorOpcion != miValor) {
opcion.prop('disabled', true);
} else {
opcion.prop('disabled', false);
}
});
});
}
</script> </script>
@endpush
</x-layout> </x-layout>