Compare commits

..

7 Commits

55 changed files with 1025 additions and 1319 deletions

View File

@@ -5,7 +5,6 @@ namespace App\Domains\Cart\Models;
use App\Domains\Auth\Models\User; use App\Domains\Auth\Models\User;
use App\Domains\Catalog\Models\CatalogItem; use App\Domains\Catalog\Models\CatalogItem;
use App\Domains\Catalog\Models\Inventory; use App\Domains\Catalog\Models\Inventory;
use App\Domains\Catalog\Models\StockReservation;
use App\Domains\Catalog\Models\Variant; use App\Domains\Catalog\Models\Variant;
use App\Domains\Catalog\Services\CatalogInventoryService; use App\Domains\Catalog\Services\CatalogInventoryService;
use App\Domains\Catalog\Services\StockReservationService; use App\Domains\Catalog\Services\StockReservationService;
@@ -29,7 +28,6 @@ use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
'status', 'status',
'origin', 'origin',
'current_purchase_id', 'current_purchase_id',
'current_stock_reservation_id',
])] ])]
class Cart extends Model class Cart extends Model
{ {
@@ -47,7 +45,6 @@ class Cart extends Model
return [ return [
'user_id' => 'integer', 'user_id' => 'integer',
'current_purchase_id' => 'integer', 'current_purchase_id' => 'integer',
'current_stock_reservation_id' => 'integer',
]; ];
} }
@@ -87,15 +84,6 @@ class Cart extends Model
return $this->belongsTo(Purchase::class, 'current_purchase_id'); return $this->belongsTo(Purchase::class, 'current_purchase_id');
} }
/** @return BelongsTo<StockReservation, $this> */
public function currentStockReservation(): BelongsTo
{
return $this->belongsTo(
StockReservation::class,
'current_stock_reservation_id',
);
}
public function getTotalAmount(): float public function getTotalAmount(): float
{ {
$items = $this->relationLoaded('items') $items = $this->relationLoaded('items')
@@ -152,11 +140,12 @@ class Cart extends Model
'cantidad' => $quantity, 'cantidad' => $quantity,
]); ]);
} else { } else {
app(StockReservationService::class)->ensure($item, $selectedItem);
$item->cantidad += $quantity; $item->cantidad += $quantity;
$item->save(); $item->save();
} }
app(StockReservationService::class)->syncCart($this); app(StockReservationService::class)->reserve($item, $selectedItem, $quantity);
return $item->fresh(); return $item->fresh();
}); });
@@ -216,6 +205,7 @@ class Cart extends Model
$nextAvailableQuantity, $nextAvailableQuantity,
); );
app(StockReservationService::class)->release($item, $currentSelection, $item->cantidad);
$availableQuantity = $inventoryService->availableQuantity($nextSelection); $availableQuantity = $inventoryService->availableQuantity($nextSelection);
if ($availableQuantity !== null && $availableQuantity < $quantity) { if ($availableQuantity !== null && $availableQuantity < $quantity) {
@@ -232,10 +222,11 @@ class Cart extends Model
->first(); ->first();
if ($targetItem !== null) { if ($targetItem !== null) {
app(StockReservationService::class)->ensure($targetItem, $nextSelection);
$targetItem->cantidad += $quantity; $targetItem->cantidad += $quantity;
$targetItem->save(); $targetItem->save();
app(StockReservationService::class)->reserve($targetItem, $nextSelection, $quantity);
$item->delete(); $item->delete();
app(StockReservationService::class)->syncCart($this);
return $targetItem->fresh(); return $targetItem->fresh();
} }
@@ -243,7 +234,7 @@ class Cart extends Model
$item->variant_id = $variantId; $item->variant_id = $variantId;
$item->cantidad = $quantity; $item->cantidad = $quantity;
$item->save(); $item->save();
app(StockReservationService::class)->syncCart($this); app(StockReservationService::class)->reserve($item, $nextSelection, $quantity);
return $item->fresh(); return $item->fresh();
} }
@@ -272,9 +263,16 @@ class Cart extends Model
]); ]);
} }
if ($delta > 0) {
app(StockReservationService::class)->reserve($item, $currentSelection, $delta);
}
if ($delta < 0) {
app(StockReservationService::class)->release($item, $currentSelection, abs($delta));
}
$item->cantidad = $quantity; $item->cantidad = $quantity;
$item->save(); $item->save();
app(StockReservationService::class)->syncCart($this);
return $item->fresh(); return $item->fresh();
}); });
@@ -291,8 +289,17 @@ class Cart extends Model
->lockForUpdate() ->lockForUpdate()
->firstOrFail(); ->firstOrFail();
$selectedItem = $this->resolveScopedItem(
$item->catalog_item_id,
$item->variant_id,
true,
);
app(StockReservationService::class)->release(
$item,
$selectedItem,
$item->cantidad,
);
$item->delete(); $item->delete();
app(StockReservationService::class)->syncCart($this);
}); });
} }
@@ -340,10 +347,7 @@ class Cart extends Model
]); ]);
} }
app(StockReservationService::class)->releaseForPurchase( app(StockReservationService::class)->detachFromPurchase($currentPurchase);
$currentPurchase,
reason: StockReservationService::REASON_PURCHASE_SUPERSEDED,
);
self::query() self::query()
->whereKey($cart->getKey()) ->whereKey($cart->getKey())
->where('current_purchase_id', $currentPurchase->getKey()) ->where('current_purchase_id', $currentPurchase->getKey())

View File

@@ -3,11 +3,13 @@
namespace App\Domains\Cart\Models; namespace App\Domains\Cart\Models;
use App\Domains\Catalog\Models\CatalogItem; use App\Domains\Catalog\Models\CatalogItem;
use App\Domains\Catalog\Models\StockReservation;
use App\Domains\Catalog\Models\Variant; use App\Domains\Catalog\Models\Variant;
use Illuminate\Database\Eloquent\Attributes\Fillable; use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo; use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
#[Fillable([ #[Fillable([
'cart_id', 'cart_id',
@@ -55,4 +57,10 @@ class CartItem extends Model
{ {
return $this->variant ?? $this->catalogItem; return $this->variant ?? $this->catalogItem;
} }
/** @return HasMany<StockReservation, $this> */
public function stockReservations(): HasMany
{
return $this->hasMany(StockReservation::class);
}
} }

View File

@@ -3,82 +3,119 @@
namespace App\Domains\Cart\Services; namespace App\Domains\Cart\Services;
use App\Domains\Cart\Models\Cart; use App\Domains\Cart\Models\Cart;
use App\Domains\Cart\Models\CartItem;
use App\Domains\Catalog\Models\Inventory;
use App\Domains\Catalog\Models\StockReservation; use App\Domains\Catalog\Models\StockReservation;
use App\Domains\Catalog\Services\StockReservationService;
use App\Domains\Purchase\Models\Purchase;
use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\DB;
class ExpireCartReservationsService class ExpireCartReservationsService
{ {
public function __construct(
private readonly StockReservationService $reservations,
) {}
public function expireOverdue(): int public function expireOverdue(): int
{ {
$expired = 0; $expiredItems = 0;
$lastReservationId = 0; $lastCartItemId = 0;
do { do {
$reservationIds = StockReservation::query() $cartItemIds = StockReservation::query()
->where('status', StockReservation::STATUS_ACTIVE) ->where('status', StockReservation::STATUS_ACTIVE)
->whereNull('purchase_id')
->whereNotNull('cart_item_id')
->whereNotNull('expires_at') ->whereNotNull('expires_at')
->where('expires_at', '<=', now()) ->where('expires_at', '<=', now())
->where('id', '>', $lastReservationId) ->where('cart_item_id', '>', $lastCartItemId)
->whereHas('currentCart', fn ($query) => $query->where('status', 'active')) ->whereHas('cartItem.cart', fn ($query) => $query->where('status', 'active'))
->whereDoesntHave('purchase', fn ($query) => $query->whereIn('status', [ ->select('cart_item_id')
Purchase::STATUS_CREATED, ->distinct()
Purchase::STATUS_PENDING_PAYMENT, ->orderBy('cart_item_id')
Purchase::STATUS_IN_REVIEW,
]))
->orderBy('id')
->limit(500) ->limit(500)
->pluck('id'); ->pluck('cart_item_id');
foreach ($reservationIds as $reservationId) { foreach ($cartItemIds as $cartItemId) {
$lastReservationId = (int) $reservationId; $lastCartItemId = (int) $cartItemId;
if ($this->expireReservation($lastReservationId)) { if ($this->expireCartItem($lastCartItemId)) {
$expired++; $expiredItems++;
} }
} }
} while ($reservationIds->count() === 500); } while ($cartItemIds->count() === 500);
return $expired; return $expiredItems;
} }
private function expireReservation(int $reservationId): bool private function expireCartItem(int $cartItemId): bool
{ {
$cartId = Cart::query() /** @var CartItem|null $candidate */
->where('current_stock_reservation_id', $reservationId) $candidate = CartItem::query()->select(['id', 'cart_id'])->find($cartItemId);
->where('status', 'active') if ($candidate === null) {
->value('id');
if ($cartId === null) {
return false; return false;
} }
return DB::transaction(function () use ($cartId, $reservationId): bool { return DB::transaction(function () use ($candidate, $cartItemId): bool {
/** @var Cart|null $cart */ /** @var Cart|null $cart */
$cart = Cart::query() $cart = Cart::query()
->whereKey($cartId) ->whereKey($candidate->cart_id)
->where('current_stock_reservation_id', $reservationId)
->where('status', 'active') ->where('status', 'active')
->lockForUpdate() ->lockForUpdate()
->first(); ->first();
if ($cart === null) { if ($cart === null) {
return false; return false;
} }
/** @var StockReservation|null $reservation */ /** @var CartItem|null $cartItem */
$reservation = StockReservation::query()->lockForUpdate()->find($reservationId); $cartItem = $cart->items()
if ($reservation === null ->whereKey($cartItemId)
|| $reservation->status !== StockReservation::STATUS_ACTIVE ->lockForUpdate()
|| $reservation->expires_at === null ->first();
|| $reservation->expires_at->isFuture()) {
if ($cartItem === null) {
return false; return false;
} }
$this->reservations->expire($reservation); $reservations = StockReservation::query()
->where('cart_item_id', $cartItem->getKey())
->where('status', StockReservation::STATUS_ACTIVE)
->orderBy('inventory_id')
->lockForUpdate()
->get();
if (
$reservations->isEmpty()
|| $reservations->contains(
fn (StockReservation $reservation): bool => $reservation->purchase_id !== null
|| $reservation->expires_at === null
|| $reservation->expires_at->isFuture(),
)
) {
return false;
}
$inventories = Inventory::query()
->whereKey($reservations->pluck('inventory_id'))
->orderBy('id')
->lockForUpdate()
->get()
->keyBy('id');
foreach ($reservations as $reservation) {
$inventory = $inventories->get($reservation->inventory_id)
?? throw new \InvalidArgumentException('No se encontro el inventario reservado.');
$inventory->release((int) $reservation->quantity);
$reservation->update([
'quantity' => 0,
'status' => StockReservation::STATUS_EXPIRED,
'expires_at' => null,
'released_at' => now(),
]);
}
$cartItem->delete();
if (! $cart->items()->exists()) {
$cart->update(['status' => 'expired']);
$cart->delete();
}
return true; return true;
}); });

View File

@@ -6,13 +6,13 @@ Gestiona el carrito activo de un tenant tanto para visitantes como para usuarios
## Modelo ## Modelo
- `Cart`: pertenece a un tenant y opcionalmente a un usuario; calcula el total, permite agregar, actualizar o quitar ítems y apunta a su reserva de stock vigente mediante `current_stock_reservation_id`. - `Cart`: pertenece a un tenant y opcionalmente a un usuario; calcula el total y permite agregar, actualizar o quitar ítems.
- `CartItem`: referencia un `CatalogItem` y, opcionalmente, una `Variant`; sólo persiste la selección y cantidad, y expone siempre los datos vigentes del catálogo. - `CartItem`: referencia un `CatalogItem` y, opcionalmente, una `Variant`; sólo persiste la selección y cantidad, y expone siempre los datos vigentes del catálogo.
## Servicios ## Servicios
- `CartService`: obtiene el carrito, modifica ítems y administra la cookie del token invitado. - `CartService`: obtiene el carrito, modifica ítems y administra la cookie del token invitado.
- `ExpireCartReservationsService`: libera como conjunto las reservas vencidas de carritos activos sin eliminar el contenido del carrito. - `ExpireCartReservationsService`: libera las reservas vencidas de carritos activos y elimina los carritos que quedan vacíos.
- `GuestCartMergeService`: incorpora el carrito invitado al usuario cuando este se autentica. - `GuestCartMergeService`: incorpora el carrito invitado al usuario cuando este se autentica.
## Endpoints ## Endpoints
@@ -34,6 +34,4 @@ Depende de `Catalog` para productos y variantes, de `Tenant` para aislar datos y
Un carrito puede pasar a `checkout`. Las compras directas usan un carrito técnico con `origin=direct_checkout`; los carritos normales conservan `origin=user` y pueden restaurarse al cancelar o vencer la compra. Un carrito puede pasar a `checkout`. Las compras directas usan un carrito técnico con `origin=direct_checkout`; los carritos normales conservan `origin=user` y pueden restaurarse al cancelar o vencer la compra.
Cada edición sincroniza una única reserva para el carrito completo. Si varios ítems o bundles consumen el mismo inventario, se persiste una sola línea con la cantidad agregada. Al editar durante checkout, la compra anterior queda `superseded`, su reserva se libera con el motivo correspondiente y se crea otra para el carrito actualizado. El comando unificado `php artisan reservations:expire` procesa primero las compras vencidas y luego las reservas activas sin compra cuyo `expires_at` haya vencido. Se ejecuta cada minuto mediante el scheduler, conserva la fila de reserva con estado `expired`, elimina el ítem abandonado y elimina lógicamente el carrito cuando queda vacío. Cada intento registra sus resultados o su error en el log diario `storage/logs/commands/commands-AAAA-MM-DD.log`.
El comando unificado `php artisan reservations:expire` procesa primero las compras vencidas y luego las reservas activas de carrito cuyo `expires_at` haya vencido. Se ejecuta cada minuto mediante el scheduler, conserva la reserva y sus líneas como historial, libera el stock como conjunto y deja intactos el carrito y sus ítems.

View File

@@ -123,6 +123,10 @@ class CatalogController extends Controller
$variantId === null ? null : (int) $variantId, $variantId === null ? null : (int) $variantId,
); );
$allowances->attach(collect([$item]), $this->userId($request)); $allowances->attach(collect([$item]), $this->userId($request));
abort_unless($allowances->availability(
$item->availableStock(),
$item->getAttribute('remaining_user_quota'),
)->isVisible(), 404);
return CatalogItemDetailResource::make($item); return CatalogItemDetailResource::make($item);
} }

View File

@@ -0,0 +1,10 @@
<?php
namespace App\Domains\Catalog\Enums;
enum AvailabilityEffect: string
{
case Hide = 'hide';
case Restrict = 'restrict';
case Notice = 'notice';
}

View File

@@ -0,0 +1,11 @@
<?php
namespace App\Domains\Catalog\Enums;
enum CatalogAction: string
{
case SelectVariant = 'select_variant';
case ChangeQuantity = 'change_quantity';
case AddToCart = 'add_to_cart';
case BuyNow = 'buy_now';
}

View File

@@ -27,7 +27,6 @@ use Illuminate\Support\Collection;
'type', 'type',
'slug', 'slug',
'nombre', 'nombre',
'group_order',
'descripcion', 'descripcion',
'precio', 'precio',
'inventory_policy', 'inventory_policy',
@@ -48,7 +47,6 @@ class CatalogItem extends Model
'inventory_policy' => InventoryPolicy::Tracked->value, 'inventory_policy' => InventoryPolicy::Tracked->value,
'inventory_subject' => InventorySubject::Product->value, 'inventory_subject' => InventorySubject::Product->value,
'has_tickets' => false, 'has_tickets' => false,
'group_order' => 0,
]; ];
protected function casts(): array protected function casts(): array
@@ -58,7 +56,6 @@ class CatalogItem extends Model
'brand_id' => 'integer', 'brand_id' => 'integer',
'inventory_id' => 'integer', 'inventory_id' => 'integer',
'type' => CatalogItemType::class, 'type' => CatalogItemType::class,
'group_order' => 'integer',
'precio' => 'decimal:2', 'precio' => 'decimal:2',
'inventory_policy' => InventoryPolicy::class, 'inventory_policy' => InventoryPolicy::class,
'inventory_subject' => InventorySubject::class, 'inventory_subject' => InventorySubject::class,
@@ -175,30 +172,18 @@ class CatalogItem extends Model
} }
/** @param Builder<CatalogItem> $query */ /** @param Builder<CatalogItem> $query */
public function scopeWhereAvailable(Builder $query): Builder public function scopeWhereVariantsAvailable(Builder $query): Builder
{ {
return $query->where(function (Builder $query): void { return $query->where(function (Builder $query): void {
$query $query
->where('catalog_items.inventory_policy', InventoryPolicy::Unlimited->value) ->whereDoesntHave('variants')
->orWhere('catalog_items.inventory_policy', InventoryPolicy::Unlimited->value)
->orWhereHas( ->orWhereHas(
'variants.inventory', 'variants.inventory',
fn (Builder $inventoryQuery): Builder => $inventoryQuery fn (Builder $inventoryQuery): Builder => $inventoryQuery
->whereColumn('inventories.real_stock', '>', 'inventories.reserved_stock') ->whereColumn('inventories.real_stock', '>', 'inventories.reserved_stock')
)
->orWhere(function (Builder $directItemQuery): void {
$directItemQuery
->whereDoesntHave('variants')
->where(function (Builder $inventoryQuery): void {
$inventoryQuery
->whereNull('catalog_items.inventory_id')
->orWhereHas(
'inventory',
fn (Builder $availableInventoryQuery): Builder => $availableInventoryQuery
->whereColumn('inventories.real_stock', '>', 'inventories.reserved_stock')
); );
}); });
});
});
} }
/** @return Collection<int, Variant> */ /** @return Collection<int, Variant> */

View File

@@ -48,10 +48,10 @@ class Inventory extends Model
return $this->hasOne(Variant::class); return $this->hasOne(Variant::class);
} }
/** @return HasMany<StockReservationLine, $this> */ /** @return HasMany<StockReservation, $this> */
public function stockReservationLines(): HasMany public function stockReservations(): HasMany
{ {
return $this->hasMany(StockReservationLine::class); return $this->hasMany(StockReservation::class);
} }
public function availableStock(): int public function availableStock(): int

View File

@@ -2,20 +2,21 @@
namespace App\Domains\Catalog\Models; namespace App\Domains\Catalog\Models;
use App\Domains\Cart\Models\Cart; use App\Domains\Cart\Models\CartItem;
use App\Domains\Purchase\Models\Purchase; use App\Domains\Purchase\Models\Purchase;
use Illuminate\Database\Eloquent\Attributes\Fillable; use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany; use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasOne;
#[Fillable([ #[Fillable([
'inventory_id',
'cart_item_id',
'purchase_id',
'quantity',
'status', 'status',
'expires_at', 'expires_at',
'committed_at', 'committed_at',
'released_at', 'released_at',
'expired_at',
'release_reason',
])] ])]
class StockReservation extends Model class StockReservation extends Model
{ {
@@ -30,28 +31,31 @@ class StockReservation extends Model
protected function casts(): array protected function casts(): array
{ {
return [ return [
'inventory_id' => 'integer',
'cart_item_id' => 'integer',
'purchase_id' => 'integer',
'quantity' => 'integer',
'expires_at' => 'datetime', 'expires_at' => 'datetime',
'committed_at' => 'datetime', 'committed_at' => 'datetime',
'released_at' => 'datetime', 'released_at' => 'datetime',
'expired_at' => 'datetime',
]; ];
} }
/** @return HasMany<StockReservationLine, $this> */ /** @return BelongsTo<Inventory, $this> */
public function lines(): HasMany public function inventory(): BelongsTo
{ {
return $this->hasMany(StockReservationLine::class); return $this->belongsTo(Inventory::class);
} }
/** @return HasOne<Cart, $this> */ /** @return BelongsTo<CartItem, $this> */
public function currentCart(): HasOne public function cartItem(): BelongsTo
{ {
return $this->hasOne(Cart::class, 'current_stock_reservation_id'); return $this->belongsTo(CartItem::class);
} }
/** @return HasOne<Purchase, $this> */ /** @return BelongsTo<Purchase, $this> */
public function purchase(): HasOne public function purchase(): BelongsTo
{ {
return $this->hasOne(Purchase::class); return $this->belongsTo(Purchase::class);
} }
} }

View File

@@ -1,38 +0,0 @@
<?php
namespace App\Domains\Catalog\Models;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
#[Fillable([
'stock_reservation_id',
'inventory_id',
'quantity',
'tracks_inventory',
])]
class StockReservationLine extends Model
{
protected function casts(): array
{
return [
'stock_reservation_id' => 'integer',
'inventory_id' => 'integer',
'quantity' => 'integer',
'tracks_inventory' => 'boolean',
];
}
/** @return BelongsTo<StockReservation, $this> */
public function reservation(): BelongsTo
{
return $this->belongsTo(StockReservation::class, 'stock_reservation_id');
}
/** @return BelongsTo<Inventory, $this> */
public function inventory(): BelongsTo
{
return $this->belongsTo(Inventory::class);
}
}

View File

