refactor(stock): make reservation expiration authoritative

This commit is contained in:
2026-08-25 15:28:17 -03:00
parent 6db99e775a
commit 7a85e1731d
16 changed files with 304 additions and 207 deletions

View File

@@ -158,9 +158,12 @@ class StockReservationService
});
}
public function attachToPurchase(Cart $cart, Purchase $purchase): StockReservation
{
return DB::transaction(function () use ($cart, $purchase): StockReservation {
public function attachToPurchase(
Cart $cart,
Purchase $purchase,
Carbon $expiresAt,
): StockReservation {
return DB::transaction(function () use ($cart, $purchase, $expiresAt): StockReservation {
/** @var Cart $lockedCart */
$lockedCart = Cart::query()->lockForUpdate()->findOrFail($cart->getKey());
/** @var Purchase $lockedPurchase */
@@ -185,7 +188,7 @@ class StockReservationService
}
$lockedPurchase->update(['stock_reservation_id' => $reservation->getKey()]);
$reservation->update(['expires_at' => $lockedPurchase->expires_at]);
$reservation->update(['expires_at' => $expiresAt]);
$purchase->stock_reservation_id = $reservation->getKey();
$cart->current_stock_reservation_id = $reservation->getKey();
@@ -299,16 +302,25 @@ class StockReservationService
});
}
public function syncPurchaseExpiration(Purchase $purchase): void
public function refreshForPurchase(Purchase $purchase, ?Carbon $expiresAt): void
{
if ($purchase->stock_reservation_id === null) {
return;
}
DB::transaction(function () use ($purchase, $expiresAt): void {
/** @var Purchase $purchase */
$purchase = Purchase::query()->lockForUpdate()->findOrFail($purchase->getKey());
if ($purchase->stock_reservation_id === null) {
throw new \InvalidArgumentException('La compra no tiene una reserva de stock.');
}
StockReservation::query()
->whereKey($purchase->stock_reservation_id)
->where('status', StockReservation::STATUS_ACTIVE)
->update(['expires_at' => $purchase->expires_at]);
/** @var StockReservation $reservation */
$reservation = StockReservation::query()
->lockForUpdate()
->findOrFail($purchase->stock_reservation_id);
if ($reservation->status !== StockReservation::STATUS_ACTIVE) {
throw new \InvalidArgumentException('La reserva de stock no está activa.');
}
$reservation->update(['expires_at' => $expiresAt]);
});
}
/**