56 lines
1.6 KiB
PHP
56 lines
1.6 KiB
PHP
<?php
|
|
|
|
namespace App\Actions;
|
|
|
|
use App\Data\OrderRequestDTO;
|
|
use App\Enums\CartStatus;
|
|
use App\Exceptions\StaleCartException;
|
|
use App\Models\Address;
|
|
use App\Models\Cart;
|
|
use App\Models\Order;
|
|
use App\Models\User;
|
|
use Illuminate\Http\JsonResponse;
|
|
|
|
final readonly class CreateOrderAction
|
|
{
|
|
/**
|
|
* Execute the action.
|
|
* @throws StaleCartException
|
|
*/
|
|
public function execute(OrderRequestDTO $dto, User $user): JsonResponse
|
|
{
|
|
/** @var Cart $cart */
|
|
$cart = Cart::query()->where('id', $dto->cartId)->sole();
|
|
|
|
if ($cart->status !== CartStatus::Active) {
|
|
throw new StaleCartException(userId: $user->id, cartId: $cart->id);
|
|
}
|
|
|
|
// check if the user has an order with the same cart id
|
|
if ($user->orders()->where('cart_id', $cart->id)->exists()) {
|
|
return response()->json([
|
|
'message' => 'User already has an order with this cart'
|
|
]);
|
|
}
|
|
|
|
/** @var Address $address */
|
|
$address = $user->addresses()->where('id', $dto->addressId)->sole();
|
|
|
|
/** @var Order $order */
|
|
$order = $user->orders()->make();
|
|
|
|
$order->cart_id = $cart->id;
|
|
$order->shipping_first_name = $address->first_name;
|
|
$order->shipping_last_name = $address->last_name;
|
|
$order->shipping_street = $address->street;
|
|
$order->shipping_city = $address->city;
|
|
$order->shipping_state = $address->state;
|
|
$order->shipping_pin = $address->pin;
|
|
$order->save();
|
|
|
|
return response()->json([
|
|
'message' => 'Order created successfully'
|
|
], 201);
|
|
}
|
|
}
|