58 lines
1.7 KiB
PHP
58 lines
1.7 KiB
PHP
<?php
|
|
|
|
namespace App\Domains\Catalog\Services;
|
|
|
|
use App\Domains\Catalog\Models\CatalogItem;
|
|
use App\Domains\Purchase\Services\UserPurchaseLimitService;
|
|
use Illuminate\Support\Collection;
|
|
|
|
class CatalogItemAllowanceService
|
|
{
|
|
private const USER_QUOTA_REACHED_MESSAGE = 'Alcanzaste el cupo máximo permitido para este producto.';
|
|
|
|
private const OUT_OF_STOCK_MESSAGE = 'Este producto no tiene stock disponible.';
|
|
|
|
public function __construct(
|
|
private readonly UserPurchaseLimitService $purchaseLimits,
|
|
) {}
|
|
|
|
/** @param Collection<int, CatalogItem> $catalogItems */
|
|
public function attach(Collection $catalogItems, ?int $userId): void
|
|
{
|
|
$remaining = $this->purchaseLimits->remainingByCatalogItem($catalogItems, $userId);
|
|
|
|
foreach ($catalogItems as $catalogItem) {
|
|
$catalogItem->setAttribute(
|
|
'remaining_user_quota',
|
|
$remaining->get($catalogItem->getKey()),
|
|
);
|
|
}
|
|
}
|
|
|
|
public function maximumAddableQuantity(?int $availableStock, ?int $remainingUserQuota): ?int
|
|
{
|
|
if ($availableStock === null) {
|
|
return $remainingUserQuota;
|
|
}
|
|
|
|
if ($remainingUserQuota === null) {
|
|
return $availableStock;
|
|
}
|
|
|
|
return min($availableStock, $remainingUserQuota);
|
|
}
|
|
|
|
public function unavailableMessage(?int $availableStock, ?int $remainingUserQuota): ?string
|
|
{
|
|
if ($remainingUserQuota !== null && $remainingUserQuota <= 0) {
|
|
return self::USER_QUOTA_REACHED_MESSAGE;
|
|
}
|
|
|
|
if ($availableStock !== null && $availableStock <= 0) {
|
|
return self::OUT_OF_STOCK_MESSAGE;
|
|
}
|
|
|
|
return null;
|
|
}
|
|
}
|