@@ -51,7 +51,6 @@ class StoreCatalogItemRequest extends FormRequest
), ),
], ],
'nombre' => ['required', 'string', 'max:255'], 'nombre' => ['required', 'string', 'max:255'],
'group_order' => ['sometimes', 'integer', 'min:0'],
'descripcion' => ['sometimes', 'nullable', 'string'], 'descripcion' => ['sometimes', 'nullable', 'string'],
'precio' => ['required', 'numeric', 'min:0'], 'precio' => ['required', 'numeric', 'min:0'],
'inventory_policy' => [Rule::prohibitedIf($isBundle), 'sometimes', Rule::enum(InventoryPolicy::class)], 'inventory_policy' => [Rule::prohibitedIf($isBundle), 'sometimes', Rule::enum(InventoryPolicy::class)],

View File

@@ -38,19 +38,13 @@ class CatalogFeaturedItemResource extends JsonResource
'nombre' => $catalogItem->nombre, 'nombre' => $catalogItem->nombre,
'descripcion' => $catalogItem->descripcion, 'descripcion' => $catalogItem->descripcion,
'precio' => $catalogItem->precio, 'precio' => $catalogItem->precio,
'maximum_addable_quantity' => $this->maximumAddable( 'availability' => $this->availability($availableStock, $remainingUserQuota),
$availableStock, 'variants' => $catalogItem->variants
$remainingUserQuota, ->map(function (Variant $variant) use ($catalogItem): array {
),
'unavailable_message' => $this->unavailableMessage(
$availableStock,
$remainingUserQuota,
),
'variants' => $catalogItem->visibleVariants()
->map(function (Variant $variant) use ($catalogItem, $remainingUserQuota): array {
$variantStock = $catalogItem->inventory_policy === InventoryPolicy::Unlimited $variantStock = $catalogItem->inventory_policy === InventoryPolicy::Unlimited
? null ? null
: $variant->inventory->availableStock(); : $variant->inventory->availableStock();
$availability = $this->availability($variantStock, null);
return [ return [
'id' => $variant->id, 'id' => $variant->id,
@@ -60,17 +54,11 @@ class CatalogFeaturedItemResource extends JsonResource
'event_dates' => $variant->selectedEventDates()->map(fn ($eventDate): string => $eventDate->date->format('Y-m-d'))->values(), 'event_dates' => $variant->selectedEventDates()->map(fn ($eventDate): string => $eventDate->date->format('Y-m-d'))->values(),
'descripcion' => $variant->getDescription(), 'descripcion' => $variant->getDescription(),
'precio' => number_format($variant->getPrice(), 2, '.', ''), 'precio' => number_format($variant->getPrice(), 2, '.', ''),
'maximum_addable_quantity' => $this->maximumAddable( 'availability' => $availability,
$variantStock,
$remainingUserQuota,
),
'unavailable_message' => $this->unavailableMessage(
$variantStock,
$remainingUserQuota,
),
'values' => $variant->selectorOptions($catalogItem->itemAttributes), 'values' => $variant->selectorOptions($catalogItem->itemAttributes),
]; ];
}) })
->filter(fn (array $variant): bool => $variant['availability']['state'] === 'visible')
->values(), ->values(),
]; ];
@@ -90,8 +78,7 @@ class CatalogFeaturedItemResource extends JsonResource
'descripcion' => $catalogItem->descripcion, 'descripcion' => $catalogItem->descripcion,
'precio' => $catalogItem->precio, 'precio' => $catalogItem->precio,
'image' => $this->firstImageUrl($catalogItem), 'image' => $this->firstImageUrl($catalogItem),
'maximum_addable_quantity' => $this->maximumAddable($availableStock, $remainingUserQuota), 'availability' => $this->availability($availableStock, $remainingUserQuota),
'unavailable_message' => $this->unavailableMessage($availableStock, $remainingUserQuota),
]; ];
} }
@@ -107,30 +94,27 @@ class CatalogFeaturedItemResource extends JsonResource
'nombre' => $catalogItem->nombre, 'nombre' => $catalogItem->nombre,
'precio' => $catalogItem->precio, 'precio' => $catalogItem->precio,
'image' => $this->firstImageUrl($catalogItem), 'image' => $this->firstImageUrl($catalogItem),
'maximum_addable_quantity' => $this->maximumAddable($availableStock, $remainingUserQuota), 'availability' => $this->availability($availableStock, $remainingUserQuota),
'unavailable_message' => $this->unavailableMessage($availableStock, $remainingUserQuota),
]; ];
} }
private function firstImageUrl(CatalogItem $catalogItem): ?string private function firstImageUrl(CatalogItem $catalogItem): ?string
{ {
$attachment = $catalogItem->attachments->first() $attachment = $catalogItem->attachments->first()
?? $catalogItem->visibleVariants() ?? $catalogItem->variants
->flatMap(fn (Variant $variant) => $variant->attachments) ->flatMap(fn (Variant $variant) => $variant->attachments)
->first(); ->first();
return $attachment?->getTemporaryUrl(1440); return $attachment?->getTemporaryUrl(1440);
} }
private function maximumAddable(?int $stock, ?int $remainingUserQuota): ?int /** @return array<string, mixed> */
{ private function availability(
?int $stock,
?int $remainingUserQuota,
): array {
return app(CatalogItemAllowanceService::class) return app(CatalogItemAllowanceService::class)
->maximumAddableQuantity($stock, $remainingUserQuota); ->availability($stock, $remainingUserQuota)
} ->toArray();
private function unavailableMessage(?int $stock, ?int $remainingUserQuota): ?string
{
return app(CatalogItemAllowanceService::class)
->unavailableMessage($stock, $remainingUserQuota);
} }
} }

View File

@@ -38,20 +38,14 @@ class CatalogItemDetailResource extends JsonResource
'max_units_per_user' => $this->max_units_per_user, 'max_units_per_user' => $this->max_units_per_user,
'has_tickets' => $this->has_tickets, 'has_tickets' => $this->has_tickets,
'attributes' => $this->attributesData(), 'attributes' => $this->attributesData(),
'maximum_addable_quantity' => $this->when( 'availability' => $this->availability($this->availableStock()),
$selectedVariant === null,
fn () => $this->maximumAddable($this->availableStock()),
),
'unavailable_message' => $this->when(
$selectedVariant === null,
fn () => $this->unavailableMessage($this->availableStock()),
),
'images' => $this->when( 'images' => $this->when(
$selectedVariant === null, $selectedVariant === null,
fn () => $this->imageUrls($this->attachments), fn () => $this->imageUrls($this->attachments),
), ),
'variants' => $this->variants 'variants' => $this->variants
->map(fn (Variant $variant): array => $this->variantData($variant)) ->map(fn (Variant $variant): array => $this->variantData($variant))
->filter(fn (array $variant): bool => $variant['availability']['state'] === 'visible')
->values(), ->values(),
'selected_variant' => $this->when( 'selected_variant' => $this->when(
$selectedVariant !== null, $selectedVariant !== null,
@@ -164,6 +158,10 @@ class CatalogItemDetailResource extends JsonResource
$values = $variant->selectionOptions($this->itemAttributes); $values = $variant->selectionOptions($this->itemAttributes);
$eventDates = $variant->selectedEventDates(); $eventDates = $variant->selectedEventDates();
$variantStock = $this->variantStock($variant); $variantStock = $this->variantStock($variant);
$availability = $this->availability(
$variantStock,
false,
);
return [ return [
'id' => $variant->id, 'id' => $variant->id,
@@ -173,8 +171,7 @@ class CatalogItemDetailResource extends JsonResource
'event_dates' => $eventDates->map(fn ($eventDate): string => $eventDate->date->format('Y-m-d'))->values(), 'event_dates' => $eventDates->map(fn ($eventDate): string => $eventDate->date->format('Y-m-d'))->values(),
'descripcion' => $variant->getDescription(), 'descripcion' => $variant->getDescription(),
'precio' => number_format($variant->getPrice(), 2, '.', ''), 'precio' => number_format($variant->getPrice(), 2, '.', ''),
'maximum_addable_quantity' => $this->maximumAddable($variantStock), 'availability' => $availability,
'unavailable_message' => $this->unavailableMessage($variantStock),
'values' => $values, 'values' => $values,
]; ];
} }
@@ -194,19 +191,14 @@ class CatalogItemDetailResource extends JsonResource
: $variant->inventory->availableStock(); : $variant->inventory->availableStock();
} }
private function maximumAddable(?int $stock): ?int /** @return array<string, mixed> */
{ private function availability(
return app(CatalogItemAllowanceService::class)->maximumAddableQuantity( ?int $stock,
bool $includeUserQuota = true,
): array {
return app(CatalogItemAllowanceService::class)->availability(
$stock, $stock,
$this->getAttribute('remaining_user_quota'), $includeUserQuota ? $this->getAttribute('remaining_user_quota') : null,
); )->toArray();
}
private function unavailableMessage(?int $stock): ?string
{
return app(CatalogItemAllowanceService::class)->unavailableMessage(
$stock,
$this->getAttribute('remaining_user_quota'),
);
} }
} }

View File

@@ -16,9 +16,8 @@ class CatalogSearchItemResource extends JsonResource
public function toArray(Request $request): array public function toArray(Request $request): array
{ {
$availableStock = $this->availableStock(); $availableStock = $this->availableStock();
$visibleVariants = $this->visibleVariants();
$attachment = $this->attachments->first() $attachment = $this->attachments->first()
?? $visibleVariants ?? $this->variants
->flatMap(fn (Variant $variant) => $variant->attachments) ->flatMap(fn (Variant $variant) => $variant->attachments)
->first(); ->first();
@@ -29,13 +28,16 @@ class CatalogSearchItemResource extends JsonResource
'descripcion' => $this->descripcion, 'descripcion' => $this->descripcion,
'precio' => $this->precio, 'precio' => $this->precio,
'image' => $attachment?->getTemporaryUrl(1440), 'image' => $attachment?->getTemporaryUrl(1440),
'maximum_addable_quantity' => $this->maximumAddable($availableStock), 'availability' => $this->availability($availableStock),
'unavailable_message' => $this->unavailableMessage($availableStock), 'variants' => $this->variants
'variants' => $visibleVariants
->map(function (Variant $variant): array { ->map(function (Variant $variant): array {
$variantStock = $this->inventory_policy === InventoryPolicy::Unlimited $variantStock = $this->inventory_policy === InventoryPolicy::Unlimited
? null ? null
: $variant->inventory?->availableStock(); : $variant->inventory?->availableStock();
$availability = $this->availability(
$variantStock,
false,
);
return [ return [
'id' => $variant->id, 'id' => $variant->id,
@@ -45,28 +47,23 @@ class CatalogSearchItemResource extends JsonResource
'event_dates' => $variant->selectedEventDates()->map(fn ($eventDate): string => $eventDate->date->format('Y-m-d'))->values(), 'event_dates' => $variant->selectedEventDates()->map(fn ($eventDate): string => $eventDate->date->format('Y-m-d'))->values(),
'descripcion' => $variant->getDescription(), 'descripcion' => $variant->getDescription(),
'precio' => number_format($variant->getPrice(), 2, '.', ''), 'precio' => number_format($variant->getPrice(), 2, '.', ''),
'maximum_addable_quantity' => $this->maximumAddable($variantStock), 'availability' => $availability,
'unavailable_message' => $this->unavailableMessage($variantStock),
'values' => $variant->selectorOptions($this->itemAttributes), 'values' => $variant->selectorOptions($this->itemAttributes),
]; ];
}) })
->filter(fn (array $variant): bool => $variant['availability']['state'] === 'visible')
->values(), ->values(),
]; ];
} }
private function maximumAddable(?int $stock): ?int /** @return array<string, mixed> */
{ private function availability(
return app(CatalogItemAllowanceService::class)->maximumAddableQuantity( ?int $stock,
bool $includeUserQuota = true,
): array {
return app(CatalogItemAllowanceService::class)->availability(
$stock, $stock,
$this->getAttribute('remaining_user_quota'), $includeUserQuota ? $this->getAttribute('remaining_user_quota') : null,
); )->toArray();
}
private function unavailableMessage(?int $stock): ?string
{
return app(CatalogItemAllowanceService::class)->unavailableMessage(
$stock,
$this->getAttribute('remaining_user_quota'),
);
} }
} }

View File

@@ -0,0 +1,63 @@
<?php
namespace App\Domains\Catalog\Services;
use App\Domains\Catalog\Enums\CatalogAction;
final readonly class AvailabilityDecision
{
/**
* @param list<CatalogAction> $allowedActions
* @param list<array{code: string, message: string}> $reasons
*/
private function __construct(
private bool $visible,
private ?int $maximumQuantity,
private array $allowedActions,
private array $reasons,
) {}
/** @param list<array{code: string, message: string}> $reasons */
public static function hidden(array $reasons): self
{
return new self(false, null, [], $reasons);
}
/**
* @param list<CatalogAction> $allowedActions
* @param list<array{code: string, message: string}> $reasons
*/
public static function visible(
?int $maximumQuantity,
array $allowedActions,
array $reasons,
): self {
return new self(true, $maximumQuantity, $allowedActions, $reasons);
}
public function isVisible(): bool
{
return $this->visible;
}
/** @return array<string, mixed> */
public function toArray(): array
{
if (! $this->visible) {
return [
'state' => 'hidden',
'reasons' => $this->reasons,
];
}
return [
'state' => 'visible',
'maximum_quantity' => $this->maximumQuantity,
'allowed_actions' => array_map(
fn (CatalogAction $action): string => $action->value,
$this->allowedActions,
),
'reasons' => $this->reasons,
];
}
}

View File

@@ -0,0 +1,26 @@
<?php
namespace App\Domains\Catalog\Services;
use App\Domains\Catalog\Enums\AvailabilityEffect;
use App\Domains\Catalog\Enums\CatalogAction;
final class AvailabilityPolicyResolver
{
/** @return array{effect: AvailabilityEffect, denied_actions: list<CatalogAction>} */
public function resolve(string $restrictionCode): array
{
/** @var array{effect?: string, denied_actions?: list<string>} $configured */
$configured = config("catalog.availability.rules.{$restrictionCode}", []);
return [
'effect' => AvailabilityEffect::from(
$configured['effect'] ?? AvailabilityEffect::Notice->value,
),
'denied_actions' => array_map(
fn (string $action): CatalogAction => CatalogAction::from($action),
$configured['denied_actions'] ?? [],
),
];
}
}

View File

@@ -25,24 +25,6 @@ class CatalogInventoryService
); );
} }
/**
* @return array<int, array{quantity: int, tracks_inventory: bool}>
*/
public function detailedRequirementsFor(CatalogItem|Variant $selection, int $quantity = 1): array
{
if ($quantity <= 0) {
throw new \InvalidArgumentException('La cantidad debe ser mayor a cero.');
}
return array_map(
fn (array $requirement): array => [
...$requirement,
'quantity' => $requirement['quantity'] * $quantity,
],
$this->inventoryRequirements($selection),
);
}
public function availableQuantity(CatalogItem|Variant $selection): ?int public function availableQuantity(CatalogItem|Variant $selection): ?int
{ {
if ($selection instanceof CatalogItem if ($selection instanceof CatalogItem

View File

@@ -2,6 +2,8 @@
namespace App\Domains\Catalog\Services; namespace App\Domains\Catalog\Services;
use App\Domains\Catalog\Enums\AvailabilityEffect;
use App\Domains\Catalog\Enums\CatalogAction;
use App\Domains\Catalog\Models\CatalogItem; use App\Domains\Catalog\Models\CatalogItem;
use App\Domains\Purchase\Services\UserPurchaseLimitService; use App\Domains\Purchase\Services\UserPurchaseLimitService;
use Illuminate\Support\Collection; use Illuminate\Support\Collection;
@@ -14,6 +16,7 @@ class CatalogItemAllowanceService
public function __construct( public function __construct(
private readonly UserPurchaseLimitService $purchaseLimits, private readonly UserPurchaseLimitService $purchaseLimits,
private readonly AvailabilityPolicyResolver $policies,
) {} ) {}
/** @param Collection<int, CatalogItem> $catalogItems */ /** @param Collection<int, CatalogItem> $catalogItems */
@@ -42,16 +45,82 @@ class CatalogItemAllowanceService
return min($availableStock, $remainingUserQuota); return min($availableStock, $remainingUserQuota);
} }
public function unavailableMessage(?int $availableStock, ?int $remainingUserQuota): ?string public function availability(
{ ?int $availableStock,
?int $remainingUserQuota,
): AvailabilityDecision {
$reasons = [];
if ($remainingUserQuota !== null && $remainingUserQuota <= 0) { if ($remainingUserQuota !== null && $remainingUserQuota <= 0) {
return self::USER_QUOTA_REACHED_MESSAGE; $reasons[] = [
'code' => 'user_quota_reached',
'message' => self::USER_QUOTA_REACHED_MESSAGE,
];
} }
if ($availableStock !== null && $availableStock <= 0) { if ($availableStock !== null && $availableStock <= 0) {
return self::OUT_OF_STOCK_MESSAGE; $reasons[] = [
'code' => 'out_of_stock',
'message' => self::OUT_OF_STOCK_MESSAGE,
];
} }
return null; return $this->decision(
$this->maximumAddableQuantity($availableStock, $remainingUserQuota),
$reasons,
);
}
public function purchaseLimitExceededAvailability(
int $maximumQuantity,
string $message,
): AvailabilityDecision {
$reasons = [];
if ($maximumQuantity <= 0) {
$reasons[] = [
'code' => 'user_quota_reached',
'message' => self::USER_QUOTA_REACHED_MESSAGE,
];
} else {
$reasons[] = [
'code' => 'requested_quantity_exceeds_user_quota',
'message' => $message,
];
}
return $this->decision($maximumQuantity, $reasons);
}
/**
* @param list<array{code: string, message: string}> $reasons
*/
private function decision(?int $maximumQuantity, array $reasons): AvailabilityDecision
{
/** @var list<string> $configuredActions */
$configuredActions = config('catalog.availability.default_actions', []);
$allowedActions = collect($configuredActions)
->map(fn (string $action): CatalogAction => CatalogAction::from($action));
foreach ($reasons as $reason) {
$policy = $this->policies->resolve($reason['code']);
if ($policy['effect'] === AvailabilityEffect::Hide) {
return AvailabilityDecision::hidden($reasons);
}
if ($policy['effect'] === AvailabilityEffect::Restrict) {
$deniedActions = $policy['denied_actions'];
$allowedActions = $allowedActions->reject(
fn (CatalogAction $action): bool => in_array($action, $deniedActions, true),
);
}
}
return AvailabilityDecision::visible(
$maximumQuantity,
$allowedActions->values()->all(),
$reasons,
);
} }
} }

View File

