13 Commits

52 changed files with 1175 additions and 1719 deletions

View File

@@ -2,7 +2,6 @@
namespace App\Domains\Cart\Controllers;
use App\Domains\Cart\Models\Cart;
use App\Domains\Cart\Models\CartItem;
use App\Domains\Cart\Requests\AddCartItemRequest;
use App\Domains\Cart\Requests\UpdateCartItemQuantityRequest;
@@ -78,36 +77,6 @@ class CartController extends Controller
]);
}
public function updateCheckoutItem(
UpdateCartItemQuantityRequest $request,
Tenant $tenant,
Cart $cart,
CartItem $cartItem,
): CartResource {
$updatesVariant = $request->exists('variant_id');
return CartResource::make(
$this->cartService->updateCheckoutItem(
$tenant,
$request,
$cart,
$cartItem->getKey(),
(int) $request->validated('cantidad'),
$updatesVariant
? ($request->validated('variant_id') !== null
? (int) $request->validated('variant_id')
: null)
: $cartItem->variant_id,
$updatesVariant,
),
)->additional([
'code' => $updatesVariant ? 'cart.item_updated' : 'cart.quantity_updated',
'message' => $updatesVariant
? __('api.cart.item_updated')
: __('api.cart.quantity_updated'),
]);
}
public function removeItem(Request $request, Tenant $tenant, CartItem $cartItem): CartResource
{
return CartResource::make(
@@ -117,23 +86,4 @@ class CartController extends Controller
'message' => __('api.cart.item_removed'),
]);
}
public function removeCheckoutItem(
Request $request,
Tenant $tenant,
Cart $cart,
CartItem $cartItem,
): CartResource {
return CartResource::make(
$this->cartService->removeCheckoutItem(
$tenant,
$request,
$cart,
$cartItem->getKey(),
),
)->additional([
'code' => 'cart.item_removed',
'message' => __('api.cart.item_removed'),
]);
}
}

View File

@@ -27,6 +27,7 @@ use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
'guest_token',
'status',
'origin',
'current_purchase_id',
])]
class Cart extends Model
{
@@ -43,6 +44,7 @@ class Cart extends Model
{
return [
'user_id' => 'integer',
'current_purchase_id' => 'integer',
];
}
@@ -76,6 +78,12 @@ class Cart extends Model
return $this->hasMany(Purchase::class, 'cart_id');
}
/** @return BelongsTo<Purchase, $this> */
public function currentPurchase(): BelongsTo
{
return $this->belongsTo(Purchase::class, 'current_purchase_id');
}
public function getTotalAmount(): float
{
$items = $this->relationLoaded('items')
@@ -98,7 +106,7 @@ class Cart extends Model
}
return DB::transaction(function () use ($catalogItemId, $variantId, $quantity): CartItem {
self::query()->whereKey($this->getKey())->lockForUpdate()->firstOrFail();
$this->invalidateCurrentCheckout();
$selectedItem = $this->resolveScopedItem($catalogItemId, $variantId, true);
$cartQuantity = (int) $this->items()
->where('catalog_item_id', $catalogItemId)
@@ -163,6 +171,8 @@ class Cart extends Model
$updateVariant,
$excludedPurchaseId,
): CartItem {
$this->invalidateCurrentCheckout();
/** @var CartItem $item */
$item = $this->items()
->where('id', $cartItemId)
@@ -271,6 +281,8 @@ class Cart extends Model
public function removeItem(int $cartItemId): void
{
DB::transaction(function () use ($cartItemId): void {
$this->invalidateCurrentCheckout();
/** @var CartItem $item */
$item = $this->items()
->where('id', $cartItemId)
@@ -291,6 +303,58 @@ class Cart extends Model
});
}
private function invalidateCurrentCheckout(): void
{
$candidatePurchaseId = self::query()
->whereKey($this->getKey())
->value('current_purchase_id');
$currentPurchase = $candidatePurchaseId === null
? null
: Purchase::query()->lockForUpdate()->find($candidatePurchaseId);
/** @var self $cart */
$cart = self::query()->lockForUpdate()->findOrFail($this->getKey());
if ($cart->current_purchase_id !== $candidatePurchaseId) {
if ($cart->current_purchase_id !== null) {
throw ValidationException::withMessages([
'cart' => __('api.purchase.checkout_in_progress'),
]);
}
$this->current_purchase_id = null;
return;
}
if ($currentPurchase === null) {
return;
}
if ($currentPurchase->status === Purchase::STATUS_PAID) {
throw ValidationException::withMessages([
'cart' => __('api.cart.editing_disabled'),
]);
}
if (in_array($currentPurchase->status, [
Purchase::STATUS_CREATED,
Purchase::STATUS_PENDING_PAYMENT,
], true)) {
$currentPurchase->update([
'status' => Purchase::STATUS_SUPERSEDED,
'expires_at' => null,
]);
}
app(StockReservationService::class)->detachFromPurchase($currentPurchase);
self::query()
->whereKey($cart->getKey())
->where('current_purchase_id', $currentPurchase->getKey())
->update(['current_purchase_id' => null]);
$this->current_purchase_id = null;
}
protected function resolveScopedItem(
int $catalogItemId,
?int $variantId,

View File

@@ -2,7 +2,6 @@
namespace App\Domains\Cart\Resources;
use App\Domains\Cart\Models\Cart;
use App\Domains\Cart\Models\CartItem;
use App\Domains\Catalog\Enums\InventoryPolicy;
use App\Domains\Catalog\Models\Variant;
@@ -23,13 +22,9 @@ class CartItemResource extends JsonResource
$selectedItem = $this->selectedItem();
$imageUrl = null;
$tenant = $request->route('tenant');
$checkoutCart = $request->route('cart');
$displayImage = ! $tenant instanceof Tenant || $tenant->display_cart_item_images;
$includeVariants = $tenant instanceof Tenant
&& ($checkoutCart instanceof Cart
? $tenant->checkout_editing_policy
: $tenant->cart_editing_policy)
->allowsVariantChanges();
&& $tenant->cart_editing_policy->allowsVariantChanges();
if ($displayImage && $selectedItem?->relationLoaded('attachments')) {
$imageUrl = $selectedItem->attachments->first()?->getTemporaryUrl(1440);

View File

@@ -4,14 +4,9 @@ namespace App\Domains\Cart\Services;
use App\Domains\Auth\Models\User;
use App\Domains\Cart\Models\Cart;
use App\Domains\Cart\Models\CartItem;
use App\Domains\Catalog\Services\StockReservationService;
use App\Domains\Purchase\Models\Purchase;
use App\Domains\Purchase\Services\PurchaseStateGuard;
use App\Domains\Tenant\Models\Tenant;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
use Illuminate\Validation\ValidationException;
use Symfony\Component\HttpFoundation\Cookie;
@@ -19,11 +14,6 @@ use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
class CartService
{
public function __construct(
private readonly StockReservationService $reservations,
private readonly PurchaseStateGuard $purchaseState,
) {}
public function show(Tenant $tenant, Request $request): Cart
{
$resolvedIdentity = $this->resolveIdentity($request);
@@ -89,125 +79,6 @@ class CartService
return $this->loadCart($cart, $tenant);
}
public function updateCheckoutItem(
Tenant $tenant,
Request $request,
Cart $cart,
int $cartItemId,
int $quantity,
?int $variantId,
bool $updateVariant,
): Cart {
$user = $request->user() ?? Auth::guard('sanctum')->user();
if (! $user instanceof User) {
throw new NotFoundHttpException('Checkout cart not found.');
}
return DB::transaction(function () use (
$tenant,
$user,
$cart,
$cartItemId,
$quantity,
$variantId,
$updateVariant,
): Cart {
/** @var Purchase|null $purchase */
$purchase = Purchase::query()
->where('cart_id', $cart->getKey())
->where('tenant_codigo', $tenant->codigo)
->where('user_id', $user->getKey())
->whereDoesntHave('items')
->lockForUpdate()
->first();
if ($purchase === null) {
throw new NotFoundHttpException('Checkout cart not found.');
}
$this->purchaseState->assertNotExpired($purchase);
if (! in_array($purchase->status, [
Purchase::STATUS_CREATED,
Purchase::STATUS_PENDING_PAYMENT,
], true)) {
throw new NotFoundHttpException('Checkout cart not found.');
}
/** @var Cart|null $checkoutCart */
$checkoutCart = Cart::query()
->whereKey($cart->getKey())
->where('tenant_codigo', $tenant->codigo)
->where('user_id', $user->getKey())
->where('status', 'checkout')
->lockForUpdate()
->first();
if ($checkoutCart === null) {
throw new NotFoundHttpException('Checkout cart not found.');
}
/** @var CartItem|null $cartItem */
$cartItem = $checkoutCart->items()
->whereKey($cartItemId)
->lockForUpdate()
->first();
if ($cartItem === null) {
throw new NotFoundHttpException('Checkout item not found.');
}
$hasChanges = (int) $cartItem->cantidad !== $quantity
|| ($updateVariant && $cartItem->variant_id !== $variantId);
if (! $hasChanges) {
return $this->loadCart($checkoutCart, $tenant, true);
}
if (
(int) $cartItem->cantidad !== $quantity
&& ! $tenant->checkout_editing_policy->allowsQuantityChanges()
) {
throw ValidationException::withMessages([
'cantidad' => __('api.cart.editing_disabled'),
]);
}
if (
$updateVariant
&& $cartItem->variant_id !== $variantId
&& ! $tenant->checkout_editing_policy->allowsVariantChanges()
) {
throw ValidationException::withMessages([
'variant_id' => __('api.cart.variant_change_disabled'),
]);
}
$checkoutCart->updateItem(
$cartItemId,
$quantity,
$variantId,
$updateVariant,
$purchase->getKey(),
);
$purchase->telepagosQr()->delete();
$purchase->update([
'status' => Purchase::STATUS_CREATED,
'payment_method' => null,
'transfer_payer_dni' => null,
'total' => $checkoutCart->getTotalAmount(),
'expires_at' => now()->addMinutes(
max(1, (int) config('purchase.checkout_expiration_minutes', 30)),
),
]);
$this->reservations->syncPurchaseExpiration($purchase);
return $this->loadCart($checkoutCart, $tenant, true);
});
}
public function removeItem(Tenant $tenant, Request $request, int $cartItemId): Cart
{
if (! $tenant->cart_editing_policy->allowsRemoval()) {
@@ -223,77 +94,6 @@ class CartService
return $this->loadCart($cart, $tenant);
}
public function removeCheckoutItem(
Tenant $tenant,
Request $request,
Cart $cart,
int $cartItemId,
): Cart {
if (! $tenant->checkout_editing_policy->allowsRemoval()) {
throw ValidationException::withMessages([
'cart_item' => __('api.cart.editing_disabled'),
]);
}
$user = $request->user() ?? Auth::guard('sanctum')->user();
if (! $user instanceof User) {
throw new NotFoundHttpException('Checkout cart not found.');
}
return DB::transaction(function () use ($tenant, $user, $cart, $cartItemId): Cart {
/** @var Purchase|null $purchase */
$purchase = Purchase::query()
->where('cart_id', $cart->getKey())
->where('tenant_codigo', $tenant->codigo)
->where('user_id', $user->getKey())
->whereDoesntHave('items')
->lockForUpdate()
->first();
if ($purchase === null) {
throw new NotFoundHttpException('Checkout cart not found.');
}
$this->purchaseState->assertNotExpired($purchase);
if (! in_array($purchase->status, [
Purchase::STATUS_CREATED,
Purchase::STATUS_PENDING_PAYMENT,
], true)) {
throw new NotFoundHttpException('Checkout cart not found.');
}
/** @var Cart|null $checkoutCart */
$checkoutCart = Cart::query()
->whereKey($cart->getKey())
->where('tenant_codigo', $tenant->codigo)
->where('user_id', $user->getKey())
->where('status', 'checkout')
->lockForUpdate()
->first();
if ($checkoutCart === null) {
throw new NotFoundHttpException('Checkout cart not found.');
}
$checkoutCart->removeItem($cartItemId);
$purchase->telepagosQr()->delete();
$purchase->update([
'status' => Purchase::STATUS_CREATED,
'payment_method' => null,
'transfer_payer_dni' => null,
'total' => $checkoutCart->getTotalAmount(),
'expires_at' => now()->addMinutes(
max(1, (int) config('purchase.checkout_expiration_minutes', 30)),
),
]);
$this->reservations->syncPurchaseExpiration($purchase);
return $this->loadCart($checkoutCart, $tenant, true);
});
}
public function makeGuestTokenCookie(string $guestToken): Cookie
{
$secure = (bool) config('session.secure');
@@ -327,7 +127,7 @@ class CartService
return $cart;
}
protected function loadCart(Cart $cart, Tenant $tenant, bool $isCheckout = false): Cart
protected function loadCart(Cart $cart, Tenant $tenant): Cart
{
$relations = [
'items.catalogItem.attachments',
@@ -340,11 +140,7 @@ class CartService
'items.variant.eventDate',
];
$editingPolicy = $isCheckout
? $tenant->checkout_editing_policy
: $tenant->cart_editing_policy;
if ($editingPolicy->allowsVariantChanges()) {
if ($tenant->cart_editing_policy->allowsVariantChanges()) {
$relations = [
...$relations,
'items.catalogItem.variants' => fn ($query) => $query->orderBy('id'),

View File

@@ -10,10 +10,3 @@ Route::prefix('tenants/{tenant:codigo}')
Route::patch('cart/items/{cartItem}', [CartController::class, 'updateItemQuantity']);
Route::delete('cart/items/{cartItem}', [CartController::class, 'removeItem']);
});
Route::prefix('tenants/{tenant:codigo}')
->middleware('auth:sanctum')
->group(function (): void {
Route::patch('checkout-carts/{cart}/items/{cartItem}', [CartController::class, 'updateCheckoutItem'])->withTrashed();
Route::delete('checkout-carts/{cart}/items/{cartItem}', [CartController::class, 'removeCheckoutItem'])->withTrashed();
});

View File

@@ -20,7 +20,6 @@ class CatalogFeaturedItemResource extends JsonResource
$catalogItem = $this->resource;
/** @var FeaturedGroup $featuredGroup */
$featuredGroup = $catalogItem->getRelation('featuredGroup');
$remainingUserQuota = $catalogItem->getAttribute('remaining_user_quota');
if ($featuredGroup->product_layout === ProductLayout::ColumnWithImage) {
return $this->columnWithImageData($catalogItem);
@@ -30,6 +29,9 @@ class CatalogFeaturedItemResource extends JsonResource
return $this->ticketSelectorData($catalogItem);
}
$remainingUserQuota = $catalogItem->getAttribute('remaining_user_quota');
$availableStock = $catalogItem->availableStock();
$data = [
'id' => $catalogItem->id,
'type' => $catalogItem->type->value,
@@ -37,26 +39,38 @@ class CatalogFeaturedItemResource extends JsonResource
'descripcion' => $catalogItem->descripcion,
'precio' => $catalogItem->precio,
'maximum_addable_quantity' => $this->maximumAddable(
$catalogItem->availableStock(),
$availableStock,
$remainingUserQuota,
),
'variants' => $catalogItem->visibleVariants()
->map(fn (Variant $variant): array => [
'id' => $variant->id,
'event_date_id' => $variant->event_date_id,
'event_date' => $variant->eventDate?->date?->format('Y-m-d'),
'event_date_ids' => $variant->selectedEventDates()->pluck('id')->values(),
'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(
$catalogItem->inventory_policy === InventoryPolicy::Unlimited
? null
: $variant->inventory->availableStock(),
$remainingUserQuota,
),
'values' => $variant->selectorOptions($catalogItem->itemAttributes),
])
'unavailable_message' => $this->unavailableMessage(
$availableStock,
$remainingUserQuota,
),
'variants' => $catalogItem->variants
->map(function (Variant $variant) use ($catalogItem, $remainingUserQuota): array {
$variantStock = $catalogItem->inventory_policy === InventoryPolicy::Unlimited
? null
: $variant->inventory->availableStock();
return [
'id' => $variant->id,
'event_date_id' => $variant->event_date_id,
'event_date' => $variant->eventDate?->date?->format('Y-m-d'),
'event_date_ids' => $variant->selectedEventDates()->pluck('id')->values(),
'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,
),
'values' => $variant->selectorOptions($catalogItem->itemAttributes),
];
})
->values(),
];
@@ -66,6 +80,9 @@ class CatalogFeaturedItemResource extends JsonResource
/** @return array<string, mixed> */
private function ticketSelectorData(CatalogItem $catalogItem): array
{
$availableStock = $catalogItem->availableStock();
$remainingUserQuota = $catalogItem->getAttribute('remaining_user_quota');
return [
'id' => $catalogItem->id,
'type' => $catalogItem->type->value,
@@ -73,18 +90,25 @@ 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),
];
}
/** @return array<string, mixed> */
private function columnWithImageData(CatalogItem $catalogItem): array
{
$availableStock = $catalogItem->availableStock();
$remainingUserQuota = $catalogItem->getAttribute('remaining_user_quota');
return [
'id' => $catalogItem->id,
'type' => $catalogItem->type->value,
'nombre' => $catalogItem->nombre,
'precio' => $catalogItem->precio,
'image' => $this->firstImageUrl($catalogItem),
'maximum_addable_quantity' => $this->maximumAddable($availableStock, $remainingUserQuota),
'unavailable_message' => $this->unavailableMessage($availableStock, $remainingUserQuota),
];
}
@@ -103,4 +127,10 @@ class CatalogFeaturedItemResource extends JsonResource
return app(CatalogItemAllowanceService::class)
->maximumAddableQuantity($stock, $remainingUserQuota);
}
private function unavailableMessage(?int $stock, ?int $remainingUserQuota): ?string
{
return app(CatalogItemAllowanceService::class)
->unavailableMessage($stock, $remainingUserQuota);
}
}

View File

@@ -42,11 +42,15 @@ class CatalogItemDetailResource extends JsonResource
$selectedVariant === null,
fn () => $this->maximumAddable($this->availableStock()),
),
'unavailable_message' => $this->when(
$selectedVariant === null,
fn () => $this->unavailableMessage($this->availableStock()),
),
'images' => $this->when(
$selectedVariant === null,
fn () => $this->imageUrls($this->attachments),
),
'variants' => $this->visibleVariants()
'variants' => $this->variants
->map(fn (Variant $variant): array => $this->variantData($variant))
->values(),
'selected_variant' => $this->when(
@@ -159,6 +163,7 @@ class CatalogItemDetailResource extends JsonResource
{
$values = $variant->selectionOptions($this->itemAttributes);
$eventDates = $variant->selectedEventDates();
$variantStock = $this->variantStock($variant);
return [
'id' => $variant->id,
@@ -168,7 +173,8 @@ 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($this->variantStock($variant)),
'maximum_addable_quantity' => $this->maximumAddable($variantStock),
'unavailable_message' => $this->unavailableMessage($variantStock),
'values' => $values,
];
}
@@ -195,4 +201,12 @@ class CatalogItemDetailResource extends JsonResource
$this->getAttribute('remaining_user_quota'),
);
}
private function unavailableMessage(?int $stock): ?string
{
return app(CatalogItemAllowanceService::class)->unavailableMessage(
$stock,
$this->getAttribute('remaining_user_quota'),
);
}
}

