FUNCIONA VENTAS (quedo horrible la vista, despues la cambio, pero anda!)

This commit is contained in:
BryamE
2026-01-08 04:23:06 -03:00
parent 37e8f498be
commit 8f10e3595d
9 changed files with 263 additions and 236 deletions
+1 -1
View File
@@ -19,7 +19,7 @@ class ClientController extends Controller
*/
public function create()
{
//
return view('clients.create');
}
/**
@@ -169,21 +169,4 @@ class ProductosController extends Controller
return redirect()->route('productos.index')
->with('success', 'Producto eliminado.');
}
/**
* Vista simplificada para consultar precios (empleados).
*/
public function checker(Request $request)
{
$search = $request->input('query');
$result = null;
if ($search) {
$result = Product::where('sku', $search)
->orWhere('name', 'like', "%{$search}%")
->first(); // Devuelve el primer resultado encontrado
}
return view('productos.checker', compact('result', 'search'));
}
}
+2 -2
View File
@@ -46,10 +46,10 @@ class SaleController extends Controller
foreach ($request->items as $item) {
$product = Product::find($item['product_id']);
$totalSale += $product->precio * $item['quantity'];
$totalSale += $product->price * $item['quantity'];
if ($product->stock_quantity < $item['quantity']) {
throw new \Exception("No hay suficiente stock de " . $product->nombre);
throw new \Exception("No hay suficiente stock de " . $product->name);
}
}
+8 -2
View File
@@ -11,13 +11,19 @@ class Sale extends Model
// Permitimos asignación masiva para poder guardar rápido
protected $guarded = [];
// Relación 1: Una venta pertenece a un Cliente (User)
// Relación 1: Una venta la realiza un Usuario (User)
public function user()
{
return $this->belongsTo(User::class);
}
// Relación 2: Una venta tiene muchos items o detalles
// Relación 2: Una venta pertenece a un Cliente (User)
public function client()
{
return $this->belongsTo(Client::class);
}
// Relación 3: Una venta tiene muchos items o detalles
public function details()
{
return $this->hasMany(SaleDetail::class);
+2 -4
View File
@@ -1,5 +1,3 @@
@extends('layouts.app')
@section('main')
<x-layout>
<h1>formulario de crear cliente</h1>
@endsection
</x-layout>
@@ -35,5 +35,7 @@
btn.addEventListener('click', () => menu.classList.toggle('hidden'));
}
</script>
@stack('scripts')
</body>
</html>
+236 -197
View File
@@ -1,223 +1,262 @@
<x-layout>
<div class="py-12 bg-gray-100 min-h-screen">
<div class="max-w-7xl mx-auto sm:px-6 lg:px-8">
<x-layout title="Nueva Venta">
<div class="bg-white overflow-hidden shadow-sm sm:rounded-lg p-6">
<div class="mb-6 border-b pb-2">
<h2 class="text-2xl font-bold text-gray-800">Nueva Venta en Mostrador</h2>
</div>
<x-section-header subtitle="Punto de Venta" title="Registrar " highlight="Venta" />
@if (session('success'))
<div class="bg-green-100 border border-green-400 text-green-700 px-4 py-3 rounded relative mb-4">
<strong class="font-bold">¡Éxito!</strong> {{ session('success') }}
</div>
@endif
<!-- Mensajes de Alerta -->
<x-ui.alert />
@if (session('error'))
<div class="bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded relative mb-4">
<strong class="font-bold">Error:</strong> {{ session('error') }}
</div>
@endif
<form action="{{ route('sales.store') }}" method="POST" id="sale-form" class="pb-20">
@csrf
@if ($errors->any())
<div class="bg-red-50 text-red-600 p-4 mb-4 rounded border border-red-200">
<ul>
@foreach ($errors->all() as $error)
<li> {{ $error }}</li>
@endforeach
</ul>
</div>
@endif
<div class="grid grid-cols-1 lg:grid-cols-3 gap-6">
<!-- COLUMNA IZQUIERDA: DATOS GENERALES -->
<div class="lg:col-span-1 space-y-6">
<!-- Tarjeta Cliente -->
<div class="bg-panel-bg border border-neutral-800 rounded-xl p-6 shadow-lg">
<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>
<form action="{{ route('sales.store') }}" method="POST" id="sale-form">
@csrf
<div class="mb-6 bg-gray-50 p-4 rounded-lg border border-gray-200">
<label class="block text-sm font-medium text-gray-700 mb-1">Cliente</label>
<div class="flex gap-2">
<select name="client_id" class="select2-enable w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 py-2 px-3 border">
<option value="">-- Consumidor Final (Anónimo) --</option>
<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)
<option value="{{ $client->id }}">{{ $client->name }} ({{ $client->phone }})</option>
<option value="{{ $client->id }}">{{ $client->name }}</option>
@endforeach
</select>
<a href="{{ route('clients.create') }}" 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 id="items-container" class="space-y-4">
<div class="item-row grid grid-cols-1 md:grid-cols-12 gap-4 items-end bg-gray-50 p-4 rounded-lg border border-gray-200">
<div class="md:col-span-6">
<label class="block text-sm font-medium text-gray-700 mb-1">Producto</label>
<select name="items[0][product_id]" class="product-select select2-enable w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 py-2 px-3 border" required onchange="calcularTotal()">
<option value="" data-price="0" selected disabled>Seleccione...</option>
@foreach($products as $product)
<option value="{{ $product->id }}" data-price="{{ $product->price }}">
{{ $product->sku }} - {{ $product->name }} (${{ $product->price }})
</option>
@endforeach
</select>
</div>
<div class="md:col-span-3">
<label class="block text-sm font-medium text-gray-700 mb-1">Cantidad</label>
<input type="number" name="items[0][quantity]" value="1" min="1" class="quantity-input w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 py-2 px-3 border" required oninput="calcularTotal()">
</div>
<div class="md:col-span-2 text-right font-mono text-gray-600 self-center pt-6">
$<span class="row-subtotal">0.00</span>
</div>
<div class="md:col-span-1 text-right">
<button type="button" class="text-gray-400 cursor-not-allowed" disabled>
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor" class="w-6 h-6 inline">
<path stroke-linecap="round" stroke-linejoin="round" d="M14.74 9l-.346 9m-4.788 0L9.26 9m9.968-3.21c.342.052.682.107 1.022.166m-1.022-.165L18.16 19.673a2.25 2.25 0 01-2.244 2.077H8.084a2.25 2.25 0 01-2.244-2.077L4.772 5.79m14.456 0a48.108 48.108 0 00-3.478-.397m-12 .562c.34-.059.68-.114 1.022-.165m0 0a48.11 48.11 0 013.478-.397m7.5 0v-.916c0-1.18-.91-2.164-2.09-2.201a51.964 51.964 0 00-3.32 0c-1.18.037-2.09 1.022-2.09 2.201v.916m7.5 0a48.667 48.667 0 00-7.5 0" />
</svg>
</button>
</div>
</div>
</div>
<div class="mt-4">
<button type="button" onclick="agregarFila()" class="flex items-center text-indigo-600 hover:text-indigo-800 font-semibold">
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor" class="w-5 h-5 mr-1">
<path stroke-linecap="round" stroke-linejoin="round" d="M12 4.5v15m7.5-7.5h-15" />
</svg>
Agregar otro producto
</button>
</div>
<div class="flex justify-end mt-6 border-t pt-4">
<div class="text-2xl font-bold text-gray-800">
Total a Pagar: <span class="text-indigo-600">$<span id="total-display">0.00</span></span>
</div>
</div>
<div class="mt-6 grid grid-cols-1 md:grid-cols-2 gap-6 items-center">
<div>
<label class="block text-sm font-medium text-gray-700 mb-1">Método de Pago</label>
<select name="payment_method" class="w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 py-2 px-3 border">
<label class="block text-xs font-bold text-gray-400 uppercase mb-2">Método de Pago</label>
<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">
<option value="Efectivo">Efectivo</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="Transferencia">Transferencia</option>
</select>
</div>
</div>
</div>
</div>
<div class="flex items-end gap-4 justify-end">
<a href="{{ route('sales.create') }}" class="bg-white hover:bg-gray-100 text-gray-800 font-semibold py-2 px-4 border border-gray-400 rounded shadow">
Cancelar
</a>
<button type="submit" class="bg-indigo-600 hover:bg-indigo-700 text-white font-bold py-2 px-6 rounded shadow-lg">
<!-- 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">
<a href="{{ route('sales.index') }}" class="px-6 py-3 text-gray-400 hover:text-white transition-colors font-medium">Cancelar</a>
<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">
Confirmar Venta
</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</form>
@push('scripts')
{{-- SCRIPTS --}}
<script type="module">
// 1. Base de datos de productos en JS (Para búsqueda rápida)
const productsDB = @json($products);
let rowIndex = 0;
$(document).ready(function() {
// Agregamos una fila inicial
agregarFila();
});
// Función para agregar nueva fila
window.agregarFila = function() {
$('#empty-message').hide();
const rowId = `row-${rowIndex}`;
const html = `
<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 {
html = '<div class="p-2 text-xs text-gray-500 italic">No encontrado</div>';
}
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
$(document).on('input', '.quantity-input', function() {
let row = $(this).closest('tr');
calcularFila(row);
});
// Funciones de Cálculo
function calcularFila(row) {
let price = parseFloat(row.find('.price-display').data('price')) || 0;
let qty = parseInt(row.find('.quantity-input').val()) || 0;
let subtotal = price * qty;
row.find('.subtotal-display').text('$' + subtotal.toFixed(2));
row.find('.subtotal-display').data('subtotal', subtotal);
calcularTotalGeneral();
}
function calcularTotalGeneral() {
let total = 0;
$('.subtotal-display').each(function() {
total += $(this).data('subtotal') || 0;
});
$('#total-display').text(total.toFixed(2));
}
</script>
@endpush
</x-layout>
@push('scripts')
<script>
let itemIndex = 0;
$(document).ready(function() {
inicializarSelect2();
});
function inicializarSelect2() {
$('.select2-enable').select2({
width: '100%',
placeholder: "Escribe para buscar...",
allowClear: true
});
}
function agregarFila() {
itemIndex++;
const container = document.getElementById('items-container');
const firstRow = container.querySelector('.item-row');
// 1. Destruimos Select2 temporalmente para clonar limpio
$('.select2-enable').select2('destroy');
// 2. Clonamos
const newRow = firstRow.cloneNode(true);
// 3. Reactivamos en los originales
inicializarSelect2();
// Limpiamos valores de la copia
const select = newRow.querySelector('select');
const input = newRow.querySelector('input');
const subtotal = newRow.querySelector('.row-subtotal');
select.name = `items[${itemIndex}][product_id]`;
select.value = "";
input.name = `items[${itemIndex}][quantity]`;
input.value = 1;
subtotal.innerText = "0.00";
// Botón Eliminar
const deleteBtnDiv = newRow.querySelector('div:last-child');
deleteBtnDiv.innerHTML = `
<button type="button" onclick="eliminarFila(this)" class="text-red-500 hover:text-red-700">
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor" class="w-6 h-6 inline">
<path stroke-linecap="round" stroke-linejoin="round" d="M14.74 9l-.346 9m-4.788 0L9.26 9m9.968-3.21c.342.052.682.107 1.022.166m-1.022-.165L18.16 19.673a2.25 2.25 0 01-2.244 2.077H8.084a2.25 2.25 0 01-2.244-2.077L4.772 5.79m14.456 0a48.108 48.108 0 00-3.478-.397m-12 .562c.34-.059.68-.114 1.022-.165m0 0a48.11 48.11 0 013.478-.397m7.5 0v-.916c0-1.18-.91-2.164-2.09-2.201a51.964 51.964 0 00-3.32 0c-1.18.037-2.09 1.022-2.09 2.201v.916m7.5 0a48.667 48.667 0 00-7.5 0" />
</svg>
</button>
`;
container.appendChild(newRow);
// 4. Inicializamos en el nuevo
inicializarSelect2();
// Evento extra para Select2
$(select).on('select2:select', function (e) {
calcularTotal();
});
}
function eliminarFila(button) {
const row = button.closest('.item-row');
row.remove();
calcularTotal();
}
function calcularTotal() {
let total = 0;
const rows = document.querySelectorAll('.item-row');
rows.forEach(row => {
const select = row.querySelector('.product-select');
const input = row.querySelector('.quantity-input');
const subtotalSpan = row.querySelector('.row-subtotal');
const selectedOption = $(select).find(':selected');
const price = parseFloat(selectedOption.attr('data-price')) || 0;
const quantity = parseInt(input.value) || 0;
const subtotal = price * quantity;
subtotalSpan.innerText = subtotal.toFixed(2);
total += subtotal;
});
document.getElementById('total-display').innerText = total.toFixed(2);
}
$(document).on('select2:select', '.product-select', function (e) {
calcularTotal();
});
</script>
@endpush
+5 -6
View File
@@ -39,17 +39,16 @@ Route::view('register', 'register')->name('register');
Route::post('register', RegisterController::class)->name('register.store');
Route::middleware(['auth'])->group(function () {
Route::resource('clients', ClientController::class);
Route::resource('productos', ProductosController::class)->parameters([
'productos' => 'product'
]);
Route::resource('clients', ClientController::class);
Route::get('/checker', [ProductosController::class, 'checker'])->name('productos.checker');
Route::controller(SaleController::class)->prefix('sales')->name('sales.')->group(function () {
Route::get('/', 'index')->name('index'); // Historial (Nueva)
Route::get('/create', 'create')->name('create'); // Formulario (Existente)
Route::post('/', 'store')->name('store'); // Guardar (CORREGIDO a POST)
Route::get('/{sale}', 'show')->name('show'); // Ver detalle de una venta (Opcional futura)
Route::get('/', 'index')->name('index');
Route::get('/create', 'create')->name('create');
Route::post('/', 'store')->name('store');
Route::get('/{sale}', 'show')->name('show');
});
});