intento
This commit is contained in:
@@ -7,6 +7,8 @@ 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
|
||||
{
|
||||
@@ -14,14 +16,17 @@ class SaleController extends Controller
|
||||
{
|
||||
// Buscamos productos que tengan stock mayor a 0 para mostrar en el selector
|
||||
$products = Product::where('stock', '>', 0)->get();
|
||||
|
||||
return view('sales.create', compact('products'));
|
||||
|
||||
$clients = \App\Models\Client::orderBy('nombre')->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',
|
||||
@@ -30,32 +35,36 @@ class SaleController extends Controller
|
||||
try {
|
||||
DB::transaction(function () use ($request) {
|
||||
$totalVenta = 0;
|
||||
|
||||
foreach ($request->items as $item) {
|
||||
$producto = Product::find($item['product_id']);
|
||||
$totalVenta += $producto->price * $item['quantity'];
|
||||
$product = Product::find($item['product_id']);
|
||||
$totalVenta += $product->precio * $item['quantity'];
|
||||
|
||||
if ($producto->stock < $item['quantity']) {
|
||||
throw new \Exception("No hay suficiente stock de " . $producto->name);
|
||||
if ($product->stock < $item['quantity']) {
|
||||
throw new \Exception("No hay suficiente stock de " . $product->nombre);
|
||||
}
|
||||
}
|
||||
|
||||
// raro arreglar
|
||||
//cabecera
|
||||
$sale = Sale::create([
|
||||
'user_id' => auth()->id(), // El empleado logueado
|
||||
//'user_id' => auth()->id(), //empleado logueado
|
||||
'client_id' => $request->client_id,
|
||||
'total' => $totalVenta,
|
||||
'payment_method' => $request->payment_method,
|
||||
]);
|
||||
|
||||
foreach ($request->items as $item) {
|
||||
$producto = Product::find($item['product_id']);
|
||||
$product = Product::find($item['product_id']);
|
||||
|
||||
SaleDetail::create([
|
||||
'sale_id' => $sale->id,
|
||||
'product_id' => $producto->id,
|
||||
'quantity' => $item['quantity'],
|
||||
'price' => $producto->price,
|
||||
'product_id' => $product->id,
|
||||
'cantidad' => $item['quantity'],
|
||||
'precio' => $product->precio,
|
||||
]);
|
||||
$producto->decrement('stock', $item['quantity']);
|
||||
$nuevoStock = $product->stock - $item['quantity'];
|
||||
$product->stock = $nuevoStock;
|
||||
$product->save();
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
Reference in New Issue
Block a user