View File

@@ -15,6 +15,7 @@ class CatalogSearchItemResource extends JsonResource
/** @return array<string, mixed> */
public function toArray(Request $request): array
{
$availableStock = $this->availableStock();
$attachment = $this->attachments->first()
?? $this->variants
->flatMap(fn (Variant $variant) => $variant->attachments)
@@ -27,23 +28,27 @@ class CatalogSearchItemResource extends JsonResource
'descripcion' => $this->descripcion,
'precio' => $this->precio,
'image' => $attachment?->getTemporaryUrl(1440),
'maximum_addable_quantity' => $this->maximumAddable($this->availableStock()),
'variants' => $this->visibleVariants()
->map(fn (Variant $variant): array => [
'id' => $variant->id,
'event_date_id' => $variant->event_date_id,
'event_date' => $variant->eventDate?->date?->format('Y-m-d'),
'event_date_ids' => $variant->selectedEventDates()->pluck('id')->values(),
'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(
$this->inventory_policy === InventoryPolicy::Unlimited
? null
: $variant->inventory?->availableStock(),
),
'values' => $variant->selectorOptions($this->itemAttributes),
])
'maximum_addable_quantity' => $this->maximumAddable($availableStock),
'unavailable_message' => $this->unavailableMessage($availableStock),
'variants' => $this->variants
->map(function (Variant $variant): array {
$variantStock = $this->inventory_policy === InventoryPolicy::Unlimited
? null
: $variant->inventory?->availableStock();
return [
'id' => $variant->id,
'event_date_id' => $variant->event_date_id,
'event_date' => $variant->eventDate?->date?->format('Y-m-d'),
'event_date_ids' => $variant->selectedEventDates()->pluck('id')->values(),
'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),
'values' => $variant->selectorOptions($this->itemAttributes),
];
})
->values(),
];
}
@@ -55,4 +60,12 @@ class CatalogSearchItemResource extends JsonResource
$this->getAttribute('remaining_user_quota'),
);
}
private function unavailableMessage(?int $stock): ?string
{
return app(CatalogItemAllowanceService::class)->unavailableMessage(
$stock,
$this->getAttribute('remaining_user_quota'),
);
}
}

View File

@@ -8,6 +8,10 @@ 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,
) {}
@@ -37,4 +41,17 @@ class CatalogItemAllowanceService
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;
}
}

View File

