refactor(checkout): materialize purchase items on confirmation

This commit is contained in:
2026-08-19 12:06:29 -03:00
parent e6c4b40a37
commit f1649e0e4b
14 changed files with 487 additions and 145 deletions

View File

@@ -2,9 +2,12 @@
namespace App\Domains\Purchase\Services\Checkout;
use App\Domains\Cart\Models\CartItem;
use App\Domains\Catalog\Services\CatalogInventoryService;
use App\Domains\Catalog\Services\StockReservationService;
use App\Domains\Purchase\Models\Purchase;
use App\Domains\Purchase\Models\PurchaseItem;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\DB;
use Illuminate\Validation\ValidationException;
@@ -12,8 +15,10 @@ class CompleteCheckoutService
{
public function __construct(
private readonly CatalogInventoryService $inventory,
private readonly StockReservationService $reservations,
private readonly CatalogSelectionResolver $selections,
private readonly SourceCartService $sourceCart,
private readonly PurchaseItemSnapshotFactory $snapshots,
) {}
public function complete(Purchase $purchase): Purchase
@@ -59,6 +64,7 @@ class CompleteCheckoutService
}
$purchase->update(['expires_at' => null]);
$this->reservations->syncPurchaseExpiration($purchase);
return $this->loadPurchase($purchase);
});
@@ -88,6 +94,51 @@ class CompleteCheckoutService
->lockForUpdate()
->get();
if ($items->isEmpty() && ! $purchase->items()->exists()) {
$cart = $purchase->cart()->lockForUpdate()->first();
if ($cart === null || $cart->status !== 'checkout') {
throw ValidationException::withMessages([
'items' => __('api.purchase.inconsistent_reservation'),
]);
}
$cartItems = $cart->items()->orderBy('id')->lockForUpdate()->get();
if ($cartItems->isEmpty()) {
throw ValidationException::withMessages([
'items' => __('api.purchase.inconsistent_reservation'),
]);
}
$this->loadCartItems($cartItems);
$items = $purchase->items()->createMany(
$this->snapshots->fromCartItems($cartItems),
);
foreach ($cartItems as $cartItem) {
$selection = $cartItem->selectedItem();
if ($selection === null) {
throw ValidationException::withMessages([
'items' => __('api.purchase.inconsistent_reservation'),
]);
}
try {
$this->reservations->commit($cartItem, $selection);
} catch (\InvalidArgumentException) {
throw ValidationException::withMessages([
'items' => __('api.purchase.inconsistent_reservation'),
]);
}
}
$purchase->items()->update([
'reservation_status' => PurchaseItem::RESERVATION_COMMITTED,
]);
$this->sourceCart->finalize($purchase);
return;
}
foreach ($items as $item) {
$selection = $this->selections->resolvePurchaseItem($purchase->tenant, $item);
@@ -126,6 +177,30 @@ class CompleteCheckoutService
private function loadPurchase(Purchase $purchase): Purchase
{
return $purchase->load(['items.imageAttachment']);
return $purchase->load([
'items.imageAttachment',
'cart.items.catalogItem.inventory',
'cart.items.catalogItem.attachments',
'cart.items.variant.inventory',
'cart.items.variant.attachments',
'cart.items.variant.definitions.itemAttribute.attribute',
'cart.items.variant.eventDates',
'cart.items.variant.eventDate',
]);
}
/** @param Collection<int, CartItem> $cartItems */
private function loadCartItems(Collection $cartItems): void
{
$cartItems->load([
'catalogItem.inventory',
'catalogItem.attachments',
'variant.inventory',
'variant.attachments',
'variant.catalogItem',
'variant.definitions.itemAttribute.attribute',
'variant.eventDates',
'variant.eventDate',
]);
}
}

View File

