Compare commits

..

7 Commits

30 changed files with 496 additions and 306 deletions

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -246,7 +246,7 @@ class CartControllerTest extends TestCase
->assertJsonPath('code', 'purchase.limit_exceeded')
->assertJsonPath('catalog_item_id', $item->id)
->assertJsonPath('catalog_item_name', $item->nombre)
->assertJsonPath('maximum_addable_quantity', 1)
->assertJsonPath('availability.maximum_quantity', 1)
->assertJsonPath(
'message',
"Podés agregar hasta 1 unidad más de “{$item->nombre}”.",

View File

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

View File

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

View File

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

View File

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

View File

@@ -62,24 +62,8 @@ class CatalogSearchTest extends TestCase
$this->createCatalogItem($tenant, "Running {$number}");
}
$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,
]);
$outOfStockMatch = $this->createCatalogItem($tenant, 'Running unavailable');
$outOfStockMatch->inventory->update(['real_stock' => 0]);
$this->createCatalogItem($tenant, 'Unrelated');
$this->createCatalogItem($otherTenant, 'Running foreign');
@@ -94,8 +78,7 @@ class CatalogSearchTest extends TestCase
->assertJsonPath('meta.total', 6)
->assertJsonCount(4, 'data')
->assertJsonPath('data.0.id', $exactMatch->id)
->assertJsonMissing(['nombre' => 'Running sold out'])
->assertJsonMissing(['nombre' => 'Running direct sold out'])
->assertJsonMissing(['nombre' => 'Running unavailable'])
->assertJsonMissing(['nombre' => 'Running foreign'])
->assertJsonMissing(['nombre' => 'Unrelated']);
}

View File

@@ -29,17 +29,6 @@ class CategoryDetailTest extends TestCase
$this->createCatalogItem($tenant, $category, 'Remera C');
$firstItem = $this->createCatalogItem($tenant, $category, 'Remera A');
$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->getJson("/api/tenants/{$tenant->codigo}/categories/{$category->id}")
@@ -55,7 +44,6 @@ class CategoryDetailTest extends TestCase
->assertJsonCount(2, 'data')
->assertJsonPath('data.0.id', $firstItem->id)
->assertJsonPath('data.1.id', $secondItem->id)
->assertJsonMissing(['nombre' => 'Remera agotada'])
->assertJsonMissing(['nombre' => 'Pantalón']);
}

View File

@@ -394,7 +394,7 @@ class StorePurchaseTest extends TestCase
->assertJsonPath('code', 'purchase.limit_exceeded')
->assertJsonPath('catalog_item_id', $variant->catalog_item_id)
->assertJsonPath('catalog_item_name', $variant->catalogItem->nombre)
->assertJsonPath('maximum_addable_quantity', 1);
->assertJsonPath('availability.maximum_quantity', 1);
$this->actingAs($otherUser, 'sanctum')
->postJson('/api/tenants/sonder/compras/start-checkout', [

View File

@@ -70,14 +70,6 @@ class FiestaFutbolInfantilProductSeederTest extends TestCase
['abono', 'alojamiento', 'camiseta', 'comida'],
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(
CatalogItem::query()
->where('tenant_code', $tenant->codigo)

View File

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

View File

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