@@ -231,7 +231,6 @@ class CatalogService
$paginator = CatalogItem::query()
->where('tenant_code', $tenant->codigo)
->whereVariantsAvailable()
->where(function (Builder $query) use ($containsPattern): void {
$query
->whereRaw('LOWER(nombre) LIKE ?', [$containsPattern])
@@ -281,7 +280,6 @@ class CatalogService
return CatalogItem::query()
->where('tenant_code', $tenant->codigo)
->where('category_id', $category->id)
->whereVariantsAvailable()
->with([
'attachments',
'inventory',

View File

@@ -49,7 +49,6 @@ class FeaturedGroupService
{
$query = CatalogItem::query()
->where('catalog_items.tenant_code', $featuredGroup->tenant_code)
->whereVariantsAvailable()
->with([
'inventory',
'attachments',

View File

@@ -37,16 +37,24 @@ class StockReservationService
});
}
public function commit(CartItem $cartItem, CatalogItem|Variant $selection): void
{
DB::transaction(function () use ($cartItem, $selection): void {
public function commit(
CartItem $cartItem,
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);
foreach ($requirements as $inventoryId => $quantity) {
$reservation = $this->lockReservation($cartItem, $inventoryId);
if ($reservation === null || $reservation->status !== StockReservation::STATUS_ACTIVE || $reservation->quantity !== $quantity) {
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.');
}
@@ -118,6 +126,37 @@ class StockReservationService
]);
}
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;
}
if ($activeReservations->isNotEmpty()) {
throw new \InvalidArgumentException('La reserva de stock del carrito es inconsistente.');
}
$this->inventory->reserve($selection, (int) $cartItem->cantidad);
$this->recordIncrease($cartItem, $selection, (int) $cartItem->cantidad);
});
}
public function syncPurchaseExpiration(Purchase $purchase): void
{
StockReservation::query()

View File

@@ -17,21 +17,25 @@ class InvitationPurchaseProvisioner
private const PAYMENT_METHOD = 'invitation';
/**
* @var list<array{sector: string, row: int, seats: int, type: string}>
* @var list<array{sector: string, row: int, first_seat: int, last_seat: int, type: string}>
*/
private const ALLOCATIONS = [
['sector' => 'A', 'row' => 1, 'seats' => 16, 'type' => 'NORMAL'],
['sector' => 'A', 'row' => 3, 'seats' => 14, 'type' => 'NORMAL'],
['sector' => 'C', 'row' => 1, 'seats' => 16, 'type' => 'VIP + LUNCH'],
['sector' => 'A', 'row' => 1, 'first_seat' => 1, 'last_seat' => 16, 'type' => 'NORMAL'],
['sector' => 'A', 'row' => 3, 'first_seat' => 1, 'last_seat' => 14, 'type' => 'NORMAL'],
['sector' => 'C', 'row' => 1, 'first_seat' => 1, 'last_seat' => 16, 'type' => 'VIP + LUNCH'],
['sector' => 'C', 'row' => 3, 'first_seat' => 6, 'last_seat' => 7, 'type' => 'NORMAL'],
];
public function provision(): void
/**
* @param list<array{sector: string, row: int, first_seat: int, last_seat: int, type: string}>|null $allocations
*/
public function provision(?array $allocations = null): void
{
if (! $this->prerequisitesExist()) {
return;
}
DB::transaction(function (): void {
DB::transaction(function () use ($allocations): void {
$now = now();
$userId = $this->userId($now);
$purchaseId = $this->purchaseId($userId, $now);
@@ -44,8 +48,8 @@ class InvitationPurchaseProvisioner
throw new RuntimeException('No se encontró el catálogo de entradas del desfile.');
}
foreach (self::ALLOCATIONS as $allocation) {
foreach (range(1, $allocation['seats']) as $seat) {
foreach ($allocations ?? self::ALLOCATIONS as $allocation) {
foreach (range($allocation['first_seat'], $allocation['last_seat']) as $seat) {
$variant = $this->variant(
(int) $catalogItem->id,
$allocation['sector'],

View File

@@ -12,10 +12,12 @@ class SaleFormService
$names = [
Purchase::STATUS_CREATED => 'Creada',
Purchase::STATUS_PENDING_PAYMENT => 'Esperando pago',
Purchase::STATUS_IN_REVIEW => 'En revisión',
Purchase::STATUS_PAID => 'Confirmada',
Purchase::STATUS_CANCELLED => 'Cancelada',
Purchase::STATUS_REJECTED => 'Rechazada',
Purchase::STATUS_EXPIRED => 'Vencida',
Purchase::STATUS_SUPERSEDED => 'Reemplazada',
];
return [

View File

@@ -78,6 +78,7 @@ class TelepagosWebhookService
->whereIn('status', [
Purchase::STATUS_CREATED,
Purchase::STATUS_PENDING_PAYMENT,
Purchase::STATUS_IN_REVIEW,
])
->where('payment_method', 'transfer')
->where('total', $amount)

View File

@@ -4,11 +4,9 @@ namespace App\Domains\Purchase\Controllers;
use App\Domains\Integration\Services\TelepagosIntegrationService;
use App\Domains\Purchase\Models\Purchase;
use App\Domains\Purchase\Models\PurchaseItem;
use App\Domains\Purchase\Requests\PaymentIntentRequest;
use App\Domains\Purchase\Requests\StartCheckoutRequest;
use App\Domains\Purchase\Requests\UpdatePurchaseCustomerRequest;
use App\Domains\Purchase\Requests\UpdatePurchaseItemRequest;
use App\Domains\Purchase\Resources\PurchaseResource;
use App\Domains\Purchase\Services\Checkout\PurchaseResponseLoader;
use App\Domains\Purchase\Services\CheckoutService;
@@ -81,53 +79,6 @@ class PurchaseController extends Controller
);
}
public function updateItem(
UpdatePurchaseItemRequest $request,
Tenant $tenant,
Purchase $compra,
PurchaseItem $item,
CheckoutService $checkoutService,
): PurchaseResource {
$compra = $this->resolveScopedPurchase($tenant, $request->user()->id, $compra);
return PurchaseResource::make(
$checkoutService->updateItem(
$compra,
$item,
$request->exists('quantity') ? (int) $request->validated('quantity') : null,
$request->exists('variant_id') ? (int) $request->validated('variant_id') : null,
$request->exists('variant_id'),
),
);
}
public function prepareItemEditing(
Request $request,
Tenant $tenant,
Purchase $compra,
CheckoutService $checkoutService,
): PurchaseResource {
$compra = $this->resolveScopedPurchase($tenant, $request->user()->id, $compra);
return PurchaseResource::make(
$checkoutService->prepareItemEditing($compra),
);
}
public function removeItem(
Request $request,
Tenant $tenant,
Purchase $compra,
PurchaseItem $item,
CheckoutService $checkoutService,
): PurchaseResource {
$compra = $this->resolveScopedPurchase($tenant, $request->user()->id, $compra);
return PurchaseResource::make(
$checkoutService->removeItem($compra, $item),
);
}
public function paymentIntent(
PaymentIntentRequest $request,
Tenant $tenant,
@@ -163,6 +114,8 @@ class PurchaseController extends Controller
return false;
}
$purchaseState->lockCurrentCart($purchase);
$purchaseUpdate = [
'payment_method' => $method,
'status' => Purchase::STATUS_PENDING_PAYMENT,

View File

@@ -39,6 +39,8 @@ class Purchase extends Model
public const STATUS_PENDING_PAYMENT = 'pending_payment';
public const STATUS_IN_REVIEW = 'in_review';
public const STATUS_PAID = 'paid';
public const STATUS_CANCELLED = 'cancelled';
@@ -47,16 +49,20 @@ class Purchase extends Model
public const STATUS_EXPIRED = 'expired';
public const STATUS_SUPERSEDED = 'superseded';
/** @return list<string> */
public static function statuses(): array
{
return [
self::STATUS_CREATED,
self::STATUS_PENDING_PAYMENT,
self::STATUS_IN_REVIEW,
self::STATUS_PAID,
self::STATUS_CANCELLED,
self::STATUS_REJECTED,
self::STATUS_EXPIRED,
self::STATUS_SUPERSEDED,
];
}
@@ -154,12 +160,7 @@ class Purchase extends Model
return (float) $this->getRelation('items')->sum('total');
}
$itemsTotal = (float) $this->items()->sum('total');
if ($itemsTotal > 0 || $this->items()->exists()) {
return $itemsTotal;
}
return (float) ($this->cart?->getTotalAmount() ?? $this->total ?? 0);
return (float) $this->items()->sum('total');
}
protected function valueChangeTenantCode(): string

View File

@@ -1,22 +0,0 @@
<?php
namespace App\Domains\Purchase\Requests;
use Illuminate\Foundation\Http\FormRequest;
class UpdatePurchaseItemRequest extends FormRequest
{
public function authorize(): bool
{
return $this->user() !== null;
}
/** @return array<string, mixed> */
public function rules(): array
{
return [
'quantity' => ['sometimes', 'required_without:variant_id', 'integer', 'min:1', 'max:100'],
'variant_id' => ['sometimes', 'required_without:quantity', 'integer', 'min:1'],
];
}
}

View File

@@ -2,16 +2,12 @@
namespace App\Domains\Purchase\Resources;
use App\Domains\Cart\Models\CartItem;
use App\Domains\Catalog\Enums\InventoryPolicy;
use App\Domains\Catalog\Models\CatalogItem;
use App\Domains\Catalog\Models\Variant;
use App\Domains\Purchase\Models\PurchaseItem;
use App\Domains\Tenant\Models\Tenant;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;
/** @mixin PurchaseItem|CartItem */
/** @mixin PurchaseItem */
class PurchaseItemResource extends JsonResource
{
/** @return array<string, mixed> */
@@ -20,158 +16,29 @@ class PurchaseItemResource extends JsonResource
$tenant = $request->route('tenant');
$displayImage = ! $tenant instanceof Tenant || $tenant->display_cart_item_images;
if ($this->resource instanceof PurchaseItem) {
$imageUrl = $displayImage
? $this->imageAttachment?->getTemporaryUrl(1440)
: null;
$attributes = $this->variant_attributes ?? [];
$catalogItem = $this->relationLoaded('sourceCatalogItem')
? $this->sourceCatalogItem
: null;
$includeVariants = $tenant instanceof Tenant
&& $tenant->checkout_editing_policy->allowsVariantChanges()
&& $catalogItem !== null
&& $catalogItem->relationLoaded('variants');
return [
'id' => $this->id,
'quantity' => (int) $this->cantidad,
'unit_price' => $this->formatMoney($this->precio_unitario),
'line_total' => $this->formatMoney($this->total),
'source_catalog_item_id' => $this->source_catalog_item_id,
'source_variant_id' => $this->source_variant_id,
'item_details' => [
'nombre' => $this->item_nombre,
'descripcion' => $this->descripcion,
'slug' => $this->slug,
'imagen' => $imageUrl,
'attributes' => $attributes,
],
'variants' => $this->when(
$includeVariants,
fn () => $catalogItem
->visibleVariants($this->source_variant_id)
->map(fn (Variant $variant): array => $this->variantData($catalogItem, $variant))
->values(),
),
];
}
$selectedItem = $this->selectedItem();
$catalogItem = $this->catalogItem;
$variant = $this->variant;
$quantity = (int) ($this->cantidad ?? 0);
$unitPrice = $this->resolveUnitPrice($selectedItem);
$lineTotal = $unitPrice * $quantity;
$imageUrl = $displayImage
? $this->resolveImageUrl($selectedItem, $catalogItem)
? $this->imageAttachment?->getTemporaryUrl(1440)
: null;
$includeVariants = $tenant instanceof Tenant
&& $tenant->checkout_editing_policy->allowsVariantChanges()
&& $catalogItem?->relationLoaded('variants');
return [
'id' => $this->id,
'quantity' => $quantity,
'unit_price' => $this->formatMoney($unitPrice),
'line_total' => $this->formatMoney($lineTotal),
'source_catalog_item_id' => $this->catalog_item_id,
'source_variant_id' => $this->variant_id,
'item_details' => $selectedItem === null ? null : [
'nombre' => $selectedItem->getName(),
'descripcion' => $selectedItem->getDescription(),
'slug' => $catalogItem?->slug,
'quantity' => (int) $this->cantidad,
'unit_price' => $this->formatMoney($this->precio_unitario),
'line_total' => $this->formatMoney($this->total),
'source_catalog_item_id' => $this->source_catalog_item_id,
'source_variant_id' => $this->source_variant_id,
'item_details' => [
'nombre' => $this->item_nombre,
'descripcion' => $this->descripcion,
'slug' => $this->slug,
'imagen' => $imageUrl,
'attributes' => $variant === null ? [] : $this->resolveAttributes($variant),
'attributes' => $this->variant_attributes ?? [],
],
'variants' => $this->when(
$includeVariants,
fn () => $catalogItem
->visibleVariants($this->variant_id)
->map(fn (Variant $availableVariant): array => $this->variantData(
$catalogItem,
$availableVariant,
))
->values(),
),
];
}
private function resolveUnitPrice(CatalogItem|Variant|null $selectedItem): float
{
return (float) ($selectedItem?->getPrice() ?? 0);
}
private function resolveImageUrl(
CatalogItem|Variant|null $selectedItem,
?CatalogItem $catalogItem,
): ?string {
$attachment = $selectedItem?->relationLoaded('attachments')
? $selectedItem->attachments->first()
: null;
if ($attachment === null && $catalogItem?->relationLoaded('attachments')) {
$attachment = $catalogItem->attachments->first();
}
return $attachment?->getTemporaryUrl(1440);
}
/** @return array<int, array{name: string, value: mixed}> */
private function resolveAttributes(Variant $variant): array
{
if (! $variant->relationLoaded('definitions')) {
return [];
}
$attributes = $variant->definitions
->groupBy('item_attribute_id')
->map(function ($definitions): array {
$itemAttribute = $definitions->first()?->itemAttribute;
$values = $definitions->pluck('value')->values();
return [
'name' => (string) ($itemAttribute?->attribute?->nombre ?? ''),
'value' => $itemAttribute?->allow_multi_select
? $values->all()
: $values->first(),
];
})
->filter(fn (array $attribute): bool => $attribute['name'] !== '' || $attribute['value'] !== null)
->values();
$eventDates = $variant->relationLoaded('eventDates')
? $variant->selectedEventDates()
: collect();
if ($eventDates->isNotEmpty()) {
$attributes->prepend([
'name' => 'Fecha',
'value' => $eventDates
->map(fn ($eventDate): string => $eventDate->date->format('Y-m-d'))
->values()
->all(),
]);
}
return $attributes->all();
}
private function formatMoney(float|int|string|null $amount): string
{
return number_format((float) ($amount ?? 0), 2, '.', '');
}
/** @return array<string, mixed> */
private function variantData(CatalogItem $catalogItem, Variant $variant): array
{
return [
'id' => $variant->id,
'precio' => $this->formatMoney($variant->precio ?? $catalogItem->precio),
'stock_tecnico' => $catalogItem->inventory_policy === InventoryPolicy::Unlimited
? null
: $variant->inventory->availableStock(),
'values' => $variant->selectorOptions($catalogItem->itemAttributes),
];
}
}

View File

@@ -2,7 +2,6 @@
namespace App\Domains\Purchase\Resources;
use App\Domains\Cart\Models\CartItem;
use App\Domains\Purchase\Models\Purchase;
use App\Domains\Purchase\Models\PurchaseItem;
use Illuminate\Http\Request;
@@ -18,28 +17,16 @@ class PurchaseResource extends JsonResource
*/
public function toArray(Request $request): array
{
$purchaseItems = $this->resource->relationLoaded('items')
$items = $this->resource->relationLoaded('items')
? $this->resource->getRelation('items')
: collect();
$cartItems = $this->resource->relationLoaded('cart')
&& $this->resource->getRelation('cart')?->relationLoaded('items')
? $this->resource->getRelation('cart')->getRelation('items')
: null;
$usesCartItems = in_array($this->status, [
Purchase::STATUS_CREATED,
Purchase::STATUS_PENDING_PAYMENT,
], true) && $cartItems !== null;
$items = $usesCartItems ? $cartItems : $purchaseItems;
$itemsSource = $usesCartItems
? 'cart'
: ($purchaseItems->isNotEmpty() ? 'purchase' : null);
$ticketsCount = array_key_exists('tickets_count', $this->resource->getAttributes())
? (int) $this->resource->getAttribute('tickets_count')
: null;
$subtotal = $items->isNotEmpty()
? $items->reduce(
fn (float $carry, PurchaseItem|CartItem $item): float => $carry + $this->resolveItemSubtotal($item),
fn (float $carry, PurchaseItem $item): float => $carry + $this->resolveItemSubtotal($item),
0.0,
)
: (float) ($this->total ?? 0);
@@ -48,7 +35,7 @@ class PurchaseResource extends JsonResource
? (float) $this->total
: ($items->isNotEmpty()
? $items->reduce(
fn (float $carry, PurchaseItem|CartItem $item): float => $carry + $this->resolveItemTotal($item),
fn (float $carry, PurchaseItem $item): float => $carry + $this->resolveItemTotal($item),
0.0,
)
: (float) ($this->total ?? 0));
@@ -67,7 +54,7 @@ class PurchaseResource extends JsonResource
'telefono' => $this->telefono,
'nombre_apellido' => $this->nombre_apellido,
'email' => $this->email,
'items_source' => $itemsSource,
'items_source' => $items->isNotEmpty() ? 'purchase' : null,
'items' => PurchaseItemResource::collection($items),
'tickets_count' => $this->when($ticketsCount !== null, $ticketsCount),
'has_generated_tickets' => $this->when($ticketsCount !== null, $ticketsCount > 0),
@@ -76,21 +63,13 @@ class PurchaseResource extends JsonResource
];
}
protected function resolveItemSubtotal(PurchaseItem|CartItem $item): float
protected function resolveItemSubtotal(PurchaseItem $item): float
{
if ($item instanceof CartItem) {
return (float) ($item->selectedItem()?->getPrice() ?? 0) * $item->cantidad;
}
return (float) $item->precio_unitario * $item->cantidad;
}
protected function resolveItemTotal(PurchaseItem|CartItem $item): float
protected function resolveItemTotal(PurchaseItem $item): float
{
if ($item instanceof CartItem) {
return $this->resolveItemSubtotal($item);
}
return (float) ($item->total ?? 0);
}

View File

@@ -15,7 +15,6 @@ class CompleteCheckoutService
public function __construct(
private readonly StockReservationService $reservations,
private readonly SourceCartService $sourceCart,
private readonly PurchaseItemSnapshotFactory $snapshots,
private readonly PurchaseStateGuard $purchaseState,
) {}
@@ -35,6 +34,8 @@ class CompleteCheckoutService
return $this->loadPurchase($purchase);
}
$this->purchaseState->lockCurrentCart($purchase);
$purchase->update([
'status' => Purchase::STATUS_PENDING_PAYMENT,
'total' => $purchase->calculateCurrentTotalAmount(),
@@ -54,6 +55,12 @@ class CompleteCheckoutService
return $this->loadPurchase($purchase);
}
if ($purchase->status === Purchase::STATUS_IN_REVIEW) {
return $this->loadPurchase($purchase);
}
$this->purchaseState->lockCurrentCart($purchase);
if (
$purchase->status !== Purchase::STATUS_PENDING_PAYMENT
|| ($purchase->expires_at !== null && $purchase->expires_at->isPast())
@@ -63,7 +70,10 @@ class CompleteCheckoutService
]);
}
$purchase->update(['expires_at' => null]);
$purchase->update([
'status' => Purchase::STATUS_IN_REVIEW,
'expires_at' => null,
]);
$this->reservations->syncPurchaseExpiration($purchase);
return $this->loadPurchase($purchase);
@@ -84,25 +94,26 @@ class CompleteCheckoutService
Purchase::STATUS_CANCELLED,
Purchase::STATUS_REJECTED,
Purchase::STATUS_EXPIRED,
Purchase::STATUS_SUPERSEDED,
], true)) {
throw ValidationException::withMessages([
'purchase' => __('api.purchase.cannot_confirm'),
]);
}
if ($purchase->items()->exists()) {
$cart = $purchase->cart()->withTrashed()->lockForUpdate()->first();
if ($cart?->status === 'converted' && $cart->trashed()) {
return;
}
if (! $purchase->items()->exists()) {
throw ValidationException::withMessages([
'items' => __('api.purchase.inconsistent_reservation'),
]);
}
$cart = $purchase->cart()->lockForUpdate()->first();
if ($cart === null || $cart->status !== 'checkout') {
$cart = $this->purchaseState->lockCurrentCart($purchase);
if ($cart->status === 'converted' && $cart->trashed()) {
return;
}
if (! in_array($cart->status, ['active', 'checkout'], true)) {
throw ValidationException::withMessages([
'items' => __('api.purchase.inconsistent_reservation'),
]);
@@ -115,10 +126,32 @@ class CompleteCheckoutService
]);
}
$snapshotQuantities = $purchase->items()
->lockForUpdate()
->get(['source_catalog_item_id', 'source_variant_id', 'cantidad'])
->groupBy(fn ($item): string => $this->itemKey(
(int) $item->source_catalog_item_id,
$item->source_variant_id === null ? null : (int) $item->source_variant_id,
))
->map(fn (Collection $items): int => (int) $items->sum('cantidad'))
->sortKeys()
->all();
$cartQuantities = $cartItems
->groupBy(fn (CartItem $item): string => $this->itemKey(
(int) $item->catalog_item_id,
$item->variant_id === null ? null : (int) $item->variant_id,
))
->map(fn (Collection $items): int => (int) $items->sum('cantidad'))
->sortKeys()
->all();
if ($snapshotQuantities !== $cartQuantities) {
throw ValidationException::withMessages([
'items' => __('api.purchase.inconsistent_reservation'),
]);
}
$this->loadCartItems($cartItems);
$purchase->items()->createMany(
$this->snapshots->fromCartItems($cartItems),
);
foreach ($cartItems as $cartItem) {
$selection = $cartItem->selectedItem();
@@ -129,7 +162,7 @@ class CompleteCheckoutService
}
try {
$this->reservations->commit($cartItem, $selection);
$this->reservations->commit($cartItem, $selection, $purchase);
} catch (\InvalidArgumentException) {
throw ValidationException::withMessages([
'items' => __('api.purchase.inconsistent_reservation'),
@@ -145,9 +178,11 @@ class CompleteCheckoutService
{
return in_array($purchase->status, [
Purchase::STATUS_PAID,
Purchase::STATUS_IN_REVIEW,
Purchase::STATUS_CANCELLED,
Purchase::STATUS_REJECTED,
Purchase::STATUS_EXPIRED,
Purchase::STATUS_SUPERSEDED,
], true);
}
@@ -159,16 +194,12 @@ class CompleteCheckoutService
private function loadPurchase(Purchase $purchase): Purchase
{
return $purchase->load([
'items.imageAttachment',
'cart.items.catalogItem.inventory',
'cart.items.catalogItem.attachments',
'cart.items.variant.inventory',
'cart.items.variant.attachments',
'cart.items.variant.definitions.itemAttribute.attribute',
'cart.items.variant.eventDates',
'cart.items.variant.eventDate',
]);
return $purchase->load(['items.imageAttachment']);
}
private function itemKey(int $catalogItemId, ?int $variantId): string
{
return $catalogItemId.':'.($variantId ?? 'none');
}
/** @param Collection<int, CartItem> $cartItems */

View File

@@ -2,24 +2,14 @@
namespace App\Domains\Purchase\Services\Checkout;
use App\Domains\Catalog\Models\Variant;
use App\Domains\Catalog\Services\CatalogInventoryService;
use App\Domains\Purchase\Models\Purchase;
use App\Domains\Purchase\Models\PurchaseItem;
use App\Domains\Purchase\Services\PurchaseStateGuard;
use App\Domains\Purchase\Services\UserPurchaseLimitService;
use Illuminate\Support\Facades\DB;
use Illuminate\Validation\ValidationException;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
class EditCheckoutService
{
public function __construct(
private readonly CatalogInventoryService $inventory,
private readonly UserPurchaseLimitService $purchaseLimits,
private readonly CatalogSelectionResolver $selections,
private readonly SourceCartService $sourceCart,
private readonly PurchaseItemSnapshotFactory $snapshots,
private readonly PurchaseResponseLoader $responses,
private readonly PurchaseStateGuard $purchaseState,
) {}
@@ -28,295 +18,24 @@ class EditCheckoutService
public function updateCustomer(Purchase $purchase, array $customerData): Purchase
{
return DB::transaction(function () use ($purchase, $customerData): Purchase {
$purchase = $this->lockPurchase($purchase);
$this->purchaseState->assertNotExpired($purchase);
$this->assertEditable($purchase);
$purchase->update($customerData);
return $this->loadPurchase($purchase);
});
}
public function updateItem(
Purchase $purchase,
PurchaseItem $purchaseItem,
?int $quantity,
?int $variantId,
bool $updateVariant,
): Purchase {
return DB::transaction(function () use (
$purchase,
$purchaseItem,
$quantity,
$variantId,
$updateVariant,
): Purchase {
$purchase = $this->lockPurchase($purchase);
/** @var Purchase $purchase */
$purchase = Purchase::query()->lockForUpdate()->findOrFail($purchase->getKey());
$this->purchaseState->assertNotExpired($purchase);
if ($purchase->status !== Purchase::STATUS_CREATED || $this->hasExpired($purchase)) {
if (! in_array($purchase->status, [
Purchase::STATUS_CREATED,
Purchase::STATUS_PENDING_PAYMENT,
], true)) {
throw ValidationException::withMessages([
'purchase' => __('api.purchase.not_editable'),
]);
}
$purchaseItem = $this->lockPurchaseItem($purchase, $purchaseItem);
$tenant = $purchase->tenant()->firstOrFail();
$finalQuantity = $quantity ?? (int) $purchaseItem->cantidad;
$this->purchaseState->lockCurrentCart($purchase);
if ($quantity !== null && ! $tenant->checkout_editing_policy->allowsQuantityChanges()) {
throw ValidationException::withMessages([
'quantity' => __('api.cart.editing_disabled'),
]);
}
$purchase->update($customerData);
if ($updateVariant && ! $tenant->checkout_editing_policy->allowsVariantChanges()) {
throw ValidationException::withMessages([
'variant_id' => __('api.purchase.variant_change_disabled'),
]);
}
if ($updateVariant && $variantId !== $purchaseItem->source_variant_id) {
$this->changeItemVariant(
$purchase,
$purchaseItem,
(int) $variantId,
$finalQuantity,
);
} else {
$difference = $finalQuantity - (int) $purchaseItem->cantidad;
if ($difference !== 0) {
$this->adjustReservation($purchase, $purchaseItem, $finalQuantity, $difference);
$purchaseItem->update([
'cantidad' => $finalQuantity,
'total' => (float) $purchaseItem->precio_unitario * $finalQuantity,
]);
$this->sourceCart->syncItemQuantity($purchase, $purchaseItem, $finalQuantity);
}
}
$purchase->update([
'total' => $purchase->calculateCurrentTotalAmount(),
]);
return $this->loadPurchase($purchase);
return $this->responses->load($purchase);
});
}
private function changeItemVariant(
Purchase $purchase,
PurchaseItem $sourceItem,
int $variantId,
int $quantity,
): void {
$tenant = $purchase->tenant()->firstOrFail();
$currentSelection = $this->selections->resolvePurchaseItem($tenant, $sourceItem);
$targetSelection = $this->selections->resolve(
$tenant,
(int) $sourceItem->source_catalog_item_id,
$variantId,
'item',
);
if (! $targetSelection instanceof Variant) {
throw ValidationException::withMessages([
'variant_id' => __('api.cart.variant_required'),
]);
}
/** @var PurchaseItem|null $targetItem */
$targetItem = $purchase->items()
->where('source_catalog_item_id', $sourceItem->source_catalog_item_id)
->where('source_variant_id', $targetSelection->id)
->whereKeyNot($sourceItem->getKey())
->lockForUpdate()
->first();
if ($targetItem !== null && $targetItem->reservation_status !== PurchaseItem::RESERVATION_ACTIVE) {
throw ValidationException::withMessages([
'variant_id' => __('api.purchase.item_not_editable'),
]);
}
$otherItemQuantity = (int) $purchase->items()
->where('source_catalog_item_id', $sourceItem->source_catalog_item_id)
->whereKeyNot($sourceItem->getKey())
->sum('cantidad');
$this->purchaseLimits->assertCanPurchase(
$targetSelection->catalogItem,
(int) $purchase->user_id,
$otherItemQuantity + $quantity,
$purchase->getKey(),
'variant_id',
);
try {
$this->inventory->release($currentSelection, (int) $sourceItem->cantidad);
$this->inventory->reserve($targetSelection, $quantity);
} catch (\InvalidArgumentException) {
throw ValidationException::withMessages([
'variant_id' => __('api.purchase.insufficient_stock'),
]);
}
$previousVariantId = $sourceItem->source_variant_id;
$finalQuantity = $quantity;
if ($targetItem !== null) {
$finalQuantity += (int) $targetItem->cantidad;
$targetItem->update($this->snapshots->fromVariant($targetSelection, $finalQuantity));
$sourceItem->delete();
} else {
$sourceItem->update($this->snapshots->fromVariant($targetSelection, $finalQuantity));
}
$this->sourceCart->syncItemSelection(
$purchase,
(int) $sourceItem->source_catalog_item_id,
$previousVariantId,
$targetSelection->id,
$finalQuantity,
);
}
public function prepareItemEditing(Purchase $purchase): Purchase
{
return DB::transaction(function () use ($purchase): Purchase {
$purchase = $this->lockPurchase($purchase);
$this->purchaseState->assertNotExpired($purchase);
$this->assertEditable($purchase);
if (! $purchase->tenant()->firstOrFail()->checkout_editing_policy->allowsModification()) {
throw ValidationException::withMessages([
'purchase' => __('api.cart.editing_disabled'),
]);
}
$purchase->telepagosQr()->delete();
$purchase->update([
'status' => Purchase::STATUS_CREATED,
'payment_method' => null,
'transfer_payer_dni' => null,
'expires_at' => now()->addMinutes(
max(1, (int) config('purchase.checkout_expiration_minutes', 30)),
),
]);
return $this->loadPurchase($purchase);
});
}
public function removeItem(Purchase $purchase, PurchaseItem $purchaseItem): Purchase
{
return DB::transaction(function () use ($purchase, $purchaseItem): Purchase {
$purchase = $this->lockPurchase($purchase);
$this->purchaseState->assertNotExpired($purchase);
$this->assertEditable($purchase);
if (! $purchase->tenant()->firstOrFail()->checkout_editing_policy->allowsRemoval()) {
throw ValidationException::withMessages([
'item' => __('api.cart.editing_disabled'),
]);
}
$purchaseItem = $this->lockPurchaseItem($purchase, $purchaseItem);
$selection = $this->selections->resolvePurchaseItem($purchase->tenant, $purchaseItem);
$this->inventory->release($selection, (int) $purchaseItem->cantidad);
$this->sourceCart->removeItem($purchase, $purchaseItem);
$purchaseItem->delete();
$purchase->update([
'total' => $purchase->calculateCurrentTotalAmount(),
]);
return $this->loadPurchase($purchase);
});
}
private function adjustReservation(
Purchase $purchase,
PurchaseItem $purchaseItem,
int $quantity,
int $difference,
): void {
$selection = $this->selections->resolvePurchaseItem($purchase->tenant, $purchaseItem);
try {
if ($difference > 0) {
$otherItemQuantity = (int) $purchase->items()
->where('source_catalog_item_id', $purchaseItem->source_catalog_item_id)
->whereKeyNot($purchaseItem->getKey())
->sum('cantidad');
$catalogItem = $selection instanceof Variant ? $selection->catalogItem : $selection;
$this->purchaseLimits->assertCanPurchase(
$catalogItem,
(int) $purchase->user_id,
$otherItemQuantity + $quantity,
$purchase->getKey(),
);
$this->inventory->reserve($selection, $difference);
} else {
$this->inventory->release($selection, abs($difference));
}
} catch (\InvalidArgumentException) {
throw ValidationException::withMessages([
'quantity' => __('api.purchase.insufficient_stock'),
]);
}
}
private function lockPurchaseItem(Purchase $purchase, PurchaseItem $item): PurchaseItem
{
/** @var PurchaseItem|null $lockedItem */
$lockedItem = $purchase->items()
->whereKey($item->getKey())
->lockForUpdate()
->first();
if ($lockedItem === null) {
throw new NotFoundHttpException('Purchase item not found.');
}
if ($lockedItem->reservation_status !== PurchaseItem::RESERVATION_ACTIVE) {
throw ValidationException::withMessages([
'item' => __('api.purchase.item_not_editable'),
]);
}
return $lockedItem;
}
private function assertEditable(Purchase $purchase): void
{
if (
! in_array($purchase->status, [
Purchase::STATUS_CREATED,
Purchase::STATUS_PENDING_PAYMENT,
], true)
|| $this->hasExpired($purchase)
) {
throw ValidationException::withMessages([
'purchase' => __('api.purchase.not_editable'),
]);
}
}
private function hasExpired(Purchase $purchase): bool
{
return $purchase->expires_at !== null && $purchase->expires_at->isPast();
}
private function lockPurchase(Purchase $purchase): Purchase
{
/** @var Purchase */
return Purchase::query()->lockForUpdate()->findOrFail($purchase->getKey());
}
private function loadPurchase(Purchase $purchase): Purchase
{
return $this->responses->load($purchase);
}
}

View File

@@ -9,35 +9,6 @@ use Illuminate\Support\Collection;
class PurchaseItemSnapshotFactory
{
/** @return array<string, mixed> */
public function fromVariant(Variant $variant, int $quantity): array
{
$variant->loadMissing([
'attachments',
'catalogItem.attachments',
'definitions.itemAttribute.attribute.options',
'eventDates',
'eventDate',
]);
$unitPrice = $variant->getPrice();
return [
'source_variant_id' => $variant->id,
'image_attachment_id' => $variant->attachments->first()?->id
?? $variant->catalogItem->attachments->first()?->id,
'nombre' => $variant->catalogItem->nombre,
'descripcion' => $variant->getDescription(),
'slug' => $variant->catalogItem->slug,
'item_nombre' => $variant->getName(),
'variant_attributes' => $this->snapshotAttributes($variant),
'cantidad' => $quantity,
'precio_unitario' => $unitPrice,
'discount_total' => null,
'tax_total' => null,
'total' => $unitPrice * $quantity,
];
}
/**
* @param Collection<int, CartItem> $cartItems
* @return array<int, array<string, mixed>>

View File

@@ -8,51 +8,6 @@ class PurchaseResponseLoader
{
public function load(Purchase $purchase): Purchase
{
$purchase->load(['tenant', 'items.imageAttachment']);
if (
$purchase->cart_id !== null
&& (
in_array($purchase->status, [
Purchase::STATUS_CREATED,
Purchase::STATUS_PENDING_PAYMENT,
], true)
|| $purchase->items->isEmpty()
)
) {
$purchase->load([
'cart.items.catalogItem.inventory',
'cart.items.catalogItem.attachments',
'cart.items.variant.inventory',
'cart.items.variant.attachments',
'cart.items.variant.catalogItem',
'cart.items.variant.definitions.itemAttribute.attribute',
'cart.items.variant.eventDates',
'cart.items.variant.eventDate',
]);
}
if (! $purchase->tenant->checkout_editing_policy->allowsVariantChanges()) {
return $purchase;
}
$purchase->load([
'items.sourceCatalogItem.itemAttributes.attribute',
'items.sourceCatalogItem.variants' => fn ($query) => $query->orderBy('id'),
'items.sourceCatalogItem.variants.inventory',
'items.sourceCatalogItem.variants.definitions' => fn ($query) => $query->orderBy('id'),
'items.sourceCatalogItem.variants.definitions.itemAttribute.attribute.options',
'items.sourceCatalogItem.variants.eventDates',
'items.sourceCatalogItem.variants.eventDate',
'cart.items.catalogItem.itemAttributes.attribute',
'cart.items.catalogItem.variants' => fn ($query) => $query->orderBy('id'),
'cart.items.catalogItem.variants.inventory',
'cart.items.catalogItem.variants.definitions' => fn ($query) => $query->orderBy('id'),
'cart.items.catalogItem.variants.definitions.itemAttribute.attribute.options',
'cart.items.catalogItem.variants.eventDates',
'cart.items.catalogItem.variants.eventDate',
]);
return $purchase;
return $purchase->load(['tenant', 'items.imageAttachment']);
}
}

View File

@@ -2,10 +2,10 @@
namespace App\Domains\Purchase\Services\Checkout;
use App\Domains\Cart\Models\Cart;
use App\Domains\Catalog\Models\StockReservation;
use App\Domains\Catalog\Services\StockReservationService;
use App\Domains\Purchase\Models\Purchase;
use App\Domains\Purchase\Services\PurchaseStateGuard;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Validation\ValidationException;
@@ -15,8 +15,6 @@ class ReleaseCheckoutService
{
public function __construct(
private readonly StockReservationService $reservations,
private readonly SourceCartService $sourceCart,
private readonly PurchaseStateGuard $purchaseState,
) {}
public function cancel(Purchase $purchase): Purchase
@@ -24,9 +22,9 @@ class ReleaseCheckoutService
return $this->release($purchase, Purchase::STATUS_CANCELLED);
}
public function cancelWithoutRestoringCart(Purchase $purchase): Purchase
public function cancelFromAdmin(Purchase $purchase): Purchase
{
return $this->release($purchase, Purchase::STATUS_CANCELLED);
return $this->release($purchase, Purchase::STATUS_CANCELLED, allowInReviewCancellation: true);
}
public function expire(Purchase $purchase): Purchase
@@ -68,15 +66,18 @@ class ReleaseCheckoutService
return $expiredCount;
}
private function release(Purchase $purchase, string $targetStatus): Purchase
{
return DB::transaction(function () use ($purchase, $targetStatus): Purchase {
private function release(
Purchase $purchase,
string $targetStatus,
bool $allowInReviewCancellation = false,
): Purchase {
return DB::transaction(function () use (
$purchase,
$targetStatus,
$allowInReviewCancellation,
): Purchase {
$purchase = $this->lockPurchase($purchase);
if ($targetStatus !== Purchase::STATUS_EXPIRED) {
$this->purchaseState->assertNotExpired($purchase);
}
if ($purchase->status === Purchase::STATUS_PAID) {
if ($targetStatus === Purchase::STATUS_EXPIRED) {
return $this->loadPurchase($purchase);
@@ -87,6 +88,14 @@ class ReleaseCheckoutService
]);
}
if (
$purchase->status === Purchase::STATUS_IN_REVIEW
&& $targetStatus === Purchase::STATUS_CANCELLED
&& ! $allowInReviewCancellation
) {
return $this->createNewCartWithoutCancelling($purchase);
}
if ($this->isAlreadyReleased($purchase)) {
return $this->loadPurchase($purchase);
}
@@ -98,13 +107,7 @@ class ReleaseCheckoutService
return $this->loadPurchase($purchase);
}
if ($purchase->items()->exists()) {
throw ValidationException::withMessages([
'items' => __('api.purchase.inconsistent_reservation'),
]);
}
$this->releaseCartReservations($purchase, $targetStatus);
$this->releasePurchaseReservations($purchase, $targetStatus);
$purchase->update(['status' => $targetStatus]);
@@ -112,15 +115,27 @@ class ReleaseCheckoutService
});
}
private function releaseCartReservations(
Purchase $purchase,
string $targetStatus,
): void {
private function releasePurchaseReservations(Purchase $purchase, string $targetStatus): void
{
$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',
@@ -158,12 +173,40 @@ class ReleaseCheckoutService
}
}
private function createNewCartWithoutCancelling(Purchase $purchase): Purchase
{
return DB::transaction(function () use ($purchase): Purchase {
$purchase = $this->lockPurchase($purchase);
if ($purchase->status !== Purchase::STATUS_IN_REVIEW || $purchase->user_id === null) {
return $this->loadPurchase($purchase);
}
/** @var Cart|null $sourceCart */
$sourceCart = $purchase->cart()->withTrashed()->lockForUpdate()->first();
if ($sourceCart !== null && ! $sourceCart->trashed() && $sourceCart->status === 'active') {
$sourceCart->update(['status' => 'checkout']);
}
Cart::query()->firstOrCreate([
'tenant_codigo' => $purchase->tenant_codigo,
'user_id' => $purchase->user_id,
'guest_token' => null,
'status' => 'active',
'origin' => Cart::ORIGIN_USER,
]);
return $this->loadPurchase($purchase);
});
}
private function isAlreadyReleased(Purchase $purchase): bool
{
return in_array($purchase->status, [
Purchase::STATUS_CANCELLED,
Purchase::STATUS_REJECTED,
Purchase::STATUS_EXPIRED,
Purchase::STATUS_SUPERSEDED,
], true);
}
@@ -175,15 +218,6 @@ class ReleaseCheckoutService
private function loadPurchase(Purchase $purchase): Purchase
{
return $purchase->load([
'items.imageAttachment',
'cart.items.catalogItem.inventory',
'cart.items.catalogItem.attachments',
'cart.items.variant.inventory',
'cart.items.variant.attachments',
'cart.items.variant.definitions.itemAttribute.attribute',
'cart.items.variant.eventDates',
'cart.items.variant.eventDate',
]);
return $purchase->load(['items.imageAttachment']);
}
}

View File

@@ -7,88 +7,6 @@ use App\Domains\Purchase\Models\Purchase;
class SourceCartService
{
public function syncItemQuantity(
Purchase $purchase,
PurchaseItem $purchaseItem,
int $quantity,
): void {
$sourceCart = $this->findSourceCart($purchase);
if ($sourceCart === null) {
return;
}
$sourceCart->items()
->where('catalog_item_id', $purchaseItem->source_catalog_item_id)
->where('variant_id', $purchaseItem->source_variant_id)
->update(['cantidad' => $quantity]);
}
public function syncItemSelection(
Purchase $purchase,
int $catalogItemId,
?int $previousVariantId,
int $newVariantId,
int $finalQuantity,
): void {
$sourceCart = $this->findSourceCart($purchase);
if ($sourceCart === null) {
return;
}
/** @var CartItem|null $previousItem */
$previousItem = $sourceCart->items()
->where('catalog_item_id', $catalogItemId)
->where('variant_id', $previousVariantId)
->lockForUpdate()
->first();
/** @var CartItem|null $targetItem */
$targetItem = $sourceCart->items()
->where('catalog_item_id', $catalogItemId)
->where('variant_id', $newVariantId)
->when($previousItem !== null, fn ($query) => $query->whereKeyNot($previousItem->getKey()))
->lockForUpdate()
->first();
if ($targetItem !== null) {
$targetItem->update(['cantidad' => $finalQuantity]);
$previousItem?->delete();
return;
}
if ($previousItem !== null) {
$previousItem->update([
'variant_id' => $newVariantId,
'cantidad' => $finalQuantity,
]);
return;
}
$sourceCart->items()->create([
'catalog_item_id' => $catalogItemId,
'variant_id' => $newVariantId,
'cantidad' => $finalQuantity,
]);
}
public function removeItem(Purchase $purchase, PurchaseItem $purchaseItem): void
{
$sourceCart = $this->findSourceCart($purchase);
if ($sourceCart === null) {
return;
}
$sourceCart->items()
->where('catalog_item_id', $purchaseItem->source_catalog_item_id)
->where('variant_id', $purchaseItem->source_variant_id)
->delete();
}
public function finalize(Purchase $purchase): void
{
$sourceCart = $this->findSourceCart($purchase);

View File

@@ -26,6 +26,7 @@ class StartCheckoutService
private readonly CatalogSelectionResolver $selections,
private readonly InsufficientStockMessageBuilder $stockMessages,
private readonly PurchaseResponseLoader $responses,
private readonly PurchaseItemSnapshotFactory $snapshots,
) {}
/** @param array<string, mixed> $purchaseData */
@@ -192,6 +193,11 @@ class StartCheckoutService
),
$cart->getKey(),
);
$cart->update(['current_purchase_id' => $purchase->getKey()]);
$cartItems = $cart->items()->orderBy('id')->lockForUpdate()->get();
$this->loadCartItems($cartItems);
$purchase->items()->createMany($this->snapshots->fromCartItems($cartItems));
foreach ($cartItems as $index => $cartItem) {
$this->reservations->attachToPurchase(
@@ -259,6 +265,9 @@ class StartCheckoutService
$cart->getTotalAmount(),
$cart->getKey(),
);
$cart->update(['current_purchase_id' => $purchase->getKey()]);
$purchase->items()->createMany($this->snapshots->fromCartItems($cartItems));
foreach ($cartItems as $cartItem) {
$this->reservations->attachToPurchase(
$cartItem,
@@ -267,21 +276,57 @@ class StartCheckoutService
);
}
// The purchase owns the reservation until checkout finishes. The cart is
// retained so it can be restored if the purchase is cancelled or expires.
$cart->update([
'status' => 'checkout',
'guest_token' => null,
]);
return $this->loadPurchase($purchase);
}
private function resolveCart(Tenant $tenant, int $userId, int $cartId): Cart
{
/** @var Cart|null $candidate */
$candidate = Cart::query()->find($cartId);
$this->assertCartCanCheckout($candidate, $tenant, $userId);
$candidatePurchaseId = $candidate->current_purchase_id;
$currentPurchase = $candidatePurchaseId === null
? null
: Purchase::query()->lockForUpdate()->find($candidatePurchaseId);
/** @var Cart|null $cart */
$cart = Cart::query()->lockForUpdate()->find($cartId);
$this->assertCartCanCheckout($cart, $tenant, $userId);
if ($cart->current_purchase_id !== $candidatePurchaseId) {
if ($cart->current_purchase_id !== null) {
throw ValidationException::withMessages([
'cart_id' => __('api.purchase.checkout_in_progress'),
]);
}
$currentPurchase = null;
}
if ($currentPurchase?->status === Purchase::STATUS_PAID) {
throw ValidationException::withMessages([
'cart_id' => __('api.purchase.checkout_in_progress'),
]);
}
if ($currentPurchase !== null && in_array($currentPurchase->status, [
Purchase::STATUS_CREATED,
Purchase::STATUS_PENDING_PAYMENT,
], true)) {
$currentPurchase->update([
'status' => Purchase::STATUS_SUPERSEDED,
'expires_at' => null,
]);
}
return $cart;
}
private function assertCartCanCheckout(?Cart $cart, Tenant $tenant, int $userId): void
{
if ($cart === null || $cart->tenant_codigo !== $tenant->codigo || $cart->user_id !== $userId) {
throw new NotFoundHttpException('Cart not found for tenant.');
}
@@ -291,8 +336,6 @@ class StartCheckoutService
'cart_id' => __('api.purchase.inactive_cart'),
]);
}
return $cart;
}
/** @param Collection<int, CartItem> $cartItems */

