236 lines
8.5 KiB
PHP
236 lines
8.5 KiB
PHP
<?php
|
|
|
|
namespace App\Domains\Purchase\Services;
|
|
|
|
use App\Domains\Cart\Models\Cart;
|
|
use App\Domains\Cart\Models\CartItem;
|
|
use App\Domains\Catalog\Models\ProductVariant;
|
|
use App\Domains\Purchase\Models\Purchase;
|
|
use App\Domains\Tenant\Models\Tenant;
|
|
use Illuminate\Support\Collection;
|
|
use Illuminate\Support\Facades\DB;
|
|
use Illuminate\Validation\ValidationException;
|
|
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
|
|
|
|
class CheckoutService
|
|
{
|
|
public function startCheckout(Tenant $tenant, int $userId, array $purchaseData): Purchase
|
|
{
|
|
$cartId = (int) $purchaseData['cart_id'];
|
|
unset($purchaseData['cart_id']);
|
|
|
|
return DB::transaction(function () use ($tenant, $userId, $purchaseData, $cartId): Purchase {
|
|
$cart = $this->resolveCheckoutCart($tenant, $userId, $cartId);
|
|
$cartItems = $cart->items()->lockForUpdate()->get();
|
|
|
|
if ($cartItems->isEmpty()) {
|
|
throw ValidationException::withMessages([
|
|
'cart_id' => 'The selected cart does not contain items.',
|
|
]);
|
|
}
|
|
|
|
$cartItems->load('variant.product');
|
|
$cart->setRelation('items', $cartItems);
|
|
$totalAmount = $cart->getTotalAmount();
|
|
|
|
/** @var Purchase|null $purchase */
|
|
$purchase = Purchase::query()
|
|
->where('cart_id', $cart->getKey())
|
|
->where('tenant_codigo', $tenant->codigo)
|
|
->where('user_id', $userId)
|
|
->whereIn('status', [Purchase::STATUS_CREATED, Purchase::STATUS_PENDING_PAYMENT])
|
|
->latest('id')
|
|
->first();
|
|
|
|
if ($purchase === null) {
|
|
/** @var Purchase $purchase */
|
|
$purchase = Purchase::query()->create([
|
|
...$purchaseData,
|
|
'cart_id' => $cart->getKey(),
|
|
'tenant_codigo' => $tenant->codigo,
|
|
'user_id' => $userId,
|
|
'status' => Purchase::STATUS_CREATED,
|
|
'payment_method' => null,
|
|
'total' => $totalAmount,
|
|
]);
|
|
} else {
|
|
$purchase->fill([
|
|
...$purchaseData,
|
|
'status' => Purchase::STATUS_CREATED,
|
|
'payment_method' => null,
|
|
'total' => $totalAmount,
|
|
]);
|
|
$purchase->save();
|
|
}
|
|
|
|
return $purchase->load(['items.variant.product', 'items.variant.definitions.productAttribute.attribute']);
|
|
});
|
|
}
|
|
|
|
public function finalizePurchase(Purchase $purchase): Purchase
|
|
{
|
|
return DB::transaction(function () use ($purchase): Purchase {
|
|
/** @var Purchase $purchase */
|
|
$purchase = Purchase::query()
|
|
->lockForUpdate()
|
|
->findOrFail($purchase->getKey());
|
|
|
|
if ($purchase->payment_method === null) {
|
|
throw ValidationException::withMessages([
|
|
'payment_method' => 'The purchase payment method must be selected before finalizing.',
|
|
]);
|
|
}
|
|
|
|
if (in_array($purchase->status, [Purchase::STATUS_PAID, Purchase::STATUS_CANCELLED, Purchase::STATUS_REJECTED], true)) {
|
|
return $purchase->load(['items.variant.product', 'items.variant.definitions.productAttribute.attribute']);
|
|
}
|
|
|
|
$purchase->update([
|
|
'status' => Purchase::STATUS_PENDING_PAYMENT,
|
|
'total' => $purchase->calculateCurrentTotalAmount(),
|
|
]);
|
|
|
|
return $purchase->load(['items.variant.product', 'items.variant.definitions.productAttribute.attribute']);
|
|
});
|
|
}
|
|
|
|
public function confirmPurchase(Purchase $purchase): void
|
|
{
|
|
DB::transaction(function () use ($purchase): void {
|
|
/** @var Cart|null $cart */
|
|
$cart = $purchase->cart()->lockForUpdate()->first();
|
|
|
|
if ($cart === null) {
|
|
throw ValidationException::withMessages([
|
|
'cart_id' => 'The purchase cart is no longer available.',
|
|
]);
|
|
}
|
|
|
|
$cartItems = $cart->items()->lockForUpdate()->get();
|
|
|
|
if ($cartItems->isEmpty()) {
|
|
throw ValidationException::withMessages([
|
|
'cart_id' => 'The purchase cart does not contain items.',
|
|
]);
|
|
}
|
|
|
|
if ($purchase->items()->exists()) {
|
|
return;
|
|
}
|
|
|
|
$cartItems->load('variant.product');
|
|
$variants = $this->resolveTenantVariants($purchase->tenant, $cartItems);
|
|
$purchaseItemsPayload = $this->buildPurchaseItemsPayload($cartItems, $variants);
|
|
|
|
$purchase->items()->createMany($purchaseItemsPayload);
|
|
$this->completeCartConversion($cart, $cartItems, $variants);
|
|
});
|
|
}
|
|
|
|
/**
|
|
* @return Collection<int, ProductVariant>
|
|
*/
|
|
protected function resolveTenantVariants(Tenant $tenant, Collection $cartItems): Collection
|
|
{
|
|
$variantIds = $cartItems
|
|
->pluck('producto_variante_id')
|
|
->map(static fn (mixed $id): int => (int) $id)
|
|
->unique()
|
|
->values();
|
|
|
|
/** @var Collection<int, ProductVariant> $variants */
|
|
$variants = ProductVariant::query()
|
|
->with('product')
|
|
->whereIn('id', $variantIds)
|
|
->whereHas('product', fn ($query) => $query->where('tenant_codigo', $tenant->codigo))
|
|
->lockForUpdate()
|
|
->get()
|
|
->keyBy('id');
|
|
|
|
if ($variants->count() !== $variantIds->count()) {
|
|
throw ValidationException::withMessages([
|
|
'cart_id' => 'One or more product variants do not belong to the tenant.',
|
|
]);
|
|
}
|
|
|
|
return $variants;
|
|
}
|
|
|
|
/**
|
|
* @param Collection<int, CartItem> $cartItems
|
|
* @return \Illuminate\Support\Collection<int, ProductVariant>
|
|
*/
|
|
protected function resolveCheckoutCart(Tenant $tenant, int $userId, int $cartId): Cart
|
|
{
|
|
/** @var Cart|null $cart */
|
|
$cart = Cart::query()
|
|
->lockForUpdate()
|
|
->find($cartId);
|
|
|
|
if ($cart === null || $cart->tenant_codigo !== $tenant->codigo || $cart->user_id !== $userId) {
|
|
throw new NotFoundHttpException('Cart not found for tenant.');
|
|
}
|
|
|
|
if ($cart->status !== 'active') {
|
|
throw ValidationException::withMessages([
|
|
'cart_id' => 'The selected cart is no longer active.',
|
|
]);
|
|
}
|
|
|
|
return $cart;
|
|
}
|
|
|
|
/**
|
|
* @param Collection<int, CartItem> $cartItems
|
|
* @param Collection<int, ProductVariant> $variants
|
|
* @return array<int, array<string, mixed>>
|
|
*/
|
|
protected function buildPurchaseItemsPayload(Collection $cartItems, Collection $variants): array
|
|
{
|
|
return $cartItems
|
|
->map(function (CartItem $item) use ($variants): array {
|
|
/** @var ProductVariant $variant */
|
|
$variant = $variants->get((int) $item['producto_variante_id']);
|
|
$quantity = (int) $item['cantidad'];
|
|
$unitPrice = (float) ($variant->product?->precio ?? 0);
|
|
|
|
return [
|
|
'producto_variante_id' => $variant->getKey(),
|
|
'cantidad' => $quantity,
|
|
'precio_unitario' => $unitPrice,
|
|
'discount_total' => null,
|
|
'tax_total' => null,
|
|
'total' => $unitPrice * $quantity,
|
|
];
|
|
})
|
|
->all();
|
|
}
|
|
|
|
/**
|
|
* @param Collection<int, CartItem> $cartItems
|
|
* @param Collection<int, ProductVariant> $variants
|
|
*/
|
|
protected function completeCartConversion(Cart $cart, Collection $cartItems, Collection $variants): void
|
|
{
|
|
foreach ($cartItems as $item) {
|
|
/** @var ProductVariant $variant */
|
|
$variant = $variants->get((int) $item->producto_variante_id);
|
|
$quantity = (int) $item->cantidad;
|
|
|
|
try {
|
|
$variant->confirmReservedStock($quantity);
|
|
} catch (\InvalidArgumentException $exception) {
|
|
throw ValidationException::withMessages([
|
|
'cart_id' => 'The selected cart has inconsistent stock state.',
|
|
]);
|
|
}
|
|
}
|
|
|
|
$cart->status = 'converted';
|
|
$cart->user_id = null;
|
|
$cart->guest_token = null;
|
|
$cart->save();
|
|
$cart->delete();
|
|
}
|
|
}
|