@@ -22,7 +22,10 @@ use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
class CatalogService class CatalogService
{ {
public function __construct(protected AttachmentService $attachmentService) {} public function __construct(
protected AttachmentService $attachmentService,
private readonly VisibleCatalogItemsQuery $visibleCatalogItems,
) {}
/** /**
* @param array<string, mixed> $data * @param array<string, mixed> $data
@@ -205,13 +208,6 @@ class CatalogService
]); ]);
$visibleVariants = $catalogItem->visibleVariants(); $visibleVariants = $catalogItem->visibleVariants();
if ($catalogItem->type === CatalogItemType::Standard
&& ($catalogItem->inventory_id !== null || $catalogItem->variants->isNotEmpty())
&& ! $catalogItem->isAvailable()) {
throw new NotFoundHttpException('Catalog item is out of stock.');
}
$catalogItem->setRelation('variants', $visibleVariants);
$selectedVariant = $variantId === null $selectedVariant = $variantId === null
? $visibleVariants->first() ? $visibleVariants->first()
: $visibleVariants->firstWhere('id', $variantId); : $visibleVariants->firstWhere('id', $variantId);
@@ -236,9 +232,8 @@ class CatalogService
$containsPattern = "%{$normalizedTerm}%"; $containsPattern = "%{$normalizedTerm}%";
$startsWithPattern = "{$normalizedTerm}%"; $startsWithPattern = "{$normalizedTerm}%";
$paginator = CatalogItem::query() $query = CatalogItem::query()
->where('tenant_code', $tenant->codigo) ->where('tenant_code', $tenant->codigo)
->whereAvailable()
->where(function (Builder $query) use ($containsPattern): void { ->where(function (Builder $query) use ($containsPattern): void {
$query $query
->whereRaw('LOWER(nombre) LIKE ?', [$containsPattern]) ->whereRaw('LOWER(nombre) LIKE ?', [$containsPattern])
@@ -265,7 +260,10 @@ class CatalogService
'variants.definitions.itemAttribute.attribute.options', 'variants.definitions.itemAttribute.attribute.options',
'bundleComponents.catalogItem', 'bundleComponents.catalogItem',
'bundleComponents.variant.catalogItem', 'bundleComponents.variant.catalogItem',
]) ]);
$paginator = $this->visibleCatalogItems
->apply($query)
->orderByRaw( ->orderByRaw(
'CASE WHEN LOWER(nombre) = ? THEN 0 WHEN LOWER(nombre) LIKE ? THEN 1 ELSE 2 END', 'CASE WHEN LOWER(nombre) = ? THEN 0 WHEN LOWER(nombre) LIKE ? THEN 1 ELSE 2 END',
[$normalizedTerm, $startsWithPattern], [$normalizedTerm, $startsWithPattern],
@@ -285,10 +283,9 @@ class CatalogService
int $perPage, int $perPage,
int $page, int $page,
): LengthAwarePaginator { ): LengthAwarePaginator {
return CatalogItem::query() $query = CatalogItem::query()
->where('tenant_code', $tenant->codigo) ->where('tenant_code', $tenant->codigo)
->where('category_id', $category->id) ->where('category_id', $category->id)
->whereAvailable()
->with([ ->with([
'attachments', 'attachments',
'inventory', 'inventory',
@@ -300,7 +297,10 @@ class CatalogService
'variants.definitions.itemAttribute.attribute.options', 'variants.definitions.itemAttribute.attribute.options',
'bundleComponents.catalogItem', 'bundleComponents.catalogItem',
'bundleComponents.variant.catalogItem', 'bundleComponents.variant.catalogItem',
]) ]);
return $this->visibleCatalogItems
->apply($query)
->orderBy('nombre') ->orderBy('nombre')
->paginate(perPage: $perPage, pageName: 'page', page: $page); ->paginate(perPage: $perPage, pageName: 'page', page: $page);
} }

View File

@@ -15,7 +15,7 @@ class ExpireStockReservationsService
) {} ) {}
/** /**
* @return array{purchases: int, cart_reservations: int} * @return array{purchases: int, cart_items: int}
*/ */
public function expireOverdue(): array public function expireOverdue(): array
{ {
@@ -29,19 +29,19 @@ class ExpireStockReservationsService
Log::channel('commands')->info('Stock reservation cleanup completed.', [ Log::channel('commands')->info('Stock reservation cleanup completed.', [
'command' => 'reservations:expire', 'command' => 'reservations:expire',
'expired_purchases' => $expiredPurchases, 'expired_purchases' => $expiredPurchases,
'expired_cart_reservations' => $expiredCartItems, 'expired_cart_items' => $expiredCartItems,
'total_expired' => $expiredPurchases + $expiredCartItems, 'total_expired' => $expiredPurchases + $expiredCartItems,
]); ]);
return [ return [
'purchases' => $expiredPurchases, 'purchases' => $expiredPurchases,
'cart_reservations' => $expiredCartItems, 'cart_items' => $expiredCartItems,
]; ];
} catch (Throwable $exception) { } catch (Throwable $exception) {
Log::channel('commands')->error('Stock reservation cleanup failed.', [ Log::channel('commands')->error('Stock reservation cleanup failed.', [
'command' => 'reservations:expire', 'command' => 'reservations:expire',
'expired_purchases' => $expiredPurchases, 'expired_purchases' => $expiredPurchases,
'expired_cart_reservations' => $expiredCartItems, 'expired_cart_items' => $expiredCartItems,
'exception' => $exception, 'exception' => $exception,
]); ]);

View File

@@ -17,6 +17,7 @@ class FeaturedGroupService
/** @return array<array-key, mixed> */ /** @return array<array-key, mixed> */
public function __construct( public function __construct(
private readonly CatalogItemAllowanceService $allowances, private readonly CatalogItemAllowanceService $allowances,
private readonly VisibleCatalogItemsQuery $visibleCatalogItems,
) {} ) {}
public function itemsResponse(FeaturedGroup $featuredGroup, int $page, ?int $userId = null): array public function itemsResponse(FeaturedGroup $featuredGroup, int $page, ?int $userId = null): array
@@ -49,7 +50,6 @@ class FeaturedGroupService
{ {
$query = CatalogItem::query() $query = CatalogItem::query()
->where('catalog_items.tenant_code', $featuredGroup->tenant_code) ->where('catalog_items.tenant_code', $featuredGroup->tenant_code)
->whereAvailable()
->where(function (Builder $query): void { ->where(function (Builder $query): void {
$query $query
->whereDoesntHave('category') ->whereDoesntHave('category')
@@ -72,6 +72,8 @@ class FeaturedGroupService
'bundleComponents.variant.catalogItem', 'bundleComponents.variant.catalogItem',
]); ]);
$query = $this->visibleCatalogItems->apply($query);
return match ($featuredGroup->source_type) { return match ($featuredGroup->source_type) {
FeaturedGroupSource::Manual => $query FeaturedGroupSource::Manual => $query
->select('catalog_items.*') ->select('catalog_items.*')
@@ -82,9 +84,7 @@ class FeaturedGroupService
FeaturedGroupSource::Category => $query FeaturedGroupSource::Category => $query
->where('catalog_items.category_id', $featuredGroup->category_id) ->where('catalog_items.category_id', $featuredGroup->category_id)
->orderBy('catalog_items.id'), ->orderBy('catalog_items.id'),
FeaturedGroupSource::All => $query FeaturedGroupSource::All => $query->orderBy('catalog_items.id'),
->orderBy('catalog_items.group_order')
->orderBy('catalog_items.id'),
}; };
} }

View File

@@ -2,415 +2,262 @@
namespace App\Domains\Catalog\Services; namespace App\Domains\Catalog\Services;
use App\Domains\Cart\Models\Cart;
use App\Domains\Cart\Models\CartItem; use App\Domains\Cart\Models\CartItem;
use App\Domains\Catalog\Models\Inventory; use App\Domains\Catalog\Models\CatalogItem;
use App\Domains\Catalog\Models\StockReservation; use App\Domains\Catalog\Models\StockReservation;
use App\Domains\Catalog\Models\StockReservationLine; use App\Domains\Catalog\Models\Variant;
use App\Domains\Purchase\Models\Purchase; use App\Domains\Purchase\Models\Purchase;
use Illuminate\Support\Carbon; use Illuminate\Support\Carbon;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\DB;
class StockReservationService class StockReservationService
{ {
public const REASON_CART_EMPTY = 'cart_empty';
public const REASON_CART_CHANGED = 'cart_changed';
public const REASON_PURCHASE_SUPERSEDED = 'purchase_superseded';
public const REASON_PURCHASE_CANCELLED = 'purchase_cancelled';
public const REASON_PAYMENT_REJECTED = 'payment_rejected';
public const REASON_MANUAL_RELEASE = 'manual_release';
public function __construct( public function __construct(
private readonly CatalogInventoryService $inventory, private readonly CatalogInventoryService $inventory,
) {} ) {}
public function syncCart(Cart $cart): ?StockReservation public function reserve(CartItem $cartItem, CatalogItem|Variant $selection, int $quantity): void
{ {
return DB::transaction(function () use ($cart): ?StockReservation { DB::transaction(function () use ($cartItem, $selection, $quantity): void {
/** @var Cart $lockedCart */ $this->inventory->reserve($selection, $quantity);
$lockedCart = Cart::query()->lockForUpdate()->findOrFail($cart->getKey()); $this->recordIncrease($cartItem, $selection, $quantity);
$items = $lockedCart->items()->orderBy('id')->lockForUpdate()->get();
$this->loadSelections($items);
$requirements = $this->requirementsForItems($items);
$reservation = $lockedCart->current_stock_reservation_id === null
? null
: StockReservation::query()->lockForUpdate()->find($lockedCart->current_stock_reservation_id);
if ($reservation !== null
&& $reservation->status === StockReservation::STATUS_ACTIVE
&& $reservation->expires_at !== null
&& $reservation->expires_at->isPast()) {
$this->finalizeLocked($reservation, StockReservation::STATUS_EXPIRED, null);
$lockedCart->update(['current_stock_reservation_id' => null]);
$reservation = null;
}
if ($requirements === []) {
if ($reservation !== null && $reservation->status === StockReservation::STATUS_ACTIVE) {
$this->finalizeLocked(
$reservation,
StockReservation::STATUS_RELEASED,
self::REASON_CART_EMPTY,
);
}
$lockedCart->update(['current_stock_reservation_id' => null]);
$cart->current_stock_reservation_id = null;
return null;
}
if ($reservation === null || $reservation->status !== StockReservation::STATUS_ACTIVE) {
$reservation = StockReservation::query()->create([
'status' => StockReservation::STATUS_ACTIVE,
'expires_at' => $this->expiration(),
]);
$lockedCart->update(['current_stock_reservation_id' => $reservation->getKey()]);
}
if (Purchase::query()->where('stock_reservation_id', $reservation->getKey())->exists()) {
throw new \InvalidArgumentException('La reserva vinculada a una compra no se puede modificar.');
}
$currentLines = StockReservationLine::query()
->where('stock_reservation_id', $reservation->getKey())
->orderBy('inventory_id')
->lockForUpdate()
->get()
->keyBy('inventory_id');
$inventoryIds = collect(array_keys($requirements))
->merge($currentLines->keys())
->map(fn ($id): int => (int) $id)
->unique()
->sort()
->values();
$inventories = Inventory::query()
->whereKey($inventoryIds)
->orderBy('id')
->lockForUpdate()
->get()
->keyBy('id');
foreach ($inventoryIds as $inventoryId) {
$inventory = $inventories->get($inventoryId)
?? throw new \InvalidArgumentException('No se encontró el inventario requerido.');
$previous = (int) ($currentLines->get($inventoryId)?->quantity ?? 0);
$required = (int) ($requirements[$inventoryId]['quantity'] ?? 0);
$delta = $required - $previous;
if ($delta > 0
&& $requirements[$inventoryId]['tracks_inventory']
&& $inventory->availableStock() < $delta) {
throw new \InvalidArgumentException('No hay suficiente stock disponible para reservar el carrito.');
}
if ($delta < 0 && $inventory->reserved_stock < abs($delta)) {
throw new \InvalidArgumentException('La reserva de stock del carrito es inconsistente.');
}
}
foreach ($inventoryIds as $inventoryId) {
/** @var Inventory $inventory */
$inventory = $inventories->get($inventoryId);
$line = $currentLines->get($inventoryId);
$previous = (int) ($line?->quantity ?? 0);
$required = (int) ($requirements[$inventoryId]['quantity'] ?? 0);
$delta = $required - $previous;
if ($delta > 0) {
$inventory->reserve($delta, $requirements[$inventoryId]['tracks_inventory']);
} elseif ($delta < 0) {
$inventory->release(abs($delta));
}
if ($required === 0) {
$line?->delete();
continue;
}
StockReservationLine::query()->updateOrCreate(
[
'stock_reservation_id' => $reservation->getKey(),
'inventory_id' => $inventoryId,
],
[
'quantity' => $required,
'tracks_inventory' => $requirements[$inventoryId]['tracks_inventory'],
],
);
}
$reservation->update([
'expires_at' => $this->expiration(),
'release_reason' => null,
]);
$cart->current_stock_reservation_id = $reservation->getKey();
return $reservation->fresh('lines');
}); });
} }
public function attachToPurchase(Cart $cart, Purchase $purchase): StockReservation public function release(
{ CartItem $cartItem,
return DB::transaction(function () use ($cart, $purchase): StockReservation { CatalogItem|Variant $selection,
/** @var Cart $lockedCart */ int $quantity,
$lockedCart = Cart::query()->lockForUpdate()->findOrFail($cart->getKey()); string $releasedStatus = StockReservation::STATUS_RELEASED,
/** @var Purchase $lockedPurchase */ ): void {
$lockedPurchase = Purchase::query()->lockForUpdate()->findOrFail($purchase->getKey()); DB::transaction(function () use ($cartItem, $selection, $quantity, $releasedStatus): void {
$this->ensure($cartItem, $selection);
if ($lockedCart->current_stock_reservation_id === null) { $this->inventory->release($selection, $quantity);
throw new \InvalidArgumentException('El carrito no tiene una reserva de stock activa.'); $this->recordDecrease($cartItem, $selection, $quantity, $releasedStatus);
}
/** @var StockReservation $reservation */
$reservation = StockReservation::query()->lockForUpdate()->findOrFail($lockedCart->current_stock_reservation_id);
if ($reservation->status !== StockReservation::STATUS_ACTIVE) {
throw new \InvalidArgumentException('La reserva de stock no está activa.');
}
$linkedPurchase = Purchase::query()
->where('stock_reservation_id', $reservation->getKey())
->whereKeyNot($lockedPurchase->getKey())
->exists();
if ($linkedPurchase) {
throw new \InvalidArgumentException('La reserva de stock ya pertenece a otra compra.');
}
$lockedPurchase->update(['stock_reservation_id' => $reservation->getKey()]);
$reservation->update(['expires_at' => $lockedPurchase->expires_at]);
$purchase->stock_reservation_id = $reservation->getKey();
$cart->current_stock_reservation_id = $reservation->getKey();
return $reservation->fresh('lines');
}); });
} }
public function commit(Purchase $purchase): void public function commit(
{ CartItem $cartItem,
DB::transaction(function () use ($purchase): void { CatalogItem|Variant $selection,
/** @var Purchase $purchase */ Purchase $purchase,
$purchase = Purchase::query()->lockForUpdate()->findOrFail($purchase->getKey()); ): void {
if ($purchase->stock_reservation_id === null) { DB::transaction(function () use ($cartItem, $selection, $purchase): void {
throw new \InvalidArgumentException('La compra no tiene una reserva de stock.'); $this->ensure($cartItem, $selection);
} $this->inventory->commit($selection, (int) $cartItem->cantidad);
/** @var StockReservation $reservation */ $requirements = $this->inventory->requirementsFor($selection, (int) $cartItem->cantidad);
$reservation = StockReservation::query()->lockForUpdate()->findOrFail($purchase->stock_reservation_id); foreach ($requirements as $inventoryId => $quantity) {
if ($reservation->status === StockReservation::STATUS_COMMITTED) { $reservation = $this->lockReservation($cartItem, $inventoryId);
return; if (
} $reservation === null
if ($reservation->status !== StockReservation::STATUS_ACTIVE) { || $reservation->status !== StockReservation::STATUS_ACTIVE
throw new \InvalidArgumentException('La reserva de stock no está activa.'); || $reservation->purchase_id !== $purchase->getKey()
} || $reservation->quantity !== $quantity
) {
$lines = $this->lockLines($reservation); throw new \InvalidArgumentException('La reserva de stock no coincide con el item del carrito.');
if ($lines->isEmpty()) {
throw new \InvalidArgumentException('La reserva de stock no tiene inventarios.');
}
$inventories = $this->lockInventories($lines);
foreach ($lines as $line) {
$inventory = $inventories->get($line->inventory_id)
?? throw new \InvalidArgumentException('No se encontró el inventario reservado.');
if ($inventory->reserved_stock < $line->quantity
|| ($line->tracks_inventory && $inventory->real_stock < $line->quantity)) {
throw new \InvalidArgumentException('La reserva de stock no alcanza para confirmar la compra.');
}
}
foreach ($lines as $line) {
$inventories->get($line->inventory_id)->buy(
(int) $line->quantity,
(bool) $line->tracks_inventory,
);
} }
$reservation->update([ $reservation->update([
'status' => StockReservation::STATUS_COMMITTED, 'status' => StockReservation::STATUS_COMMITTED,
'expires_at' => null,
'committed_at' => now(), 'committed_at' => now(),
'expires_at' => null,
]);
}
});
}
public function ensure(CartItem $cartItem, CatalogItem|Variant $selection): void
{
$requirements = $this->inventory->requirementsFor($selection, (int) $cartItem->cantidad);
foreach ($requirements as $inventoryId => $quantity) {
$reservation = $this->lockReservation($cartItem, $inventoryId);
if ($reservation === null) {
StockReservation::query()->create([
'inventory_id' => $inventoryId,
'cart_item_id' => $cartItem->getKey(),
'quantity' => $quantity,
'status' => StockReservation::STATUS_ACTIVE,
'expires_at' => $this->expiration(),
]);
continue;
}
if ($reservation->status !== StockReservation::STATUS_ACTIVE || $reservation->quantity !== $quantity) {
$reservation->update([
'quantity' => $quantity,
'status' => StockReservation::STATUS_ACTIVE,
'committed_at' => null,
'released_at' => null, 'released_at' => null,
'expired_at' => null, 'expires_at' => $this->expiration(),
'release_reason' => null, ]);
}
}
}
public function attachToPurchase(
CartItem $cartItem,
CatalogItem|Variant $selection,
Purchase $purchase,
): void {
DB::transaction(function () use ($cartItem, $selection, $purchase): void {
$this->ensure($cartItem, $selection);
StockReservation::query()
->where('cart_item_id', $cartItem->getKey())
->where('status', StockReservation::STATUS_ACTIVE)
->update([
'purchase_id' => $purchase->getKey(),
'expires_at' => $purchase->expires_at,
]); ]);
}); });
} }
public function releaseForPurchase( public function detachFromPurchase(Purchase $purchase): void
Purchase $purchase,
string $status = StockReservation::STATUS_RELEASED,
?string $reason = null,
): void {
DB::transaction(function () use ($purchase, $status, $reason): void {
/** @var Purchase $purchase */
$purchase = Purchase::query()->lockForUpdate()->findOrFail($purchase->getKey());
if ($purchase->stock_reservation_id === null) {
return;
}
/** @var StockReservation|null $reservation */
$reservation = StockReservation::query()->lockForUpdate()->find($purchase->stock_reservation_id);
if ($reservation !== null) {
$this->finalizeLocked($reservation, $status, $reason);
}
});
}
public function releaseCurrentCartReservation(
Cart $cart,
string $reason = self::REASON_CART_CHANGED,
): void {
DB::transaction(function () use ($cart, $reason): void {
/** @var Cart $cart */
$cart = Cart::query()->lockForUpdate()->findOrFail($cart->getKey());
if ($cart->current_stock_reservation_id === null) {
return;
}
/** @var StockReservation|null $reservation */
$reservation = StockReservation::query()->lockForUpdate()->find($cart->current_stock_reservation_id);
if ($reservation !== null) {
$this->finalizeLocked($reservation, StockReservation::STATUS_RELEASED, $reason);
}
$cart->update(['current_stock_reservation_id' => null]);
});
}
public function expire(StockReservation $reservation): void
{ {
DB::transaction(function () use ($reservation): void { StockReservation::query()
/** @var StockReservation $reservation */ ->where('purchase_id', $purchase->getKey())
$reservation = StockReservation::query()->lockForUpdate()->findOrFail($reservation->getKey()); ->where('status', StockReservation::STATUS_ACTIVE)
if ($reservation->status !== StockReservation::STATUS_ACTIVE ->update([
|| $reservation->expires_at === null 'purchase_id' => null,
|| $reservation->expires_at->isFuture()) { 'expires_at' => $this->expiration(),
]);
}
public function restore(CartItem $cartItem, CatalogItem|Variant $selection): void
{
DB::transaction(function () use ($cartItem, $selection): void {
$requirements = $this->inventory->requirementsFor(
$selection,
(int) $cartItem->cantidad,
);
$activeReservations = StockReservation::query()
->where('cart_item_id', $cartItem->getKey())
->where('status', StockReservation::STATUS_ACTIVE)
->lockForUpdate()
->get()
->keyBy('inventory_id');
$hasCompleteReservation = collect($requirements)->every(
fn (int $quantity, int $inventoryId): bool => (int) ($activeReservations->get($inventoryId)?->quantity ?? 0) === $quantity,
);
if ($hasCompleteReservation) {
return; return;
} }
$this->finalizeLocked($reservation, StockReservation::STATUS_EXPIRED, null); if ($activeReservations->isNotEmpty()) {
throw new \InvalidArgumentException('La reserva de stock del carrito es inconsistente.');
}
$this->inventory->reserve($selection, (int) $cartItem->cantidad);
$this->recordIncrease($cartItem, $selection, (int) $cartItem->cantidad);
}); });
} }
public function syncPurchaseExpiration(Purchase $purchase): void public function syncPurchaseExpiration(Purchase $purchase): void
{ {
if ($purchase->stock_reservation_id === null) {
return;
}
StockReservation::query() StockReservation::query()
->whereKey($purchase->stock_reservation_id) ->where('purchase_id', $purchase->getKey())
->where('status', StockReservation::STATUS_ACTIVE) ->where('status', StockReservation::STATUS_ACTIVE)
->update(['expires_at' => $purchase->expires_at]); ->update(['expires_at' => $purchase->expires_at]);
} }
/** public function transfer(CartItem $source, CartItem $target): void
* @param Collection<int, CartItem> $items
* @return array<int, array{quantity: int, tracks_inventory: bool}>
*/
private function requirementsForItems(Collection $items): array
{ {
$requirements = []; DB::transaction(function () use ($source, $target): void {
foreach ($items as $item) { $sourceReservations = StockReservation::query()
$selection = $item->selectedItem(); ->where('cart_item_id', $source->getKey())
if ($selection === null) { ->where('status', StockReservation::STATUS_ACTIVE)
throw new \InvalidArgumentException('El carrito contiene un item de catálogo inexistente.'); ->orderBy('inventory_id')
} ->lockForUpdate()
->get();
foreach ($this->inventory->detailedRequirementsFor($selection, (int) $item->cantidad) as $inventoryId => $requirement) { foreach ($sourceReservations as $sourceReservation) {
if (isset($requirements[$inventoryId])) { $targetReservation = $this->lockReservation($target, (int) $sourceReservation->inventory_id);
$requirements[$inventoryId]['quantity'] += $requirement['quantity'];
$requirements[$inventoryId]['tracks_inventory'] = if ($targetReservation === null) {
$requirements[$inventoryId]['tracks_inventory'] || $requirement['tracks_inventory']; $sourceItemQuantity = (int) $source->cantidad;
$targetItemQuantity = (int) $target->fresh()->cantidad;
$perItemQuantity = intdiv((int) $sourceReservation->quantity, $sourceItemQuantity);
$sourceReservation->update([
'cart_item_id' => $target->getKey(),
'purchase_id' => null,
'quantity' => $perItemQuantity * $targetItemQuantity,
'expires_at' => $this->expiration(),
]);
continue; continue;
} }
$requirements[$inventoryId] = $requirement; $targetReservation->update([
} 'quantity' => $targetReservation->quantity + $sourceReservation->quantity,
} 'status' => StockReservation::STATUS_ACTIVE,
'expires_at' => $this->expiration(),
ksort($requirements);
return $requirements;
}
/** @param Collection<int, CartItem> $items */
private function loadSelections(Collection $items): void
{
$items->load([
'catalogItem.inventory',
'catalogItem.bundleComponents.catalogItem.inventory',
'catalogItem.bundleComponents.variant.inventory',
'catalogItem.bundleComponents.variant.catalogItem',
'variant.inventory',
'variant.catalogItem',
]); ]);
$sourceReservation->delete();
}
});
} }
/** @return Collection<int, StockReservationLine> */ private function recordIncrease(CartItem $cartItem, CatalogItem|Variant $selection, int $quantity): void
private function lockLines(StockReservation $reservation): Collection
{ {
return StockReservationLine::query() foreach ($this->inventory->requirementsFor($selection, $quantity) as $inventoryId => $requiredQuantity) {
->where('stock_reservation_id', $reservation->getKey()) $reservation = $this->lockReservation($cartItem, $inventoryId);
->orderBy('inventory_id')
->lockForUpdate() if ($reservation === null) {
->get(); StockReservation::query()->create([
'inventory_id' => $inventoryId,
'cart_item_id' => $cartItem->getKey(),
'quantity' => $requiredQuantity,
'status' => StockReservation::STATUS_ACTIVE,
'expires_at' => $this->expiration(),
]);
continue;
} }
/**
* @param Collection<int, StockReservationLine> $lines
* @return Collection<int, Inventory>
*/
private function lockInventories(Collection $lines): Collection
{
return Inventory::query()
->whereKey($lines->pluck('inventory_id'))
->orderBy('id')
->lockForUpdate()
->get()
->keyBy('id');
}
private function finalizeLocked(
StockReservation $reservation,
string $status,
?string $reason,
): void {
if ($reservation->status !== StockReservation::STATUS_ACTIVE) {
return;
}
if (! in_array($status, [StockReservation::STATUS_RELEASED, StockReservation::STATUS_EXPIRED], true)) {
throw new \InvalidArgumentException('El estado final de la reserva no es válido.');
}
$lines = $this->lockLines($reservation);
$inventories = $this->lockInventories($lines);
foreach ($lines as $line) {
$inventory = $inventories->get($line->inventory_id)
?? throw new \InvalidArgumentException('No se encontró el inventario reservado.');
$inventory->release((int) $line->quantity);
}
$now = now();
$reservation->update([ $reservation->update([
'status' => $status, 'quantity' => ($reservation->status === StockReservation::STATUS_ACTIVE ? $reservation->quantity : 0) + $requiredQuantity,
'expires_at' => null, 'status' => StockReservation::STATUS_ACTIVE,
'released_at' => $status === StockReservation::STATUS_RELEASED ? $now : null, 'committed_at' => null,
'expired_at' => $status === StockReservation::STATUS_EXPIRED ? $now : null, 'released_at' => null,
'release_reason' => $status === StockReservation::STATUS_RELEASED ? $reason : null, 'expires_at' => $this->expiration(),
]); ]);
}
}
Cart::query() private function recordDecrease(
->where('current_stock_reservation_id', $reservation->getKey()) CartItem $cartItem,
->update(['current_stock_reservation_id' => null]); CatalogItem|Variant $selection,
int $quantity,
string $releasedStatus,
): void {
foreach ($this->inventory->requirementsFor($selection, $quantity) as $inventoryId => $requiredQuantity) {
$reservation = $this->lockReservation($cartItem, $inventoryId);
if ($reservation === null || $reservation->status !== StockReservation::STATUS_ACTIVE || $reservation->quantity < $requiredQuantity) {
throw new \InvalidArgumentException('La reserva de stock no alcanza para liberar la cantidad solicitada.');
}
$remaining = $reservation->quantity - $requiredQuantity;
$reservation->update([
'quantity' => $remaining,
'status' => $remaining === 0 ? $releasedStatus : StockReservation::STATUS_ACTIVE,
'released_at' => $remaining === 0 ? now() : null,
'expires_at' => $remaining === 0 ? null : $reservation->expires_at,
]);
}
}
private function lockReservation(CartItem $cartItem, int $inventoryId): ?StockReservation
{
return StockReservation::query()
->where('cart_item_id', $cartItem->getKey())
->where('inventory_id', $inventoryId)
->lockForUpdate()
->first();
} }
private function expiration(): Carbon private function expiration(): Carbon

View File

@@ -10,6 +10,10 @@ use Illuminate\Support\Collection;
class VariantSelectionService class VariantSelectionService
{ {
public function __construct(
private readonly CatalogItemAllowanceService $allowances,
) {}
/** /**
* @param array<string, mixed> $selectedValues * @param array<string, mixed> $selectedValues
* @return array<string, mixed> * @return array<string, mixed>
@@ -188,13 +192,17 @@ class VariantSelectionService
/** @return array<string, mixed> */ /** @return array<string, mixed> */
private function variantData(CatalogItem $catalogItem, Variant $variant): array private function variantData(CatalogItem $catalogItem, Variant $variant): array
{ {
$availableStock = $catalogItem->inventory_policy === InventoryPolicy::Unlimited
? null
: $variant->inventory?->availableStock();
return [ return [
'id' => $variant->id, 'id' => $variant->id,
'descripcion' => $variant->getDescription(), 'descripcion' => $variant->getDescription(),
'precio' => number_format($variant->getPrice(), 2, '.', ''), 'precio' => number_format($variant->getPrice(), 2, '.', ''),
'stock_tecnico' => $catalogItem->inventory_policy === InventoryPolicy::Unlimited 'availability' => $this->allowances
? null ->availability($availableStock, null)
: $variant->inventory?->availableStock(), ->toArray(),
'values' => $variant->selectorOptions($catalogItem->itemAttributes), 'values' => $variant->selectorOptions($catalogItem->itemAttributes),
]; ];
} }

View File

@@ -0,0 +1,81 @@
<?php
namespace App\Domains\Catalog\Services;
use App\Domains\Catalog\Enums\AvailabilityEffect;
use App\Domains\Catalog\Enums\CatalogItemType;
use App\Domains\Catalog\Enums\InventoryPolicy;
use App\Domains\Catalog\Models\CatalogItem;
use Illuminate\Database\Eloquent\Builder;
final class VisibleCatalogItemsQuery
{
public function __construct(
private readonly AvailabilityPolicyResolver $policies,
) {}
/** @param Builder<CatalogItem> $query */
public function apply(Builder $query): Builder
{
if ($this->policies->resolve('out_of_stock')['effect'] !== AvailabilityEffect::Hide) {
return $query;
}
return $query->where(function (Builder $query): void {
$query
->where(fn (Builder $query) => $this->applyStandardItemAvailability($query))
->orWhere(fn (Builder $query) => $this->applyBundleAvailability($query));
});
}
/** @param Builder<CatalogItem> $query */
private function applyStandardItemAvailability(Builder $query): Builder
{
return $query
->where('catalog_items.type', CatalogItemType::Standard->value)
->where(function (Builder $query): void {
$query
->where('catalog_items.inventory_policy', InventoryPolicy::Unlimited->value)
->orWhereHas(
'inventory',
fn (Builder $query): Builder => $query
->whereColumn('inventories.real_stock', '>', 'inventories.reserved_stock'),
)
->orWhereHas(
'variants.inventory',
fn (Builder $query): Builder => $query
->whereColumn('inventories.real_stock', '>', 'inventories.reserved_stock'),
);
});
}
/** @param Builder<CatalogItem> $query */
private function applyBundleAvailability(Builder $query): Builder
{
return $query
->where('catalog_items.type', CatalogItemType::Bundle->value)
->whereRaw(<<<'SQL'
NOT EXISTS (
SELECT 1
FROM bundle_components AS availability_components
INNER JOIN catalog_items AS availability_items
ON availability_items.id = availability_components.component_catalog_item_id
LEFT JOIN variantes AS availability_variants
ON availability_variants.id = availability_components.component_variant_id
INNER JOIN inventories AS availability_inventories
ON availability_inventories.id = COALESCE(
availability_variants.inventory_id,
availability_items.inventory_id
)
WHERE availability_components.bundle_catalog_item_id = catalog_items.id
AND availability_items.inventory_policy = ?
GROUP BY availability_inventories.id,
availability_inventories.real_stock,
availability_inventories.reserved_stock
HAVING availability_inventories.real_stock
- availability_inventories.reserved_stock
< SUM(availability_components.quantity)
)
SQL, [InventoryPolicy::Tracked->value]);
}
}

View File

@@ -9,7 +9,7 @@ Modela y publica la oferta comercial del tenant: productos, variantes, categorí
- `CatalogItem` es la raíz del producto y se relaciona con tenant, categoría, marca, inventario, variantes, atributos, adjuntos y grupos destacados. - `CatalogItem` es la raíz del producto y se relaciona con tenant, categoría, marca, inventario, variantes, atributos, adjuntos y grupos destacados.
- `Variant`, `ItemAttribute`, `Attribute`, `AttributeOption` y `VariantDefinition` describen opciones comercializables. - `Variant`, `ItemAttribute`, `Attribute`, `AttributeOption` y `VariantDefinition` describen opciones comercializables.
- `Inventory` administra stock disponible, reservado y comprado. - `Inventory` administra stock disponible, reservado y comprado.
- `StockReservation` representa la reserva completa de un carrito o checkout, con estados `active`, `committed`, `released` y `expired`. Sus `StockReservationLine` agregan la cantidad requerida por inventario, incluso cuando varios ítems o bundles consumen el mismo stock. - `StockReservation` atribuye cada unidad reservada a un ítem de carrito y, durante checkout, a una compra, con estados `active`, `committed`, `released` y `expired`.
- `Category` soporta jerarquía y categorías globales o propias del tenant. - `Category` soporta jerarquía y categorías globales o propias del tenant.
- `FeaturedGroup` y `FeaturedItem` organizan secciones destacadas. - `FeaturedGroup` y `FeaturedItem` organizan secciones destacadas.
- `BundleComponent` representa los componentes de un paquete. - `BundleComponent` representa los componentes de un paquete.
@@ -18,7 +18,7 @@ Modela y publica la oferta comercial del tenant: productos, variantes, categorí
- `CatalogService`: alta, búsqueda, detalle, listado por categoría y eliminación. - `CatalogService`: alta, búsqueda, detalle, listado por categoría y eliminación.
- `CatalogInventoryService`: consulta, reserva, libera y confirma inventario. - `CatalogInventoryService`: consulta, reserva, libera y confirma inventario.
- `StockReservationService`: sincroniza el carrito como conjunto, bloquea todos sus inventarios en orden estable y mantiene el ledger agregado consistente con `Inventory.reserved_stock`. - `StockReservationService`: mantiene el ledger de reservas sincronizado con `Inventory.reserved_stock`.
- `FeaturedGroupService`: pagina los ítems destacados para la tienda. - `FeaturedGroupService`: pagina los ítems destacados para la tienda.
- `OnTicketFeaturedGroupService`: administra grupos destacados del panel para sitios de tickets. - `OnTicketFeaturedGroupService`: administra grupos destacados del panel para sitios de tickets.

View File

@@ -392,28 +392,15 @@ class InvitationPurchaseProvisioner
'sold_units' => $inventory->sold_units + 1, 'sold_units' => $inventory->sold_units + 1,
]); ]);
$reservationId = DB::table('compras')->where('id', $purchaseId)->value('stock_reservation_id'); DB::table('stock_reservations')->insert([
if ($reservationId === null) { 'inventory_id' => $inventory->id,
$reservationId = DB::table('stock_reservations')->insertGetId([ 'cart_item_id' => null,
'purchase_id' => $purchaseId,
'quantity' => 1,
'status' => 'committed', 'status' => 'committed',
'expires_at' => null, 'expires_at' => null,
'committed_at' => $now, 'committed_at' => $now,
'released_at' => null, 'released_at' => null,
'expired_at' => null,
'release_reason' => null,
'created_at' => $now,
'updated_at' => $now,
]);
DB::table('compras')->where('id', $purchaseId)->update([
'stock_reservation_id' => $reservationId,
]);
}
DB::table('stock_reservation_lines')->insert([
'stock_reservation_id' => $reservationId,
'inventory_id' => $inventory->id,
'quantity' => 1,
'tracks_inventory' => true,
'created_at' => $now, 'created_at' => $now,
'updated_at' => $now, 'updated_at' => $now,
]); ]);

View File

@@ -19,7 +19,6 @@ use Illuminate\Support\Facades\DB;
#[Fillable([ #[Fillable([
'cart_id', 'cart_id',
'stock_reservation_id',
'tenant_codigo', 'tenant_codigo',
'user_id', 'user_id',
'status', 'status',
@@ -78,7 +77,6 @@ class Purchase extends Model
{ {
return [ return [
'cart_id' => 'integer', 'cart_id' => 'integer',
'stock_reservation_id' => 'integer',
'user_id' => 'integer', 'user_id' => 'integer',
'expires_at' => 'datetime', 'expires_at' => 'datetime',
'total' => 'decimal:2', 'total' => 'decimal:2',
@@ -125,10 +123,10 @@ class Purchase extends Model
return $this->hasMany(Ticket::class, 'source_purchase_id'); return $this->hasMany(Ticket::class, 'source_purchase_id');
} }
/** @return BelongsTo<StockReservation, $this> */ /** @return HasMany<StockReservation, $this> */
public function stockReservation(): BelongsTo public function stockReservations(): HasMany
{ {
return $this->belongsTo(StockReservation::class); return $this->hasMany(StockReservation::class);
} }
/** /**

View File

@@ -161,15 +161,14 @@ class CompleteCheckoutService
]); ]);
} }
}
try { try {
$this->reservations->commit($purchase); $this->reservations->commit($cartItem, $selection, $purchase);
} catch (\InvalidArgumentException) { } catch (\InvalidArgumentException) {
throw ValidationException::withMessages([ throw ValidationException::withMessages([
'items' => __('api.purchase.inconsistent_reservation'), 'items' => __('api.purchase.inconsistent_reservation'),
]); ]);
} }
}
$this->sourceCart->finalize($purchase); $this->sourceCart->finalize($purchase);
}); });

View File

@@ -118,40 +118,16 @@ class ReleaseCheckoutService
private function releasePurchaseReservations(Purchase $purchase, string $targetStatus): void private function releasePurchaseReservations(Purchase $purchase, string $targetStatus): void
{ {
$cart = $purchase->cart()->withTrashed()->lockForUpdate()->first(); $cart = $purchase->cart()->withTrashed()->lockForUpdate()->first();
try {
$this->reservations->releaseForPurchase(
$purchase,
$targetStatus === Purchase::STATUS_EXPIRED
? StockReservation::STATUS_EXPIRED
: StockReservation::STATUS_RELEASED,
$targetStatus === Purchase::STATUS_CANCELLED
? StockReservationService::REASON_PURCHASE_CANCELLED
: ($targetStatus === Purchase::STATUS_REJECTED
? StockReservationService::REASON_PAYMENT_REJECTED
: null),
);
} catch (\InvalidArgumentException) {
throw ValidationException::withMessages([
'items' => __('api.purchase.inconsistent_reservation'),
]);
}
if ($cart === null) { if ($cart === null) {
return; return;
} }
if ($cart->status === 'active') { if ($cart->status === 'active') {
$this->reservations->detachFromPurchase($purchase);
Cart::query() Cart::query()
->whereKey($cart->getKey()) ->whereKey($cart->getKey())
->where('current_purchase_id', $purchase->getKey()) ->where('current_purchase_id', $purchase->getKey())
->update([ ->update(['current_purchase_id' => null]);
'current_purchase_id' => null,
'current_stock_reservation_id' => null,
]);
if ($targetStatus === Purchase::STATUS_CANCELLED) {
$this->reservations->syncCart($cart);
}
return; return;
} }
@@ -160,6 +136,37 @@ class ReleaseCheckoutService
return; 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()) { if (! $cart->trashed()) {
$cart->update(['status' => 'converted']); $cart->update(['status' => 'converted']);
$cart->delete(); $cart->delete();

View File

@@ -169,31 +169,21 @@ class StartCheckoutService
'cantidad' => $line['quantity'], 'cantidad' => $line['quantity'],
]); ]);
try {
$this->reservations->reserve($cartItem, $line['selection'], $line['quantity']);
} catch (\InvalidArgumentException) {
$availableQuantity = $this->inventory->availableQuantity($line['selection']) ?? 0;
throw new InsufficientStockException([
$this->unavailableItem($line, $availableQuantity),
]);
}
$cartItem->setRelation('catalogItem', $line['catalog_item']); $cartItem->setRelation('catalogItem', $line['catalog_item']);
$cartItem->setRelation('variant', $line['selection'] instanceof Variant ? $line['selection'] : null); $cartItem->setRelation('variant', $line['selection'] instanceof Variant ? $line['selection'] : null);
$cartItems->push($cartItem); $cartItems->push($cartItem);
} }
try {
$this->reservations->syncCart($cart);
} catch (\InvalidArgumentException) {
$unavailable = $resolvedLines
->map(function (array $line): ?array {
$availableQuantity = $this->inventory->availableQuantity($line['selection']);
return $availableQuantity !== null && $availableQuantity < $line['quantity']
? $this->unavailableItem($line, $availableQuantity)
: null;
})
->filter()
->values()
->all();
throw new InsufficientStockException($unavailable !== [] ? $unavailable : [
$this->unavailableItem($resolvedLines->first(), 0),
]);
}
$purchase = $this->createPurchase( $purchase = $this->createPurchase(
$tenant, $tenant,
$userId, $userId,
@@ -204,12 +194,19 @@ class StartCheckoutService
$cart->getKey(), $cart->getKey(),
); );
$cart->update(['current_purchase_id' => $purchase->getKey()]); $cart->update(['current_purchase_id' => $purchase->getKey()]);
$this->reservations->attachToPurchase($cart, $purchase);
$cartItems = $cart->items()->orderBy('id')->lockForUpdate()->get(); $cartItems = $cart->items()->orderBy('id')->lockForUpdate()->get();
$this->loadCartItems($cartItems); $this->loadCartItems($cartItems);
$purchase->items()->createMany($this->snapshots->fromCartItems($cartItems)); $purchase->items()->createMany($this->snapshots->fromCartItems($cartItems));
foreach ($cartItems as $index => $cartItem) {
$this->reservations->attachToPurchase(
$cartItem,
$resolvedLines->get($index)['selection'],
$purchase,
);
}
return $this->loadPurchase($purchase); return $this->loadPurchase($purchase);
} }
@@ -260,7 +257,6 @@ class StartCheckoutService
$this->verifyTenantItems($tenant, $cartItems); $this->verifyTenantItems($tenant, $cartItems);
$this->assertCartPurchaseLimits($tenant, $userId, $cartItems, $cart->getKey()); $this->assertCartPurchaseLimits($tenant, $userId, $cartItems, $cart->getKey());
$cart->setRelation('items', $cartItems); $cart->setRelation('items', $cartItems);
$this->reservations->syncCart($cart);
$purchase = $this->createPurchase( $purchase = $this->createPurchase(
$tenant, $tenant,
@@ -270,9 +266,16 @@ class StartCheckoutService
$cart->getKey(), $cart->getKey(),
); );
$cart->update(['current_purchase_id' => $purchase->getKey()]); $cart->update(['current_purchase_id' => $purchase->getKey()]);
$this->reservations->attachToPurchase($cart, $purchase);
$purchase->items()->createMany($this->snapshots->fromCartItems($cartItems)); $purchase->items()->createMany($this->snapshots->fromCartItems($cartItems));
foreach ($cartItems as $cartItem) {
$this->reservations->attachToPurchase(
$cartItem,
$cartItem->selectedItem(),
$purchase,
);
}
return $this->loadPurchase($purchase); return $this->loadPurchase($purchase);
} }
@@ -317,14 +320,6 @@ class StartCheckoutService
'status' => Purchase::STATUS_SUPERSEDED, 'status' => Purchase::STATUS_SUPERSEDED,
'expires_at' => null, 'expires_at' => null,
]); ]);
$this->reservations->releaseForPurchase(
$currentPurchase,
reason: StockReservationService::REASON_PURCHASE_SUPERSEDED,
);
$cart->update([
'current_purchase_id' => null,
'current_stock_reservation_id' => null,
]);
} }
return $cart; return $cart;

View File

@@ -135,25 +135,11 @@ class TenantTransactionResetService
*/ */
private function reservationQuery(array $scope): Builder private function reservationQuery(array $scope): Builder
{ {
$reservationIds = DB::table('carritos')
->whereIn('id', $scope['cart_ids'])
->whereNotNull('current_stock_reservation_id')
->pluck('current_stock_reservation_id')
->merge(
DB::table('compras')
->whereIn('id', $scope['purchase_ids'])
->whereNotNull('stock_reservation_id')
->pluck('stock_reservation_id'),
)
->merge(
DB::table('stock_reservation_lines')
->whereIn('inventory_id', $scope['inventory_ids'])
->pluck('stock_reservation_id'),
)
->unique()
->values();
return DB::table('stock_reservations') return DB::table('stock_reservations')
->whereIn('id', $reservationIds); ->where(function (Builder $query) use ($scope): void {
$query->whereIn('inventory_id', $scope['inventory_ids'])
->orWhereIn('purchase_id', $scope['purchase_ids'])
->orWhereIn('cart_item_id', $scope['cart_item_ids']);
});
} }
} }

View File

@@ -88,9 +88,9 @@ class UserPurchaseLimitService
$excludedCartId !== null, $excludedCartId !== null,
fn ($query) => $query->whereKeyNot($excludedCartId), fn ($query) => $query->whereKeyNot($excludedCartId),
)) ))
->whereHas('cart.currentStockReservation', fn ($query) => $query ->whereHas('stockReservations', fn ($query) => $query
->where('status', 'active') ->where('status', 'active')
->whereDoesntHave('purchase')) ->whereNull('purchase_id'))
->sum('cantidad'); ->sum('cantidad');
if ($purchasedQuantity + $checkoutQuantity + $reservedCartQuantity + $requestedQuantity > $limit) { if ($purchasedQuantity + $checkoutQuantity + $reservedCartQuantity + $requestedQuantity > $limit) {
@@ -161,9 +161,9 @@ class UserPurchaseLimitService
->whereHas('cart', fn ($query) => $query ->whereHas('cart', fn ($query) => $query
->where('user_id', $userId) ->where('user_id', $userId)
->where('status', 'active')) ->where('status', 'active'))
->whereHas('cart.currentStockReservation', fn ($query) => $query ->whereHas('stockReservations', fn ($query) => $query
->where('status', 'active') ->where('status', 'active')
->whereDoesntHave('purchase')) ->whereNull('purchase_id'))
->groupBy('catalog_item_id') ->groupBy('catalog_item_id')
->pluck('quantity', 'catalog_item_id'); ->pluck('quantity', 'catalog_item_id');

View File

@@ -6,7 +6,7 @@ Implementa el ciclo de compra y checkout: crea la cabecera de compra desde un ca
## Modelo ## Modelo
- `Purchase`: raíz de la compra; estados `created`, `pending_payment`, `in_review`, `paid`, `cancelled`, `rejected` y `expired`, y referencia la reserva que respaldó ese intento de checkout. - `Purchase`: raíz de la compra; estados `created`, `pending_payment`, `in_review`, `paid`, `cancelled`, `rejected` y `expired`.
- `PurchaseItem`: snapshot definitivo del producto o variante, creado recién al confirmar la compra. - `PurchaseItem`: snapshot definitivo del producto o variante, creado recién al confirmar la compra.
- `TelepagosQr` y `TelepagosPayment`: datos del QR e intentos/resultados del proveedor. - `TelepagosQr` y `TelepagosPayment`: datos del QR e intentos/resultados del proveedor.
- `PurchasePaid`: evento emitido una sola vez al pasar a pagada bajo bloqueo transaccional. - `PurchasePaid`: evento emitido una sola vez al pasar a pagada bajo bloqueo transaccional.
@@ -15,7 +15,7 @@ Implementa el ciclo de compra y checkout: crea la cabecera de compra desde un ca
`CheckoutService` es la fachada estable. Delega en: `CheckoutService` es la fachada estable. Delega en:
- `StartCheckoutService`: inicia la compra desde el carrito o crea un carrito técnico para compra directa, refresca el vencimiento de la reserva agregada y crea los snapshots `PurchaseItem`. - `StartCheckoutService`: inicia la compra desde el carrito o crea un carrito técnico para compra directa, sin crear todavía `PurchaseItem`.
- `EditCheckoutService`: modifica los datos del comprador antes del cierre. - `EditCheckoutService`: modifica los datos del comprador antes del cierre.
- `CompleteCheckoutService`: completa, envía a revisión o materializa los `PurchaseItem` al confirmar el pago. - `CompleteCheckoutService`: completa, envía a revisión o materializa los `PurchaseItem` al confirmar el pago.
- `ReleaseCheckoutService`: cancela, vence y procesa vencimientos pendientes. - `ReleaseCheckoutService`: cancela, vence y procesa vencimientos pendientes.
@@ -24,7 +24,7 @@ Implementa el ciclo de compra y checkout: crea la cabecera de compra desde un ca
Al informar una transferencia, la compra pasa de `pending_payment` a `in_review` y deja de vencer. Si el comprador abandona el checkout durante la revisión, la compra y sus reservas permanecen intactas y se crea un carrito activo nuevo para que pueda seguir comprando. Adminapp puede confirmar o anular explícitamente la compra en revisión. Al informar una transferencia, la compra pasa de `pending_payment` a `in_review` y deja de vencer. Si el comprador abandona el checkout durante la revisión, la compra y sus reservas permanecen intactas y se crea un carrito activo nuevo para que pueda seguir comprando. Adminapp puede confirmar o anular explícitamente la compra en revisión.
Las cantidades y variantes se editan mediante el dominio Cart. El endpoint autenticado `PATCH /checkout-carts/{cart}/items/{cartItem}` valida que el carrito pertenezca al usuario y a una compra editable. Cuando existe un cambio real, invalida atómicamente el intento de pago anterior, libera su reserva completa y crea otra para el contenido actualizado; Purchase no expone operaciones sobre líneas antes de la confirmación. Las cantidades y variantes se editan mediante el dominio Cart. El endpoint autenticado `PATCH /checkout-carts/{cart}/items/{cartItem}` valida que el carrito pertenezca al usuario y a una compra editable. Cuando existe un cambio real, invalida atómicamente el intento de pago anterior, recalcula el total y renueva la reserva; Purchase no expone operaciones sobre líneas antes de la confirmación.
`UserPurchaseLimitService` controla límites de compra y `CheckoutService` conserva el punto de entrada para controladores e integraciones. `UserPurchaseLimitService` controla límites de compra y `CheckoutService` conserva el punto de entrada para controladores e integraciones.

View File

@@ -1,6 +1,7 @@
<?php <?php
use App\Domains\Auth\Exceptions\AccountLockedException; use App\Domains\Auth\Exceptions\AccountLockedException;
use App\Domains\Catalog\Services\CatalogItemAllowanceService;
use App\Domains\Purchase\Exceptions\InsufficientStockException; use App\Domains\Purchase\Exceptions\InsufficientStockException;
use App\Domains\Purchase\Exceptions\PurchaseExpiredException; use App\Domains\Purchase\Exceptions\PurchaseExpiredException;
use App\Domains\Purchase\Exceptions\PurchaseLimitExceededException; use App\Domains\Purchase\Exceptions\PurchaseLimitExceededException;
@@ -100,7 +101,11 @@ return Application::configure(basePath: dirname(__DIR__))
'errors' => $exception->errors(), 'errors' => $exception->errors(),
'catalog_item_id' => $exception->catalogItemId, 'catalog_item_id' => $exception->catalogItemId,
'catalog_item_name' => $exception->catalogItemName, 'catalog_item_name' => $exception->catalogItemName,
'maximum_addable_quantity' => $exception->maximumAddableQuantity, 'availability' => app(CatalogItemAllowanceService::class)
->purchaseLimitExceededAvailability(
$exception->maximumAddableQuantity,
$exception->getMessage(),
)->toArray(),
], 422); ], 422);
}); });
$exceptions->render(function (PurchaseExpiredException $exception, Request $request) { $exceptions->render(function (PurchaseExpiredException $exception, Request $request) {

View File

@@ -2,4 +2,33 @@
return [ return [
'stock_reservation_expiration_minutes' => (int) env('STOCK_RESERVATION_EXPIRATION_MINUTES', 30), 'stock_reservation_expiration_minutes' => (int) env('STOCK_RESERVATION_EXPIRATION_MINUTES', 30),
'availability' => [
'default_actions' => [
'select_variant',
'change_quantity',
'add_to_cart',
'buy_now',
],
'rules' => [
'user_quota_reached' => [
'effect' => 'restrict',
'denied_actions' => [
'select_variant',
'change_quantity',
'add_to_cart',
'buy_now',
],
],
'out_of_stock' => [
'effect' => 'hide',
],
'requested_quantity_exceeds_user_quota' => [
'effect' => 'restrict',
'denied_actions' => [
'add_to_cart',
'buy_now',
],
],
],
],
]; ];

View File

@@ -1,53 +0,0 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
Schema::table('catalog_items', function (Blueprint $table): void {
$table->unsignedInteger('group_order')->default(0)->after('nombre');
});
$footballOrder = [
1 => [
'slugs' => ['camiseta', 'camiseta-oficial-fnfi'],
'names' => ['Camiseta', 'CAMISETA OFICIAL FNFI'],
],
2 => [
'slugs' => ['alojamiento', 'camping'],
'names' => ['Alojamiento', 'CAMPING'],
],
3 => [
'slugs' => ['abono'],
'names' => ['Abono', 'ABONO'],
],
4 => [
'slugs' => ['comida'],
'names' => ['Comida', 'COMIDA'],
],
];
foreach ($footballOrder as $order => $identifiers) {
DB::table('catalog_items')
->where('tenant_code', 'fiesta_futbol_infantil')
->where(function ($query) use ($identifiers): void {
$query
->whereIn('slug', $identifiers['slugs'])
->orWhereIn('nombre', $identifiers['names']);
})
->update(['group_order' => $order]);
}
}
public function down(): void
{
Schema::table('catalog_items', function (Blueprint $table): void {
$table->dropColumn('group_order');
});
}
};

View File

@@ -1,180 +0,0 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
Schema::rename('stock_reservations', 'stock_reservation_lines');
Schema::create('stock_reservations', function (Blueprint $table): void {
$table->id();
$table->string('status')->default('active');
$table->dateTime('expires_at')->nullable();
$table->dateTime('committed_at')->nullable();
$table->dateTime('released_at')->nullable();
$table->dateTime('expired_at')->nullable();
$table->string('release_reason')->nullable();
$table->timestamps();
$table->index(['status', 'expires_at']);
});
Schema::table('stock_reservation_lines', function (Blueprint $table): void {
$table->foreignId('stock_reservation_id')->nullable()->after('id');
$table->boolean('tracks_inventory')->default(true)->after('quantity');
});
Schema::table('carritos', function (Blueprint $table): void {
$table->foreignId('current_stock_reservation_id')->nullable()->after('current_purchase_id');
});
Schema::table('compras', function (Blueprint $table): void {
$table->foreignId('stock_reservation_id')->nullable()->after('cart_id');
});
$cartIdsByItem = DB::table('carrito_items')->pluck('cart_id', 'id');
$unlimitedInventoryIds = DB::table('catalog_items')
->where('inventory_policy', 'unlimited')
->whereNotNull('inventory_id')
->pluck('inventory_id')
->merge(
DB::table('variantes')
->join('catalog_items', 'catalog_items.id', '=', 'variantes.catalog_item_id')
->where('catalog_items.inventory_policy', 'unlimited')
->pluck('variantes.inventory_id'),
)
->map(fn ($id): int => (int) $id)
->unique();
$legacyRows = DB::table('stock_reservation_lines')->orderBy('id')->get();
$groups = $legacyRows->groupBy(function (object $row) use ($cartIdsByItem): string {
if ($row->purchase_id !== null) {
return 'purchase:'.$row->purchase_id;
}
$cartId = $row->cart_item_id === null ? null : $cartIdsByItem->get($row->cart_item_id);
return $cartId === null ? 'legacy:'.$row->id : 'cart:'.$cartId;
});
foreach ($groups as $key => $rows) {
$statuses = $rows->pluck('status');
$status = $statuses->contains('active')
? 'active'
: ($statuses->contains('committed')
? 'committed'
: ($statuses->contains('expired') ? 'expired' : 'released'));
$first = $rows->first();
$reservationId = DB::table('stock_reservations')->insertGetId([
'status' => $status,
'expires_at' => $status === 'active' ? $rows->pluck('expires_at')->filter()->max() : null,
'committed_at' => $status === 'committed' ? $rows->pluck('committed_at')->filter()->max() : null,
'released_at' => $status === 'released' ? $rows->pluck('released_at')->filter()->max() : null,
'expired_at' => $status === 'expired' ? $rows->pluck('released_at')->filter()->max() : null,
'release_reason' => null,
'created_at' => $first->created_at,
'updated_at' => $rows->pluck('updated_at')->filter()->max() ?? $first->updated_at,
]);
foreach ($rows->groupBy('inventory_id') as $inventoryRows) {
$line = $inventoryRows->first();
DB::table('stock_reservation_lines')->where('id', $line->id)->update([
'stock_reservation_id' => $reservationId,
'quantity' => $inventoryRows->sum('quantity'),
'tracks_inventory' => ! $unlimitedInventoryIds->contains((int) $line->inventory_id),
]);
DB::table('stock_reservation_lines')
->whereIn('id', $inventoryRows->pluck('id')->skip(1))
->delete();
}
if (str_starts_with($key, 'purchase:')) {
$purchaseId = (int) substr($key, strlen('purchase:'));
DB::table('compras')->where('id', $purchaseId)->update([
'stock_reservation_id' => $reservationId,
]);
$cartId = DB::table('compras')->where('id', $purchaseId)->value('cart_id');
$isCurrent = $cartId !== null
&& (int) DB::table('carritos')->where('id', $cartId)->value('current_purchase_id') === $purchaseId;
if ($status === 'active' && $isCurrent) {
DB::table('carritos')->where('id', $cartId)->update([
'current_stock_reservation_id' => $reservationId,
]);
}
} elseif (str_starts_with($key, 'cart:') && $status === 'active') {
DB::table('carritos')->where('id', (int) substr($key, strlen('cart:')))->update([
'current_stock_reservation_id' => $reservationId,
]);
}
}
if (DB::getDriverName() !== 'sqlite') {
Schema::table('stock_reservation_lines', function (Blueprint $table): void {
$table->dropForeign('stock_reservations_cart_item_id_foreign');
$table->dropForeign('stock_reservations_purchase_id_foreign');
$table->dropUnique('stock_reservations_cart_item_id_inventory_id_unique');
$table->dropIndex('stock_reservations_purchase_id_status_index');
$table->dropIndex('stock_reservations_status_expires_at_index');
});
}
Schema::table('stock_reservation_lines', function (Blueprint $table): void {
$table->unsignedBigInteger('stock_reservation_id')->nullable(false)->change();
$table->dropColumn([
'cart_item_id',
'purchase_id',
'status',
'expires_at',
'committed_at',
'released_at',
]);
$table->foreign('stock_reservation_id', 'reservation_lines_reservation_fk')
->references('id')
->on('stock_reservations')
->cascadeOnDelete();
$table->unique(
['stock_reservation_id', 'inventory_id'],
'reservation_lines_reservation_inventory_unique',
);
});
Schema::table('carritos', function (Blueprint $table): void {
$table->foreign('current_stock_reservation_id', 'carts_current_stock_reservation_fk')
->references('id')
->on('stock_reservations')
->nullOnDelete();
$table->unique('current_stock_reservation_id', 'carts_current_stock_reservation_unique');
});
Schema::table('compras', function (Blueprint $table): void {
$table->foreign('stock_reservation_id', 'purchases_stock_reservation_fk')
->references('id')
->on('stock_reservations')
->nullOnDelete();
$table->unique('stock_reservation_id', 'purchases_stock_reservation_unique');
});
}
public function down(): void
{
Schema::table('compras', function (Blueprint $table): void {
$table->dropUnique('purchases_stock_reservation_unique');
$table->dropForeign('purchases_stock_reservation_fk');
$table->dropColumn('stock_reservation_id');
});
Schema::table('carritos', function (Blueprint $table): void {
$table->dropUnique('carts_current_stock_reservation_unique');
$table->dropForeign('carts_current_stock_reservation_fk');
$table->dropColumn('current_stock_reservation_id');
});
Schema::dropIfExists('stock_reservation_lines');
Schema::dropIfExists('stock_reservations');
}
};