View File

@@ -4,7 +4,6 @@ namespace App\Domains\Purchase\Services;
use App\Domains\Catalog\Services\StockReservationService;
use App\Domains\Purchase\Models\Purchase;
use App\Domains\Purchase\Models\PurchaseItem;
use App\Domains\Purchase\Services\Checkout\CompleteCheckoutService;
use App\Domains\Purchase\Services\Checkout\EditCheckoutService;
use App\Domains\Purchase\Services\Checkout\ReleaseCheckoutService;
@@ -49,32 +48,6 @@ class CheckoutService
return $this->editor->updateCustomer($purchase, $customerData);
}
public function updateItem(
Purchase $purchase,
PurchaseItem $purchaseItem,
?int $quantity,
?int $variantId,
bool $updateVariant,
): Purchase {
return $this->editor->updateItem(
$purchase,
$purchaseItem,
$quantity,
$variantId,
$updateVariant,
);
}
public function prepareItemEditing(Purchase $purchase): Purchase
{
return $this->editor->prepareItemEditing($purchase);
}
public function removeItem(Purchase $purchase, PurchaseItem $purchaseItem): Purchase
{
return $this->editor->removeItem($purchase, $purchaseItem);
}
public function confirmPurchase(Purchase $purchase): void
{
$this->completer->confirm($purchase);
@@ -95,9 +68,9 @@ class CheckoutService
return $this->releaser->cancel($purchase);
}
public function cancelPurchaseWithoutRestoringCart(Purchase $purchase): Purchase
public function cancelPurchaseFromAdmin(Purchase $purchase): Purchase
{
return $this->releaser->cancelWithoutRestoringCart($purchase);
return $this->releaser->cancelFromAdmin($purchase);
}
public function expirePurchase(Purchase $purchase): Purchase

