80 lines
2.8 KiB
PHP
80 lines
2.8 KiB
PHP
<?php
|
|
|
|
namespace App\Http\Controllers;
|
|
|
|
use Illuminate\Http\Request;
|
|
use App\Models\Product;
|
|
use App\Models\Client;
|
|
use App\Models\Sale;
|
|
use App\Models\SaleDetail;
|
|
use Illuminate\Support\Facades\DB;
|
|
|
|
class SaleController extends Controller
|
|
{
|
|
public function create()
|
|
{
|
|
// Traemos productos con stock y clientes para los selectores
|
|
$products = Product::where('stock_quantity', '>', 0)->get();
|
|
$clients = Client::orderBy('name')->get();
|
|
|
|
return view('sales.create', compact('products', 'clients'));
|
|
}
|
|
|
|
public function store(Request $request)
|
|
{
|
|
// Validación estricta
|
|
$request->validate([
|
|
'client_id' => 'nullable|exists:clients,id',
|
|
'payment_method' => 'required|string',
|
|
'items' => 'required|array',
|
|
'items.*.product_id' => 'required|exists:products,id',
|
|
'items.*.quantity' => 'required|integer|min:1',
|
|
]);
|
|
|
|
try {
|
|
DB::transaction(function () use ($request) {
|
|
|
|
$totalVenta = 0;
|
|
|
|
// 1. Calcular total previo (Solo habrá 1 item por ahora, pero el bucle sirve igual)
|
|
foreach ($request->items as $itemData) {
|
|
$product = Product::findOrFail($itemData['product_id']);
|
|
|
|
if ($product->stock_quantity < $itemData['quantity']) {
|
|
throw new \Exception("Stock insuficiente para: " . $product->name);
|
|
}
|
|
|
|
$totalVenta += $product->price * $itemData['quantity'];
|
|
}
|
|
|
|
// 2. Crear Venta
|
|
$sale = Sale::create([
|
|
'client_id' => $request->client_id,
|
|
'total' => $totalVenta,
|
|
'payment_method' => $request->payment_method,
|
|
// 'user_id' => auth()->id(), // Descomenta si usas autenticación
|
|
]);
|
|
|
|
// 3. Guardar Detalle y Restar Stock
|
|
foreach ($request->items as $itemData) {
|
|
$product = Product::findOrFail($itemData['product_id']);
|
|
|
|
SaleDetail::create([
|
|
'sale_id' => $sale->id,
|
|
'product_id' => $product->id,
|
|
'quantity' => $itemData['quantity'],
|
|
'price' => $product->price,
|
|
]);
|
|
|
|
$product->decrement('stock_quantity', $itemData['quantity']);
|
|
}
|
|
});
|
|
|
|
return redirect()->route('sales.create')->with('success', '¡Venta registrada correctamente!');
|
|
|
|
} catch (\Exception $e) {
|
|
return back()->with('error', $e->getMessage())->withInput();
|
|
}
|
|
}
|
|
}
|