View File

@@ -78,7 +78,6 @@ class FiestaFutbolInfantilProductSeeder extends Seeder
$this->createProduct($tenant, [ $this->createProduct($tenant, [
'slug' => 'camiseta', 'slug' => 'camiseta',
'nombre' => 'Camiseta', 'nombre' => 'Camiseta',
'group_order' => 1,
'category_id' => $categories['merchandising']->id, 'category_id' => $categories['merchandising']->id,
'precio' => 18000, 'precio' => 18000,
'attribute_codes' => ['color', 'talle'], 'attribute_codes' => ['color', 'talle'],
@@ -93,7 +92,6 @@ class FiestaFutbolInfantilProductSeeder extends Seeder
$this->createProduct($tenant, [ $this->createProduct($tenant, [
'slug' => 'alojamiento', 'slug' => 'alojamiento',
'nombre' => 'Alojamiento', 'nombre' => 'Alojamiento',
'group_order' => 2,
'category_id' => $categories['alojamientos']->id, 'category_id' => $categories['alojamientos']->id,
'precio' => 35000, 'precio' => 35000,
'attribute_codes' => ['tipo_alojamiento'], 'attribute_codes' => ['tipo_alojamiento'],
@@ -106,7 +104,6 @@ class FiestaFutbolInfantilProductSeeder extends Seeder
$this->createProduct($tenant, [ $this->createProduct($tenant, [
'slug' => 'comida', 'slug' => 'comida',
'nombre' => 'Comida', 'nombre' => 'Comida',
'group_order' => 4,
'category_id' => $categories['comidas']->id, 'category_id' => $categories['comidas']->id,
'precio' => 4000, 'precio' => 4000,
'attribute_codes' => ['event_date', 'horario', 'servicio'], 'attribute_codes' => ['event_date', 'horario', 'servicio'],
@@ -129,7 +126,6 @@ class FiestaFutbolInfantilProductSeeder extends Seeder
$this->createProduct($tenant, [ $this->createProduct($tenant, [
'slug' => 'abono', 'slug' => 'abono',
'nombre' => 'Abono', 'nombre' => 'Abono',
'group_order' => 3,
'category_id' => $categories['entradas']->id, 'category_id' => $categories['entradas']->id,
'precio' => 40000, 'precio' => 40000,
'has_tickets' => true, 'has_tickets' => true,

View File

@@ -15,7 +15,7 @@ Artisan::command('reservations:expire', function (): void {
$expired = app(ExpireStockReservationsService::class)->expireOverdue(); $expired = app(ExpireStockReservationsService::class)->expireOverdue();
$this->info("Expired purchases: {$expired['purchases']}"); $this->info("Expired purchases: {$expired['purchases']}");
$this->info("Expired cart reservations: {$expired['cart_reservations']}"); $this->info("Expired cart items: {$expired['cart_items']}");
})->purpose('Release expired stock reservations from purchases and abandoned carts'); })->purpose('Release expired stock reservations from purchases and abandoned carts');
Schedule::command('reservations:expire') Schedule::command('reservations:expire')

View File

@@ -5,12 +5,10 @@ namespace Tests\Feature\Cart;
use App\Domains\Attachable\Enums\AttachmentType; use App\Domains\Attachable\Enums\AttachmentType;
use App\Domains\Attachable\Models\Attachment; use App\Domains\Attachable\Models\Attachment;
use App\Domains\Auth\Models\User; use App\Domains\Auth\Models\User;
use App\Domains\Cart\Models\Cart;
use App\Domains\Catalog\Enums\InventoryPolicy; use App\Domains\Catalog\Enums\InventoryPolicy;
use App\Domains\Catalog\Models\CatalogItem; use App\Domains\Catalog\Models\CatalogItem;
use App\Domains\Catalog\Models\Inventory; use App\Domains\Catalog\Models\Inventory;
use App\Domains\Catalog\Models\Variant; use App\Domains\Catalog\Models\Variant;
use App\Domains\Catalog\Services\CatalogService;
use App\Domains\Purchase\Models\Purchase; use App\Domains\Purchase\Models\Purchase;
use App\Domains\Purchase\Models\PurchaseItem; use App\Domains\Purchase\Models\PurchaseItem;
use App\Domains\Tenant\Models\Tenant; use App\Domains\Tenant\Models\Tenant;
@@ -30,80 +28,6 @@ class CartControllerTest extends TestCase
])); ]));
$this->assertFalse(Schema::hasColumn('carrito_items', 'buyable_type')); $this->assertFalse(Schema::hasColumn('carrito_items', 'buyable_type'));
$this->assertFalse(Schema::hasColumn('carrito_items', 'buyable_id')); $this->assertFalse(Schema::hasColumn('carrito_items', 'buyable_id'));
$this->assertTrue(Schema::hasColumns('stock_reservations', [
'status',
'expires_at',
'committed_at',
'released_at',
'expired_at',
'release_reason',
]));
$this->assertFalse(Schema::hasColumn('stock_reservations', 'quantity'));
$this->assertTrue(Schema::hasColumns('stock_reservation_lines', [
'stock_reservation_id',
'inventory_id',
'quantity',
'tracks_inventory',
]));
$this->assertTrue(Schema::hasColumn('carritos', 'current_stock_reservation_id'));
$this->assertTrue(Schema::hasColumn('compras', 'stock_reservation_id'));
}
public function test_it_aggregates_shared_inventory_into_one_cart_reservation_line(): void
{
$tenant = $this->createTenant('acme');
$firstItem = $this->createDirectItem($tenant, 10, '10.00');
$secondItem = app(CatalogService::class)->create([
'tenant_code' => $tenant->codigo,
'type' => 'bundle',
'slug' => 'second-shared-item',
'nombre' => 'Second shared item',
'precio' => '20.00',
'components' => [[
'catalog_item_id' => $firstItem->id,
'quantity' => 1,
]],
]);
$firstResponse = $this->postJson('/api/tenants/acme/cart/items', [
'catalog_item_id' => $firstItem->id,
'cantidad' => 2,
])->assertOk();
$guestToken = $firstResponse->getCookie('guest_token', false)?->getValue();
$this->call(
'POST',
'/api/tenants/acme/cart/items',
[],
['guest_token' => $guestToken],
[],
['HTTP_Accept' => 'application/json', 'CONTENT_TYPE' => 'application/json'],
json_encode([
'catalog_item_id' => $secondItem->id,
'cantidad' => 3,
]),
)->assertOk();
$reservationId = (int) $firstResponse->json('data.id');
$reservationId = (int) Cart::query()
->findOrFail($reservationId)
->current_stock_reservation_id;
$this->assertDatabaseCount('stock_reservations', 1);
$this->assertDatabaseHas('stock_reservations', [
'id' => $reservationId,
'status' => 'active',
]);
$this->assertDatabaseHas('stock_reservation_lines', [
'stock_reservation_id' => $reservationId,
'inventory_id' => $firstItem->inventory_id,
'quantity' => 5,
]);
$this->assertDatabaseCount('stock_reservation_lines', 1);
$this->assertDatabaseHas('inventories', [
'id' => $firstItem->inventory_id,
'reserved_stock' => 5,
]);
} }
public function test_it_adds_a_catalog_item_without_a_variant(): void public function test_it_adds_a_catalog_item_without_a_variant(): void
@@ -150,11 +74,9 @@ class CartControllerTest extends TestCase
'id' => $item->inventory_id, 'id' => $item->inventory_id,
'reserved_stock' => 2, 'reserved_stock' => 2,
]); ]);
$this->assertDatabaseHas('stock_reservation_lines', [ $this->assertDatabaseHas('stock_reservations', [
'inventory_id' => $item->inventory_id, 'inventory_id' => $item->inventory_id,
'quantity' => 2, 'quantity' => 2,
]);
$this->assertDatabaseHas('stock_reservations', [
'status' => 'active', 'status' => 'active',
]); ]);
} }
@@ -174,18 +96,16 @@ class CartControllerTest extends TestCase
])->assertOk(); ])->assertOk();
$this->assertDatabaseHas('stock_reservations', [ $this->assertDatabaseHas('stock_reservations', [
'status' => 'active',
'expires_at' => $now->copy()->addMinutes(45)->toDateTimeString(),
]);
$this->assertDatabaseHas('stock_reservation_lines', [
'inventory_id' => $item->inventory_id, 'inventory_id' => $item->inventory_id,
'quantity' => 2, 'quantity' => 2,
'status' => 'active',
'expires_at' => $now->copy()->addMinutes(45)->toDateTimeString(),
]); ]);
$this->travelBack(); $this->travelBack();
} }
public function test_it_expires_abandoned_cart_reservations_without_deleting_the_cart(): void public function test_it_expires_abandoned_cart_reservations_and_removes_empty_carts(): void
{ {
config()->set('catalog.stock_reservation_expiration_minutes', 30); config()->set('catalog.stock_reservation_expiration_minutes', 30);
$tenant = $this->createTenant('acme'); $tenant = $this->createTenant('acme');
@@ -200,14 +120,14 @@ class CartControllerTest extends TestCase
$this->artisan('reservations:expire') $this->artisan('reservations:expire')
->expectsOutput('Expired purchases: 0') ->expectsOutput('Expired purchases: 0')
->expectsOutput('Expired cart reservations: 0') ->expectsOutput('Expired cart items: 0')
->assertSuccessful(); ->assertSuccessful();
$this->travel(31)->minutes(); $this->travel(31)->minutes();
$this->artisan('reservations:expire') $this->artisan('reservations:expire')
->expectsOutput('Expired purchases: 0') ->expectsOutput('Expired purchases: 0')
->expectsOutput('Expired cart reservations: 1') ->expectsOutput('Expired cart items: 1')
->assertSuccessful(); ->assertSuccessful();
$this->assertDatabaseHas('inventories', [ $this->assertDatabaseHas('inventories', [
@@ -215,25 +135,23 @@ class CartControllerTest extends TestCase
'real_stock' => 10, 'real_stock' => 10,
'reserved_stock' => 0, 'reserved_stock' => 0,
]); ]);
$this->assertDatabaseHas('carrito_items', ['id' => $cartItemId]); $this->assertDatabaseMissing('carrito_items', ['id' => $cartItemId]);
$this->assertDatabaseHas('carritos', [ $this->assertSoftDeleted('carritos', [
'id' => $cartId, 'id' => $cartId,
'status' => 'active', 'status' => 'expired',
'current_stock_reservation_id' => null,
'deleted_at' => null,
]); ]);
$this->assertDatabaseHas('stock_reservations', [ $this->assertDatabaseHas('stock_reservations', [
'inventory_id' => $item->inventory_id,
'cart_item_id' => null,
'purchase_id' => null,
'quantity' => 0,
'status' => 'expired', 'status' => 'expired',
'expires_at' => null, 'expires_at' => null,
]); ]);
$this->assertDatabaseHas('stock_reservation_lines', [
'inventory_id' => $item->inventory_id,
'quantity' => 2,
]);
$this->artisan('reservations:expire') $this->artisan('reservations:expire')
->expectsOutput('Expired purchases: 0') ->expectsOutput('Expired purchases: 0')
->expectsOutput('Expired cart reservations: 0') ->expectsOutput('Expired cart items: 0')
->assertSuccessful(); ->assertSuccessful();
$this->travelBack(); $this->travelBack();
@@ -294,11 +212,10 @@ class CartControllerTest extends TestCase
'id' => $variant->inventory_id, 'id' => $variant->inventory_id,
'reserved_stock' => 5, 'reserved_stock' => 5,
]); ]);
$this->assertDatabaseHas('stock_reservation_lines', [ $this->assertDatabaseHas('stock_reservations', [
'cart_item_id' => $response->json('data.items.0.id'),
'inventory_id' => $variant->inventory_id, 'inventory_id' => $variant->inventory_id,
'quantity' => 5, 'quantity' => 5,
]);
$this->assertDatabaseHas('stock_reservations', [
'status' => 'active', 'status' => 'active',
]); ]);
} }
@@ -312,7 +229,6 @@ class CartControllerTest extends TestCase
$this->createPurchaseItem($tenant, $user, $item, 1); $this->createPurchaseItem($tenant, $user, $item, 1);
$this->actingAs($user, 'sanctum') $this->actingAs($user, 'sanctum')
->withHeader('Accept-Language', 'es')
->postJson('/api/tenants/acme/cart/items', [ ->postJson('/api/tenants/acme/cart/items', [
'catalog_item_id' => $item->id, 'catalog_item_id' => $item->id,
'cantidad' => 2, 'cantidad' => 2,
@@ -321,7 +237,6 @@ class CartControllerTest extends TestCase
->assertJsonPath('data.items.0.cantidad', 2); ->assertJsonPath('data.items.0.cantidad', 2);
$this->actingAs($user, 'sanctum') $this->actingAs($user, 'sanctum')
->withHeader('Accept-Language', 'es')
->postJson('/api/tenants/acme/cart/items', [ ->postJson('/api/tenants/acme/cart/items', [
'catalog_item_id' => $item->id, 'catalog_item_id' => $item->id,
'cantidad' => 2, 'cantidad' => 2,
@@ -331,7 +246,7 @@ class CartControllerTest extends TestCase
->assertJsonPath('code', 'purchase.limit_exceeded') ->assertJsonPath('code', 'purchase.limit_exceeded')
->assertJsonPath('catalog_item_id', $item->id) ->assertJsonPath('catalog_item_id', $item->id)
->assertJsonPath('catalog_item_name', $item->nombre) ->assertJsonPath('catalog_item_name', $item->nombre)
->assertJsonPath('maximum_addable_quantity', 1) ->assertJsonPath('availability.maximum_quantity', 1)
->assertJsonPath( ->assertJsonPath(
'message', 'message',
"Podés agregar hasta 1 unidad más de “{$item->nombre}”.", "Podés agregar hasta 1 unidad más de “{$item->nombre}”.",
@@ -466,12 +381,10 @@ class CartControllerTest extends TestCase
'reserved_stock' => 0, 'reserved_stock' => 0,
]); ]);
$this->assertDatabaseHas('stock_reservations', [ $this->assertDatabaseHas('stock_reservations', [
'status' => 'released', 'cart_item_id' => null,
'release_reason' => 'cart_empty',
]);
$this->assertDatabaseHas('stock_reservation_lines', [
'inventory_id' => $variant->inventory_id, 'inventory_id' => $variant->inventory_id,
'quantity' => 5, 'quantity' => 0,
'status' => 'released',
]); ]);
} }

View File

@@ -267,7 +267,7 @@ class BundleCatalogItemTest extends TestCase
$this->getJson("/api/tenants/{$this->tenant->codigo}/catalog-items/{$bundleId}") $this->getJson("/api/tenants/{$this->tenant->codigo}/catalog-items/{$bundleId}")
->assertOk() ->assertOk()
->assertJsonPath('data.type', CatalogItemType::Bundle->value) ->assertJsonPath('data.type', CatalogItemType::Bundle->value)
->assertJsonPath('data.maximum_addable_quantity', 4) ->assertJsonPath('data.availability.maximum_quantity', 4)
->assertJsonMissingPath('data.stock_tecnico') ->assertJsonMissingPath('data.stock_tecnico')
->assertJsonCount(1, 'data.components') ->assertJsonCount(1, 'data.components')
->assertJsonPath('data.components.0.catalog_item_id', $component->id) ->assertJsonPath('data.components.0.catalog_item_id', $component->id)

View File

@@ -41,7 +41,7 @@ class CatalogControllerTest extends TestCase
$directItem = $this->createItem($tenant, 'Direct', $directInventory); $directItem = $this->createItem($tenant, 'Direct', $directInventory);
$row->featuredItems()->create(['catalog_item_id' => $directItem->id]); $row->featuredItems()->create(['catalog_item_id' => $directItem->id]);
$variantItem = $this->createItem($tenant, 'Variants'); $variantItem = $this->createItem($tenant, 'Variants', withoutInventory: true);
$firstInventory = Inventory::query()->create([ $firstInventory = Inventory::query()->create([
'real_stock' => 5, 'real_stock' => 5,
'reserved_stock' => 1, 'reserved_stock' => 1,
@@ -56,7 +56,7 @@ class CatalogControllerTest extends TestCase
]); ]);
$variantItem->variants()->create(['inventory_id' => $firstInventory->id]); $variantItem->variants()->create(['inventory_id' => $firstInventory->id]);
$variantItem->variants()->create(['inventory_id' => $secondInventory->id]); $variantItem->variants()->create(['inventory_id' => $secondInventory->id]);
$unavailableVariant = $variantItem->variants()->create([ $variantItem->variants()->create([
'inventory_id' => $unavailableInventory->id, 'inventory_id' => $unavailableInventory->id,
]); ]);
$cart->featuredItems()->create(['catalog_item_id' => $variantItem->id]); $cart->featuredItems()->create(['catalog_item_id' => $variantItem->id]);
@@ -72,19 +72,16 @@ class CatalogControllerTest extends TestCase
->assertJsonPath('0.items.0.nombre', 'Variants') ->assertJsonPath('0.items.0.nombre', 'Variants')
->assertJsonPath('0.items.0.descripcion', 'Variants description') ->assertJsonPath('0.items.0.descripcion', 'Variants description')
->assertJsonPath('0.items.0.precio', '100.00') ->assertJsonPath('0.items.0.precio', '100.00')
->assertJsonPath('0.items.0.maximum_addable_quantity', 7) ->assertJsonPath('0.items.0.availability.state', 'visible')
->assertJsonPath('0.items.0.availability.maximum_quantity', 7)
->assertJsonCount(2, '0.items.0.variants') ->assertJsonCount(2, '0.items.0.variants')
->assertJsonPath('0.items.0.variants.0.maximum_addable_quantity', 4) ->assertJsonPath('0.items.0.variants.0.availability.maximum_quantity', 4)
->assertJsonPath('0.items.0.variants.1.maximum_addable_quantity', 3) ->assertJsonPath('0.items.0.variants.0.availability.state', 'visible')
->assertJsonPath('0.items.0.variants.1.availability.maximum_quantity', 3)
->assertJsonPath('1.title', 'Row') ->assertJsonPath('1.title', 'Row')
->assertJsonPath('1.items.data.0.maximum_addable_quantity', 8) ->assertJsonPath('1.items.data.0.availability.maximum_quantity', 8)
->assertJsonMissingPath('1.items.data.0.stock_tecnico') ->assertJsonMissingPath('1.items.data.0.stock_tecnico')
->assertJsonCount(0, '1.items.data.0.variants'); ->assertJsonCount(0, '1.items.data.0.variants');
$this->assertNotContains(
$unavailableVariant->id,
collect($response->json('0.items.0.variants'))->pluck('id')->all(),
);
} }
public function test_maximum_addable_quantity_shares_the_authenticated_user_quota_between_variants(): void public function test_maximum_addable_quantity_shares_the_authenticated_user_quota_between_variants(): void
@@ -97,7 +94,7 @@ class CatalogControllerTest extends TestCase
groupLayout: GroupLayout::Simple, groupLayout: GroupLayout::Simple,
); );
$user = User::factory()->create(); $user = User::factory()->create();
$item = $this->createItem($tenant, 'Limited variants'); $item = $this->createItem($tenant, 'Limited variants', withoutInventory: true);
$item->update(['max_units_per_user' => 3]); $item->update(['max_units_per_user' => 3]);
$firstVariant = $item->variants()->create([ $firstVariant = $item->variants()->create([
'inventory_id' => Inventory::query()->create(['real_stock' => 10])->id, 'inventory_id' => Inventory::query()->create(['real_stock' => 10])->id,
@@ -118,21 +115,21 @@ class CatalogControllerTest extends TestCase
$this->actingAs($user, 'sanctum') $this->actingAs($user, 'sanctum')
->getJson("/api/tenants/{$tenant->codigo}/catalog") ->getJson("/api/tenants/{$tenant->codigo}/catalog")
->assertOk() ->assertOk()
->assertJsonPath('0.items.0.variants.0.maximum_addable_quantity', 0) ->assertJsonPath('0.items.0.availability.maximum_quantity', 0)
->assertJsonPath('0.items.0.variants.1.maximum_addable_quantity', 0) ->assertJsonPath('0.items.0.availability.allowed_actions', [])
->assertJsonPath( ->assertJsonPath(
'0.items.0.variants.0.unavailable_message', '0.items.0.availability.reasons.0.message',
'Alcanzaste el cupo máximo permitido para este producto.',
)
->assertJsonPath(
'0.items.0.variants.1.unavailable_message',
'Alcanzaste el cupo máximo permitido para este producto.', 'Alcanzaste el cupo máximo permitido para este producto.',
) )
->assertJsonPath('0.items.0.variants.0.availability.maximum_quantity', 8)
->assertJsonPath('0.items.0.variants.1.availability.maximum_quantity', 9)
->assertJsonCount(0, '0.items.0.variants.0.availability.reasons')
->assertJsonCount(0, '0.items.0.variants.1.availability.reasons')
->assertJsonMissingPath('0.items.0.variants.0.stock_tecnico') ->assertJsonMissingPath('0.items.0.variants.0.stock_tecnico')
->assertJsonMissingPath('0.items.0.variants.1.stock_tecnico'); ->assertJsonMissingPath('0.items.0.variants.1.stock_tecnico');
} }
public function test_it_excludes_out_of_stock_items(): void public function test_it_hides_out_of_stock_items_before_building_the_group_response(): void
{ {
$tenant = $this->createTenant('catalog-available-variants'); $tenant = $this->createTenant('catalog-available-variants');
$group = $this->createGroup( $group = $this->createGroup(
@@ -142,7 +139,7 @@ class CatalogControllerTest extends TestCase
groupLayout: GroupLayout::SimpleVertical, groupLayout: GroupLayout::SimpleVertical,
); );
$unavailableItem = $this->createItem($tenant, 'Unavailable'); $unavailableItem = $this->createItem($tenant, 'Unavailable', withoutInventory: true);
$unavailableInventory = Inventory::query()->create([ $unavailableInventory = Inventory::query()->create([
'real_stock' => 4, 'real_stock' => 4,
'reserved_stock' => 4, 'reserved_stock' => 4,
@@ -150,7 +147,7 @@ class CatalogControllerTest extends TestCase
$unavailableItem->variants()->create(['inventory_id' => $unavailableInventory->id]); $unavailableItem->variants()->create(['inventory_id' => $unavailableInventory->id]);
$group->featuredItems()->create(['catalog_item_id' => $unavailableItem->id]); $group->featuredItems()->create(['catalog_item_id' => $unavailableItem->id]);
$availableItem = $this->createItem($tenant, 'Available'); $availableItem = $this->createItem($tenant, 'Available', withoutInventory: true);
$availableInventory = Inventory::query()->create([ $availableInventory = Inventory::query()->create([
'real_stock' => 4, 'real_stock' => 4,
'reserved_stock' => 3, 'reserved_stock' => 3,
@@ -162,8 +159,7 @@ class CatalogControllerTest extends TestCase
->assertOk() ->assertOk()
->assertJsonCount(1, '0.items') ->assertJsonCount(1, '0.items')
->assertJsonPath('0.items.0.nombre', 'Available') ->assertJsonPath('0.items.0.nombre', 'Available')
->assertJsonPath('0.items.0.unavailable_message', null) ->assertJsonCount(0, '0.items.0.availability.reasons');
->assertJsonMissing(['nombre' => 'Unavailable']);
} }
public function test_column_with_image_uses_item_image_then_variant_image_then_null(): void public function test_column_with_image_uses_item_image_then_variant_image_then_null(): void
@@ -180,8 +176,8 @@ class CatalogControllerTest extends TestCase
'order' => 0, 'order' => 0,
]); ]);
$variantItem = $this->createItem($tenant, 'Variant image'); $variantItem = $this->createItem($tenant, 'Variant image', withoutInventory: true);
$variantInventory = Inventory::query()->create(); $variantInventory = Inventory::query()->create(['real_stock' => 1]);
$variant = $variantItem->variants()->create(['inventory_id' => $variantInventory->id]); $variant = $variantItem->variants()->create(['inventory_id' => $variantInventory->id]);
$variantImage = $this->createAttachment('variant'); $variantImage = $this->createAttachment('variant');
$variant->attachments()->attach($variantImage, ['orden' => 0]); $variant->attachments()->attach($variantImage, ['orden' => 0]);
@@ -348,10 +344,8 @@ class CatalogControllerTest extends TestCase
]); ]);
$food = $this->createItem($tenant, 'Hamburger'); $food = $this->createItem($tenant, 'Hamburger');
$food->update(['group_order' => 2]);
$food->category()->associate($category)->save(); $food->category()->associate($category)->save();
$parking = $this->createItem($tenant, 'Parking'); $this->createItem($tenant, 'Parking');
$parking->update(['group_order' => 1]);
$this->getJson("/api/tenants/{$tenant->codigo}/catalog") $this->getJson("/api/tenants/{$tenant->codigo}/catalog")
->assertOk() ->assertOk()
@@ -360,9 +354,6 @@ class CatalogControllerTest extends TestCase
->assertJsonPath('0.items.0.nombre', 'Hamburger') ->assertJsonPath('0.items.0.nombre', 'Hamburger')
->assertJsonPath('1.title', 'All products') ->assertJsonPath('1.title', 'All products')
->assertJsonCount(2, '1.items.data') ->assertJsonCount(2, '1.items.data')
->assertJsonPath('1.items.data.0.nombre', 'Parking')
->assertJsonPath('1.items.data.1.nombre', 'Hamburger')
->assertJsonMissingPath('1.items.data.0.group_order')
->assertJsonPath('1.items.meta.total', 2); ->assertJsonPath('1.items.meta.total', 2);
} }
@@ -433,7 +424,12 @@ class CatalogControllerTest extends TestCase
Tenant $tenant, Tenant $tenant,
string $name, string $name,
?Inventory $inventory = null, ?Inventory $inventory = null,
bool $withoutInventory = false,
): CatalogItem { ): CatalogItem {
$inventory ??= $withoutInventory
? null
: Inventory::query()->create(['real_stock' => 10]);
return CatalogItem::query()->create([ return CatalogItem::query()->create([
'tenant_code' => $tenant->codigo, 'tenant_code' => $tenant->codigo,
'inventory_id' => $inventory?->id, 'inventory_id' => $inventory?->id,

View File

@@ -31,7 +31,6 @@ class CatalogItemControllerTest extends TestCase
$response = $this->postJson("/api/tenants/{$tenant->codigo}/catalog-items", [ $response = $this->postJson("/api/tenants/{$tenant->codigo}/catalog-items", [
'slug' => 'shirt', 'slug' => 'shirt',
'nombre' => 'Shirt', 'nombre' => 'Shirt',
'group_order' => 7,
'precio' => 100, 'precio' => 100,
'max_units_per_user' => 4, 'max_units_per_user' => 4,
'attribute_codes' => [$attribute->codigo], 'attribute_codes' => [$attribute->codigo],
@@ -48,7 +47,6 @@ class CatalogItemControllerTest extends TestCase
$response $response
->assertCreated() ->assertCreated()
->assertJsonPath('data.nombre', 'Shirt') ->assertJsonPath('data.nombre', 'Shirt')
->assertJsonMissingPath('data.group_order')
->assertJsonPath('data.max_units_per_user', 4) ->assertJsonPath('data.max_units_per_user', 4)
->assertJsonCount(2, 'data.images') ->assertJsonCount(2, 'data.images')
->assertJsonCount(1, 'data.variants') ->assertJsonCount(1, 'data.variants')
@@ -59,7 +57,6 @@ class CatalogItemControllerTest extends TestCase
$this->assertSame([0, 1], $item->attachments()->get()->pluck('pivot.orden')->all()); $this->assertSame([0, 1], $item->attachments()->get()->pluck('pivot.orden')->all());
$this->assertSame(4, $item->max_units_per_user); $this->assertSame(4, $item->max_units_per_user);
$this->assertSame(7, $item->group_order);
$this->assertSame([0], $variant->attachments()->get()->pluck('pivot.orden')->all()); $this->assertSame([0], $variant->attachments()->get()->pluck('pivot.orden')->all());
$this->assertDatabaseHas('catalog_items_attachments', [ $this->assertDatabaseHas('catalog_items_attachments', [
'catalog_item_id' => $item->id, 'catalog_item_id' => $item->id,

View File

@@ -40,7 +40,7 @@ class CatalogItemDetailControllerTest extends TestCase
$response $response
->assertOk() ->assertOk()
->assertJsonPath('data.maximum_addable_quantity', 7) ->assertJsonPath('data.availability.maximum_quantity', 7)
->assertJsonMissingPath('data.stock_tecnico') ->assertJsonMissingPath('data.stock_tecnico')
->assertJsonCount(0, 'data.variants') ->assertJsonCount(0, 'data.variants')
->assertJsonCount(1, 'data.images'); ->assertJsonCount(1, 'data.images');
@@ -48,7 +48,18 @@ class CatalogItemDetailControllerTest extends TestCase
$this->assertStringContainsString($itemImage->path, $response->json('data.images.0')); $this->assertStringContainsString($itemImage->path, $response->json('data.images.0'));
} }
public function test_it_omits_unavailable_variants_and_selects_the_first_available_one(): void public function test_it_does_not_return_an_out_of_stock_product_detail(): void
{
$tenant = $this->createTenant('detail-hidden');
$inventory = Inventory::query()->create(['real_stock' => 0]);
$item = $this->createItem($tenant, 'Hidden item', $inventory);
$this->getJson(
"/api/tenants/{$tenant->codigo}/catalog-items/{$item->id}",
)->assertNotFound();
}
public function test_it_hides_unavailable_variants_and_selects_the_first_available_one(): void
{ {
Storage::fake('s3'); Storage::fake('s3');
$tenant = $this->createTenant('detail-default'); $tenant = $this->createTenant('detail-default');
@@ -71,17 +82,14 @@ class CatalogItemDetailControllerTest extends TestCase
->assertOk() ->assertOk()
->assertJsonCount(1, 'data.variants') ->assertJsonCount(1, 'data.variants')
->assertJsonPath('data.variants.0.id', $secondVariant->id) ->assertJsonPath('data.variants.0.id', $secondVariant->id)
->assertJsonPath('data.variants.0.availability.state', 'visible')
->assertJsonPath('data.selected_variant.id', $secondVariant->id) ->assertJsonPath('data.selected_variant.id', $secondVariant->id)
->assertJsonPath('data.selected_variant.maximum_addable_quantity', 6) ->assertJsonPath('data.selected_variant.availability.maximum_quantity', 6)
->assertJsonMissingPath('data.selected_variant.stock_tecnico') ->assertJsonMissingPath('data.selected_variant.stock_tecnico')
->assertJsonCount(1, 'data.selected_variant.images'); ->assertJsonCount(1, 'data.selected_variant.images');
$response $response
->assertJsonMissingPath('data.stock_tecnico') ->assertJsonMissingPath('data.stock_tecnico')
->assertJsonMissingPath('data.images'); ->assertJsonMissingPath('data.images');
$this->assertNotContains(
$firstVariant->id,
collect($response->json('data.variants'))->pluck('id')->all(),
);
$this->assertStringContainsString($secondImage->path, $response->json('data.selected_variant.images.0')); $this->assertStringContainsString($secondImage->path, $response->json('data.selected_variant.images.0'));
$this->assertStringNotContainsString($firstImage->path, $response->json('data.selected_variant.images.0')); $this->assertStringNotContainsString($firstImage->path, $response->json('data.selected_variant.images.0'));
$this->assertStringNotContainsString($itemImage->path, $response->json('data.selected_variant.images.0')); $this->assertStringNotContainsString($itemImage->path, $response->json('data.selected_variant.images.0'));
@@ -91,19 +99,6 @@ class CatalogItemDetailControllerTest extends TestCase
)->assertNotFound(); )->assertNotFound();
} }
public function test_it_does_not_return_an_out_of_stock_item(): void
{
$tenant = $this->createTenant('detail-out-of-stock');
$inventory = Inventory::query()->create([
'real_stock' => 5,
'reserved_stock' => 5,
]);
$item = $this->createItem($tenant, 'Sold out item', $inventory);
$this->getJson("/api/tenants/{$tenant->codigo}/catalog-items/{$item->id}")
->assertNotFound();
}
public function test_it_selects_the_requested_variant_and_lists_variant_values_and_stock(): void public function test_it_selects_the_requested_variant_and_lists_variant_values_and_stock(): void
{ {
Storage::fake('s3'); Storage::fake('s3');
@@ -144,11 +139,11 @@ class CatalogItemDetailControllerTest extends TestCase
$response $response
->assertOk() ->assertOk()
->assertJsonPath('data.variants.0.id', $firstVariant->id) ->assertJsonPath('data.variants.0.id', $firstVariant->id)
->assertJsonPath('data.variants.0.maximum_addable_quantity', 4) ->assertJsonPath('data.variants.0.availability.maximum_quantity', 4)
->assertJsonPath('data.variants.0.values.size.value', 'S') ->assertJsonPath('data.variants.0.values.size.value', 'S')
->assertJsonPath('data.variants.0.values.size.label', 'Small') ->assertJsonPath('data.variants.0.values.size.label', 'Small')
->assertJsonPath('data.variants.1.id', $secondVariant->id) ->assertJsonPath('data.variants.1.id', $secondVariant->id)
->assertJsonPath('data.variants.1.maximum_addable_quantity', 7) ->assertJsonPath('data.variants.1.availability.maximum_quantity', 7)
->assertJsonPath('data.variants.1.values.size.value', 'M') ->assertJsonPath('data.variants.1.values.size.value', 'M')
->assertJsonPath('data.variants.1.values.size.label', 'Medium') ->assertJsonPath('data.variants.1.values.size.label', 'Medium')
->assertJsonPath('data.attributes.0.codigo', 'size') ->assertJsonPath('data.attributes.0.codigo', 'size')
@@ -156,7 +151,7 @@ class CatalogItemDetailControllerTest extends TestCase
->assertJsonPath('data.attributes.0.options.1.value', 'M') ->assertJsonPath('data.attributes.0.options.1.value', 'M')
->assertJsonCount(2, 'data.attributes.0.options') ->assertJsonCount(2, 'data.attributes.0.options')
->assertJsonPath('data.selected_variant.id', $secondVariant->id) ->assertJsonPath('data.selected_variant.id', $secondVariant->id)
->assertJsonPath('data.selected_variant.maximum_addable_quantity', 7) ->assertJsonPath('data.selected_variant.availability.maximum_quantity', 7)
->assertJsonPath('data.selected_variant.values.size.value', 'M') ->assertJsonPath('data.selected_variant.values.size.value', 'M')
->assertJsonPath('data.selected_variant.values.size.label', 'Medium') ->assertJsonPath('data.selected_variant.values.size.label', 'Medium')
->assertJsonCount(1, 'data.selected_variant.images'); ->assertJsonCount(1, 'data.selected_variant.images');
@@ -196,9 +191,9 @@ class CatalogItemDetailControllerTest extends TestCase
$this->getJson("/api/tenants/{$tenant->codigo}/catalog-items/{$item->id}") $this->getJson("/api/tenants/{$tenant->codigo}/catalog-items/{$item->id}")
->assertOk() ->assertOk()
->assertJsonPath('data.selected_variant.id', $variant->id) ->assertJsonPath('data.selected_variant.id', $variant->id)
->assertJsonPath('data.selected_variant.maximum_addable_quantity', null) ->assertJsonPath('data.selected_variant.availability.maximum_quantity', null)
->assertJsonMissingPath('data.stock_tecnico') ->assertJsonMissingPath('data.stock_tecnico')
->assertJsonPath('data.variants.0.maximum_addable_quantity', null) ->assertJsonPath('data.variants.0.availability.maximum_quantity', null)
->assertJsonMissingPath('data.selected_variant.stock_tecnico') ->assertJsonMissingPath('data.selected_variant.stock_tecnico')
->assertJsonMissingPath('data.variants.0.stock_tecnico'); ->assertJsonMissingPath('data.variants.0.stock_tecnico');
} }
@@ -365,6 +360,9 @@ class CatalogItemDetailControllerTest extends TestCase
->assertJsonPath('data.resolved_variant', null) ->assertJsonPath('data.resolved_variant', null)
->assertJsonCount(3, 'data.variants') ->assertJsonCount(3, 'data.variants')
->assertJsonPath('data.variants.0.id', $first->id) ->assertJsonPath('data.variants.0.id', $first->id)
->assertJsonPath('data.variants.0.availability.state', 'visible')
->assertJsonPath('data.variants.0.availability.maximum_quantity', 1)
->assertJsonPath('data.variants.0.availability.allowed_actions.2', 'add_to_cart')
->assertJsonPath('data.variants.0.values.sector.value', 'A') ->assertJsonPath('data.variants.0.values.sector.value', 'A')
->assertJsonPath('data.variants.0.values.seat.value', '1') ->assertJsonPath('data.variants.0.values.seat.value', '1')
->assertJsonCount(2, 'data.selectors') ->assertJsonCount(2, 'data.selectors')
@@ -432,7 +430,9 @@ class CatalogItemDetailControllerTest extends TestCase
->assertOk() ->assertOk()
->assertJsonPath('data.selected_values.sector', 'VIP') ->assertJsonPath('data.selected_values.sector', 'VIP')
->assertJsonPath('data.selected_values.seat', 'A-12') ->assertJsonPath('data.selected_values.seat', 'A-12')
->assertJsonPath('data.resolved_variant.id', $variant->id); ->assertJsonPath('data.resolved_variant.id', $variant->id)
->assertJsonPath('data.resolved_variant.availability.state', 'hidden')
->assertJsonMissingPath('data.resolved_variant.availability.allowed_actions');
} }
private function createItem( private function createItem(

View File

@@ -62,24 +62,8 @@ class CatalogSearchTest extends TestCase
$this->createCatalogItem($tenant, "Running {$number}"); $this->createCatalogItem($tenant, "Running {$number}");
} }
$exactMatch = $this->createCatalogItem($tenant, 'Running'); $exactMatch = $this->createCatalogItem($tenant, 'Running');
$outOfStock = CatalogItem::query()->create([ $outOfStockMatch = $this->createCatalogItem($tenant, 'Running unavailable');
'tenant_code' => $tenant->codigo, $outOfStockMatch->inventory->update(['real_stock' => 0]);
'slug' => 'running-sold-out',
'nombre' => 'Running sold out',
'descripcion' => 'Running sold out description',
'precio' => 100,
]);
$outOfStock->variants()->create([
'inventory_id' => Inventory::query()->create(['real_stock' => 0])->id,
]);
CatalogItem::query()->create([
'tenant_code' => $tenant->codigo,
'inventory_id' => Inventory::query()->create(['real_stock' => 2, 'reserved_stock' => 2])->id,
'slug' => 'running-direct-sold-out',
'nombre' => 'Running direct sold out',
'descripcion' => 'Running direct sold out description',
'precio' => 100,
]);
$this->createCatalogItem($tenant, 'Unrelated'); $this->createCatalogItem($tenant, 'Unrelated');
$this->createCatalogItem($otherTenant, 'Running foreign'); $this->createCatalogItem($otherTenant, 'Running foreign');
@@ -94,8 +78,7 @@ class CatalogSearchTest extends TestCase
->assertJsonPath('meta.total', 6) ->assertJsonPath('meta.total', 6)
->assertJsonCount(4, 'data') ->assertJsonCount(4, 'data')
->assertJsonPath('data.0.id', $exactMatch->id) ->assertJsonPath('data.0.id', $exactMatch->id)
->assertJsonMissing(['nombre' => 'Running sold out']) ->assertJsonMissing(['nombre' => 'Running unavailable'])
->assertJsonMissing(['nombre' => 'Running direct sold out'])
->assertJsonMissing(['nombre' => 'Running foreign']) ->assertJsonMissing(['nombre' => 'Running foreign'])
->assertJsonMissing(['nombre' => 'Unrelated']); ->assertJsonMissing(['nombre' => 'Unrelated']);
} }

View File

@@ -29,17 +29,6 @@ class CategoryDetailTest extends TestCase
$this->createCatalogItem($tenant, $category, 'Remera C'); $this->createCatalogItem($tenant, $category, 'Remera C');
$firstItem = $this->createCatalogItem($tenant, $category, 'Remera A'); $firstItem = $this->createCatalogItem($tenant, $category, 'Remera A');
$secondItem = $this->createCatalogItem($tenant, $category, 'Remera B'); $secondItem = $this->createCatalogItem($tenant, $category, 'Remera B');
$outOfStock = CatalogItem::query()->create([
'tenant_code' => $tenant->codigo,
'category_id' => $category->id,
'slug' => 'remera-agotada',
'nombre' => 'Remera agotada',
'descripcion' => 'Sin stock',
'precio' => 100,
]);
$outOfStock->variants()->create([
'inventory_id' => Inventory::query()->create(['real_stock' => 0])->id,
]);
$this->createCatalogItem($tenant, $otherCategory, 'Pantalón'); $this->createCatalogItem($tenant, $otherCategory, 'Pantalón');
$this->getJson("/api/tenants/{$tenant->codigo}/categories/{$category->id}") $this->getJson("/api/tenants/{$tenant->codigo}/categories/{$category->id}")
@@ -55,7 +44,6 @@ class CategoryDetailTest extends TestCase
->assertJsonCount(2, 'data') ->assertJsonCount(2, 'data')
->assertJsonPath('data.0.id', $firstItem->id) ->assertJsonPath('data.0.id', $firstItem->id)
->assertJsonPath('data.1.id', $secondItem->id) ->assertJsonPath('data.1.id', $secondItem->id)
->assertJsonMissing(['nombre' => 'Remera agotada'])
->assertJsonMissing(['nombre' => 'Pantalón']); ->assertJsonMissing(['nombre' => 'Pantalón']);
} }

View File

@@ -198,16 +198,11 @@ class TelepagosWebhookTest extends TestCase
'compra_id' => $newerPurchase->id, 'compra_id' => $newerPurchase->id,
'cantidad' => 2, 'cantidad' => 2,
]); ]);
$newerReservationId = $newerPurchase->fresh()->stock_reservation_id;
$this->assertNotNull($newerReservationId);
$this->assertDatabaseHas('stock_reservations', [ $this->assertDatabaseHas('stock_reservations', [
'id' => $newerReservationId, 'purchase_id' => $newerPurchase->id,
'status' => 'active',
]);
$this->assertDatabaseHas('stock_reservation_lines', [
'stock_reservation_id' => $newerReservationId,
'inventory_id' => $variant->inventory_id, 'inventory_id' => $variant->inventory_id,
'quantity' => 2, 'quantity' => 2,
'status' => 'active',
]); ]);
$this->assertSoftDeleted('carritos', [ $this->assertSoftDeleted('carritos', [

View File

@@ -32,45 +32,6 @@ class StorePurchaseTest extends TestCase
Queue::fake(); Queue::fake();
} }
public function test_checkout_keeps_the_cart_reservation_and_refreshes_its_expiration(): void
{
config()->set('catalog.stock_reservation_expiration_minutes', 5);
config()->set('purchase.checkout_expiration_minutes', 30);
$now = now()->startOfSecond();
$this->travelTo($now);
$tenant = $this->createTenant('sonder', 'Sonder', 'sonder.com.ar');
$user = User::factory()->create();
$variant = $this->createVariantForTenant('sonder', 10, '50.00');
$cart = Cart::query()->create([
'tenant_codigo' => $tenant->codigo,
'user_id' => $user->id,
'status' => 'active',
]);
$cart->addItem($variant->catalog_item_id, $variant->id, 2);
$reservationId = $cart->fresh()->current_stock_reservation_id;
$this->assertDatabaseHas('stock_reservations', [
'id' => $reservationId,
'status' => 'active',
'expires_at' => $now->copy()->addMinutes(5)->toDateTimeString(),
]);
$this->travel(2)->minutes();
$purchase = app(CheckoutService::class)->startCheckout($tenant, $user->id, [
'cart_id' => $cart->id,
]);
$this->assertSame($reservationId, $purchase->stock_reservation_id);
$this->assertDatabaseHas('stock_reservations', [
'id' => $reservationId,
'status' => 'active',
'expires_at' => $now->copy()->addMinutes(32)->toDateTimeString(),
]);
$this->travelBack();
}
public function test_it_starts_checkout_from_cart_with_purchase_item_snapshots(): void public function test_it_starts_checkout_from_cart_with_purchase_item_snapshots(): void
{ {
$tenant = $this->createTenant('sonder', 'Sonder', 'sonder.com.ar'); $tenant = $this->createTenant('sonder', 'Sonder', 'sonder.com.ar');
@@ -158,7 +119,12 @@ class StorePurchaseTest extends TestCase
'precio_unitario' => '50.00', 'precio_unitario' => '50.00',
'total' => '100.00', 'total' => '100.00',
]); ]);
$this->assertPurchaseReservation($purchaseId, $inventory->id, 2, 'active'); $this->assertDatabaseHas('stock_reservations', [
'inventory_id' => $inventory->id,
'purchase_id' => $purchaseId,
'quantity' => 2,
'status' => 'active',
]);
$this->assertDatabaseHas('carritos', [ $this->assertDatabaseHas('carritos', [
'id' => $cartId, 'id' => $cartId,
'user_id' => $user->id, 'user_id' => $user->id,
@@ -202,7 +168,12 @@ class StorePurchaseTest extends TestCase
'id' => $cartId, 'id' => $cartId,
'current_purchase_id' => $replacementPurchaseId, 'current_purchase_id' => $replacementPurchaseId,
]); ]);
$this->assertPurchaseReservation($replacementPurchaseId, $inventory->id, 2, 'active'); $this->assertDatabaseHas('stock_reservations', [
'inventory_id' => $inventory->id,
'purchase_id' => $replacementPurchaseId,
'quantity' => 2,
'status' => 'active',
]);
$this->assertDatabaseHas('inventories', [ $this->assertDatabaseHas('inventories', [
'id' => $inventory->id, 'id' => $inventory->id,
'reserved_stock' => 2, 'reserved_stock' => 2,
@@ -256,7 +227,12 @@ class StorePurchaseTest extends TestCase
'precio_unitario' => '50.00', 'precio_unitario' => '50.00',
'total' => '150.00', 'total' => '150.00',
]); ]);
$this->assertPurchaseReservation($response->json('data.id'), $variant->inventory_id, 3, 'active'); $this->assertDatabaseHas('stock_reservations', [
'inventory_id' => $variant->inventory_id,
'purchase_id' => $response->json('data.id'),
'quantity' => 3,
'status' => 'active',
]);
$this->assertDatabaseHas('inventories', [ $this->assertDatabaseHas('inventories', [
'id' => $variant->inventory_id, 'id' => $variant->inventory_id,
'real_stock' => 10, 'real_stock' => 10,
@@ -268,7 +244,10 @@ class StorePurchaseTest extends TestCase
->assertOk() ->assertOk()
->assertJsonPath('data.status', Purchase::STATUS_CANCELLED); ->assertJsonPath('data.status', Purchase::STATUS_CANCELLED);
$this->assertPurchaseReservation($response->json('data.id'), $variant->inventory_id, 3, 'released'); $this->assertDatabaseHas('stock_reservations', [
'purchase_id' => $response->json('data.id'),
'status' => 'released',
]);
$this->assertDatabaseHas('inventories', [ $this->assertDatabaseHas('inventories', [
'id' => $variant->inventory_id, 'id' => $variant->inventory_id,
'real_stock' => 10, 'real_stock' => 10,
@@ -317,8 +296,18 @@ class StorePurchaseTest extends TestCase
'origin' => Cart::ORIGIN_DIRECT_CHECKOUT, 'origin' => Cart::ORIGIN_DIRECT_CHECKOUT,
]); ]);
$this->assertDatabaseCount('compra_items', 2); $this->assertDatabaseCount('compra_items', 2);
$this->assertPurchaseReservation($purchaseId, $firstVariant->inventory_id, 1, 'active'); $this->assertDatabaseHas('stock_reservations', [
$this->assertPurchaseReservation($purchaseId, $secondVariant->inventory_id, 1, 'active'); 'inventory_id' => $firstVariant->inventory_id,
'purchase_id' => $purchaseId,
'quantity' => 1,
'status' => 'active',
]);
$this->assertDatabaseHas('stock_reservations', [
'inventory_id' => $secondVariant->inventory_id,
'purchase_id' => $purchaseId,
'quantity' => 1,
'status' => 'active',
]);
$this->assertDatabaseHas('inventories', [ $this->assertDatabaseHas('inventories', [
'id' => $firstVariant->inventory_id, 'id' => $firstVariant->inventory_id,
'reserved_stock' => 1, 'reserved_stock' => 1,
@@ -405,7 +394,7 @@ class StorePurchaseTest extends TestCase
->assertJsonPath('code', 'purchase.limit_exceeded') ->assertJsonPath('code', 'purchase.limit_exceeded')
->assertJsonPath('catalog_item_id', $variant->catalog_item_id) ->assertJsonPath('catalog_item_id', $variant->catalog_item_id)
->assertJsonPath('catalog_item_name', $variant->catalogItem->nombre) ->assertJsonPath('catalog_item_name', $variant->catalogItem->nombre)
->assertJsonPath('maximum_addable_quantity', 1); ->assertJsonPath('availability.maximum_quantity', 1);
$this->actingAs($otherUser, 'sanctum') $this->actingAs($otherUser, 'sanctum')
->postJson('/api/tenants/sonder/compras/start-checkout', [ ->postJson('/api/tenants/sonder/compras/start-checkout', [
@@ -441,7 +430,7 @@ class StorePurchaseTest extends TestCase
$tenant = $this->createTenant('sonder', 'Sonder', 'sonder.com.ar'); $tenant = $this->createTenant('sonder', 'Sonder', 'sonder.com.ar');
$user = User::factory()->create(); $user = User::factory()->create();
$firstVariant = $this->createVariantForTenant('sonder', 20, '50.00'); $firstVariant = $this->createVariantForTenant('sonder', 20, '50.00');
$firstVariant->catalogItem->update(['max_units_per_user' => 4]); $firstVariant->catalogItem->update(['max_units_per_user' => 3]);
$secondInventory = Inventory::query()->create(['real_stock' => 20]); $secondInventory = Inventory::query()->create(['real_stock' => 20]);
$secondVariant = Variant::query()->create([ $secondVariant = Variant::query()->create([
'catalog_item_id' => $firstVariant->catalog_item_id, 'catalog_item_id' => $firstVariant->catalog_item_id,
@@ -454,7 +443,6 @@ class StorePurchaseTest extends TestCase
]); ]);
$cart->addItem($firstVariant->catalog_item_id, $firstVariant->id, 2); $cart->addItem($firstVariant->catalog_item_id, $firstVariant->id, 2);
$cart->addItem($secondVariant->catalog_item_id, $secondVariant->id, 2); $cart->addItem($secondVariant->catalog_item_id, $secondVariant->id, 2);
$firstVariant->catalogItem->update(['max_units_per_user' => 3]);
$this->actingAs($user, 'sanctum') $this->actingAs($user, 'sanctum')
->postJson('/api/tenants/sonder/compras/start-checkout', [ ->postJson('/api/tenants/sonder/compras/start-checkout', [
@@ -512,16 +500,11 @@ class StorePurchaseTest extends TestCase
'id' => $variant->inventory_id, 'id' => $variant->inventory_id,
'reserved_stock' => 3, 'reserved_stock' => 3,
]); ]);
$activeCart->refresh();
$this->assertNotNull($activeCart->current_stock_reservation_id);
$this->assertDatabaseHas('stock_reservations', [ $this->assertDatabaseHas('stock_reservations', [
'id' => $activeCart->current_stock_reservation_id, 'cart_item_id' => $cartItemId,
'status' => 'active', 'purchase_id' => null,
]);
$this->assertDatabaseHas('stock_reservation_lines', [
'stock_reservation_id' => $activeCart->current_stock_reservation_id,
'inventory_id' => $variant->inventory_id,
'quantity' => 3, 'quantity' => 3,
'status' => 'active',
]); ]);
$this->assertSame(1, $activeCart->items()->count()); $this->assertSame(1, $activeCart->items()->count());
} }
@@ -533,7 +516,6 @@ class StorePurchaseTest extends TestCase
$variant = $this->createVariantForTenant('sonder', 10, '50.00'); $variant = $this->createVariantForTenant('sonder', 10, '50.00');
$previousPurchase = $this->createCheckoutPurchase($user, 'sonder', $variant, 2); $previousPurchase = $this->createCheckoutPurchase($user, 'sonder', $variant, 2);
$cart = $previousPurchase->cart; $cart = $previousPurchase->cart;
$previousReservationId = $previousPurchase->stock_reservation_id;
$previousPurchase->update([ $previousPurchase->update([
'status' => Purchase::STATUS_PENDING_PAYMENT, 'status' => Purchase::STATUS_PENDING_PAYMENT,
@@ -556,13 +538,11 @@ class StorePurchaseTest extends TestCase
'id' => $cart->id, 'id' => $cart->id,
'current_purchase_id' => $currentPurchase->id, 'current_purchase_id' => $currentPurchase->id,
]); ]);
$this->assertNotSame($previousReservationId, $currentPurchase->stock_reservation_id);
$this->assertDatabaseHas('stock_reservations', [ $this->assertDatabaseHas('stock_reservations', [
'id' => $previousReservationId, 'purchase_id' => $currentPurchase->id,
'status' => 'released', 'quantity' => 2,
'release_reason' => 'purchase_superseded', 'status' => 'active',
]); ]);
$this->assertPurchaseReservation($currentPurchase->id, $variant->inventory_id, 2, 'active');
try { try {
app(CheckoutService::class)->confirmPaidPurchase($previousPurchase->fresh()); app(CheckoutService::class)->confirmPaidPurchase($previousPurchase->fresh());
@@ -576,7 +556,11 @@ class StorePurchaseTest extends TestCase
'reserved_stock' => 2, 'reserved_stock' => 2,
'sold_units' => 0, 'sold_units' => 0,
]); ]);
$this->assertPurchaseReservation($currentPurchase->id, $variant->inventory_id, 2, 'active'); $this->assertDatabaseHas('stock_reservations', [
'purchase_id' => $currentPurchase->id,
'quantity' => 2,
'status' => 'active',
]);
} }
public function test_removing_a_checkout_item_supersedes_the_purchase_and_restores_the_user_quota(): void public function test_removing_a_checkout_item_supersedes_the_purchase_and_restores_the_user_quota(): void
@@ -605,12 +589,11 @@ class StorePurchaseTest extends TestCase
'current_purchase_id' => null, 'current_purchase_id' => null,
]); ]);
$this->assertDatabaseHas('stock_reservations', [ $this->assertDatabaseHas('stock_reservations', [
'status' => 'released',
'release_reason' => 'purchase_superseded',
]);
$this->assertDatabaseHas('stock_reservation_lines', [
'inventory_id' => $variant->inventory_id, 'inventory_id' => $variant->inventory_id,
'quantity' => 2, 'cart_item_id' => null,
'purchase_id' => null,
'quantity' => 0,
'status' => 'released',
]); ]);
$this->assertDatabaseHas('inventories', [ $this->assertDatabaseHas('inventories', [
'id' => $variant->inventory_id, 'id' => $variant->inventory_id,
@@ -645,7 +628,7 @@ class StorePurchaseTest extends TestCase
]); ]);
$this->assertDatabaseHas('inventories', [ $this->assertDatabaseHas('inventories', [
'id' => $variant->inventory_id, 'id' => $variant->inventory_id,
'reserved_stock' => 0, 'reserved_stock' => 3,
]); ]);
$this->assertDatabaseHas('carritos', [ $this->assertDatabaseHas('carritos', [
'id' => $activeCart->id, 'id' => $activeCart->id,
@@ -654,7 +637,12 @@ class StorePurchaseTest extends TestCase
'current_purchase_id' => null, 'current_purchase_id' => null,
'deleted_at' => null, 'deleted_at' => null,
]); ]);
$this->assertPurchaseReservation($purchase->id, $variant->inventory_id, 3, 'expired'); $this->assertDatabaseHas('stock_reservations', [
'cart_item_id' => $cartItemId,
'purchase_id' => null,
'quantity' => 3,
'status' => 'active',
]);
$this->assertSame(1, $activeCart->items()->count()); $this->assertSame(1, $activeCart->items()->count());
} }
@@ -924,7 +912,10 @@ class StorePurchaseTest extends TestCase
'current_purchase_id' => null, 'current_purchase_id' => null,
'deleted_at' => null, 'deleted_at' => null,
]); ]);
$this->assertPurchaseReservation($purchase->id, $variant->inventory_id, 2, 'active'); $this->assertDatabaseHas('stock_reservations', [
'purchase_id' => $purchase->id,
'status' => 'active',
]);
} }
public function test_it_rejects_review_for_a_purchase_that_is_not_awaiting_payment(): void public function test_it_rejects_review_for_a_purchase_that_is_not_awaiting_payment(): void
@@ -966,7 +957,7 @@ class StorePurchaseTest extends TestCase
$this->artisan('reservations:expire') $this->artisan('reservations:expire')
->expectsOutput('Expired purchases: 1') ->expectsOutput('Expired purchases: 1')
->expectsOutput('Expired cart reservations: 0') ->expectsOutput('Expired cart items: 0')
->assertSuccessful(); ->assertSuccessful();
$this->assertDatabaseHas('compras', [ $this->assertDatabaseHas('compras', [
@@ -977,11 +968,15 @@ class StorePurchaseTest extends TestCase
'compra_id' => $purchase->id, 'compra_id' => $purchase->id,
'cantidad' => 3, 'cantidad' => 3,
]); ]);
$this->assertPurchaseReservation($purchase->id, $variant->inventory_id, 3, 'expired'); $this->assertDatabaseHas('stock_reservations', [
'purchase_id' => null,
'quantity' => 3,
'status' => 'active',
]);
$this->assertDatabaseHas('inventories', [ $this->assertDatabaseHas('inventories', [
'id' => $variant->inventory_id, 'id' => $variant->inventory_id,
'real_stock' => 10, 'real_stock' => 10,
'reserved_stock' => 0, 'reserved_stock' => 3,
'sold_units' => 0, 'sold_units' => 0,
]); ]);
$this->assertDatabaseHas('carritos', [ $this->assertDatabaseHas('carritos', [
@@ -994,7 +989,7 @@ class StorePurchaseTest extends TestCase
$this->artisan('reservations:expire') $this->artisan('reservations:expire')
->expectsOutput('Expired purchases: 0') ->expectsOutput('Expired purchases: 0')
->expectsOutput('Expired cart reservations: 0') ->expectsOutput('Expired cart items: 0')
->assertSuccessful(); ->assertSuccessful();
} }
@@ -1011,7 +1006,6 @@ class StorePurchaseTest extends TestCase
'source_catalog_item_id' => $variant->catalog_item_id, 'source_catalog_item_id' => $variant->catalog_item_id,
'source_variant_id' => $variant->id, 'source_variant_id' => $variant->id,
'nombre' => 'Inconsistent item', 'nombre' => 'Inconsistent item',
'item_nombre' => 'Inconsistent item',
'slug' => 'inconsistent-item', 'slug' => 'inconsistent-item',
'cantidad' => 1, 'cantidad' => 1,
'precio_unitario' => '50.00', 'precio_unitario' => '50.00',
@@ -1024,7 +1018,7 @@ class StorePurchaseTest extends TestCase
$this->artisan('reservations:expire') $this->artisan('reservations:expire')
->expectsOutput('Expired purchases: 2') ->expectsOutput('Expired purchases: 2')
->expectsOutput('Expired cart reservations: 0') ->expectsOutput('Expired cart items: 0')
->assertSuccessful(); ->assertSuccessful();
$this->assertDatabaseHas('compras', [ $this->assertDatabaseHas('compras', [
@@ -1166,7 +1160,12 @@ class StorePurchaseTest extends TestCase
'reserved_stock' => 0, 'reserved_stock' => 0,
'sold_units' => 2, 'sold_units' => 2,
]); ]);
$this->assertPurchaseReservation($purchase->id, $variant->inventory_id, 2, 'committed'); $this->assertDatabaseHas('stock_reservations', [
'purchase_id' => $purchase->id,
'inventory_id' => $variant->inventory_id,
'quantity' => 2,
'status' => 'committed',
]);
$this->assertSoftDeleted('carritos', [ $this->assertSoftDeleted('carritos', [
'id' => $purchase->cart_id, 'id' => $purchase->cart_id,
@@ -1441,26 +1440,6 @@ class StorePurchaseTest extends TestCase
]); ]);
} }
protected function assertPurchaseReservation(
int $purchaseId,
int $inventoryId,
int $quantity,
string $status,
): void {
$reservationId = Purchase::query()->findOrFail($purchaseId)->stock_reservation_id;
$this->assertNotNull($reservationId);
$this->assertDatabaseHas('stock_reservations', [
'id' => $reservationId,
'status' => $status,
]);
$this->assertDatabaseHas('stock_reservation_lines', [
'stock_reservation_id' => $reservationId,
'inventory_id' => $inventoryId,
'quantity' => $quantity,
]);
}
protected function createTenant(string $codigo, string $nombre, string $dominio): Tenant protected function createTenant(string $codigo, string $nombre, string $dominio): Tenant
{ {
$hdrKey = (string) Str::uuid(); $hdrKey = (string) Str::uuid();

View File

@@ -520,10 +520,8 @@ class AdminAppSaleControllerTest extends TestCase
->assertJsonPath('data.status', Purchase::STATUS_CANCELLED); ->assertJsonPath('data.status', Purchase::STATUS_CANCELLED);
$this->assertSoftDeleted('carritos', ['id' => $sourceCartId]); $this->assertSoftDeleted('carritos', ['id' => $sourceCartId]);
$reservationId = $purchase->fresh()->stock_reservation_id;
$this->assertNotNull($reservationId);
$this->assertDatabaseHas('stock_reservations', [ $this->assertDatabaseHas('stock_reservations', [
'id' => $reservationId, 'purchase_id' => $purchase->id,
'status' => 'released', 'status' => 'released',
]); ]);
} }

