Refactor order creation logic by introducing CreateOrderService and removing the create method from OrderRepository. Update ProductRepository with stricter type declarations and fix minor typos in comments.
This commit is contained in:
1 parent
d0f962220c
commit
eaae8b9be9
5 files changed
+160
-54
No files matched your search
@@ -0,0 +1,62 @@
|
||||
<?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
|
||||
*
|
||||
* @param User $user
|
||||
* @param array $data
|
||||
* @return Order
|
||||
*/
|
||||
public function execute(User $user, array $data): Order
|
||||
{
|
||||
return DB::transaction(function () use ($user, $data) {
|
||||
// 1. Create the order
|
||||
$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;
|
||||
});
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user