feat(cart): implement user purchase limit validation for cart items and add related tests
This commit is contained in:
@@ -21,6 +21,7 @@ class CheckoutService
|
||||
{
|
||||
public function __construct(
|
||||
private readonly CatalogInventoryService $catalogInventoryService,
|
||||
private readonly UserPurchaseLimitService $userPurchaseLimitService,
|
||||
) {}
|
||||
|
||||
public function startCheckout(Tenant $tenant, int $userId, array $purchaseData): Purchase
|
||||
@@ -709,34 +710,13 @@ class CheckoutService
|
||||
?int $excludedPurchaseId = null,
|
||||
string $field = 'quantity',
|
||||
): void {
|
||||
$limit = $catalogItem->max_units_per_user;
|
||||
|
||||
if ($limit === null) {
|
||||
return;
|
||||
}
|
||||
|
||||
$purchasedQuantity = (int) PurchaseItem::query()
|
||||
->where('source_catalog_item_id', $catalogItem->getKey())
|
||||
->whereHas('purchase', function ($query) use ($userId, $excludedPurchaseId): void {
|
||||
$query
|
||||
->where('user_id', $userId)
|
||||
->whereIn('status', [
|
||||
Purchase::STATUS_CREATED,
|
||||
Purchase::STATUS_PENDING_PAYMENT,
|
||||
Purchase::STATUS_PAID,
|
||||
])
|
||||
->when(
|
||||
$excludedPurchaseId !== null,
|
||||
fn ($query) => $query->whereKeyNot($excludedPurchaseId),
|
||||
);
|
||||
})
|
||||
->sum('cantidad');
|
||||
|
||||
if ($purchasedQuantity + $requestedQuantity > $limit) {
|
||||
throw ValidationException::withMessages([
|
||||
$field => __('api.purchase.max_units_per_user', ['max' => $limit]),
|
||||
]);
|
||||
}
|
||||
$this->userPurchaseLimitService->assertCanPurchase(
|
||||
$catalogItem,
|
||||
$userId,
|
||||
$requestedQuantity,
|
||||
$excludedPurchaseId,
|
||||
$field,
|
||||
);
|
||||
}
|
||||
|
||||
protected function resolveCheckoutCart(Tenant $tenant, int $userId, int $cartId): Cart
|
||||
|
||||
Reference in New Issue
Block a user