Compare commits
13 Commits
feature/al
...
6db99e775a
| Author | SHA1 | Date | |
|---|---|---|---|
| 6db99e775a | |||
| e5f7ba3615 | |||
| 24bfef431b | |||
| 843659583e | |||
| c2921166bd | |||
| 0f67e66b6b | |||
| 725abed06a | |||
| 743939fc63 | |||
| eb50e65fef | |||
| 1cf13501d8 | |||
| 2eeef8d392 | |||
| 87a4fa6288 | |||
| 07d2129410 |
@@ -5,6 +5,7 @@ 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;
|
||||||
@@ -28,6 +29,7 @@ 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
|
||||||
{
|
{
|
||||||
@@ -45,6 +47,7 @@ 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',
|
||||||
];
|
];
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -84,6 +87,15 @@ 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')
|
||||||
@@ -140,12 +152,11 @@ 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)->reserve($item, $selectedItem, $quantity);
|
app(StockReservationService::class)->syncCart($this);
|
||||||
|
|
||||||
return $item->fresh();
|
return $item->fresh();
|
||||||
});
|
});
|
||||||
@@ -205,7 +216,6 @@ 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) {
|
||||||
@@ -222,11 +232,10 @@ 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();
|
||||||
}
|
}
|
||||||
@@ -234,7 +243,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)->reserve($item, $nextSelection, $quantity);
|
app(StockReservationService::class)->syncCart($this);
|
||||||
|
|
||||||
return $item->fresh();
|
return $item->fresh();
|
||||||
}
|
}
|
||||||
@@ -263,16 +272,9 @@ 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();
|
||||||
});
|
});
|
||||||
@@ -289,17 +291,8 @@ 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);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -347,7 +340,10 @@ class Cart extends Model
|
|||||||
]);
|
]);
|
||||||
}
|
}
|
||||||
|
|
||||||
app(StockReservationService::class)->detachFromPurchase($currentPurchase);
|
app(StockReservationService::class)->releaseForPurchase(
|
||||||
|
$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())
|
||||||
|
|||||||
@@ -3,13 +3,11 @@
|
|||||||
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',
|
||||||
@@ -57,10 +55,4 @@ 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);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,119 +3,82 @@
|
|||||||
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
|
||||||
{
|
{
|
||||||
$expiredItems = 0;
|
$expired = 0;
|
||||||
$lastCartItemId = 0;
|
$lastReservationId = 0;
|
||||||
|
|
||||||
do {
|
do {
|
||||||
$cartItemIds = StockReservation::query()
|
$reservationIds = 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('cart_item_id', '>', $lastCartItemId)
|
->where('id', '>', $lastReservationId)
|
||||||
->whereHas('cartItem.cart', fn ($query) => $query->where('status', 'active'))
|
->whereHas('currentCart', fn ($query) => $query->where('status', 'active'))
|
||||||
->select('cart_item_id')
|
->whereDoesntHave('purchase', fn ($query) => $query->whereIn('status', [
|
||||||
->distinct()
|
Purchase::STATUS_CREATED,
|
||||||
->orderBy('cart_item_id')
|
Purchase::STATUS_PENDING_PAYMENT,
|
||||||
|
Purchase::STATUS_IN_REVIEW,
|
||||||
|
]))
|
||||||
|
->orderBy('id')
|
||||||
->limit(500)
|
->limit(500)
|
||||||
->pluck('cart_item_id');
|
->pluck('id');
|
||||||
|
|
||||||
foreach ($cartItemIds as $cartItemId) {
|
foreach ($reservationIds as $reservationId) {
|
||||||
$lastCartItemId = (int) $cartItemId;
|
$lastReservationId = (int) $reservationId;
|
||||||
|
|
||||||
if ($this->expireCartItem($lastCartItemId)) {
|
if ($this->expireReservation($lastReservationId)) {
|
||||||
$expiredItems++;
|
$expired++;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
} while ($cartItemIds->count() === 500);
|
} while ($reservationIds->count() === 500);
|
||||||
|
|
||||||
return $expiredItems;
|
return $expired;
|
||||||
}
|
}
|
||||||
|
|
||||||
private function expireCartItem(int $cartItemId): bool
|
private function expireReservation(int $reservationId): bool
|
||||||
{
|
{
|
||||||
/** @var CartItem|null $candidate */
|
$cartId = Cart::query()
|
||||||
$candidate = CartItem::query()->select(['id', 'cart_id'])->find($cartItemId);
|
->where('current_stock_reservation_id', $reservationId)
|
||||||
if ($candidate === null) {
|
->where('status', 'active')
|
||||||
|
->value('id');
|
||||||
|
if ($cartId === null) {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
return DB::transaction(function () use ($candidate, $cartItemId): bool {
|
return DB::transaction(function () use ($cartId, $reservationId): bool {
|
||||||
/** @var Cart|null $cart */
|
/** @var Cart|null $cart */
|
||||||
$cart = Cart::query()
|
$cart = Cart::query()
|
||||||
->whereKey($candidate->cart_id)
|
->whereKey($cartId)
|
||||||
|
->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 CartItem|null $cartItem */
|
/** @var StockReservation|null $reservation */
|
||||||
$cartItem = $cart->items()
|
$reservation = StockReservation::query()->lockForUpdate()->find($reservationId);
|
||||||
->whereKey($cartItemId)
|
if ($reservation === null
|
||||||
->lockForUpdate()
|
|| $reservation->status !== StockReservation::STATUS_ACTIVE
|
||||||
->first();
|
|
||||||
|
|
||||||
if ($cartItem === null) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
$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 === null
|
||||||
|| $reservation->expires_at->isFuture(),
|
|| $reservation->expires_at->isFuture()) {
|
||||||
)
|
|
||||||
) {
|
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
$inventories = Inventory::query()
|
$this->reservations->expire($reservation);
|
||||||
->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;
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -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 y permite agregar, actualizar o quitar ítems.
|
- `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`.
|
||||||
- `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 las reservas vencidas de carritos activos y elimina los carritos que quedan vacíos.
|
- `ExpireCartReservationsService`: libera como conjunto las reservas vencidas de carritos activos sin eliminar el contenido del carrito.
|
||||||
- `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,4 +34,6 @@ 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.
|
||||||
|
|
||||||
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`.
|
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 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.
|
||||||
|
|||||||
@@ -27,6 +27,7 @@ use Illuminate\Support\Collection;
|
|||||||
'type',
|
'type',
|
||||||
'slug',
|
'slug',
|
||||||
'nombre',
|
'nombre',
|
||||||
|
'group_order',
|
||||||
'descripcion',
|
'descripcion',
|
||||||
'precio',
|
'precio',
|
||||||
'inventory_policy',
|
'inventory_policy',
|
||||||
@@ -47,6 +48,7 @@ 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
|
||||||
@@ -56,6 +58,7 @@ 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,
|
||||||
@@ -172,18 +175,30 @@ class CatalogItem extends Model
|
|||||||
}
|
}
|
||||||
|
|
||||||
/** @param Builder<CatalogItem> $query */
|
/** @param Builder<CatalogItem> $query */
|
||||||
public function scopeWhereVariantsAvailable(Builder $query): Builder
|
public function scopeWhereAvailable(Builder $query): Builder
|
||||||
{
|
{
|
||||||
return $query->where(function (Builder $query): void {
|
return $query->where(function (Builder $query): void {
|
||||||
$query
|
$query
|
||||||
->whereDoesntHave('variants')
|
->where('catalog_items.inventory_policy', InventoryPolicy::Unlimited->value)
|
||||||
->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> */
|
||||||
|
|||||||
@@ -48,10 +48,10 @@ class Inventory extends Model
|
|||||||
return $this->hasOne(Variant::class);
|
return $this->hasOne(Variant::class);
|
||||||
}
|
}
|
||||||
|
|
||||||
/** @return HasMany<StockReservation, $this> */
|
/** @return HasMany<StockReservationLine, $this> */
|
||||||
public function stockReservations(): HasMany
|
public function stockReservationLines(): HasMany
|
||||||
{
|
{
|
||||||
return $this->hasMany(StockReservation::class);
|
return $this->hasMany(StockReservationLine::class);
|
||||||
}
|
}
|
||||||
|
|
||||||
public function availableStock(): int
|
public function availableStock(): int
|
||||||
|
|||||||
@@ -2,21 +2,20 @@
|
|||||||
|
|
||||||
namespace App\Domains\Catalog\Models;
|
namespace App\Domains\Catalog\Models;
|
||||||
|
|
||||||
use App\Domains\Cart\Models\CartItem;
|
use App\Domains\Cart\Models\Cart;
|
||||||
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\BelongsTo;
|
use Illuminate\Database\Eloquent\Relations\HasMany;
|
||||||
|
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
|
||||||
{
|
{
|
||||||
@@ -31,31 +30,28 @@ 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 BelongsTo<Inventory, $this> */
|
/** @return HasMany<StockReservationLine, $this> */
|
||||||
public function inventory(): BelongsTo
|
public function lines(): HasMany
|
||||||
{
|
{
|
||||||
return $this->belongsTo(Inventory::class);
|
return $this->hasMany(StockReservationLine::class);
|
||||||
}
|
}
|
||||||
|
|
||||||
/** @return BelongsTo<CartItem, $this> */
|
/** @return HasOne<Cart, $this> */
|
||||||
public function cartItem(): BelongsTo
|
public function currentCart(): HasOne
|
||||||
{
|
{
|
||||||
return $this->belongsTo(CartItem::class);
|
return $this->hasOne(Cart::class, 'current_stock_reservation_id');
|
||||||
}
|
}
|
||||||
|
|
||||||
/** @return BelongsTo<Purchase, $this> */
|
/** @return HasOne<Purchase, $this> */
|
||||||
public function purchase(): BelongsTo
|
public function purchase(): HasOne
|
||||||
{
|
{
|
||||||
return $this->belongsTo(Purchase::class);
|
return $this->hasOne(Purchase::class);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
38
app/Domains/Catalog/Models/StockReservationLine.php
Normal file
38
app/Domains/Catalog/Models/StockReservationLine.php
Normal file
@@ -0,0 +1,38 @@
|
|||||||
|
<?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);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -51,6 +51,7 @@ 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)],
|
||||||
|
|||||||
@@ -46,7 +46,7 @@ class CatalogFeaturedItemResource extends JsonResource
|
|||||||
$availableStock,
|
$availableStock,
|
||||||
$remainingUserQuota,
|
$remainingUserQuota,
|
||||||
),
|
),
|
||||||
'variants' => $catalogItem->variants
|
'variants' => $catalogItem->visibleVariants()
|
||||||
->map(function (Variant $variant) use ($catalogItem, $remainingUserQuota): array {
|
->map(function (Variant $variant) use ($catalogItem, $remainingUserQuota): array {
|
||||||
$variantStock = $catalogItem->inventory_policy === InventoryPolicy::Unlimited
|
$variantStock = $catalogItem->inventory_policy === InventoryPolicy::Unlimited
|
||||||
? null
|
? null
|
||||||
@@ -115,7 +115,7 @@ class CatalogFeaturedItemResource extends JsonResource
|
|||||||
private function firstImageUrl(CatalogItem $catalogItem): ?string
|
private function firstImageUrl(CatalogItem $catalogItem): ?string
|
||||||
{
|
{
|
||||||
$attachment = $catalogItem->attachments->first()
|
$attachment = $catalogItem->attachments->first()
|
||||||
?? $catalogItem->variants
|
?? $catalogItem->visibleVariants()
|
||||||
->flatMap(fn (Variant $variant) => $variant->attachments)
|
->flatMap(fn (Variant $variant) => $variant->attachments)
|
||||||
->first();
|
->first();
|
||||||
|
|
||||||
|
|||||||
@@ -16,8 +16,9 @@ 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()
|
||||||
?? $this->variants
|
?? $visibleVariants
|
||||||
->flatMap(fn (Variant $variant) => $variant->attachments)
|
->flatMap(fn (Variant $variant) => $variant->attachments)
|
||||||
->first();
|
->first();
|
||||||
|
|
||||||
@@ -30,7 +31,7 @@ class CatalogSearchItemResource extends JsonResource
|
|||||||
'image' => $attachment?->getTemporaryUrl(1440),
|
'image' => $attachment?->getTemporaryUrl(1440),
|
||||||
'maximum_addable_quantity' => $this->maximumAddable($availableStock),
|
'maximum_addable_quantity' => $this->maximumAddable($availableStock),
|
||||||
'unavailable_message' => $this->unavailableMessage($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
|
||||||
|
|||||||
@@ -25,6 +25,24 @@ 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
|
||||||
|
|||||||
@@ -205,6 +205,13 @@ 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);
|
||||||
@@ -231,6 +238,7 @@ class CatalogService
|
|||||||
|
|
||||||
$paginator = CatalogItem::query()
|
$paginator = 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])
|
||||||
@@ -280,6 +288,7 @@ class CatalogService
|
|||||||
return CatalogItem::query()
|
return 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',
|
||||||
|
|||||||
@@ -15,7 +15,7 @@ class ExpireStockReservationsService
|
|||||||
) {}
|
) {}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @return array{purchases: int, cart_items: int}
|
* @return array{purchases: int, cart_reservations: 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_items' => $expiredCartItems,
|
'expired_cart_reservations' => $expiredCartItems,
|
||||||
'total_expired' => $expiredPurchases + $expiredCartItems,
|
'total_expired' => $expiredPurchases + $expiredCartItems,
|
||||||
]);
|
]);
|
||||||
|
|
||||||
return [
|
return [
|
||||||
'purchases' => $expiredPurchases,
|
'purchases' => $expiredPurchases,
|
||||||
'cart_items' => $expiredCartItems,
|
'cart_reservations' => $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_items' => $expiredCartItems,
|
'expired_cart_reservations' => $expiredCartItems,
|
||||||
'exception' => $exception,
|
'exception' => $exception,
|
||||||
]);
|
]);
|
||||||
|
|
||||||
|
|||||||
@@ -49,6 +49,7 @@ 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')
|
||||||
@@ -81,7 +82,9 @@ 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->orderBy('catalog_items.id'),
|
FeaturedGroupSource::All => $query
|
||||||
|
->orderBy('catalog_items.group_order')
|
||||||
|
->orderBy('catalog_items.id'),
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -2,262 +2,415 @@
|
|||||||
|
|
||||||
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\CatalogItem;
|
use App\Domains\Catalog\Models\Inventory;
|
||||||
use App\Domains\Catalog\Models\StockReservation;
|
use App\Domains\Catalog\Models\StockReservation;
|
||||||
use App\Domains\Catalog\Models\Variant;
|
use App\Domains\Catalog\Models\StockReservationLine;
|
||||||
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 reserve(CartItem $cartItem, CatalogItem|Variant $selection, int $quantity): void
|
public function syncCart(Cart $cart): ?StockReservation
|
||||||
{
|
{
|
||||||
DB::transaction(function () use ($cartItem, $selection, $quantity): void {
|
return DB::transaction(function () use ($cart): ?StockReservation {
|
||||||
$this->inventory->reserve($selection, $quantity);
|
/** @var Cart $lockedCart */
|
||||||
$this->recordIncrease($cartItem, $selection, $quantity);
|
$lockedCart = Cart::query()->lockForUpdate()->findOrFail($cart->getKey());
|
||||||
});
|
$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;
|
||||||
}
|
}
|
||||||
|
|
||||||
public function release(
|
if ($requirements === []) {
|
||||||
CartItem $cartItem,
|
if ($reservation !== null && $reservation->status === StockReservation::STATUS_ACTIVE) {
|
||||||
CatalogItem|Variant $selection,
|
$this->finalizeLocked(
|
||||||
int $quantity,
|
$reservation,
|
||||||
string $releasedStatus = StockReservation::STATUS_RELEASED,
|
StockReservation::STATUS_RELEASED,
|
||||||
): void {
|
self::REASON_CART_EMPTY,
|
||||||
DB::transaction(function () use ($cartItem, $selection, $quantity, $releasedStatus): void {
|
);
|
||||||
$this->ensure($cartItem, $selection);
|
|
||||||
$this->inventory->release($selection, $quantity);
|
|
||||||
$this->recordDecrease($cartItem, $selection, $quantity, $releasedStatus);
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public function commit(
|
$lockedCart->update(['current_stock_reservation_id' => null]);
|
||||||
CartItem $cartItem,
|
$cart->current_stock_reservation_id = null;
|
||||||
CatalogItem|Variant $selection,
|
|
||||||
Purchase $purchase,
|
|
||||||
): void {
|
|
||||||
DB::transaction(function () use ($cartItem, $selection, $purchase): void {
|
|
||||||
$this->ensure($cartItem, $selection);
|
|
||||||
$this->inventory->commit($selection, (int) $cartItem->cantidad);
|
|
||||||
|
|
||||||
$requirements = $this->inventory->requirementsFor($selection, (int) $cartItem->cantidad);
|
return null;
|
||||||
foreach ($requirements as $inventoryId => $quantity) {
|
|
||||||
$reservation = $this->lockReservation($cartItem, $inventoryId);
|
|
||||||
if (
|
|
||||||
$reservation === null
|
|
||||||
|| $reservation->status !== StockReservation::STATUS_ACTIVE
|
|
||||||
|| $reservation->purchase_id !== $purchase->getKey()
|
|
||||||
|| $reservation->quantity !== $quantity
|
|
||||||
) {
|
|
||||||
throw new \InvalidArgumentException('La reserva de stock no coincide con el item del carrito.');
|
|
||||||
}
|
}
|
||||||
|
|
||||||
$reservation->update([
|
if ($reservation === null || $reservation->status !== StockReservation::STATUS_ACTIVE) {
|
||||||
'status' => StockReservation::STATUS_COMMITTED,
|
$reservation = StockReservation::query()->create([
|
||||||
'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,
|
'status' => StockReservation::STATUS_ACTIVE,
|
||||||
'expires_at' => $this->expiration(),
|
'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;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
if ($reservation->status !== StockReservation::STATUS_ACTIVE || $reservation->quantity !== $quantity) {
|
StockReservationLine::query()->updateOrCreate(
|
||||||
$reservation->update([
|
[
|
||||||
'quantity' => $quantity,
|
'stock_reservation_id' => $reservation->getKey(),
|
||||||
'status' => StockReservation::STATUS_ACTIVE,
|
'inventory_id' => $inventoryId,
|
||||||
'committed_at' => null,
|
],
|
||||||
'released_at' => null,
|
[
|
||||||
'expires_at' => $this->expiration(),
|
'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
|
||||||
|
{
|
||||||
|
return DB::transaction(function () use ($cart, $purchase): StockReservation {
|
||||||
|
/** @var Cart $lockedCart */
|
||||||
|
$lockedCart = Cart::query()->lockForUpdate()->findOrFail($cart->getKey());
|
||||||
|
/** @var Purchase $lockedPurchase */
|
||||||
|
$lockedPurchase = Purchase::query()->lockForUpdate()->findOrFail($purchase->getKey());
|
||||||
|
|
||||||
|
if ($lockedCart->current_stock_reservation_id === null) {
|
||||||
|
throw new \InvalidArgumentException('El carrito no tiene una reserva de stock activa.');
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @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
|
||||||
|
{
|
||||||
|
DB::transaction(function () use ($purchase): void {
|
||||||
|
/** @var Purchase $purchase */
|
||||||
|
$purchase = Purchase::query()->lockForUpdate()->findOrFail($purchase->getKey());
|
||||||
|
if ($purchase->stock_reservation_id === null) {
|
||||||
|
throw new \InvalidArgumentException('La compra no tiene una reserva de stock.');
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @var StockReservation $reservation */
|
||||||
|
$reservation = StockReservation::query()->lockForUpdate()->findOrFail($purchase->stock_reservation_id);
|
||||||
|
if ($reservation->status === StockReservation::STATUS_COMMITTED) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if ($reservation->status !== StockReservation::STATUS_ACTIVE) {
|
||||||
|
throw new \InvalidArgumentException('La reserva de stock no está activa.');
|
||||||
|
}
|
||||||
|
|
||||||
|
$lines = $this->lockLines($reservation);
|
||||||
|
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.');
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public function attachToPurchase(
|
foreach ($lines as $line) {
|
||||||
CartItem $cartItem,
|
$inventories->get($line->inventory_id)->buy(
|
||||||
CatalogItem|Variant $selection,
|
(int) $line->quantity,
|
||||||
Purchase $purchase,
|
(bool) $line->tracks_inventory,
|
||||||
): void {
|
);
|
||||||
DB::transaction(function () use ($cartItem, $selection, $purchase): void {
|
}
|
||||||
$this->ensure($cartItem, $selection);
|
|
||||||
StockReservation::query()
|
$reservation->update([
|
||||||
->where('cart_item_id', $cartItem->getKey())
|
'status' => StockReservation::STATUS_COMMITTED,
|
||||||
->where('status', StockReservation::STATUS_ACTIVE)
|
'expires_at' => null,
|
||||||
->update([
|
'committed_at' => now(),
|
||||||
'purchase_id' => $purchase->getKey(),
|
'released_at' => null,
|
||||||
'expires_at' => $purchase->expires_at,
|
'expired_at' => null,
|
||||||
|
'release_reason' => null,
|
||||||
]);
|
]);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
public function detachFromPurchase(Purchase $purchase): void
|
public function releaseForPurchase(
|
||||||
{
|
Purchase $purchase,
|
||||||
StockReservation::query()
|
string $status = StockReservation::STATUS_RELEASED,
|
||||||
->where('purchase_id', $purchase->getKey())
|
?string $reason = null,
|
||||||
->where('status', StockReservation::STATUS_ACTIVE)
|
): void {
|
||||||
->update([
|
DB::transaction(function () use ($purchase, $status, $reason): void {
|
||||||
'purchase_id' => null,
|
/** @var Purchase $purchase */
|
||||||
'expires_at' => $this->expiration(),
|
$purchase = Purchase::query()->lockForUpdate()->findOrFail($purchase->getKey());
|
||||||
]);
|
if ($purchase->stock_reservation_id === null) {
|
||||||
}
|
|
||||||
|
|
||||||
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;
|
||||||
}
|
}
|
||||||
|
|
||||||
if ($activeReservations->isNotEmpty()) {
|
/** @var StockReservation|null $reservation */
|
||||||
throw new \InvalidArgumentException('La reserva de stock del carrito es inconsistente.');
|
$reservation = StockReservation::query()->lockForUpdate()->find($purchase->stock_reservation_id);
|
||||||
|
if ($reservation !== null) {
|
||||||
|
$this->finalizeLocked($reservation, $status, $reason);
|
||||||
|
}
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
$this->inventory->reserve($selection, (int) $cartItem->cantidad);
|
public function releaseCurrentCartReservation(
|
||||||
$this->recordIncrease($cartItem, $selection, (int) $cartItem->cantidad);
|
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 {
|
||||||
|
/** @var StockReservation $reservation */
|
||||||
|
$reservation = StockReservation::query()->lockForUpdate()->findOrFail($reservation->getKey());
|
||||||
|
if ($reservation->status !== StockReservation::STATUS_ACTIVE
|
||||||
|
|| $reservation->expires_at === null
|
||||||
|
|| $reservation->expires_at->isFuture()) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
$this->finalizeLocked($reservation, StockReservation::STATUS_EXPIRED, null);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
public function syncPurchaseExpiration(Purchase $purchase): void
|
public function syncPurchaseExpiration(Purchase $purchase): void
|
||||||
{
|
{
|
||||||
|
if ($purchase->stock_reservation_id === null) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
StockReservation::query()
|
StockReservation::query()
|
||||||
->where('purchase_id', $purchase->getKey())
|
->whereKey($purchase->stock_reservation_id)
|
||||||
->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
|
||||||
{
|
{
|
||||||
DB::transaction(function () use ($source, $target): void {
|
$requirements = [];
|
||||||
$sourceReservations = StockReservation::query()
|
foreach ($items as $item) {
|
||||||
->where('cart_item_id', $source->getKey())
|
$selection = $item->selectedItem();
|
||||||
->where('status', StockReservation::STATUS_ACTIVE)
|
if ($selection === null) {
|
||||||
|
throw new \InvalidArgumentException('El carrito contiene un item de catálogo inexistente.');
|
||||||
|
}
|
||||||
|
|
||||||
|
foreach ($this->inventory->detailedRequirementsFor($selection, (int) $item->cantidad) as $inventoryId => $requirement) {
|
||||||
|
if (isset($requirements[$inventoryId])) {
|
||||||
|
$requirements[$inventoryId]['quantity'] += $requirement['quantity'];
|
||||||
|
$requirements[$inventoryId]['tracks_inventory'] =
|
||||||
|
$requirements[$inventoryId]['tracks_inventory'] || $requirement['tracks_inventory'];
|
||||||
|
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
$requirements[$inventoryId] = $requirement;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
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',
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @return Collection<int, StockReservationLine> */
|
||||||
|
private function lockLines(StockReservation $reservation): Collection
|
||||||
|
{
|
||||||
|
return StockReservationLine::query()
|
||||||
|
->where('stock_reservation_id', $reservation->getKey())
|
||||||
->orderBy('inventory_id')
|
->orderBy('inventory_id')
|
||||||
->lockForUpdate()
|
->lockForUpdate()
|
||||||
->get();
|
->get();
|
||||||
|
|
||||||
foreach ($sourceReservations as $sourceReservation) {
|
|
||||||
$targetReservation = $this->lockReservation($target, (int) $sourceReservation->inventory_id);
|
|
||||||
|
|
||||||
if ($targetReservation === null) {
|
|
||||||
$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;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
$targetReservation->update([
|
/**
|
||||||
'quantity' => $targetReservation->quantity + $sourceReservation->quantity,
|
* @param Collection<int, StockReservationLine> $lines
|
||||||
'status' => StockReservation::STATUS_ACTIVE,
|
* @return Collection<int, Inventory>
|
||||||
'expires_at' => $this->expiration(),
|
*/
|
||||||
]);
|
private function lockInventories(Collection $lines): Collection
|
||||||
$sourceReservation->delete();
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
private function recordIncrease(CartItem $cartItem, CatalogItem|Variant $selection, int $quantity): void
|
|
||||||
{
|
{
|
||||||
foreach ($this->inventory->requirementsFor($selection, $quantity) as $inventoryId => $requiredQuantity) {
|
return Inventory::query()
|
||||||
$reservation = $this->lockReservation($cartItem, $inventoryId);
|
->whereKey($lines->pluck('inventory_id'))
|
||||||
|
->orderBy('id')
|
||||||
if ($reservation === null) {
|
|
||||||
StockReservation::query()->create([
|
|
||||||
'inventory_id' => $inventoryId,
|
|
||||||
'cart_item_id' => $cartItem->getKey(),
|
|
||||||
'quantity' => $requiredQuantity,
|
|
||||||
'status' => StockReservation::STATUS_ACTIVE,
|
|
||||||
'expires_at' => $this->expiration(),
|
|
||||||
]);
|
|
||||||
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
$reservation->update([
|
|
||||||
'quantity' => ($reservation->status === StockReservation::STATUS_ACTIVE ? $reservation->quantity : 0) + $requiredQuantity,
|
|
||||||
'status' => StockReservation::STATUS_ACTIVE,
|
|
||||||
'committed_at' => null,
|
|
||||||
'released_at' => null,
|
|
||||||
'expires_at' => $this->expiration(),
|
|
||||||
]);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private function recordDecrease(
|
|
||||||
CartItem $cartItem,
|
|
||||||
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()
|
->lockForUpdate()
|
||||||
->first();
|
->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([
|
||||||
|
'status' => $status,
|
||||||
|
'expires_at' => null,
|
||||||
|
'released_at' => $status === StockReservation::STATUS_RELEASED ? $now : null,
|
||||||
|
'expired_at' => $status === StockReservation::STATUS_EXPIRED ? $now : null,
|
||||||
|
'release_reason' => $status === StockReservation::STATUS_RELEASED ? $reason : null,
|
||||||
|
]);
|
||||||
|
|
||||||
|
Cart::query()
|
||||||
|
->where('current_stock_reservation_id', $reservation->getKey())
|
||||||
|
->update(['current_stock_reservation_id' => null]);
|
||||||
}
|
}
|
||||||
|
|
||||||
private function expiration(): Carbon
|
private function expiration(): Carbon
|
||||||
|
|||||||
@@ -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` atribuye cada unidad reservada a un ítem de carrito y, durante checkout, a una compra, con estados `active`, `committed`, `released` y `expired`.
|
- `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.
|
||||||
- `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`: mantiene el ledger de reservas sincronizado con `Inventory.reserved_stock`.
|
- `StockReservationService`: sincroniza el carrito como conjunto, bloquea todos sus inventarios en orden estable y mantiene el ledger agregado consistente 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.
|
||||||
|
|
||||||
|
|||||||
@@ -392,15 +392,28 @@ class InvitationPurchaseProvisioner
|
|||||||
'sold_units' => $inventory->sold_units + 1,
|
'sold_units' => $inventory->sold_units + 1,
|
||||||
]);
|
]);
|
||||||
|
|
||||||
DB::table('stock_reservations')->insert([
|
$reservationId = DB::table('compras')->where('id', $purchaseId)->value('stock_reservation_id');
|
||||||
'inventory_id' => $inventory->id,
|
if ($reservationId === null) {
|
||||||
'cart_item_id' => null,
|
$reservationId = DB::table('stock_reservations')->insertGetId([
|
||||||
'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,
|
||||||
]);
|
]);
|
||||||
|
|||||||
@@ -19,6 +19,7 @@ use Illuminate\Support\Facades\DB;
|
|||||||
|
|
||||||
#[Fillable([
|
#[Fillable([
|
||||||
'cart_id',
|
'cart_id',
|
||||||
|
'stock_reservation_id',
|
||||||
'tenant_codigo',
|
'tenant_codigo',
|
||||||
'user_id',
|
'user_id',
|
||||||
'status',
|
'status',
|
||||||
@@ -77,6 +78,7 @@ 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',
|
||||||
@@ -123,10 +125,10 @@ class Purchase extends Model
|
|||||||
return $this->hasMany(Ticket::class, 'source_purchase_id');
|
return $this->hasMany(Ticket::class, 'source_purchase_id');
|
||||||
}
|
}
|
||||||
|
|
||||||
/** @return HasMany<StockReservation, $this> */
|
/** @return BelongsTo<StockReservation, $this> */
|
||||||
public function stockReservations(): HasMany
|
public function stockReservation(): BelongsTo
|
||||||
{
|
{
|
||||||
return $this->hasMany(StockReservation::class);
|
return $this->belongsTo(StockReservation::class);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
@@ -161,14 +161,15 @@ class CompleteCheckoutService
|
|||||||
]);
|
]);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
$this->reservations->commit($cartItem, $selection, $purchase);
|
$this->reservations->commit($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);
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -118,53 +118,46 @@ 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();
|
||||||
if ($cart === null) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
if ($cart->status === 'active') {
|
|
||||||
$this->reservations->detachFromPurchase($purchase);
|
|
||||||
Cart::query()
|
|
||||||
->whereKey($cart->getKey())
|
|
||||||
->where('current_purchase_id', $purchase->getKey())
|
|
||||||
->update(['current_purchase_id' => null]);
|
|
||||||
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
if ($cart->status !== 'checkout') {
|
|
||||||
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 {
|
try {
|
||||||
$this->reservations->release(
|
$this->reservations->releaseForPurchase(
|
||||||
$cartItem,
|
$purchase,
|
||||||
$selection,
|
|
||||||
(int) $cartItem->cantidad,
|
|
||||||
$targetStatus === Purchase::STATUS_EXPIRED
|
$targetStatus === Purchase::STATUS_EXPIRED
|
||||||
? StockReservation::STATUS_EXPIRED
|
? StockReservation::STATUS_EXPIRED
|
||||||
: StockReservation::STATUS_RELEASED,
|
: StockReservation::STATUS_RELEASED,
|
||||||
|
$targetStatus === Purchase::STATUS_CANCELLED
|
||||||
|
? StockReservationService::REASON_PURCHASE_CANCELLED
|
||||||
|
: ($targetStatus === Purchase::STATUS_REJECTED
|
||||||
|
? StockReservationService::REASON_PAYMENT_REJECTED
|
||||||
|
: null),
|
||||||
);
|
);
|
||||||
} catch (\InvalidArgumentException) {
|
} catch (\InvalidArgumentException) {
|
||||||
throw ValidationException::withMessages([
|
throw ValidationException::withMessages([
|
||||||
'items' => __('api.purchase.inconsistent_reservation'),
|
'items' => __('api.purchase.inconsistent_reservation'),
|
||||||
]);
|
]);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if ($cart === null) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($cart->status === 'active') {
|
||||||
|
Cart::query()
|
||||||
|
->whereKey($cart->getKey())
|
||||||
|
->where('current_purchase_id', $purchase->getKey())
|
||||||
|
->update([
|
||||||
|
'current_purchase_id' => null,
|
||||||
|
'current_stock_reservation_id' => null,
|
||||||
|
]);
|
||||||
|
|
||||||
|
if ($targetStatus === Purchase::STATUS_CANCELLED) {
|
||||||
|
$this->reservations->syncCart($cart);
|
||||||
|
}
|
||||||
|
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($cart->status !== 'checkout') {
|
||||||
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (! $cart->trashed()) {
|
if (! $cart->trashed()) {
|
||||||
|
|||||||
@@ -169,21 +169,31 @@ 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,
|
||||||
@@ -194,19 +204,12 @@ 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);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -257,6 +260,7 @@ 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,
|
||||||
@@ -266,16 +270,9 @@ 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);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -320,6 +317,14 @@ 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;
|
||||||
|
|||||||
@@ -135,11 +135,25 @@ 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')
|
||||||
->where(function (Builder $query) use ($scope): void {
|
->whereIn('id', $reservationIds);
|
||||||
$query->whereIn('inventory_id', $scope['inventory_ids'])
|
|
||||||
->orWhereIn('purchase_id', $scope['purchase_ids'])
|
|
||||||
->orWhereIn('cart_item_id', $scope['cart_item_ids']);
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -88,9 +88,9 @@ class UserPurchaseLimitService
|
|||||||
$excludedCartId !== null,
|
$excludedCartId !== null,
|
||||||
fn ($query) => $query->whereKeyNot($excludedCartId),
|
fn ($query) => $query->whereKeyNot($excludedCartId),
|
||||||
))
|
))
|
||||||
->whereHas('stockReservations', fn ($query) => $query
|
->whereHas('cart.currentStockReservation', fn ($query) => $query
|
||||||
->where('status', 'active')
|
->where('status', 'active')
|
||||||
->whereNull('purchase_id'))
|
->whereDoesntHave('purchase'))
|
||||||
->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('stockReservations', fn ($query) => $query
|
->whereHas('cart.currentStockReservation', fn ($query) => $query
|
||||||
->where('status', 'active')
|
->where('status', 'active')
|
||||||
->whereNull('purchase_id'))
|
->whereDoesntHave('purchase'))
|
||||||
->groupBy('catalog_item_id')
|
->groupBy('catalog_item_id')
|
||||||
->pluck('quantity', 'catalog_item_id');
|
->pluck('quantity', 'catalog_item_id');
|
||||||
|
|
||||||
|
|||||||
@@ -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`.
|
- `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.
|
||||||
- `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, sin crear todavía `PurchaseItem`.
|
- `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`.
|
||||||
- `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, recalcula el total y renueva la reserva; 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, libera su reserva completa y crea otra para el contenido actualizado; 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.
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,53 @@
|
|||||||
|
<?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');
|
||||||
|
});
|
||||||
|
}
|
||||||
|
};
|
||||||
@@ -0,0 +1,180 @@
|
|||||||
|
<?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');
|
||||||
|
}
|
||||||
|
};
|
||||||
@@ -78,6 +78,7 @@ 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'],
|
||||||
@@ -92,6 +93,7 @@ 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'],
|
||||||
@@ -104,6 +106,7 @@ 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'],
|
||||||
@@ -126,6 +129,7 @@ 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,
|
||||||
|
|||||||
@@ -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 items: {$expired['cart_items']}");
|
$this->info("Expired cart reservations: {$expired['cart_reservations']}");
|
||||||
})->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')
|
||||||
|
|||||||
@@ -5,10 +5,12 @@ 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;
|
||||||
@@ -28,6 +30,80 @@ 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
|
||||||
@@ -74,9 +150,11 @@ class CartControllerTest extends TestCase
|
|||||||
'id' => $item->inventory_id,
|
'id' => $item->inventory_id,
|
||||||
'reserved_stock' => 2,
|
'reserved_stock' => 2,
|
||||||
]);
|
]);
|
||||||
$this->assertDatabaseHas('stock_reservations', [
|
$this->assertDatabaseHas('stock_reservation_lines', [
|
||||||
'inventory_id' => $item->inventory_id,
|
'inventory_id' => $item->inventory_id,
|
||||||
'quantity' => 2,
|
'quantity' => 2,
|
||||||
|
]);
|
||||||
|
$this->assertDatabaseHas('stock_reservations', [
|
||||||
'status' => 'active',
|
'status' => 'active',
|
||||||
]);
|
]);
|
||||||
}
|
}
|
||||||
@@ -96,16 +174,18 @@ class CartControllerTest extends TestCase
|
|||||||
])->assertOk();
|
])->assertOk();
|
||||||
|
|
||||||
$this->assertDatabaseHas('stock_reservations', [
|
$this->assertDatabaseHas('stock_reservations', [
|
||||||
'inventory_id' => $item->inventory_id,
|
|
||||||
'quantity' => 2,
|
|
||||||
'status' => 'active',
|
'status' => 'active',
|
||||||
'expires_at' => $now->copy()->addMinutes(45)->toDateTimeString(),
|
'expires_at' => $now->copy()->addMinutes(45)->toDateTimeString(),
|
||||||
]);
|
]);
|
||||||
|
$this->assertDatabaseHas('stock_reservation_lines', [
|
||||||
|
'inventory_id' => $item->inventory_id,
|
||||||
|
'quantity' => 2,
|
||||||
|
]);
|
||||||
|
|
||||||
$this->travelBack();
|
$this->travelBack();
|
||||||
}
|
}
|
||||||
|
|
||||||
public function test_it_expires_abandoned_cart_reservations_and_removes_empty_carts(): void
|
public function test_it_expires_abandoned_cart_reservations_without_deleting_the_cart(): 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');
|
||||||
@@ -120,14 +200,14 @@ class CartControllerTest extends TestCase
|
|||||||
|
|
||||||
$this->artisan('reservations:expire')
|
$this->artisan('reservations:expire')
|
||||||
->expectsOutput('Expired purchases: 0')
|
->expectsOutput('Expired purchases: 0')
|
||||||
->expectsOutput('Expired cart items: 0')
|
->expectsOutput('Expired cart reservations: 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 items: 1')
|
->expectsOutput('Expired cart reservations: 1')
|
||||||
->assertSuccessful();
|
->assertSuccessful();
|
||||||
|
|
||||||
$this->assertDatabaseHas('inventories', [
|
$this->assertDatabaseHas('inventories', [
|
||||||
@@ -135,23 +215,25 @@ class CartControllerTest extends TestCase
|
|||||||
'real_stock' => 10,
|
'real_stock' => 10,
|
||||||
'reserved_stock' => 0,
|
'reserved_stock' => 0,
|
||||||
]);
|
]);
|
||||||
$this->assertDatabaseMissing('carrito_items', ['id' => $cartItemId]);
|
$this->assertDatabaseHas('carrito_items', ['id' => $cartItemId]);
|
||||||
$this->assertSoftDeleted('carritos', [
|
$this->assertDatabaseHas('carritos', [
|
||||||
'id' => $cartId,
|
'id' => $cartId,
|
||||||
'status' => 'expired',
|
'status' => 'active',
|
||||||
|
'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 items: 0')
|
->expectsOutput('Expired cart reservations: 0')
|
||||||
->assertSuccessful();
|
->assertSuccessful();
|
||||||
|
|
||||||
$this->travelBack();
|
$this->travelBack();
|
||||||
@@ -212,10 +294,11 @@ class CartControllerTest extends TestCase
|
|||||||
'id' => $variant->inventory_id,
|
'id' => $variant->inventory_id,
|
||||||
'reserved_stock' => 5,
|
'reserved_stock' => 5,
|
||||||
]);
|
]);
|
||||||
$this->assertDatabaseHas('stock_reservations', [
|
$this->assertDatabaseHas('stock_reservation_lines', [
|
||||||
'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',
|
||||||
]);
|
]);
|
||||||
}
|
}
|
||||||
@@ -229,6 +312,7 @@ 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,
|
||||||
@@ -237,6 +321,7 @@ 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,
|
||||||
@@ -381,10 +466,12 @@ class CartControllerTest extends TestCase
|
|||||||
'reserved_stock' => 0,
|
'reserved_stock' => 0,
|
||||||
]);
|
]);
|
||||||
$this->assertDatabaseHas('stock_reservations', [
|
$this->assertDatabaseHas('stock_reservations', [
|
||||||
'cart_item_id' => null,
|
|
||||||
'inventory_id' => $variant->inventory_id,
|
|
||||||
'quantity' => 0,
|
|
||||||
'status' => 'released',
|
'status' => 'released',
|
||||||
|
'release_reason' => 'cart_empty',
|
||||||
|
]);
|
||||||
|
$this->assertDatabaseHas('stock_reservation_lines', [
|
||||||
|
'inventory_id' => $variant->inventory_id,
|
||||||
|
'quantity' => 5,
|
||||||
]);
|
]);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -73,19 +73,18 @@ class CatalogControllerTest extends TestCase
|
|||||||
->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.maximum_addable_quantity', 7)
|
||||||
->assertJsonCount(3, '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.maximum_addable_quantity', 4)
|
||||||
->assertJsonPath('0.items.0.variants.1.maximum_addable_quantity', 3)
|
->assertJsonPath('0.items.0.variants.1.maximum_addable_quantity', 3)
|
||||||
->assertJsonPath('0.items.0.variants.2.id', $unavailableVariant->id)
|
|
||||||
->assertJsonPath('0.items.0.variants.2.maximum_addable_quantity', 0)
|
|
||||||
->assertJsonPath(
|
|
||||||
'0.items.0.variants.2.unavailable_message',
|
|
||||||
'Este producto no tiene stock disponible.',
|
|
||||||
)
|
|
||||||
->assertJsonPath('1.title', 'Row')
|
->assertJsonPath('1.title', 'Row')
|
||||||
->assertJsonPath('1.items.data.0.maximum_addable_quantity', 8)
|
->assertJsonPath('1.items.data.0.maximum_addable_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
|
||||||
@@ -133,7 +132,7 @@ class CatalogControllerTest extends TestCase
|
|||||||
->assertJsonMissingPath('0.items.0.variants.1.stock_tecnico');
|
->assertJsonMissingPath('0.items.0.variants.1.stock_tecnico');
|
||||||
}
|
}
|
||||||
|
|
||||||
public function test_it_includes_out_of_stock_items_with_an_unavailable_message(): void
|
public function test_it_excludes_out_of_stock_items(): void
|
||||||
{
|
{
|
||||||
$tenant = $this->createTenant('catalog-available-variants');
|
$tenant = $this->createTenant('catalog-available-variants');
|
||||||
$group = $this->createGroup(
|
$group = $this->createGroup(
|
||||||
@@ -161,15 +160,10 @@ class CatalogControllerTest extends TestCase
|
|||||||
|
|
||||||
$this->getJson("/api/tenants/{$tenant->codigo}/catalog")
|
$this->getJson("/api/tenants/{$tenant->codigo}/catalog")
|
||||||
->assertOk()
|
->assertOk()
|
||||||
->assertJsonCount(2, '0.items')
|
->assertJsonCount(1, '0.items')
|
||||||
->assertJsonPath('0.items.0.nombre', 'Unavailable')
|
->assertJsonPath('0.items.0.nombre', 'Available')
|
||||||
->assertJsonPath('0.items.0.maximum_addable_quantity', 0)
|
->assertJsonPath('0.items.0.unavailable_message', null)
|
||||||
->assertJsonPath(
|
->assertJsonMissing(['nombre' => 'Unavailable']);
|
||||||
'0.items.0.unavailable_message',
|
|
||||||
'Este producto no tiene stock disponible.',
|
|
||||||
)
|
|
||||||
->assertJsonPath('0.items.1.nombre', 'Available')
|
|
||||||
->assertJsonPath('0.items.1.unavailable_message', null);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
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
|
||||||
@@ -354,8 +348,10 @@ 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();
|
||||||
$this->createItem($tenant, 'Parking');
|
$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()
|
||||||
@@ -364,6 +360,9 @@ 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);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -31,6 +31,7 @@ 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],
|
||||||
@@ -47,6 +48,7 @@ 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')
|
||||||
@@ -57,6 +59,7 @@ 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,
|
||||||
|
|||||||
@@ -48,7 +48,7 @@ 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_lists_unavailable_variants_and_selects_the_first_available_one(): void
|
public function test_it_omits_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');
|
||||||
@@ -69,14 +69,8 @@ class CatalogItemDetailControllerTest extends TestCase
|
|||||||
|
|
||||||
$response
|
$response
|
||||||
->assertOk()
|
->assertOk()
|
||||||
->assertJsonCount(2, 'data.variants')
|
->assertJsonCount(1, 'data.variants')
|
||||||
->assertJsonPath('data.variants.0.id', $firstVariant->id)
|
->assertJsonPath('data.variants.0.id', $secondVariant->id)
|
||||||
->assertJsonPath('data.variants.0.maximum_addable_quantity', 0)
|
|
||||||
->assertJsonPath(
|
|
||||||
'data.variants.0.unavailable_message',
|
|
||||||
'Este producto no tiene stock disponible.',
|
|
||||||
)
|
|
||||||
->assertJsonPath('data.variants.1.id', $secondVariant->id)
|
|
||||||
->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.maximum_addable_quantity', 6)
|
||||||
->assertJsonMissingPath('data.selected_variant.stock_tecnico')
|
->assertJsonMissingPath('data.selected_variant.stock_tecnico')
|
||||||
@@ -84,6 +78,10 @@ class CatalogItemDetailControllerTest extends TestCase
|
|||||||
$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'));
|
||||||
@@ -93,6 +91,19 @@ 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');
|
||||||
|
|||||||
@@ -62,6 +62,24 @@ 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([
|
||||||
|
'tenant_code' => $tenant->codigo,
|
||||||
|
'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');
|
||||||
|
|
||||||
@@ -76,6 +94,8 @@ 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 direct sold out'])
|
||||||
->assertJsonMissing(['nombre' => 'Running foreign'])
|
->assertJsonMissing(['nombre' => 'Running foreign'])
|
||||||
->assertJsonMissing(['nombre' => 'Unrelated']);
|
->assertJsonMissing(['nombre' => 'Unrelated']);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -29,6 +29,17 @@ 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}")
|
||||||
@@ -44,6 +55,7 @@ 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']);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -198,11 +198,16 @@ 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', [
|
||||||
'purchase_id' => $newerPurchase->id,
|
'id' => $newerReservationId,
|
||||||
|
'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', [
|
||||||
|
|||||||
@@ -32,6 +32,45 @@ 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');
|
||||||
@@ -119,12 +158,7 @@ class StorePurchaseTest extends TestCase
|
|||||||
'precio_unitario' => '50.00',
|
'precio_unitario' => '50.00',
|
||||||
'total' => '100.00',
|
'total' => '100.00',
|
||||||
]);
|
]);
|
||||||
$this->assertDatabaseHas('stock_reservations', [
|
$this->assertPurchaseReservation($purchaseId, $inventory->id, 2, 'active');
|
||||||
'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,
|
||||||
@@ -168,12 +202,7 @@ class StorePurchaseTest extends TestCase
|
|||||||
'id' => $cartId,
|
'id' => $cartId,
|
||||||
'current_purchase_id' => $replacementPurchaseId,
|
'current_purchase_id' => $replacementPurchaseId,
|
||||||
]);
|
]);
|
||||||
$this->assertDatabaseHas('stock_reservations', [
|
$this->assertPurchaseReservation($replacementPurchaseId, $inventory->id, 2, 'active');
|
||||||
'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,
|
||||||
@@ -227,12 +256,7 @@ class StorePurchaseTest extends TestCase
|
|||||||
'precio_unitario' => '50.00',
|
'precio_unitario' => '50.00',
|
||||||
'total' => '150.00',
|
'total' => '150.00',
|
||||||
]);
|
]);
|
||||||
$this->assertDatabaseHas('stock_reservations', [
|
$this->assertPurchaseReservation($response->json('data.id'), $variant->inventory_id, 3, 'active');
|
||||||
'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,
|
||||||
@@ -244,10 +268,7 @@ class StorePurchaseTest extends TestCase
|
|||||||
->assertOk()
|
->assertOk()
|
||||||
->assertJsonPath('data.status', Purchase::STATUS_CANCELLED);
|
->assertJsonPath('data.status', Purchase::STATUS_CANCELLED);
|
||||||
|
|
||||||
$this->assertDatabaseHas('stock_reservations', [
|
$this->assertPurchaseReservation($response->json('data.id'), $variant->inventory_id, 3, 'released');
|
||||||
'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,
|
||||||
@@ -296,18 +317,8 @@ 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->assertDatabaseHas('stock_reservations', [
|
$this->assertPurchaseReservation($purchaseId, $firstVariant->inventory_id, 1, 'active');
|
||||||
'inventory_id' => $firstVariant->inventory_id,
|
$this->assertPurchaseReservation($purchaseId, $secondVariant->inventory_id, 1, 'active');
|
||||||
'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,
|
||||||
@@ -430,7 +441,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' => 3]);
|
$firstVariant->catalogItem->update(['max_units_per_user' => 4]);
|
||||||
$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,
|
||||||
@@ -443,6 +454,7 @@ 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', [
|
||||||
@@ -500,12 +512,17 @@ 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', [
|
||||||
'cart_item_id' => $cartItemId,
|
'id' => $activeCart->current_stock_reservation_id,
|
||||||
'purchase_id' => null,
|
|
||||||
'quantity' => 3,
|
|
||||||
'status' => 'active',
|
'status' => 'active',
|
||||||
]);
|
]);
|
||||||
|
$this->assertDatabaseHas('stock_reservation_lines', [
|
||||||
|
'stock_reservation_id' => $activeCart->current_stock_reservation_id,
|
||||||
|
'inventory_id' => $variant->inventory_id,
|
||||||
|
'quantity' => 3,
|
||||||
|
]);
|
||||||
$this->assertSame(1, $activeCart->items()->count());
|
$this->assertSame(1, $activeCart->items()->count());
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -516,6 +533,7 @@ 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,
|
||||||
@@ -538,11 +556,13 @@ 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', [
|
||||||
'purchase_id' => $currentPurchase->id,
|
'id' => $previousReservationId,
|
||||||
'quantity' => 2,
|
'status' => 'released',
|
||||||
'status' => 'active',
|
'release_reason' => 'purchase_superseded',
|
||||||
]);
|
]);
|
||||||
|
$this->assertPurchaseReservation($currentPurchase->id, $variant->inventory_id, 2, 'active');
|
||||||
|
|
||||||
try {
|
try {
|
||||||
app(CheckoutService::class)->confirmPaidPurchase($previousPurchase->fresh());
|
app(CheckoutService::class)->confirmPaidPurchase($previousPurchase->fresh());
|
||||||
@@ -556,11 +576,7 @@ class StorePurchaseTest extends TestCase
|
|||||||
'reserved_stock' => 2,
|
'reserved_stock' => 2,
|
||||||
'sold_units' => 0,
|
'sold_units' => 0,
|
||||||
]);
|
]);
|
||||||
$this->assertDatabaseHas('stock_reservations', [
|
$this->assertPurchaseReservation($currentPurchase->id, $variant->inventory_id, 2, 'active');
|
||||||
'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
|
||||||
@@ -589,11 +605,12 @@ class StorePurchaseTest extends TestCase
|
|||||||
'current_purchase_id' => null,
|
'current_purchase_id' => null,
|
||||||
]);
|
]);
|
||||||
$this->assertDatabaseHas('stock_reservations', [
|
$this->assertDatabaseHas('stock_reservations', [
|
||||||
'inventory_id' => $variant->inventory_id,
|
|
||||||
'cart_item_id' => null,
|
|
||||||
'purchase_id' => null,
|
|
||||||
'quantity' => 0,
|
|
||||||
'status' => 'released',
|
'status' => 'released',
|
||||||
|
'release_reason' => 'purchase_superseded',
|
||||||
|
]);
|
||||||
|
$this->assertDatabaseHas('stock_reservation_lines', [
|
||||||
|
'inventory_id' => $variant->inventory_id,
|
||||||
|
'quantity' => 2,
|
||||||
]);
|
]);
|
||||||
$this->assertDatabaseHas('inventories', [
|
$this->assertDatabaseHas('inventories', [
|
||||||
'id' => $variant->inventory_id,
|
'id' => $variant->inventory_id,
|
||||||
@@ -628,7 +645,7 @@ class StorePurchaseTest extends TestCase
|
|||||||
]);
|
]);
|
||||||
$this->assertDatabaseHas('inventories', [
|
$this->assertDatabaseHas('inventories', [
|
||||||
'id' => $variant->inventory_id,
|
'id' => $variant->inventory_id,
|
||||||
'reserved_stock' => 3,
|
'reserved_stock' => 0,
|
||||||
]);
|
]);
|
||||||
$this->assertDatabaseHas('carritos', [
|
$this->assertDatabaseHas('carritos', [
|
||||||
'id' => $activeCart->id,
|
'id' => $activeCart->id,
|
||||||
@@ -637,12 +654,7 @@ class StorePurchaseTest extends TestCase
|
|||||||
'current_purchase_id' => null,
|
'current_purchase_id' => null,
|
||||||
'deleted_at' => null,
|
'deleted_at' => null,
|
||||||
]);
|
]);
|
||||||
$this->assertDatabaseHas('stock_reservations', [
|
$this->assertPurchaseReservation($purchase->id, $variant->inventory_id, 3, 'expired');
|
||||||
'cart_item_id' => $cartItemId,
|
|
||||||
'purchase_id' => null,
|
|
||||||
'quantity' => 3,
|
|
||||||
'status' => 'active',
|
|
||||||
]);
|
|
||||||
$this->assertSame(1, $activeCart->items()->count());
|
$this->assertSame(1, $activeCart->items()->count());
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -912,10 +924,7 @@ class StorePurchaseTest extends TestCase
|
|||||||
'current_purchase_id' => null,
|
'current_purchase_id' => null,
|
||||||
'deleted_at' => null,
|
'deleted_at' => null,
|
||||||
]);
|
]);
|
||||||
$this->assertDatabaseHas('stock_reservations', [
|
$this->assertPurchaseReservation($purchase->id, $variant->inventory_id, 2, 'active');
|
||||||
'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
|
||||||
@@ -957,7 +966,7 @@ class StorePurchaseTest extends TestCase
|
|||||||
|
|
||||||
$this->artisan('reservations:expire')
|
$this->artisan('reservations:expire')
|
||||||
->expectsOutput('Expired purchases: 1')
|
->expectsOutput('Expired purchases: 1')
|
||||||
->expectsOutput('Expired cart items: 0')
|
->expectsOutput('Expired cart reservations: 0')
|
||||||
->assertSuccessful();
|
->assertSuccessful();
|
||||||
|
|
||||||
$this->assertDatabaseHas('compras', [
|
$this->assertDatabaseHas('compras', [
|
||||||
@@ -968,15 +977,11 @@ class StorePurchaseTest extends TestCase
|
|||||||
'compra_id' => $purchase->id,
|
'compra_id' => $purchase->id,
|
||||||
'cantidad' => 3,
|
'cantidad' => 3,
|
||||||
]);
|
]);
|
||||||
$this->assertDatabaseHas('stock_reservations', [
|
$this->assertPurchaseReservation($purchase->id, $variant->inventory_id, 3, 'expired');
|
||||||
'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' => 3,
|
'reserved_stock' => 0,
|
||||||
'sold_units' => 0,
|
'sold_units' => 0,
|
||||||
]);
|
]);
|
||||||
$this->assertDatabaseHas('carritos', [
|
$this->assertDatabaseHas('carritos', [
|
||||||
@@ -989,7 +994,7 @@ class StorePurchaseTest extends TestCase
|
|||||||
|
|
||||||
$this->artisan('reservations:expire')
|
$this->artisan('reservations:expire')
|
||||||
->expectsOutput('Expired purchases: 0')
|
->expectsOutput('Expired purchases: 0')
|
||||||
->expectsOutput('Expired cart items: 0')
|
->expectsOutput('Expired cart reservations: 0')
|
||||||
->assertSuccessful();
|
->assertSuccessful();
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1006,6 +1011,7 @@ 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',
|
||||||
@@ -1018,7 +1024,7 @@ class StorePurchaseTest extends TestCase
|
|||||||
|
|
||||||
$this->artisan('reservations:expire')
|
$this->artisan('reservations:expire')
|
||||||
->expectsOutput('Expired purchases: 2')
|
->expectsOutput('Expired purchases: 2')
|
||||||
->expectsOutput('Expired cart items: 0')
|
->expectsOutput('Expired cart reservations: 0')
|
||||||
->assertSuccessful();
|
->assertSuccessful();
|
||||||
|
|
||||||
$this->assertDatabaseHas('compras', [
|
$this->assertDatabaseHas('compras', [
|
||||||
@@ -1160,12 +1166,7 @@ class StorePurchaseTest extends TestCase
|
|||||||
'reserved_stock' => 0,
|
'reserved_stock' => 0,
|
||||||
'sold_units' => 2,
|
'sold_units' => 2,
|
||||||
]);
|
]);
|
||||||
$this->assertDatabaseHas('stock_reservations', [
|
$this->assertPurchaseReservation($purchase->id, $variant->inventory_id, 2, 'committed');
|
||||||
'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,
|
||||||
@@ -1440,6 +1441,26 @@ 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();
|
||||||
|
|||||||
@@ -520,8 +520,10 @@ 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', [
|
||||||
'purchase_id' => $purchase->id,
|
'id' => $reservationId,
|
||||||
'status' => 'released',
|
'status' => 'released',
|
||||||
]);
|
]);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -300,10 +300,13 @@ 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(48, DB::table('stock_reservations')
|
$this->assertSame(1, DB::table('stock_reservations')
|
||||||
->where('purchase_id', $purchase->id)
|
->where('id', $purchase->stock_reservation_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],
|
||||||
|
|||||||
@@ -70,6 +70,14 @@ 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)
|
||||||
|
|||||||
@@ -83,11 +83,13 @@ 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,
|
||||||
@@ -100,6 +102,7 @@ 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);
|
||||||
|
|||||||
@@ -12,7 +12,7 @@ use Tests\TestCase;
|
|||||||
|
|
||||||
class ExpireStockReservationsServiceTest extends TestCase
|
class ExpireStockReservationsServiceTest extends TestCase
|
||||||
{
|
{
|
||||||
public function test_it_expires_purchases_before_abandoned_cart_items(): void
|
public function test_it_expires_purchases_before_abandoned_cart_reservations(): 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_items' => 3,
|
'expired_cart_reservations' => 3,
|
||||||
'total_expired' => 5,
|
'total_expired' => 5,
|
||||||
]);
|
]);
|
||||||
|
|
||||||
@@ -44,7 +44,7 @@ class ExpireStockReservationsServiceTest extends TestCase
|
|||||||
|
|
||||||
$this->assertSame([
|
$this->assertSame([
|
||||||
'purchases' => 2,
|
'purchases' => 2,
|
||||||
'cart_items' => 3,
|
'cart_reservations' => 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_items' => null,
|
'expired_cart_reservations' => null,
|
||||||
'exception' => $exception,
|
'exception' => $exception,
|
||||||
]);
|
]);
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user