- Removed unnecessary blank lines in various files to enhance code clarity. - Updated comments for consistency and clarity across multiple classes and methods. - Adjusted spacing in test files for better formatting and readability.
60 lines
1.9 KiB
PHP
60 lines
1.9 KiB
PHP
<?php
|
|
|
|
declare(strict_types=1);
|
|
|
|
namespace App\Services\Order;
|
|
|
|
use App\Events\Ecommerce\Product\Order\OrderCreated;
|
|
use App\Models\Ecommerce\Product\Order\Order;
|
|
use App\Models\User;
|
|
use Illuminate\Support\Facades\DB;
|
|
|
|
class CreateOrderService
|
|
{
|
|
/**
|
|
* Create a new order for the user
|
|
*/
|
|
public function execute(User $user, array $data): Order
|
|
{
|
|
return DB::transaction(function () use ($user, $data) {
|
|
// 1. Create the order
|
|
info(['service' => $data]);
|
|
$order = Order::create($data);
|
|
|
|
// 2. Process Cart Items
|
|
$user->carts()
|
|
->with(['product' => function ($query) {
|
|
$query->with(['media', 'channels']);
|
|
}])
|
|
->get()
|
|
->each(function ($cart) use ($order) {
|
|
// Create Order Item
|
|
DB::table('order_items')->insert([
|
|
'product_name' => $cart->product->name,
|
|
'product_id' => $cart->product_id,
|
|
'order_id' => $order->id,
|
|
'channel_id' => $cart->product->channels->first()?->id ?? tmpostChannel()->id,
|
|
'quantity' => $cart->product_quantity,
|
|
'unit_price_amount' => $cart->product->price_amount,
|
|
'unit_cost_amount' => $cart->product->cost_amount,
|
|
'created_at' => now(),
|
|
'updated_at' => now(),
|
|
]);
|
|
|
|
// Update Stock
|
|
$cart->product->update([
|
|
'stock' => $cart->product->stock - $cart->product_quantity,
|
|
]);
|
|
});
|
|
|
|
// 3. Clear User Cart
|
|
$user->carts()->delete();
|
|
|
|
// 4. Dispatch Event
|
|
OrderCreated::dispatch($order);
|
|
|
|
return $order;
|
|
});
|
|
}
|
|
}
|