feat(purchase): implement purchase limit enforcement and custom exception handling

This commit is contained in:
2026-08-19 16:43:59 -03:00
parent 8537d2ed0a
commit 5c0b3503b7
15 changed files with 124 additions and 41 deletions

View File

@@ -103,9 +103,14 @@ class Cart extends Model
$cartQuantity = (int) $this->items()
->where('catalog_item_id', $catalogItemId)
->sum('cantidad');
$this->assertUserPurchaseLimit($selectedItem, $cartQuantity + $quantity);
$inventoryService = app(CatalogInventoryService::class);
$availableQuantity = $inventoryService->availableQuantity($selectedItem);
$this->assertUserPurchaseLimit(
$selectedItem,
$cartQuantity + $quantity,
heldQuantity: $cartQuantity,
maximumAddableCeiling: $availableQuantity,
);
if ($availableQuantity !== null && $availableQuantity < $quantity) {
throw ValidationException::withMessages([
@@ -181,10 +186,13 @@ class Cart extends Model
->where('catalog_item_id', $item->catalog_item_id)
->whereKeyNot($item->getKey())
->sum('cantidad');
$nextAvailableQuantity = $inventoryService->availableQuantity($nextSelection);
$this->assertUserPurchaseLimit(
$nextSelection,
$otherVariantsQuantity + $quantity,
$excludedPurchaseId,
$otherVariantsQuantity + $item->cantidad,
$nextAvailableQuantity,
);
app(StockReservationService::class)->release($item, $currentSelection, $item->cantidad);
@@ -222,6 +230,7 @@ class Cart extends Model
}
$delta = $quantity - $item->cantidad;
$availableQuantity = $inventoryService->availableQuantity($currentSelection);
if ($delta > 0) {
$otherVariantsQuantity = (int) $this->items()
@@ -232,11 +241,11 @@ class Cart extends Model
$currentSelection,
$otherVariantsQuantity + $quantity,
$excludedPurchaseId,
$otherVariantsQuantity + $item->cantidad,
$availableQuantity,
);
}
$availableQuantity = $inventoryService->availableQuantity($currentSelection);
if ($delta > 0 && $availableQuantity !== null && $availableQuantity < $delta) {
$maxAvailable = $availableQuantity + $item->cantidad;
throw ValidationException::withMessages([
@@ -355,6 +364,8 @@ class Cart extends Model
CatalogItem|Variant $selectedItem,
int $cartQuantity,
?int $excludedPurchaseId = null,
int $heldQuantity = 0,
?int $maximumAddableCeiling = null,
): void {
if ($this->user_id === null) {
return;
@@ -370,6 +381,8 @@ class Cart extends Model
$cartQuantity,
$excludedPurchaseId,
$this->getKey(),
$heldQuantity,
$maximumAddableCeiling,
field: 'cantidad',
);
}

View File

@@ -36,7 +36,6 @@ class CatalogFeaturedItemResource extends JsonResource
'nombre' => $catalogItem->nombre,
'descripcion' => $catalogItem->descripcion,
'precio' => $catalogItem->precio,
'stock_tecnico' => $catalogItem->availableStock(),
'maximum_addable_quantity' => $this->maximumAddable(
$catalogItem->availableStock(),
$remainingUserQuota,
@@ -50,9 +49,6 @@ class CatalogFeaturedItemResource extends JsonResource
'event_dates' => $variant->selectedEventDates()->map(fn ($eventDate): string => $eventDate->date->format('Y-m-d'))->values(),
'descripcion' => $variant->getDescription(),
'precio' => number_format($variant->getPrice(), 2, '.', ''),
'stock_tecnico' => $catalogItem->inventory_policy === InventoryPolicy::Unlimited
? null
: $variant->inventory->availableStock(),
'maximum_addable_quantity' => $this->maximumAddable(
$catalogItem->inventory_policy === InventoryPolicy::Unlimited
? null

View File

@@ -38,10 +38,6 @@ class CatalogItemDetailResource extends JsonResource
'max_units_per_user' => $this->max_units_per_user,
'has_tickets' => $this->has_tickets,
'attributes' => $this->attributesData(),
'stock_tecnico' => $this->when(
$selectedVariant === null,
fn () => $this->availableStock(),
),
'maximum_addable_quantity' => $this->when(
$selectedVariant === null,
fn () => $this->maximumAddable($this->availableStock()),
@@ -172,7 +168,6 @@ class CatalogItemDetailResource extends JsonResource
'event_dates' => $eventDates->map(fn ($eventDate): string => $eventDate->date->format('Y-m-d'))->values(),
'descripcion' => $variant->getDescription(),
'precio' => number_format($variant->getPrice(), 2, '.', ''),
'stock_tecnico' => $this->variantStock($variant),
'maximum_addable_quantity' => $this->maximumAddable($this->variantStock($variant)),
'values' => $values,
];

View File

@@ -27,7 +27,6 @@ class CatalogSearchItemResource extends JsonResource
'descripcion' => $this->descripcion,
'precio' => $this->precio,
'image' => $attachment?->getTemporaryUrl(1440),
'stock_tecnico' => $this->availableStock(),
'maximum_addable_quantity' => $this->maximumAddable($this->availableStock()),
'variants' => $this->visibleVariants()
->map(fn (Variant $variant): array => [
@@ -38,9 +37,6 @@ class CatalogSearchItemResource extends JsonResource
'event_dates' => $variant->selectedEventDates()->map(fn ($eventDate): string => $eventDate->date->format('Y-m-d'))->values(),
'descripcion' => $variant->getDescription(),
'precio' => number_format($variant->getPrice(), 2, '.', ''),
'stock_tecnico' => $this->inventory_policy === InventoryPolicy::Unlimited
? null
: $variant->inventory?->availableStock(),
'maximum_addable_quantity' => $this->maximumAddable(
$this->inventory_policy === InventoryPolicy::Unlimited
? null

View File

@@ -0,0 +1,31 @@
<?php
namespace App\Domains\Purchase\Exceptions;
use App\Domains\Catalog\Models\CatalogItem;
use Illuminate\Validation\ValidationException;
class PurchaseLimitExceededException extends ValidationException
{
public readonly int $catalogItemId;
public readonly string $catalogItemName;
public readonly int $maximumAddableQuantity;
public function __construct(CatalogItem $catalogItem, int $maximumAddableQuantity, string $field)
{
$this->catalogItemId = (int) $catalogItem->getKey();
$this->catalogItemName = $catalogItem->nombre;
$this->maximumAddableQuantity = $maximumAddableQuantity;
parent::__construct(validator([], []));
$message = trans_choice('api.purchase_limit.exceeded', $maximumAddableQuantity, [
'max' => $maximumAddableQuantity,
'product' => $this->catalogItemName,
]);
$this->message = $message;
$this->validator->errors()->add($field, $message);
}
}

View File

@@ -120,10 +120,16 @@ class StartCheckoutService
->each(function (Collection $catalogLines) use ($userId): void {
/** @var CatalogItem $catalogItem */
$catalogItem = $catalogLines->first()['catalog_item'];
$availableQuantities = $catalogLines
->map(fn (array $line): ?int => $this->inventory->availableQuantity($line['selection']));
$maximumAddableCeiling = $availableQuantities->contains(null)
? null
: (int) $availableQuantities->sum();
$this->purchaseLimits->assertCanPurchase(
$catalogItem,
$userId,
(int) $catalogLines->sum('quantity'),
maximumAddableCeiling: $maximumAddableCeiling,
field: 'direct_items',
);
});
@@ -335,6 +341,7 @@ class StartCheckoutService
$userId,
$quantity,
excludedCartId: $cartId,
heldQuantity: $quantity,
field: 'cart_id',
);
}

View File

@@ -4,11 +4,11 @@ namespace App\Domains\Purchase\Services;
use App\Domains\Cart\Models\CartItem;
use App\Domains\Catalog\Models\CatalogItem;
use App\Domains\Purchase\Exceptions\PurchaseLimitExceededException;
use App\Domains\Purchase\Models\Purchase;
use App\Domains\Purchase\Models\PurchaseItem;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\DB;
use Illuminate\Validation\ValidationException;
class UserPurchaseLimitService
{
@@ -18,6 +18,8 @@ class UserPurchaseLimitService
int $requestedQuantity,
?int $excludedPurchaseId = null,
?int $excludedCartId = null,
int $heldQuantity = 0,
?int $maximumAddableCeiling = null,
string $field = 'quantity',
): void {
DB::transaction(function () use (
@@ -26,6 +28,8 @@ class UserPurchaseLimitService
$requestedQuantity,
$excludedPurchaseId,
$excludedCartId,
$heldQuantity,
$maximumAddableCeiling,
$field,
): void {
/** @var CatalogItem $catalogItem */
@@ -86,9 +90,20 @@ class UserPurchaseLimitService
->sum('cantidad');
if ($purchasedQuantity + $checkoutQuantity + $reservedCartQuantity + $requestedQuantity > $limit) {
throw ValidationException::withMessages([
$field => __('api.purchase_limit.exceeded', ['max' => $limit]),
]);
$remainingQuota = max(
0,
$limit - $purchasedQuantity - $checkoutQuantity - $reservedCartQuantity,
);
$maximumAddableQuantity = max(0, $remainingQuota - $heldQuantity);
throw new PurchaseLimitExceededException(
$catalogItem,
$maximumAddableCeiling === null
? $maximumAddableQuantity
: min($maximumAddableQuantity, $maximumAddableCeiling),
$field,
);
}
});
}