View File

@@ -300,13 +300,10 @@ class DesfilePuraTendenciaSeederTest extends TestCase
->where('user_id', $user->id) ->where('user_id', $user->id)
->where('source_catalog_item_id', $catalogItemId) ->where('source_catalog_item_id', $catalogItemId)
->count()); ->count());
$this->assertSame(1, DB::table('stock_reservations') $this->assertSame(48, DB::table('stock_reservations')
->where('id', $purchase->stock_reservation_id) ->where('purchase_id', $purchase->id)
->where('status', 'committed') ->where('status', 'committed')
->count()); ->count());
$this->assertSame(48, DB::table('stock_reservation_lines')
->where('stock_reservation_id', $purchase->stock_reservation_id)
->count());
foreach ([ foreach ([
['sector' => 'A', 'fila' => '1', 'tipo' => 'NORMAL', 'count' => 16], ['sector' => 'A', 'fila' => '1', 'tipo' => 'NORMAL', 'count' => 16],

View File

@@ -70,14 +70,6 @@ class FiestaFutbolInfantilProductSeederTest extends TestCase
['abono', 'alojamiento', 'camiseta', 'comida'], ['abono', 'alojamiento', 'camiseta', 'comida'],
CatalogItem::query()->where('tenant_code', $tenant->codigo)->orderBy('slug')->pluck('slug')->all(), CatalogItem::query()->where('tenant_code', $tenant->codigo)->orderBy('slug')->pluck('slug')->all(),
); );
$this->assertSame(
['camiseta', 'alojamiento', 'abono', 'comida'],
CatalogItem::query()
->where('tenant_code', $tenant->codigo)
->orderBy('group_order')
->pluck('slug')
->all(),
);
$this->assertTrue( $this->assertTrue(
CatalogItem::query() CatalogItem::query()
->where('tenant_code', $tenant->codigo) ->where('tenant_code', $tenant->codigo)

View File

@@ -2,42 +2,73 @@
namespace Tests\Unit\Catalog; namespace Tests\Unit\Catalog;
use App\Domains\Catalog\Services\AvailabilityPolicyResolver;
use App\Domains\Catalog\Services\CatalogItemAllowanceService; use App\Domains\Catalog\Services\CatalogItemAllowanceService;
use ReflectionClass; use App\Domains\Purchase\Services\UserPurchaseLimitService;
use Mockery;
use Tests\TestCase; use Tests\TestCase;
class CatalogItemAllowanceServiceTest extends TestCase class CatalogItemAllowanceServiceTest extends TestCase
{ {
private CatalogItemAllowanceService $service; public function test_a_hidden_decision_only_exposes_its_state_and_reasons(): void
protected function setUp(): void
{ {
parent::setUp(); $availability = $this->service()->availability(0, 0)->toArray();
$this->service = (new ReflectionClass(CatalogItemAllowanceService::class)) $this->assertSame('hidden', $availability['state']);
->newInstanceWithoutConstructor(); $this->assertSame(
['user_quota_reached', 'out_of_stock'],
array_column($availability['reasons'], 'code'),
);
$this->assertArrayNotHasKey('maximum_quantity', $availability);
$this->assertArrayNotHasKey('allowed_actions', $availability);
} }
public function test_it_returns_the_user_quota_message_with_priority_over_stock(): void public function test_an_available_decision_keeps_all_actions(): void
{ {
$availability = $this->service()->availability(5, 3)->toArray();
$this->assertSame('visible', $availability['state']);
$this->assertSame(3, $availability['maximum_quantity']);
$this->assertSame([], $availability['reasons']);
$this->assertSame([
'select_variant',
'change_quantity',
'add_to_cart',
'buy_now',
], $availability['allowed_actions']);
}
public function test_reaching_the_user_quota_keeps_the_product_visible_without_actions(): void
{
$availability = $this->service()->availability(5, 0)->toArray();
$this->assertSame('visible', $availability['state']);
$this->assertSame([], $availability['allowed_actions']);
$this->assertSame('user_quota_reached', $availability['reasons'][0]['code']);
}
public function test_exceeding_the_remaining_quota_allows_the_quantity_to_be_corrected(): void
{
$availability = $this->service()
->purchaseLimitExceededAvailability(1, 'Solo podés agregar una unidad.')
->toArray();
$this->assertSame(1, $availability['maximum_quantity']);
$this->assertSame( $this->assertSame(
'Alcanzaste el cupo máximo permitido para este producto.', 'requested_quantity_exceeds_user_quota',
$this->service->unavailableMessage(0, 0), $availability['reasons'][0]['code'],
);
$this->assertSame([
'select_variant',
'change_quantity',
], $availability['allowed_actions']);
}
private function service(): CatalogItemAllowanceService
{
return new CatalogItemAllowanceService(
Mockery::mock(UserPurchaseLimitService::class),
new AvailabilityPolicyResolver,
); );
} }
public function test_it_returns_the_out_of_stock_message(): void
{
$this->assertSame(
'Este producto no tiene stock disponible.',
$this->service->unavailableMessage(0, null),
);
}
public function test_it_returns_no_message_when_the_item_is_available(): void
{
$this->assertNull($this->service->unavailableMessage(1, null));
$this->assertNull($this->service->unavailableMessage(null, 1));
$this->assertNull($this->service->unavailableMessage(null, null));
}
} }

View File

@@ -83,13 +83,11 @@ class CatalogModelsTest extends TestCase
public function test_catalog_item_is_the_catalog_root(): void public function test_catalog_item_is_the_catalog_root(): void
{ {
$item = new CatalogItem; $item = new CatalogItem;
$this->assertSame(0, $item->group_order);
$item->setRawAttributes([ $item->setRawAttributes([
'category_id' => '10', 'category_id' => '10',
'brand_id' => '20', 'brand_id' => '20',
'inventory_id' => '30', 'inventory_id' => '30',
'type' => CatalogItemType::Standard->value, 'type' => CatalogItemType::Standard->value,
'group_order' => '4',
'precio' => '12.50', 'precio' => '12.50',
'inventory_policy' => InventoryPolicy::Tracked->value, 'inventory_policy' => InventoryPolicy::Tracked->value,
'inventory_subject' => InventorySubject::Seat->value, 'inventory_subject' => InventorySubject::Seat->value,
@@ -102,7 +100,6 @@ class CatalogModelsTest extends TestCase
$this->assertSame(20, $item->brand_id); $this->assertSame(20, $item->brand_id);
$this->assertSame(30, $item->inventory_id); $this->assertSame(30, $item->inventory_id);
$this->assertSame(CatalogItemType::Standard, $item->type); $this->assertSame(CatalogItemType::Standard, $item->type);
$this->assertSame(4, $item->group_order);
$this->assertSame('12.50', $item->precio); $this->assertSame('12.50', $item->precio);
$this->assertSame(InventoryPolicy::Tracked, $item->inventory_policy); $this->assertSame(InventoryPolicy::Tracked, $item->inventory_policy);
$this->assertSame(InventorySubject::Seat, $item->inventory_subject); $this->assertSame(InventorySubject::Seat, $item->inventory_subject);

View File

@@ -12,7 +12,7 @@ use Tests\TestCase;
class ExpireStockReservationsServiceTest extends TestCase class ExpireStockReservationsServiceTest extends TestCase
{ {
public function test_it_expires_purchases_before_abandoned_cart_reservations(): void public function test_it_expires_purchases_before_abandoned_cart_items(): void
{ {
$checkout = \Mockery::mock(CheckoutService::class); $checkout = \Mockery::mock(CheckoutService::class);
$checkout->shouldReceive('expireOverduePurchases') $checkout->shouldReceive('expireOverduePurchases')
@@ -36,7 +36,7 @@ class ExpireStockReservationsServiceTest extends TestCase
->with('Stock reservation cleanup completed.', [ ->with('Stock reservation cleanup completed.', [
'command' => 'reservations:expire', 'command' => 'reservations:expire',
'expired_purchases' => 2, 'expired_purchases' => 2,
'expired_cart_reservations' => 3, 'expired_cart_items' => 3,
'total_expired' => 5, 'total_expired' => 5,
]); ]);
@@ -44,7 +44,7 @@ class ExpireStockReservationsServiceTest extends TestCase
$this->assertSame([ $this->assertSame([
'purchases' => 2, 'purchases' => 2,
'cart_reservations' => 3, 'cart_items' => 3,
], $result); ], $result);
} }
@@ -67,7 +67,7 @@ class ExpireStockReservationsServiceTest extends TestCase
->with('Stock reservation cleanup failed.', [ ->with('Stock reservation cleanup failed.', [
'command' => 'reservations:expire', 'command' => 'reservations:expire',
'expired_purchases' => 2, 'expired_purchases' => 2,
'expired_cart_reservations' => null, 'expired_cart_items' => null,
'exception' => $exception, 'exception' => $exception,
]); ]);