89 lines
3.0 KiB
PHP
89 lines
3.0 KiB
PHP
<?php
|
|
|
|
namespace App\Http\Controllers;
|
|
|
|
use Illuminate\Http\Request;
|
|
use App\Models\Product;
|
|
use App\Models\Sale;
|
|
use App\Models\SaleDetail;
|
|
use Illuminate\Support\Facades\DB;
|
|
use App\Models\Client;
|
|
|
|
class SaleController extends Controller
|
|
{
|
|
public function index()
|
|
{
|
|
$sales = Sale::with('client')
|
|
->orderBy('created_at', 'desc')
|
|
->paginate(15);
|
|
|
|
return view('sales.index', compact('sales'));
|
|
}
|
|
|
|
public function create()
|
|
{
|
|
// Buscamos productos que tengan stock mayor a 0 para mostrar en el selector
|
|
$products = Product::where('stock_quantity', '>', 0)->get();
|
|
|
|
$clients = Client::orderBy('name')->get();
|
|
|
|
return view('sales.create', compact('products', 'clients'));
|
|
}
|
|
|
|
public function store(Request $request)
|
|
{
|
|
$request->validate([
|
|
'payment_method' => 'required|string',
|
|
'client_id' => 'nullable|exists:clients,id',
|
|
'items' => 'required|array',
|
|
'items.*.product_id' => 'required|exists:products,id',
|
|
'items.*.quantity' => 'required|integer|min:1',
|
|
]);
|
|
|
|
try {
|
|
DB::transaction(function () use ($request) {
|
|
$totalSale = 0;
|
|
|
|
foreach ($request->items as $item) {
|
|
$product = Product::find($item['product_id']);
|
|
$totalSale += $product->precio * $item['quantity'];
|
|
|
|
if ($product->stock_quantity < $item['quantity']) {
|
|
throw new \Exception("No hay suficiente stock de " . $product->nombre);
|
|
}
|
|
}
|
|
|
|
//cabecera
|
|
$sale = Sale::create([
|
|
//'user_id' => auth()->id(), //empleado logueado
|
|
'client_id' => $request->client_id,
|
|
'total' => $totalSale,
|
|
'payment_method' => $request->payment_method,
|
|
]);
|
|
|
|
foreach ($request->items as $item) {
|
|
$product = Product::find($item['product_id']);
|
|
|
|
SaleDetail::create([
|
|
'sale_id' => $sale->id,
|
|
'product_id' => $product->id,
|
|
'quantity' => $item['quantity'],
|
|
'price' => $product->price,
|
|
]);
|
|
$nuevoStock = $product->stock_quantity - $item['quantity'];
|
|
$product->stock_quantity = $nuevoStock;
|
|
$product->save();
|
|
}
|
|
});
|
|
|
|
// 5. REDIRECCIÓN DE ÉXITO
|
|
// Redirigimos al usuario con un mensaje flash [cite: 668]
|
|
return redirect()->route('sales.create')->with('success', '¡Venta registrada correctamente!');
|
|
|
|
} catch (\Exception $e) {
|
|
// Si algo falló (ej: falta stock), volvemos atrás con el error
|
|
return back()->with('error', 'Error en la venta: ' . $e->getMessage());
|
|
}
|
|
}
|
|
}
|