View File

@@ -2,8 +2,10 @@
namespace App\Domains\Purchase\Services;
use App\Domains\Cart\Models\Cart;
use App\Domains\Purchase\Exceptions\PurchaseExpiredException;
use App\Domains\Purchase\Models\Purchase;
use Illuminate\Validation\ValidationException;
class PurchaseStateGuard
{
@@ -21,4 +23,18 @@ class PurchaseStateGuard
throw new PurchaseExpiredException;
}
}
public function lockCurrentCart(Purchase $purchase): Cart
{
/** @var Cart|null $cart */
$cart = $purchase->cart()->withTrashed()->lockForUpdate()->first();
if ($cart === null || $cart->current_purchase_id !== $purchase->getKey()) {
throw ValidationException::withMessages([
'purchase' => __('api.purchase.not_current'),
]);
}
return $cart;
}
}

View File

@@ -51,6 +51,7 @@ class UserPurchaseLimitService
->whereIn('status', [
Purchase::STATUS_CREATED,
Purchase::STATUS_PENDING_PAYMENT,
Purchase::STATUS_IN_REVIEW,
Purchase::STATUS_PAID,
])
->when(
@@ -68,6 +69,7 @@ class UserPurchaseLimitService
->whereIn('status', [
Purchase::STATUS_CREATED,
Purchase::STATUS_PENDING_PAYMENT,
Purchase::STATUS_IN_REVIEW,
])
->whereDoesntHave('items')
->when(
@@ -86,7 +88,9 @@ class UserPurchaseLimitService
$excludedCartId !== null,
fn ($query) => $query->whereKeyNot($excludedCartId),
))
->whereHas('stockReservations', fn ($query) => $query->where('status', 'active'))
->whereHas('stockReservations', fn ($query) => $query
->where('status', 'active')
->whereNull('purchase_id'))
->sum('cantidad');
if ($purchasedQuantity + $checkoutQuantity + $reservedCartQuantity + $requestedQuantity > $limit) {
@@ -131,6 +135,7 @@ class UserPurchaseLimitService
->whereIn('status', [
Purchase::STATUS_CREATED,
Purchase::STATUS_PENDING_PAYMENT,
Purchase::STATUS_IN_REVIEW,
Purchase::STATUS_PAID,
]))
->groupBy('source_catalog_item_id')
@@ -141,7 +146,11 @@ class UserPurchaseLimitService
->whereIn('catalog_item_id', $ids)
->whereHas('cart.purchases', fn ($query) => $query
->where('user_id', $userId)
->whereIn('status', [Purchase::STATUS_CREATED, Purchase::STATUS_PENDING_PAYMENT])
->whereIn('status', [
Purchase::STATUS_CREATED,
Purchase::STATUS_PENDING_PAYMENT,
Purchase::STATUS_IN_REVIEW,
])
->whereDoesntHave('items'))
->groupBy('catalog_item_id')
->pluck('quantity', 'catalog_item_id');
@@ -152,7 +161,9 @@ class UserPurchaseLimitService
->whereHas('cart', fn ($query) => $query
->where('user_id', $userId)
->where('status', 'active'))
->whereHas('stockReservations', fn ($query) => $query->where('status', 'active'))
->whereHas('stockReservations', fn ($query) => $query
->where('status', 'active')
->whereNull('purchase_id'))
->groupBy('catalog_item_id')
->pluck('quantity', 'catalog_item_id');