@@ -2,8 +2,10 @@
namespace App\Domains\Purchase\Services\Checkout;
use App\Domains\Cart\Models\CartItem;
use App\Domains\Catalog\Models\Variant;
use App\Domains\Catalog\Services\CatalogInventoryService;
use App\Domains\Catalog\Services\StockReservationService;
use App\Domains\Purchase\Models\Purchase;
use App\Domains\Purchase\Models\PurchaseItem;
use App\Domains\Purchase\Services\UserPurchaseLimitService;
@@ -15,6 +17,7 @@ class EditCheckoutService
{
public function __construct(
private readonly CatalogInventoryService $inventory,
private readonly StockReservationService $reservations,
private readonly UserPurchaseLimitService $purchaseLimits,
private readonly CatalogSelectionResolver $selections,
private readonly SourceCartService $sourceCart,
@@ -35,10 +38,10 @@ class EditCheckoutService
public function updateItemQuantity(
Purchase $purchase,
PurchaseItem $purchaseItem,
int $itemId,
int $quantity,
): Purchase {
return DB::transaction(function () use ($purchase, $purchaseItem, $quantity): Purchase {
return DB::transaction(function () use ($purchase, $itemId, $quantity): Purchase {
$purchase = $this->lockPurchase($purchase);
if ($purchase->status !== Purchase::STATUS_CREATED || $this->hasExpired($purchase)) {
@@ -47,7 +50,11 @@ class EditCheckoutService
]);
}
$purchaseItem = $this->lockPurchaseItem($purchase, $purchaseItem);
if (! $purchase->items()->exists()) {
return $this->updateCartItemQuantity($purchase, $itemId, $quantity);
}
$purchaseItem = $this->lockPurchaseItem($purchase, $itemId);
$difference = $quantity - (int) $purchaseItem->cantidad;
if ($difference !== 0) {
@@ -84,10 +91,66 @@ class EditCheckoutService
),
]);
if (! $purchase->items()->exists()) {
$this->attachCartReservations($purchase);
}
return $this->loadPurchase($purchase);
});
}
private function updateCartItemQuantity(Purchase $purchase, int $itemId, int $quantity): Purchase
{
$cart = $purchase->cart()->lockForUpdate()->first();
if ($cart === null || $cart->status !== 'checkout') {
throw new NotFoundHttpException('Checkout cart not found.');
}
/** @var CartItem|null $cartItem */
$cartItem = $cart->items()->whereKey($itemId)->lockForUpdate()->first();
if ($cartItem === null) {
throw new NotFoundHttpException('Checkout item not found.');
}
$selection = $this->selections->resolve(
$purchase->tenant,
(int) $cartItem->catalog_item_id,
$cartItem->variant_id === null ? null : (int) $cartItem->variant_id,
'item',
);
$difference = $quantity - (int) $cartItem->cantidad;
try {
if ($difference > 0) {
$otherItemQuantity = (int) $cart->items()
->where('catalog_item_id', $cartItem->catalog_item_id)
->whereKeyNot($cartItem->getKey())
->sum('cantidad');
$catalogItem = $selection instanceof Variant ? $selection->catalogItem : $selection;
$this->purchaseLimits->assertCanPurchase(
$catalogItem,
(int) $purchase->user_id,
$otherItemQuantity + $quantity,
$purchase->getKey(),
);
$this->reservations->reserve($cartItem, $selection, $difference);
} elseif ($difference < 0) {
$this->reservations->release($cartItem, $selection, abs($difference));
}
} catch (\InvalidArgumentException) {
throw ValidationException::withMessages([
'quantity' => __('api.purchase.insufficient_stock'),
]);
}
$cartItem->update(['cantidad' => $quantity]);
$cart->unsetRelation('items');
$purchase->setRelation('cart', $cart);
$purchase->update(['total' => $cart->getTotalAmount()]);
return $this->loadPurchase($purchase);
}
private function adjustReservation(
Purchase $purchase,
PurchaseItem $purchaseItem,
@@ -121,11 +184,11 @@ class EditCheckoutService
}
}
private function lockPurchaseItem(Purchase $purchase, PurchaseItem $item): PurchaseItem
private function lockPurchaseItem(Purchase $purchase, int $itemId): PurchaseItem
{
/** @var PurchaseItem|null $lockedItem */
$lockedItem = $purchase->items()
->whereKey($item->getKey())
->whereKey($itemId)
->lockForUpdate()
->first();
@@ -142,6 +205,20 @@ class EditCheckoutService
return $lockedItem;
}
private function attachCartReservations(Purchase $purchase): void
{
$cartItems = $purchase->cart?->items()->lockForUpdate()->get() ?? collect();
foreach ($cartItems as $cartItem) {
$selection = $this->selections->resolve(
$purchase->tenant,
(int) $cartItem->catalog_item_id,
$cartItem->variant_id === null ? null : (int) $cartItem->variant_id,
'item',
);
$this->reservations->attachToPurchase($cartItem, $selection, $purchase);
}
}
private function assertEditable(Purchase $purchase): void
{
if (
@@ -170,6 +247,15 @@ class EditCheckoutService
private function loadPurchase(Purchase $purchase): Purchase
{
return $purchase->load(['items.imageAttachment']);
return $purchase->load([
'items.imageAttachment',
'cart.items.catalogItem.inventory',
'cart.items.catalogItem.attachments',
'cart.items.variant.inventory',
'cart.items.variant.attachments',
'cart.items.variant.definitions.itemAttribute.attribute',
'cart.items.variant.eventDates',
'cart.items.variant.eventDate',
]);
}
}

View File

@@ -2,7 +2,9 @@
namespace App\Domains\Purchase\Services\Checkout;
use App\Domains\Catalog\Models\StockReservation;
use App\Domains\Catalog\Services\CatalogInventoryService;
use App\Domains\Catalog\Services\StockReservationService;
use App\Domains\Purchase\Models\Purchase;
use App\Domains\Purchase\Models\PurchaseItem;
use Illuminate\Support\Facades\DB;
@@ -12,6 +14,7 @@ class ReleaseCheckoutService
{
public function __construct(
private readonly CatalogInventoryService $inventory,
private readonly StockReservationService $reservations,
private readonly CatalogSelectionResolver $selections,
private readonly SourceCartService $sourceCart,
) {}
@@ -83,6 +86,13 @@ class ReleaseCheckoutService
->get();
$reservationReturnedToCart = $restoreCart && $this->sourceCart->restore($purchase);
if ($items->isEmpty() && ! $purchase->items()->exists()) {
$this->releaseCartReservations($purchase, $reservationReturnedToCart, $targetStatus);
$purchase->update(['status' => $targetStatus]);
return $this->loadPurchase($purchase);
}
foreach ($items as $item) {
if (! $reservationReturnedToCart) {
$this->releaseInventory($purchase, $item);
@@ -99,6 +109,59 @@ class ReleaseCheckoutService
});
}
private function releaseCartReservations(
Purchase $purchase,
bool $reservationReturnedToCart,
string $targetStatus,
): void {
if ($reservationReturnedToCart) {
$this->reservations->detachFromPurchase($purchase);
return;
}
$cart = $purchase->cart()->withTrashed()->lockForUpdate()->first();
if ($cart === null) {
return;
}
$cartItems = $cart->items()->orderBy('id')->lockForUpdate()->get();
$cartItems->load([
'catalogItem.inventory',
'catalogItem.bundleComponents.catalogItem.inventory',
'catalogItem.bundleComponents.variant.inventory',
'variant.inventory',
'variant.catalogItem',
]);
foreach ($cartItems as $cartItem) {
$selection = $cartItem->selectedItem();
if ($selection === null) {
continue;
}
try {
$this->reservations->release(
$cartItem,
$selection,
(int) $cartItem->cantidad,
$targetStatus === Purchase::STATUS_EXPIRED
? StockReservation::STATUS_EXPIRED
: StockReservation::STATUS_RELEASED,
);
} catch (\InvalidArgumentException) {
throw ValidationException::withMessages([
'items' => __('api.purchase.inconsistent_reservation'),
]);
}
}
if (! $cart->trashed()) {
$cart->update(['status' => 'converted']);
$cart->delete();
}
}
private function releaseInventory(Purchase $purchase, PurchaseItem $item): void
{
$selection = $this->selections->resolvePurchaseItem($purchase->tenant, $item);
@@ -129,6 +192,15 @@ class ReleaseCheckoutService
private function loadPurchase(Purchase $purchase): Purchase
{
return $purchase->load(['items.imageAttachment']);
return $purchase->load([
'items.imageAttachment',
'cart.items.catalogItem.inventory',
'cart.items.catalogItem.attachments',
'cart.items.variant.inventory',
'cart.items.variant.attachments',
'cart.items.variant.definitions.itemAttribute.attribute',
'cart.items.variant.eventDates',
'cart.items.variant.eventDate',
]);
}
}

View File

@@ -4,11 +4,16 @@ namespace App\Domains\Purchase\Services\Checkout;
use App\Domains\Cart\Models\Cart;
use App\Domains\Cart\Models\CartItem;
use App\Domains\Catalog\Services\StockReservationService;
use App\Domains\Purchase\Models\Purchase;
use App\Domains\Purchase\Models\PurchaseItem;
class SourceCartService
{
public function __construct(
private readonly StockReservationService $reservations,
) {}
public function restore(Purchase $purchase): bool
{
$sourceCart = $this->findSourceCart($purchase);
@@ -17,6 +22,10 @@ class SourceCartService
return false;
}
if ($sourceCart->origin === Cart::ORIGIN_DIRECT_CHECKOUT) {
return false;
}
/** @var Cart|null $activeCart */
$activeCart = Cart::query()
->where('tenant_codigo', $purchase->tenant_codigo)
@@ -112,7 +121,7 @@ class SourceCartService
->first();
if ($activeItem === null) {
$activeCart->items()->create([
$activeItem = $activeCart->items()->create([
'catalog_item_id' => $sourceItem->catalog_item_id,
'variant_id' => $sourceItem->variant_id,
'cantidad' => $sourceItem->cantidad,
@@ -120,6 +129,8 @@ class SourceCartService
} else {
$activeItem->increment('cantidad', (int) $sourceItem->cantidad);
}
$this->reservations->transfer($sourceItem, $activeItem);
}
}
}

View File

@@ -7,6 +7,7 @@ use App\Domains\Cart\Models\CartItem;
use App\Domains\Catalog\Models\CatalogItem;
use App\Domains\Catalog\Models\Variant;
use App\Domains\Catalog\Services\CatalogInventoryService;
use App\Domains\Catalog\Services\StockReservationService;
use App\Domains\Purchase\Exceptions\InsufficientStockException;
use App\Domains\Purchase\Models\Purchase;
use App\Domains\Purchase\Services\UserPurchaseLimitService;
@@ -20,9 +21,9 @@ class StartCheckoutService
{
public function __construct(
private readonly CatalogInventoryService $inventory,
private readonly StockReservationService $reservations,
private readonly UserPurchaseLimitService $purchaseLimits,
private readonly CatalogSelectionResolver $selections,
private readonly PurchaseItemSnapshotFactory $snapshots,
private readonly InsufficientStockMessageBuilder $stockMessages,
) {}
@@ -144,9 +145,24 @@ class StartCheckoutService
throw new InsufficientStockException($unavailableItems);
}
$cart = Cart::query()->create([
'tenant_codigo' => $tenant->codigo,
'user_id' => $userId,
'guest_token' => null,
'status' => 'checkout',
'origin' => Cart::ORIGIN_DIRECT_CHECKOUT,
]);
$cartItems = collect();
foreach ($resolvedLines as $line) {
$cartItem = $cart->items()->create([
'catalog_item_id' => $line['catalog_item_id'],
'variant_id' => $line['variant_id'],
'cantidad' => $line['quantity'],
]);
try {
$this->inventory->reserve($line['selection'], $line['quantity']);
$this->reservations->reserve($cartItem, $line['selection'], $line['quantity']);
} catch (\InvalidArgumentException) {
$availableQuantity = $this->inventory->availableQuantity($line['selection']) ?? 0;
@@ -154,6 +170,10 @@ class StartCheckoutService
$this->unavailableItem($line, $availableQuantity),
]);
}
$cartItem->setRelation('catalogItem', $line['catalog_item']);
$cartItem->setRelation('variant', $line['selection'] instanceof Variant ? $line['selection'] : null);
$cartItems->push($cartItem);
}
$purchase = $this->createPurchase(
@@ -163,19 +183,16 @@ class StartCheckoutService
(float) $resolvedLines->sum(
fn (array $line): float => $line['selection']->getPrice() * $line['quantity'],
),
null,
$cart->getKey(),
);
$directCartItems = $resolvedLines->map(fn (array $line): CartItem => $this->makeDirectCartItem(
$line['selection'],
$line['catalog_item_id'],
$line['variant_id'],
$line['quantity'],
));
$purchase->items()->createMany(
$this->snapshots->fromCartItems($directCartItems),
);
foreach ($cartItems as $index => $cartItem) {
$this->reservations->attachToPurchase(
$cartItem,
$resolvedLines->get($index)['selection'],
$purchase,
);
}
return $this->loadPurchase($purchase);
}
@@ -235,7 +252,13 @@ class StartCheckoutService
$cart->getTotalAmount(),
$cart->getKey(),
);
$purchase->items()->createMany($this->snapshots->fromCartItems($cartItems));
foreach ($cartItems as $cartItem) {
$this->reservations->attachToPurchase(
$cartItem,
$cartItem->selectedItem(),
$purchase,
);
}
// The purchase owns the reservation until checkout finishes. The cart is
// retained so it can be restored if the purchase is cancelled or expires.
@@ -336,35 +359,6 @@ class StartCheckoutService
]);
}
private function makeDirectCartItem(
CatalogItem|Variant $selection,
int $catalogItemId,
?int $variantId,
int $quantity,
): CartItem {
$catalogItem = $selection instanceof Variant ? $selection->catalogItem : $selection;
$catalogItem->loadMissing(['inventory', 'attachments']);
if ($selection instanceof Variant) {
$selection->loadMissing([
'inventory',
'attachments',
'catalogItem',
'definitions.itemAttribute.attribute',
]);
}
$item = new CartItem([
'catalog_item_id' => $catalogItemId,
'variant_id' => $variantId,
'cantidad' => $quantity,
]);
$item->setRelation('catalogItem', $catalogItem);
$item->setRelation('variant', $selection instanceof Variant ? $selection : null);
return $item;
}
/** @param Collection<int, CartItem> $cartItems */
private function loadCartItems(Collection $cartItems): void
{
@@ -382,6 +376,15 @@ class StartCheckoutService
private function loadPurchase(Purchase $purchase): Purchase
{
return $purchase->load(['items.imageAttachment']);
return $purchase->load([
'items.imageAttachment',
'cart.items.catalogItem.inventory',
'cart.items.catalogItem.attachments',
'cart.items.variant.inventory',
'cart.items.variant.attachments',
'cart.items.variant.definitions.itemAttribute.attribute',
'cart.items.variant.eventDates',
'cart.items.variant.eventDate',
]);
}
}