View File

@@ -6,7 +6,7 @@ Implementa el ciclo de compra y checkout: crea la cabecera de compra desde un ca
## Modelo
- `Purchase`: raíz de la compra; estados `created`, `pending_payment`, `paid`, `cancelled`, `rejected` y `expired`.
- `Purchase`: raíz de la compra; estados `created`, `pending_payment`, `in_review`, `paid`, `cancelled`, `rejected` y `expired`.
- `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.
- `PurchasePaid`: evento emitido una sola vez al pasar a pagada bajo bloqueo transaccional.
@@ -22,7 +22,7 @@ Implementa el ciclo de compra y checkout: crea la cabecera de compra desde un ca
- `SourceCartService`: sincroniza o finaliza el carrito de checkout asociado a la compra.
- `CatalogSelectionResolver` y `PurchaseItemSnapshotFactory`: resuelven selecciones y generan snapshots.
Durante `created` y `pending_payment`, `PurchaseResource` publica las líneas del carrito con `items_source=cart`; una compra materializada publica `items_source=purchase`. Los datos descriptivos y económicos del checkout se resuelven siempre desde el catálogo vigente.
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.

View File

@@ -7,9 +7,6 @@ Route::prefix('tenants/{tenant:codigo}')->middleware('auth:sanctum')->group(func
Route::get('compras', [PurchaseController::class, 'index']);
Route::post('compras/start-checkout', [PurchaseController::class, 'startCheckout']);
Route::get('compras/{compra}', [PurchaseController::class, 'show']);
Route::post('compras/{compra}/edit-items', [PurchaseController::class, 'prepareItemEditing']);
Route::patch('compras/{compra}/items/{item}', [PurchaseController::class, 'updateItem']);
Route::delete('compras/{compra}/items/{item}', [PurchaseController::class, 'removeItem']);
Route::patch('compras/{compra}/customer-data', [PurchaseController::class, 'updateCustomerData']);
Route::post('compras/{compra}/payment-intent', [PurchaseController::class, 'paymentIntent']);
Route::post('compras/{compra}/complete', [PurchaseController::class, 'complete']);

View File

@@ -2,12 +2,10 @@
namespace App\Domains\Sale\Resources\AdminApp;
use App\Domains\Cart\Models\CartItem;
use App\Domains\Purchase\Models\Purchase;
use App\Domains\Purchase\Models\PurchaseItem;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;
use Illuminate\Support\Collection;
/** @mixin Purchase */
class SaleDetailResource extends JsonResource
@@ -15,44 +13,23 @@ class SaleDetailResource extends JsonResource
/** @return array<string, mixed> */
public function toArray(Request $request): array
{
$items = $this->saleItems();
return [
'id' => $this->id,
'items' => $items->map(fn (PurchaseItem|CartItem $item): array => [
'items' => $this->items->map(fn (PurchaseItem $item): array => [
'id' => $item->id,
'product' => $item instanceof PurchaseItem
? $item->item_nombre
: $item->selectedItem()?->getName(),
'product' => $item->item_nombre,
'event_dates' => $this->eventDates($item),
'quantity' => (int) $item->cantidad,
'unit_price' => $this->formatMoney($this->unitPrice($item)),
'total' => $this->formatMoney($this->lineTotal($item)),
'unit_price' => $this->formatMoney($item->precio_unitario),
'total' => $this->formatMoney($item->total),
])->values(),
'total' => $this->formatMoney($this->total),
];
}
/** @return Collection<int, PurchaseItem|CartItem> */
private function saleItems(): Collection
{
if ($this->items->isNotEmpty()) {
return $this->items;
}
return $this->cart?->items ?? collect();
}
/** @return list<string> */
private function eventDates(PurchaseItem|CartItem $item): array
private function eventDates(PurchaseItem $item): array
{
if ($item instanceof CartItem) {
return $item->variant?->selectedEventDates()
->map(fn ($eventDate): string => $eventDate->date->format('Y-m-d'))
->values()
->all() ?? [];
}
return collect($item->variant_attributes ?? [])
->filter(fn (mixed $attribute): bool => is_array($attribute)
&& mb_strtolower(trim((string) ($attribute['name'] ?? ''))) === 'fecha')
@@ -66,20 +43,6 @@ class SaleDetailResource extends JsonResource
->all();
}
private function unitPrice(PurchaseItem|CartItem $item): float|int|string|null
{
return $item instanceof PurchaseItem
? $item->precio_unitario
: $item->selectedItem()?->getPrice();
}
private function lineTotal(PurchaseItem|CartItem $item): float|int|string|null
{
return $item instanceof PurchaseItem
? $item->total
: ($item->selectedItem()?->getPrice() ?? 0) * $item->cantidad;
}
private function formatMoney(float|int|string|null $amount): string
{
return number_format((float) ($amount ?? 0), 2, '.', '');

View File

@@ -51,14 +51,7 @@ class AdminAppSaleService
{
return Purchase::query()
->where('tenant_codigo', $tenant->codigo)
->with([
'items',
'cart' => fn ($query) => $query->withTrashed(),
'cart.items.catalogItem',
'cart.items.variant.catalogItem',
'cart.items.variant.eventDates',
'cart.items.variant.eventDate',
])
->with('items')
->findOrFail($saleId);
}
@@ -86,7 +79,7 @@ class AdminAppSaleService
$sale = $this->findForTenant($tenant, $saleId);
return $this->saleForResponse(
$this->checkoutService->cancelPurchaseWithoutRestoringCart($sale)
$this->checkoutService->cancelPurchaseFromAdmin($sale)
);
}
@@ -133,6 +126,7 @@ class AdminAppSaleService
return Purchase::query()
->where('tenant_codigo', $tenant->codigo)
->where('status', '!=', Purchase::STATUS_SUPERSEDED)
->when($filters['q'] ?? null, function (Builder $query, string $search): void {
$term = trim($search);
@@ -150,19 +144,18 @@ class AdminAppSaleService
)
->when(
$filters['status'] ?? null,
fn (Builder $query, string $status): Builder => $query->where('status', $status)
fn (Builder $query, string $status): Builder => $status === Purchase::STATUS_PENDING_PAYMENT
? $query->whereIn('status', [
Purchase::STATUS_PENDING_PAYMENT,
Purchase::STATUS_IN_REVIEW,
])
: $query->where('status', $status)
)
->select('compras.*')
->selectRaw(
'CASE WHEN compras.status IN (?, ?) '
.'THEN (SELECT COALESCE(SUM(cart_items.cantidad), 0) FROM carrito_items AS cart_items '
.'WHERE cart_items.cart_id = compras.cart_id) '
.'ELSE (SELECT COALESCE(SUM(purchase_items.cantidad), 0) FROM compra_items AS purchase_items '
.'WHERE purchase_items.compra_id = compras.id) END AS quantity',
[
Purchase::STATUS_CREATED,
Purchase::STATUS_PENDING_PAYMENT,
],
'(SELECT COALESCE(SUM(purchase_items.cantidad), 0) '
.'FROM compra_items AS purchase_items '
.'WHERE purchase_items.compra_id = compras.id) AS quantity',
)
->withCount('tickets')
->orderBy($sortColumns[$sortBy], $sortDirection)
@@ -199,16 +192,11 @@ class AdminAppSaleService
protected function quantityExpression(): string
{
// El fallback se resuelve en SQL para poder ordenar por cantidad antes de paginar;
// los ítems consolidados de la compra tienen prioridad sobre los del carrito de origen.
return <<<'SQL'
COALESCE(
(SELECT SUM(compra_items.cantidad)
FROM compra_items
WHERE compra_items.compra_id = compras.id),
(SELECT SUM(carrito_items.cantidad)
FROM carrito_items
WHERE carrito_items.cart_id = compras.cart_id),
0
) AS quantity
SQL;

View File

@@ -111,7 +111,10 @@ class StoreTenantRequest extends FormRequest
'display_seach_bar' => ['sometimes', 'boolean'],
'display_cart' => ['sometimes', 'boolean'],
'cart_editing_policy' => ['sometimes', Rule::enum(CartEditingPolicy::class)],
'checkout_editing_policy' => ['sometimes', Rule::enum(CartEditingPolicy::class)],
'checkout_editing_policy' => [
'sometimes',
Rule::in([CartEditingPolicy::Disabled->value]),
],
'display_cart_item_images' => ['sometimes', 'boolean'],
'scanner_category_validation_enabled' => ['sometimes', 'boolean'],
'website_type_code' => [

View File

@@ -132,7 +132,10 @@ class UpdateTenantRequest extends FormRequest
'display_seach_bar' => ['sometimes', 'boolean'],
'display_cart' => ['sometimes', 'boolean'],
'cart_editing_policy' => ['sometimes', Rule::enum(CartEditingPolicy::class)],
'checkout_editing_policy' => ['sometimes', Rule::enum(CartEditingPolicy::class)],
'checkout_editing_policy' => [
'sometimes',
Rule::in([CartEditingPolicy::Disabled->value]),
],
'display_cart_item_images' => ['sometimes', 'boolean'],
'scanner_category_validation_enabled' => ['sometimes', 'boolean'],
];

View File

@@ -0,0 +1,20 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Support\Facades\DB;
return new class extends Migration
{
public function up(): void
{
DB::table('tenants')->update([
'checkout_editing_policy' => 'disabled',
]);
}
public function down(): void
{
// Checkout editing stays disabled because previous tenant values cannot
// be reconstructed after normalization.
}
};

View File

@@ -0,0 +1,46 @@
<?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('carritos', function (Blueprint $table): void {
$table->foreignId('current_purchase_id')
->nullable()
->after('origin')
->constrained('compras')
->nullOnDelete();
$table->unique('current_purchase_id', 'carts_current_purchase_unique');
});
DB::table('carritos')
->select('id')
->orderBy('id')
->each(function (object $cart): void {
$purchaseId = DB::table('compras')
->where('cart_id', $cart->id)
->whereIn('status', ['created', 'pending_payment'])
->latest('id')
->value('id');
if ($purchaseId !== null) {
DB::table('carritos')
->where('id', $cart->id)
->update(['current_purchase_id' => $purchaseId]);
}
});
}
public function down(): void
{
Schema::table('carritos', function (Blueprint $table): void {
$table->dropUnique('carts_current_purchase_unique');
$table->dropConstrainedForeignId('current_purchase_id');
});
}
};

View File

@@ -0,0 +1,25 @@
<?php
use App\Domains\Desfile\Services\InvitationPurchaseProvisioner;
use Illuminate\Database\Migrations\Migration;
return new class extends Migration
{
public function up(): void
{
app(InvitationPurchaseProvisioner::class)->provision([
[
'sector' => 'C',
'row' => 3,
'first_seat' => 6,
'last_seat' => 7,
'type' => 'NORMAL',
],
]);
}
public function down(): void
{
// Intentionally irreversible: issued invitation tickets may already be used.
}
};

View File

@@ -42,8 +42,9 @@ return [
'payment_method_required' => 'The purchase payment method must be selected before finalizing.',
'not_editable' => 'The purchase is no longer editable.',
'insufficient_stock' => 'There is not enough stock available.',
'cannot_confirm' => 'A cancelled, rejected, or expired purchase cannot be confirmed.',
'cannot_confirm' => 'A cancelled, rejected, expired, or superseded purchase cannot be confirmed.',
'inconsistent_reservation' => 'The purchase has an inconsistent stock reservation.',
'not_current' => 'The purchase is no longer the cart\'s current checkout.',
'paid_cannot_cancel' => 'A paid purchase cannot be cancelled.',
'stock' => [
'seat_unavailable' => 'Seat :selection is no longer available.',
@@ -55,6 +56,7 @@ return [
'catalog_item_missing' => 'One or more catalog items could not be loaded.',
'catalog_item_wrong_tenant' => 'One or more catalog items do not belong to the tenant.',
'inactive_cart' => 'The selected cart is no longer active.',
'checkout_in_progress' => 'The cart already has a purchase in progress.',
'not_available_for_payment' => 'The purchase is no longer available for payment.',
'not_available_for_review' => 'The purchase is no longer available for review.',
],

View File

@@ -42,8 +42,9 @@ return [
'payment_method_required' => 'Debes seleccionar el método de pago antes de finalizar la compra.',
'not_editable' => 'La compra ya no se puede modificar.',
'insufficient_stock' => 'No hay suficiente stock disponible.',
'cannot_confirm' => 'Una compra cancelada, rechazada o vencida no se puede confirmar.',
'cannot_confirm' => 'Una compra cancelada, rechazada, vencida o reemplazada no se puede confirmar.',
'inconsistent_reservation' => 'La compra tiene una reserva de stock inconsistente.',
'not_current' => 'La compra ya no es el checkout actual del carrito.',
'paid_cannot_cancel' => 'Una compra pagada no se puede cancelar.',
'stock' => [
'seat_unavailable' => 'El asiento :selection ya no está disponible.',
@@ -55,6 +56,7 @@ return [
'catalog_item_missing' => 'No se pudieron cargar uno o más productos del catálogo.',
'catalog_item_wrong_tenant' => 'Uno o más productos no pertenecen al tenant.',
'inactive_cart' => 'El carrito seleccionado ya no está activo.',
'checkout_in_progress' => 'El carrito ya tiene una compra en curso.',
'not_available_for_payment' => 'La compra ya no está disponible para el pago.',
'not_available_for_review' => "La compra ya no est\u{00E1} disponible para revisi\u{00F3}n.",
],

View File

@@ -73,10 +73,15 @@ class CatalogControllerTest extends TestCase
->assertJsonPath('0.items.0.descripcion', 'Variants description')
->assertJsonPath('0.items.0.precio', '100.00')
->assertJsonPath('0.items.0.maximum_addable_quantity', 7)
->assertJsonCount(2, '0.items.0.variants')
->assertJsonCount(3, '0.items.0.variants')
->assertJsonPath('0.items.0.variants.0.maximum_addable_quantity', 4)
->assertJsonPath('0.items.0.variants.1.maximum_addable_quantity', 3)
->assertJsonMissing(['id' => $unavailableVariant->id])
->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.items.data.0.maximum_addable_quantity', 8)
->assertJsonMissingPath('1.items.data.0.stock_tecnico')
@@ -94,7 +99,7 @@ class CatalogControllerTest extends TestCase
);
$user = User::factory()->create();
$item = $this->createItem($tenant, 'Limited variants');
$item->update(['max_units_per_user' => 5]);
$item->update(['max_units_per_user' => 3]);
$firstVariant = $item->variants()->create([
'inventory_id' => Inventory::query()->create(['real_stock' => 10])->id,
]);
@@ -114,13 +119,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', 2)
->assertJsonPath('0.items.0.variants.1.maximum_addable_quantity', 2)
->assertJsonPath('0.items.0.variants.0.maximum_addable_quantity', 0)
->assertJsonPath('0.items.0.variants.1.maximum_addable_quantity', 0)
->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',
'Alcanzaste el cupo máximo permitido para este producto.',
)
->assertJsonMissingPath('0.items.0.variants.0.stock_tecnico')
->assertJsonMissingPath('0.items.0.variants.1.stock_tecnico');
}
public function test_it_excludes_items_when_all_of_their_variants_are_out_of_stock(): void
public function test_it_includes_out_of_stock_items_with_an_unavailable_message(): void
{
$tenant = $this->createTenant('catalog-available-variants');
$group = $this->createGroup(
@@ -148,9 +161,15 @@ class CatalogControllerTest extends TestCase
$this->getJson("/api/tenants/{$tenant->codigo}/catalog")
->assertOk()
->assertJsonCount(1, '0.items')
->assertJsonPath('0.items.0.nombre', 'Available')
->assertJsonMissing(['nombre' => 'Unavailable']);
->assertJsonCount(2, '0.items')
->assertJsonPath('0.items.0.nombre', 'Unavailable')
->assertJsonPath('0.items.0.maximum_addable_quantity', 0)
->assertJsonPath(
'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

View File

@@ -48,7 +48,7 @@ class CatalogItemDetailControllerTest extends TestCase
$this->assertStringContainsString($itemImage->path, $response->json('data.images.0'));
}
public function test_it_filters_unavailable_variants_and_selects_the_first_available_one(): void
public function test_it_lists_unavailable_variants_and_selects_the_first_available_one(): void
{
Storage::fake('s3');
$tenant = $this->createTenant('detail-default');
@@ -69,8 +69,14 @@ class CatalogItemDetailControllerTest extends TestCase
$response
->assertOk()
->assertJsonCount(1, 'data.variants')
->assertJsonPath('data.variants.0.id', $secondVariant->id)
->assertJsonCount(2, 'data.variants')
->assertJsonPath('data.variants.0.id', $firstVariant->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.maximum_addable_quantity', 6)
->assertJsonMissingPath('data.selected_variant.stock_tecnico')

View File

@@ -51,8 +51,9 @@ class AdminAppSaleFormControllerTest extends TestCase
->assertJsonPath('data.statuses.0.code', Purchase::STATUS_CREATED)
->assertJsonPath('data.statuses.0.name', 'Creada')
->assertJsonPath('data.statuses.1.code', Purchase::STATUS_PENDING_PAYMENT)
->assertJsonPath('data.statuses.2.code', Purchase::STATUS_PAID)
->assertJsonPath('data.statuses.5.code', Purchase::STATUS_EXPIRED);
->assertJsonPath('data.statuses.2.code', Purchase::STATUS_IN_REVIEW)
->assertJsonPath('data.statuses.3.code', Purchase::STATUS_PAID)
->assertJsonPath('data.statuses.6.code', Purchase::STATUS_EXPIRED);
}
public function test_a_customer_cannot_get_the_sale_form(): void

View File

@@ -194,8 +194,9 @@ class TelepagosWebhookTest extends TestCase
'sold_units' => 1,
]);
$this->assertDatabaseMissing('compra_items', [
$this->assertDatabaseHas('compra_items', [
'compra_id' => $newerPurchase->id,
'cantidad' => 2,
]);
$this->assertDatabaseHas('stock_reservations', [
'purchase_id' => $newerPurchase->id,

File diff suppressed because it is too large Load Diff

View File

@@ -7,9 +7,12 @@ use App\Domains\Authorization\Enums\RoleCode;
use App\Domains\Cart\Models\Cart;
use App\Domains\Cart\Models\CartItem;
use App\Domains\Catalog\Models\CatalogItem;
use App\Domains\Catalog\Models\Inventory;
use App\Domains\Catalog\Models\Variant;
use App\Domains\Purchase\Events\PurchasePaid;
use App\Domains\Purchase\Models\Purchase;
use App\Domains\Purchase\Models\PurchaseItem;
use App\Domains\Purchase\Services\CheckoutService;
use App\Domains\Tenant\Models\Tenant;
use App\Domains\Tenant\Models\WebsiteType;
use App\Domains\Ticket\Models\Ticket;
@@ -31,7 +34,7 @@ class AdminAppSaleControllerTest extends TestCase
WebsiteType::query()->create(['codigo' => 'onticket', 'nombre' => 'OnTicket']);
}
public function test_sales_list_uses_cart_quantity_for_created_and_pending_payment_sales(): void
public function test_sales_list_uses_purchase_item_snapshots_for_every_status(): void
{
$tenant = $this->createTenant('acme');
Sanctum::actingAs($this->createAdminAppUser($tenant));
@@ -62,9 +65,9 @@ class AdminAppSaleControllerTest extends TestCase
'compra_id' => $createdPurchase->id,
'source_catalog_item_id' => $catalogItem->id,
'item_nombre' => $catalogItem->nombre,
'cantidad' => 1,
'cantidad' => 3,
'precio_unitario' => '10000.00',
'total' => '10000.00',
'total' => '30000.00',
]);
$pendingCart = Cart::query()->create([
@@ -82,6 +85,14 @@ class AdminAppSaleControllerTest extends TestCase
'status' => Purchase::STATUS_PENDING_PAYMENT,
'total' => '40000.00',
]);
PurchaseItem::query()->create([
'compra_id' => $pendingPurchase->id,
'source_catalog_item_id' => $catalogItem->id,
'item_nombre' => $catalogItem->nombre,
'cantidad' => 4,
'precio_unitario' => '10000.00',
'total' => '40000.00',
]);
$paidPurchase = Purchase::query()->create([
'tenant_codigo' => $tenant->codigo,
@@ -97,6 +108,20 @@ class AdminAppSaleControllerTest extends TestCase
'total' => '20000.00',
]);
$supersededPurchase = Purchase::query()->create([
'tenant_codigo' => $tenant->codigo,
'status' => Purchase::STATUS_SUPERSEDED,
'total' => '50000.00',
]);
PurchaseItem::query()->create([
'compra_id' => $supersededPurchase->id,
'source_catalog_item_id' => $catalogItem->id,
'item_nombre' => $catalogItem->nombre,
'cantidad' => 5,
'precio_unitario' => '10000.00',
'total' => '50000.00',
]);
$this->getJson('/api/v1/adminapp/tenant/sales?sort_by=id&sort_direction=asc')
->assertOk()
->assertJsonCount(3, 'data')
@@ -106,6 +131,10 @@ class AdminAppSaleControllerTest extends TestCase
->assertJsonPath('data.1.quantity', 4)
->assertJsonPath('data.2.id', $paidPurchase->id)
->assertJsonPath('data.2.quantity', 2);
$this->getJson('/api/v1/adminapp/tenant/sales?status='.Purchase::STATUS_SUPERSEDED)
->assertOk()
->assertJsonCount(0, 'data');
}
public function test_authentication_is_required_to_read_a_sale_detail(): void
@@ -113,6 +142,31 @@ class AdminAppSaleControllerTest extends TestCase
$this->getJson('/api/v1/adminapp/tenant/sales/1')->assertUnauthorized();
}
public function test_pending_payment_filter_also_returns_purchases_in_review(): void
{
$tenant = $this->createTenant('acme');
Sanctum::actingAs($this->createAdminAppUser($tenant));
$pendingPurchase = Purchase::query()->create([
'tenant_codigo' => $tenant->codigo,
'status' => Purchase::STATUS_PENDING_PAYMENT,
]);
$reviewPurchase = Purchase::query()->create([
'tenant_codigo' => $tenant->codigo,
'status' => Purchase::STATUS_IN_REVIEW,
]);
Purchase::query()->create([
'tenant_codigo' => $tenant->codigo,
'status' => Purchase::STATUS_PAID,
]);
$this->getJson('/api/v1/adminapp/tenant/sales?status=pending_payment&sort_by=id&sort_direction=asc')
->assertOk()
->assertJsonCount(2, 'data')
->assertJsonPath('data.0.id', $pendingPurchase->id)
->assertJsonPath('data.1.id', $reviewPurchase->id);
}
public function test_an_adminapp_user_can_read_a_sale_detail_from_its_tenant(): void
{
$tenant = $this->createTenant('acme');
@@ -149,7 +203,7 @@ class AdminAppSaleControllerTest extends TestCase
->assertJsonPath('data.total', '40000.00');
}
public function test_an_adminapp_user_can_read_cart_items_from_an_unconfirmed_sale(): void
public function test_an_adminapp_user_can_read_purchase_item_snapshots_from_an_unconfirmed_sale(): void
{
$tenant = $this->createTenant('acme');
Sanctum::actingAs($this->createAdminAppUser($tenant));
@@ -176,10 +230,18 @@ class AdminAppSaleControllerTest extends TestCase
'status' => Purchase::STATUS_PENDING_PAYMENT,
'total' => '25000.00',
]);
$purchaseItem = PurchaseItem::query()->create([
'compra_id' => $purchase->id,
'source_catalog_item_id' => $catalogItem->id,
'item_nombre' => $catalogItem->nombre,
'cantidad' => 2,
'precio_unitario' => '12500.00',
'total' => '25000.00',
]);
$this->getJson("/api/v1/adminapp/tenant/sales/{$purchase->id}")
->assertOk()
->assertJsonPath('data.items.0.id', $cartItem->id)
->assertJsonPath('data.items.0.id', $purchaseItem->id)
->assertJsonPath('data.items.0.product', 'Entrada general')
->assertJsonPath('data.items.0.event_dates', [])
->assertJsonPath('data.items.0.quantity', 2)
@@ -187,7 +249,7 @@ class AdminAppSaleControllerTest extends TestCase
->assertJsonPath('data.items.0.total', '25000.00');
}
public function test_sales_list_uses_cart_quantity_until_purchase_items_exist(): void
public function test_sales_list_quantity_always_comes_from_purchase_items(): void
{
$tenant = $this->createTenant('acme');
Sanctum::actingAs($this->createAdminAppUser($tenant));
@@ -214,13 +276,7 @@ class AdminAppSaleControllerTest extends TestCase
'status' => Purchase::STATUS_PENDING_PAYMENT,
'total' => '37500.00',
]);
$this->getJson('/api/v1/adminapp/tenant/sales')
->assertOk()
->assertJsonPath('data.0.id', $purchase->id)
->assertJsonPath('data.0.quantity', 3);
PurchaseItem::query()->create([
$purchaseItem = PurchaseItem::query()->create([
'compra_id' => $purchase->id,
'source_catalog_item_id' => $catalogItem->id,
'nombre' => 'Entrada general',
@@ -232,7 +288,17 @@ class AdminAppSaleControllerTest extends TestCase
$this->getJson('/api/v1/adminapp/tenant/sales')
->assertOk()
->assertJsonPath('data.0.id', $purchase->id)
->assertJsonPath('data.0.quantity', 2);
$purchaseItem->update([
'cantidad' => 4,
'total' => '50000.00',
]);
$this->getJson('/api/v1/adminapp/tenant/sales')
->assertOk()
->assertJsonPath('data.0.quantity', 4);
}
public function test_an_adminapp_user_cannot_read_a_sale_from_another_tenant(): void
@@ -329,11 +395,25 @@ class AdminAppSaleControllerTest extends TestCase
$admin = $this->createAdminAppUser($tenant);
Sanctum::actingAs($admin);
$purchase = Purchase::query()->create([
'tenant_codigo' => $tenant->codigo,
'status' => Purchase::STATUS_PENDING_PAYMENT,
'total' => '10000.00',
$inventory = Inventory::query()->create(['real_stock' => 10]);
$catalogItem = CatalogItem::query()->create([
'tenant_code' => $tenant->codigo,
'slug' => 'confirmable-item',
'nombre' => 'Confirmable item',
'precio' => '10000.00',
]);
$variant = Variant::query()->create([
'catalog_item_id' => $catalogItem->id,
'inventory_id' => $inventory->id,
]);
$purchase = app(CheckoutService::class)->startCheckout($tenant, $admin->id, [
'direct_items' => [[
'catalog_item_id' => $catalogItem->id,
'variant_id' => $variant->id,
'cantidad' => 1,
]],
]);
$purchase->update(['status' => Purchase::STATUS_PENDING_PAYMENT]);
$this->postJson("/api/v1/adminapp/tenant/sales/{$purchase->id}/confirm")
->assertOk()
@@ -385,6 +465,14 @@ class AdminAppSaleControllerTest extends TestCase
'status' => Purchase::STATUS_PENDING_PAYMENT,
'total' => '10000.00',
]);
PurchaseItem::query()->create([
'compra_id' => $purchase->id,
'source_catalog_item_id' => $catalogItem->id,
'item_nombre' => $catalogItem->nombre,
'cantidad' => 2,
'precio_unitario' => '10000.00',
'total' => '20000.00',
]);
$this->postJson("/api/v1/adminapp/tenant/sales/{$purchase->id}/cancel")
->assertOk()
@@ -401,6 +489,43 @@ class AdminAppSaleControllerTest extends TestCase
->assertJsonPath('data.items.0.quantity', 2);
}
public function test_adminapp_can_cancel_a_purchase_in_review(): void
{
$tenant = $this->createTenant('acme');
$admin = $this->createAdminAppUser($tenant);
Sanctum::actingAs($admin);
$inventory = Inventory::query()->create(['real_stock' => 10]);
$catalogItem = CatalogItem::query()->create([
'tenant_code' => $tenant->codigo,
'slug' => 'review-item',
'nombre' => 'Review item',
'precio' => '10000.00',
]);
$variant = Variant::query()->create([
'catalog_item_id' => $catalogItem->id,
'inventory_id' => $inventory->id,
]);
$purchase = app(CheckoutService::class)->startCheckout($tenant, $admin->id, [
'direct_items' => [[
'catalog_item_id' => $catalogItem->id,
'variant_id' => $variant->id,
'cantidad' => 2,
]],
]);
$purchase->update(['status' => Purchase::STATUS_IN_REVIEW]);
$sourceCartId = $purchase->cart_id;
$this->postJson("/api/v1/adminapp/tenant/sales/{$purchase->id}/cancel")
->assertOk()
->assertJsonPath('data.status', Purchase::STATUS_CANCELLED);
$this->assertSoftDeleted('carritos', ['id' => $sourceCartId]);
$this->assertDatabaseHas('stock_reservations', [
'purchase_id' => $purchase->id,
'status' => 'released',
]);
}
public function test_an_adminapp_user_cannot_change_a_sale_from_another_tenant(): void
{
$tenant = $this->createTenant('acme');

View File

@@ -288,19 +288,19 @@ class DesfilePuraTendenciaSeederTest extends TestCase
$items = DB::table('compra_items')->where('compra_id', $purchase->id);
$this->assertSame(46, (clone $items)->count());
$this->assertSame(46, (clone $items)
$this->assertSame(48, (clone $items)->count());
$this->assertSame(48, (clone $items)
->where('precio_unitario', 0)
->where('discount_total', 0)
->where('tax_total', 0)
->where('total', 0)
->count());
$this->assertSame(46, DB::table('tickets')
$this->assertSame(48, DB::table('tickets')
->where('source_purchase_id', $purchase->id)
->where('user_id', $user->id)
->where('source_catalog_item_id', $catalogItemId)
->count());
$this->assertSame(46, DB::table('stock_reservations')
$this->assertSame(48, DB::table('stock_reservations')
->where('purchase_id', $purchase->id)
->where('status', 'committed')
->count());
@@ -309,6 +309,7 @@ class DesfilePuraTendenciaSeederTest extends TestCase
['sector' => 'A', 'fila' => '1', 'tipo' => 'NORMAL', 'count' => 16],
['sector' => 'A', 'fila' => '3', 'tipo' => 'NORMAL', 'count' => 14],
['sector' => 'C', 'fila' => '1', 'tipo' => 'VIP + LUNCH', 'count' => 16],
['sector' => 'C', 'fila' => '3', 'tipo' => 'NORMAL', 'count' => 2, 'seats' => ['6', '7']],
] as $allocation) {
$allocatedVariants = DB::table('variantes')
->where('catalog_item_id', $catalogItemId)
@@ -326,6 +327,20 @@ class DesfilePuraTendenciaSeederTest extends TestCase
}
$this->assertSame($allocation['count'], $allocatedVariants->count());
if (isset($allocation['seats'])) {
$seatValues = DB::table('variant_values')
->join('item_attributes', 'item_attributes.id', '=', 'variant_values.item_attribute_id')
->join('attribute', 'attribute.id', '=', 'item_attributes.attribute_id')
->whereIn('variant_values.variant_id', (clone $allocatedVariants)->pluck('id'))
->where('attribute.codigo', 'asiento')
->pluck('variant_values.value')
->sort()
->values()
->all();
$this->assertSame($allocation['seats'], $seatValues);
}
}
}

View File

@@ -76,7 +76,7 @@ class BootstrapTenantControllerTest extends TestCase
'display_seach_bar' => false,
'display_cart' => false,
'cart_editing_policy' => 'disabled',
'checkout_editing_policy' => 'quantity_and_remove',
'checkout_editing_policy' => 'disabled',
'display_cart_item_images' => false,
]);
@@ -101,10 +101,10 @@ class BootstrapTenantControllerTest extends TestCase
->assertJsonPath('data.cart_editing_policy.allow_delete', false)
->assertJsonPath('data.cart_editing_policy.allow_update_quantity', false)
->assertJsonPath('data.cart_editing_policy.allow_update_variant', false)
->assertJsonPath('data.checkout_editing_policy.code', 'quantity_and_remove')
->assertJsonPath('data.checkout_editing_policy.allow_modify', true)
->assertJsonPath('data.checkout_editing_policy.allow_delete', true)
->assertJsonPath('data.checkout_editing_policy.allow_update_quantity', true)
->assertJsonPath('data.checkout_editing_policy.code', 'disabled')
->assertJsonPath('data.checkout_editing_policy.allow_modify', false)
->assertJsonPath('data.checkout_editing_policy.allow_delete', false)
->assertJsonPath('data.checkout_editing_policy.allow_update_quantity', false)
->assertJsonPath('data.checkout_editing_policy.allow_update_variant', false)
->assertJsonPath('data.display_cart_item_images', false)
->assertJsonPath('data.header_bg_color', '#ffffff')->assertJsonPath('data.footer_bg_color', '#ffffff');

View File

@@ -0,0 +1,43 @@
<?php
namespace Tests\Unit\Catalog;
use App\Domains\Catalog\Services\CatalogItemAllowanceService;
use ReflectionClass;
use Tests\TestCase;
class CatalogItemAllowanceServiceTest extends TestCase
{
private CatalogItemAllowanceService $service;
protected function setUp(): void
{
parent::setUp();
$this->service = (new ReflectionClass(CatalogItemAllowanceService::class))
->newInstanceWithoutConstructor();
}
public function test_it_returns_the_user_quota_message_with_priority_over_stock(): void
{
$this->assertSame(
'Alcanzaste el cupo máximo permitido para este producto.',
$this->service->unavailableMessage(0, 0),
);
}
public function test_it_returns_the_out_of_stock_message(): void
{
$this->assertSame(
'Este producto no tiene stock disponible.',
$this->service->unavailableMessage(0, null),
);
}
public function test_it_returns_no_message_when_the_item_is_available(): void
{
$this->assertNull($this->service->unavailableMessage(1, null));
$this->assertNull($this->service->unavailableMessage(null, 1));
$this->assertNull($this->service->unavailableMessage(null, null));
}
}

View File

@@ -16,10 +16,12 @@ class SaleFormServiceTest extends TestCase
$this->assertSame([
'Creada',
'Esperando pago',
'En revisión',
'Confirmada',
'Cancelada',
'Rechazada',
'Vencida',
'Reemplazada',
], array_column($form['statuses'], 'name'));
}
}

View File

@@ -2,9 +2,6 @@
namespace Tests\Unit\Sale;
use App\Domains\Cart\Models\Cart;
use App\Domains\Cart\Models\CartItem;
use App\Domains\Catalog\Models\CatalogItem;
use App\Domains\Purchase\Models\Purchase;
use App\Domains\Purchase\Models\PurchaseItem;
use App\Domains\Sale\Resources\AdminApp\SaleDetailResource;
@@ -42,38 +39,16 @@ class SaleDetailResourceTest extends TestCase
$this->assertSame('30000.00', $data['total']);
}
public function test_it_uses_the_associated_cart_items_when_the_purchase_has_no_items(): void
public function test_it_does_not_fall_back_to_cart_items_when_the_purchase_has_no_items(): void
{
$catalogItem = (new CatalogItem)->forceFill([
'id' => 21,
'nombre' => 'Entrada general',
'precio' => '12500.00',
]);
$cartItem = (new CartItem)->forceFill([
'id' => 34,
'catalog_item_id' => $catalogItem->id,
'cantidad' => 2,
]);
$cartItem->setRelation('catalogItem', $catalogItem);
$cartItem->setRelation('variant', null);
$cart = new Cart;
$cart->setRelation('items', collect([$cartItem]));
$purchase = (new Purchase)->forceFill([
'id' => 16,
'total' => '25000.00',
]);
$purchase->setRelation('items', collect());
$purchase->setRelation('cart', $cart);
$data = (new SaleDetailResource($purchase))->resolve(Request::create('/'));
$this->assertSame(34, $data['items'][0]['id']);
$this->assertSame('Entrada general', $data['items'][0]['product']);
$this->assertSame([], $data['items'][0]['event_dates']);
$this->assertSame(2, $data['items'][0]['quantity']);
$this->assertSame('12500.00', $data['items'][0]['unit_price']);
$this->assertSame('25000.00', $data['items'][0]['total']);
$this->assertCount(0, $data['items']);
}
}