View File

@@ -2,8 +2,8 @@
namespace App\Domains\Purchase\Services;
use App\Domains\Catalog\Services\StockReservationService;
use App\Domains\Purchase\Models\Purchase;
use App\Domains\Purchase\Models\PurchaseItem;
use App\Domains\Purchase\Services\Checkout\CompleteCheckoutService;
use App\Domains\Purchase\Services\Checkout\EditCheckoutService;
use App\Domains\Purchase\Services\Checkout\ReleaseCheckoutService;
@@ -23,6 +23,7 @@ class CheckoutService
private readonly EditCheckoutService $editor,
private readonly CompleteCheckoutService $completer,
private readonly ReleaseCheckoutService $releaser,
private readonly StockReservationService $reservations,
) {}
/** @param array<string, mixed> $purchaseData */
@@ -49,10 +50,10 @@ class CheckoutService
public function updateItemQuantity(
Purchase $purchase,
PurchaseItem $purchaseItem,
int $itemId,
int $quantity,
): Purchase {
return $this->editor->updateItemQuantity($purchase, $purchaseItem, $quantity);
return $this->editor->updateItemQuantity($purchase, $itemId, $quantity);
}
public function prepareItemEditing(Purchase $purchase): Purchase
@@ -94,4 +95,9 @@ class CheckoutService
{
return $this->releaser->expireOverdue();
}
public function syncReservationExpiration(Purchase $purchase): void
{
$this->reservations->syncPurchaseExpiration($purchase);
}
}

View File

@@ -2,6 +2,7 @@
namespace App\Domains\Purchase\Services;
use App\Domains\Cart\Models\CartItem;
use App\Domains\Catalog\Models\CatalogItem;
use App\Domains\Purchase\Models\Purchase;
use App\Domains\Purchase\Models\PurchaseItem;
@@ -52,7 +53,24 @@ class UserPurchaseLimitService
})
->sum('cantidad');
if ($purchasedQuantity + $requestedQuantity > $limit) {
$checkoutQuantity = (int) CartItem::query()
->where('catalog_item_id', $catalogItem->getKey())
->whereHas('cart.purchases', function ($query) use ($userId, $excludedPurchaseId): void {
$query
->where('user_id', $userId)
->whereIn('status', [
Purchase::STATUS_CREATED,
Purchase::STATUS_PENDING_PAYMENT,
])
->whereDoesntHave('items')
->when(
$excludedPurchaseId !== null,
fn ($query) => $query->whereKeyNot($excludedPurchaseId),
);
})
->sum('cantidad');
if ($purchasedQuantity + $checkoutQuantity + $requestedQuantity > $limit) {
throw ValidationException::withMessages([
$field => __('api.purchase_limit.exceeded', ['max' => $limit]),
]);