Compare commits
6 Commits
3a2dc8b7e0
...
dc0fbe06b8
| Author | SHA1 | Date | |
|---|---|---|---|
| dc0fbe06b8 | |||
| afd69b8393 | |||
| a34d5cba1a | |||
| 1650176aa0 | |||
| 79e721ae63 | |||
| 4e7e42d16e |
@@ -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'),
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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'),
|
||||
|
||||
@@ -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();
|
||||
});
|
||||
|
||||
@@ -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.');
|
||||
}
|
||||
|
||||
|
||||
@@ -16,6 +16,7 @@ class SaleFormService
|
||||
Purchase::STATUS_CANCELLED => 'Cancelada',
|
||||
Purchase::STATUS_REJECTED => 'Rechazada',
|
||||
Purchase::STATUS_EXPIRED => 'Vencida',
|
||||
Purchase::STATUS_SUPERSEDED => 'Reemplazada',
|
||||
];
|
||||
|
||||
return [
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -47,6 +47,8 @@ class Purchase extends Model
|
||||
|
||||
public const STATUS_EXPIRED = 'expired';
|
||||
|
||||
public const STATUS_SUPERSEDED = 'superseded';
|
||||
|
||||
/** @return list<string> */
|
||||
public static function statuses(): array
|
||||
{
|
||||
@@ -57,6 +59,7 @@ class Purchase extends Model
|
||||
self::STATUS_CANCELLED,
|
||||
self::STATUS_REJECTED,
|
||||
self::STATUS_EXPIRED,
|
||||
self::STATUS_SUPERSEDED,
|
||||
];
|
||||
}
|
||||
|
||||
@@ -154,12 +157,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
|
||||
|
||||
@@ -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'],
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -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,19 +16,9 @@ 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,
|
||||
@@ -46,132 +32,13 @@ class PurchaseItemResource extends JsonResource
|
||||
'descripcion' => $this->descripcion,
|
||||
'slug' => $this->slug,
|
||||
'imagen' => $imageUrl,
|
||||
'attributes' => $attributes,
|
||||
'attributes' => $this->variant_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)
|
||||
: 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,
|
||||
'imagen' => $imageUrl,
|
||||
'attributes' => $variant === null ? [] : $this->resolveAttributes($variant),
|
||||
],
|
||||
'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),
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
|
||||
@@ -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,8 @@ class CompleteCheckoutService
|
||||
return $this->loadPurchase($purchase);
|
||||
}
|
||||
|
||||
$this->purchaseState->lockCurrentCart($purchase);
|
||||
|
||||
if (
|
||||
$purchase->status !== Purchase::STATUS_PENDING_PAYMENT
|
||||
|| ($purchase->expires_at !== null && $purchase->expires_at->isPast())
|
||||
@@ -84,25 +87,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 +119,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 +155,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'),
|
||||
@@ -148,6 +174,7 @@ class CompleteCheckoutService
|
||||
Purchase::STATUS_CANCELLED,
|
||||
Purchase::STATUS_REJECTED,
|
||||
Purchase::STATUS_EXPIRED,
|
||||
Purchase::STATUS_SUPERSEDED,
|
||||
], true);
|
||||
}
|
||||
|
||||
@@ -159,16 +186,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 */
|
||||
|
||||
@@ -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);
|
||||
/** @var Purchase $purchase */
|
||||
$purchase = Purchase::query()->lockForUpdate()->findOrFail($purchase->getKey());
|
||||
$this->purchaseState->assertNotExpired($purchase);
|
||||
$this->assertEditable($purchase);
|
||||
|
||||
if (! in_array($purchase->status, [
|
||||
Purchase::STATUS_CREATED,
|
||||
Purchase::STATUS_PENDING_PAYMENT,
|
||||
], true)) {
|
||||
throw ValidationException::withMessages([
|
||||
'purchase' => __('api.purchase.not_editable'),
|
||||
]);
|
||||
}
|
||||
|
||||
$this->purchaseState->lockCurrentCart($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);
|
||||
$this->purchaseState->assertNotExpired($purchase);
|
||||
|
||||
if ($purchase->status !== Purchase::STATUS_CREATED || $this->hasExpired($purchase)) {
|
||||
throw ValidationException::withMessages([
|
||||
'purchase' => __('api.purchase.not_editable'),
|
||||
]);
|
||||
}
|
||||
|
||||
$purchaseItem = $this->lockPurchaseItem($purchase, $purchaseItem);
|
||||
$tenant = $purchase->tenant()->firstOrFail();
|
||||
$finalQuantity = $quantity ?? (int) $purchaseItem->cantidad;
|
||||
|
||||
if ($quantity !== null && ! $tenant->checkout_editing_policy->allowsQuantityChanges()) {
|
||||
throw ValidationException::withMessages([
|
||||
'quantity' => __('api.cart.editing_disabled'),
|
||||
]);
|
||||
}
|
||||
|
||||
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);
|
||||
});
|
||||
}
|
||||
|
||||
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);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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>>
|
||||
|
||||
@@ -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']);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
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;
|
||||
@@ -14,22 +15,16 @@ class ReleaseCheckoutService
|
||||
{
|
||||
public function __construct(
|
||||
private readonly StockReservationService $reservations,
|
||||
private readonly SourceCartService $sourceCart,
|
||||
) {}
|
||||
|
||||
public function cancel(Purchase $purchase): Purchase
|
||||
{
|
||||
return $this->release($purchase, Purchase::STATUS_CANCELLED, restoreCart: true);
|
||||
}
|
||||
|
||||
public function cancelWithoutRestoringCart(Purchase $purchase): Purchase
|
||||
{
|
||||
return $this->release($purchase, Purchase::STATUS_CANCELLED, restoreCart: false);
|
||||
return $this->release($purchase, Purchase::STATUS_CANCELLED);
|
||||
}
|
||||
|
||||
public function expire(Purchase $purchase): Purchase
|
||||
{
|
||||
return $this->release($purchase, Purchase::STATUS_EXPIRED, restoreCart: false);
|
||||
return $this->release($purchase, Purchase::STATUS_EXPIRED);
|
||||
}
|
||||
|
||||
public function expireOverdue(): int
|
||||
@@ -66,15 +61,11 @@ class ReleaseCheckoutService
|
||||
return $expiredCount;
|
||||
}
|
||||
|
||||
private function release(Purchase $purchase, string $targetStatus, bool $restoreCart): Purchase
|
||||
private function release(Purchase $purchase, string $targetStatus): Purchase
|
||||
{
|
||||
return DB::transaction(function () use ($purchase, $targetStatus, $restoreCart): Purchase {
|
||||
return DB::transaction(function () use ($purchase, $targetStatus): Purchase {
|
||||
$purchase = $this->lockPurchase($purchase);
|
||||
|
||||
if ($targetStatus !== Purchase::STATUS_EXPIRED && ! $restoreCart) {
|
||||
$this->purchaseState->assertNotExpired($purchase);
|
||||
}
|
||||
|
||||
if ($purchase->status === Purchase::STATUS_PAID) {
|
||||
if ($targetStatus === Purchase::STATUS_EXPIRED) {
|
||||
return $this->loadPurchase($purchase);
|
||||
@@ -85,7 +76,7 @@ class ReleaseCheckoutService
|
||||
]);
|
||||
}
|
||||
|
||||
if ($this->isAlreadyReleased($purchase) && ! ($restoreCart && $purchase->status === Purchase::STATUS_EXPIRED)) {
|
||||
if ($this->isAlreadyReleased($purchase)) {
|
||||
return $this->loadPurchase($purchase);
|
||||
}
|
||||
|
||||
@@ -96,14 +87,7 @@ class ReleaseCheckoutService
|
||||
return $this->loadPurchase($purchase);
|
||||
}
|
||||
|
||||
if ($purchase->items()->exists()) {
|
||||
throw ValidationException::withMessages([
|
||||
'items' => __('api.purchase.inconsistent_reservation'),
|
||||
]);
|
||||
}
|
||||
|
||||
$reservationReturnedToCart = $restoreCart && $this->sourceCart->restore($purchase);
|
||||
$this->releaseCartReservations($purchase, $reservationReturnedToCart, $targetStatus);
|
||||
$this->releasePurchaseReservations($purchase, $targetStatus);
|
||||
|
||||
$purchase->update(['status' => $targetStatus]);
|
||||
|
||||
@@ -111,19 +95,24 @@ class ReleaseCheckoutService
|
||||
});
|
||||
}
|
||||
|
||||
private function releaseCartReservations(
|
||||
Purchase $purchase,
|
||||
bool $reservationReturnedToCart,
|
||||
string $targetStatus,
|
||||
): void {
|
||||
if ($reservationReturnedToCart) {
|
||||
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;
|
||||
}
|
||||
|
||||
$cart = $purchase->cart()->withTrashed()->lockForUpdate()->first();
|
||||
if ($cart === null) {
|
||||
if ($cart->status !== 'checkout') {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -170,6 +159,7 @@ class ReleaseCheckoutService
|
||||
Purchase::STATUS_CANCELLED,
|
||||
Purchase::STATUS_REJECTED,
|
||||
Purchase::STATUS_EXPIRED,
|
||||
Purchase::STATUS_SUPERSEDED,
|
||||
], true);
|
||||
}
|
||||
|
||||
@@ -181,15 +171,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']);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,168 +3,10 @@
|
||||
namespace App\Domains\Purchase\Services\Checkout;
|
||||
|
||||
use App\Domains\Cart\Models\Cart;
|
||||
use App\Domains\Cart\Models\CartItem;
|
||||
use App\Domains\Catalog\Services\StockReservationService;
|
||||
use App\Domains\Purchase\Models\Purchase;
|
||||
|
||||
class SourceCartService
|
||||
{
|
||||
public function __construct(
|
||||
private readonly StockReservationService $reservations,
|
||||
) {}
|
||||
|
||||
public function restore(Purchase $purchase): bool
|
||||
{
|
||||
$sourceCart = $this->findSourceCart($purchase);
|
||||
|
||||
if ($sourceCart === null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if ($sourceCart->origin === Cart::ORIGIN_DIRECT_CHECKOUT) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$this->restoreReservations($sourceCart);
|
||||
|
||||
/** @var Cart|null $activeCart */
|
||||
$activeCart = Cart::query()
|
||||
->where('tenant_codigo', $purchase->tenant_codigo)
|
||||
->where('user_id', $purchase->user_id)
|
||||
->where('status', 'active')
|
||||
->where('id', '!=', $sourceCart->getKey())
|
||||
->lockForUpdate()
|
||||
->first();
|
||||
|
||||
if ($activeCart !== null) {
|
||||
$this->mergeIntoActiveCart($sourceCart, $activeCart);
|
||||
|
||||
$sourceCart->update([
|
||||
'status' => 'converted',
|
||||
'guest_token' => null,
|
||||
]);
|
||||
|
||||
if (! $sourceCart->trashed()) {
|
||||
$sourceCart->delete();
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
if ($sourceCart->trashed()) {
|
||||
$sourceCart->restore();
|
||||
}
|
||||
|
||||
$sourceCart->update([
|
||||
'status' => 'active',
|
||||
'user_id' => $purchase->user_id,
|
||||
'guest_token' => null,
|
||||
]);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
private function restoreReservations(Cart $cart): void
|
||||
{
|
||||
$items = $cart->items()->orderBy('id')->lockForUpdate()->get();
|
||||
$items->load([
|
||||
'catalogItem.inventory',
|
||||
'catalogItem.bundleComponents.catalogItem.inventory',
|
||||
'catalogItem.bundleComponents.variant.inventory',
|
||||
'variant.inventory',
|
||||
'variant.catalogItem',
|
||||
]);
|
||||
|
||||
foreach ($items as $item) {
|
||||
$selection = $item->selectedItem();
|
||||
if ($selection !== null) {
|
||||
$this->reservations->restore($item, $selection);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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);
|
||||
@@ -192,30 +34,4 @@ class SourceCartService
|
||||
->lockForUpdate()
|
||||
->first();
|
||||
}
|
||||
|
||||
private function mergeIntoActiveCart(Cart $sourceCart, Cart $activeCart): void
|
||||
{
|
||||
$sourceItems = $sourceCart->items()->lockForUpdate()->get();
|
||||
|
||||
foreach ($sourceItems as $sourceItem) {
|
||||
/** @var CartItem|null $activeItem */
|
||||
$activeItem = $activeCart->items()
|
||||
->where('catalog_item_id', $sourceItem->catalog_item_id)
|
||||
->where('variant_id', $sourceItem->variant_id)
|
||||
->lockForUpdate()
|
||||
->first();
|
||||
|
||||
if ($activeItem === null) {
|
||||
$activeItem = $activeCart->items()->create([
|
||||
'catalog_item_id' => $sourceItem->catalog_item_id,
|
||||
'variant_id' => $sourceItem->variant_id,
|
||||
'cantidad' => $sourceItem->cantidad,
|
||||
]);
|
||||
} else {
|
||||
$activeItem->increment('cantidad', (int) $sourceItem->cantidad);
|
||||
}
|
||||
|
||||
$this->reservations->transfer($sourceItem, $activeItem);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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 */
|
||||
|
||||
@@ -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,11 +68,6 @@ class CheckoutService
|
||||
return $this->releaser->cancel($purchase);
|
||||
}
|
||||
|
||||
public function cancelPurchaseWithoutRestoringCart(Purchase $purchase): Purchase
|
||||
{
|
||||
return $this->releaser->cancelWithoutRestoringCart($purchase);
|
||||
}
|
||||
|
||||
public function expirePurchase(Purchase $purchase): Purchase
|
||||
{
|
||||
return $this->releaser->expire($purchase);
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -86,7 +86,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) {
|
||||
@@ -152,7 +154,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');
|
||||
|
||||
|
||||
@@ -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']);
|
||||
|
||||
@@ -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, '.', '');
|
||||
|
||||
@@ -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->cancelPurchase($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);
|
||||
|
||||
@@ -154,15 +148,9 @@ class AdminAppSaleService
|
||||
)
|
||||
->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 +187,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;
|
||||
|
||||
@@ -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' => [
|
||||
|
||||
@@ -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'],
|
||||
];
|
||||
|
||||
@@ -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.
|
||||
}
|
||||
};
|
||||
@@ -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');
|
||||
});
|
||||
}
|
||||
};
|
||||
@@ -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.',
|
||||
],
|
||||
|
||||
@@ -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.",
|
||||
],
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -13,10 +13,12 @@ use App\Domains\Catalog\Models\Inventory;
|
||||
use App\Domains\Catalog\Models\Variant;
|
||||
use App\Domains\Purchase\Models\Purchase;
|
||||
use App\Domains\Purchase\Services\CheckoutService;
|
||||
use App\Domains\Purchase\Services\UserPurchaseLimitService;
|
||||
use App\Domains\Tenant\Models\Tenant;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Illuminate\Support\Facades\Queue;
|
||||
use Illuminate\Support\Str;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
use Tests\TestCase;
|
||||
|
||||
class StorePurchaseTest extends TestCase
|
||||
@@ -30,7 +32,7 @@ class StorePurchaseTest extends TestCase
|
||||
Queue::fake();
|
||||
}
|
||||
|
||||
public function test_it_starts_checkout_from_cart_without_materializing_purchase_items(): void
|
||||
public function test_it_starts_checkout_from_cart_with_purchase_item_snapshots(): void
|
||||
{
|
||||
$tenant = $this->createTenant('sonder', 'Sonder', 'sonder.com.ar');
|
||||
$tenant->update([
|
||||
@@ -90,7 +92,7 @@ class StorePurchaseTest extends TestCase
|
||||
$response->assertJsonPath('data.email', null);
|
||||
$response->assertJsonPath('data.tenant_codigo', 'sonder');
|
||||
$response->assertJsonPath('data.status', Purchase::STATUS_CREATED);
|
||||
$response->assertJsonPath('data.items_source', 'cart');
|
||||
$response->assertJsonPath('data.items_source', 'purchase');
|
||||
$response->assertJsonCount(1, 'data.items');
|
||||
$response->assertJsonPath('data.subtotal', '100.00');
|
||||
$response->assertJsonPath('data.total', '100.00');
|
||||
@@ -109,7 +111,14 @@ class StorePurchaseTest extends TestCase
|
||||
'status' => Purchase::STATUS_CREATED,
|
||||
'total' => 100,
|
||||
]);
|
||||
$this->assertDatabaseMissing('compra_items', ['compra_id' => $purchaseId]);
|
||||
$this->assertDatabaseHas('compra_items', [
|
||||
'compra_id' => $purchaseId,
|
||||
'source_catalog_item_id' => $catalogItem->id,
|
||||
'source_variant_id' => $variant->id,
|
||||
'cantidad' => 2,
|
||||
'precio_unitario' => '50.00',
|
||||
'total' => '100.00',
|
||||
]);
|
||||
$this->assertDatabaseHas('stock_reservations', [
|
||||
'inventory_id' => $inventory->id,
|
||||
'purchase_id' => $purchaseId,
|
||||
@@ -119,7 +128,9 @@ class StorePurchaseTest extends TestCase
|
||||
$this->assertDatabaseHas('carritos', [
|
||||
'id' => $cartId,
|
||||
'user_id' => $user->id,
|
||||
'status' => 'checkout',
|
||||
'status' => 'active',
|
||||
'origin' => Cart::ORIGIN_USER,
|
||||
'current_purchase_id' => $purchaseId,
|
||||
'deleted_at' => null,
|
||||
]);
|
||||
$this->assertDatabaseHas('carrito_items', [
|
||||
@@ -134,6 +145,40 @@ class StorePurchaseTest extends TestCase
|
||||
'reserved_stock' => 2,
|
||||
]);
|
||||
|
||||
$this->actingAs($user, 'sanctum')
|
||||
->getJson('/api/tenants/sonder/cart')
|
||||
->assertOk()
|
||||
->assertJsonPath('data.id', $cartId)
|
||||
->assertJsonPath('data.status', 'active')
|
||||
->assertJsonCount(1, 'data.items')
|
||||
->assertJsonPath('data.items.0.cantidad', 2);
|
||||
|
||||
$replacementResponse = $this->actingAs($user, 'sanctum')
|
||||
->postJson('/api/tenants/sonder/compras/start-checkout', [
|
||||
'cart_id' => $cartId,
|
||||
])
|
||||
->assertCreated();
|
||||
$replacementPurchaseId = $replacementResponse->json('data.id');
|
||||
|
||||
$this->assertDatabaseHas('compras', [
|
||||
'id' => $purchaseId,
|
||||
'status' => Purchase::STATUS_SUPERSEDED,
|
||||
]);
|
||||
$this->assertDatabaseHas('carritos', [
|
||||
'id' => $cartId,
|
||||
'current_purchase_id' => $replacementPurchaseId,
|
||||
]);
|
||||
$this->assertDatabaseHas('stock_reservations', [
|
||||
'inventory_id' => $inventory->id,
|
||||
'purchase_id' => $replacementPurchaseId,
|
||||
'quantity' => 2,
|
||||
'status' => 'active',
|
||||
]);
|
||||
$this->assertDatabaseHas('inventories', [
|
||||
'id' => $inventory->id,
|
||||
'reserved_stock' => 2,
|
||||
]);
|
||||
|
||||
$catalogItem->update([
|
||||
'nombre' => 'Updated Product',
|
||||
'precio' => '75.00',
|
||||
@@ -142,10 +187,10 @@ class StorePurchaseTest extends TestCase
|
||||
$this->actingAs($user, 'sanctum')
|
||||
->getJson("/api/tenants/sonder/compras/{$purchaseId}")
|
||||
->assertOk()
|
||||
->assertJsonPath('data.items_source', 'cart')
|
||||
->assertJsonPath('data.items.0.item_details.nombre', 'Updated Product')
|
||||
->assertJsonPath('data.items.0.unit_price', '75.00')
|
||||
->assertJsonPath('data.total', '150.00');
|
||||
->assertJsonPath('data.items_source', 'purchase')
|
||||
->assertJsonPath('data.items.0.item_details.nombre', 'Test Product')
|
||||
->assertJsonPath('data.items.0.unit_price', '50.00')
|
||||
->assertJsonPath('data.total', '100.00');
|
||||
}
|
||||
|
||||
public function test_it_creates_a_direct_purchase_with_a_technical_checkout_cart(): void
|
||||
@@ -165,7 +210,7 @@ class StorePurchaseTest extends TestCase
|
||||
],
|
||||
])
|
||||
->assertCreated()
|
||||
->assertJsonPath('data.items_source', 'cart')
|
||||
->assertJsonPath('data.items_source', 'purchase')
|
||||
->assertJsonPath('data.items.0.quantity', 3)
|
||||
->assertJsonPath('data.total', '150.00');
|
||||
|
||||
@@ -173,9 +218,14 @@ class StorePurchaseTest extends TestCase
|
||||
'id' => $response->json('data.cart_id'),
|
||||
'status' => 'checkout',
|
||||
'origin' => Cart::ORIGIN_DIRECT_CHECKOUT,
|
||||
'current_purchase_id' => $response->json('data.id'),
|
||||
]);
|
||||
$this->assertDatabaseMissing('compra_items', [
|
||||
$this->assertDatabaseHas('compra_items', [
|
||||
'compra_id' => $response->json('data.id'),
|
||||
'source_variant_id' => $variant->id,
|
||||
'cantidad' => 3,
|
||||
'precio_unitario' => '50.00',
|
||||
'total' => '150.00',
|
||||
]);
|
||||
$this->assertDatabaseHas('stock_reservations', [
|
||||
'inventory_id' => $variant->inventory_id,
|
||||
@@ -233,7 +283,7 @@ class StorePurchaseTest extends TestCase
|
||||
],
|
||||
])
|
||||
->assertCreated()
|
||||
->assertJsonPath('data.items_source', 'cart')
|
||||
->assertJsonPath('data.items_source', 'purchase')
|
||||
->assertJsonCount(2, 'data.items')
|
||||
->assertJsonPath('data.items.0.source_variant_id', $firstVariant->id)
|
||||
->assertJsonPath('data.items.1.source_variant_id', $secondVariant->id)
|
||||
@@ -245,7 +295,7 @@ class StorePurchaseTest extends TestCase
|
||||
'id' => $response->json('data.cart_id'),
|
||||
'origin' => Cart::ORIGIN_DIRECT_CHECKOUT,
|
||||
]);
|
||||
$this->assertDatabaseMissing('compra_items', ['compra_id' => $purchaseId]);
|
||||
$this->assertDatabaseCount('compra_items', 2);
|
||||
$this->assertDatabaseHas('stock_reservations', [
|
||||
'inventory_id' => $firstVariant->inventory_id,
|
||||
'purchase_id' => $purchaseId,
|
||||
@@ -412,18 +462,27 @@ class StorePurchaseTest extends TestCase
|
||||
]);
|
||||
}
|
||||
|
||||
public function test_it_restores_the_source_cart_when_checkout_is_cancelled(): void
|
||||
public function test_it_keeps_the_source_cart_active_and_only_cancels_the_purchase(): void
|
||||
{
|
||||
$this->createTenant('sonder', 'Sonder', 'sonder.com.ar');
|
||||
$user = User::factory()->create();
|
||||
$variant = $this->createVariantForTenant('sonder', 10, '50.00');
|
||||
$purchase = $this->createCheckoutPurchase($user, 'sonder', $variant, 3);
|
||||
$activeCart = Cart::query()
|
||||
->where('user_id', $user->id)
|
||||
->where('status', 'active')
|
||||
->firstOrFail();
|
||||
$cartItemId = $purchase->cart->items()->firstOrFail()->id;
|
||||
|
||||
$this->assertDatabaseHas('carritos', [
|
||||
'id' => $purchase->cart_id,
|
||||
'status' => 'checkout',
|
||||
'status' => 'active',
|
||||
'origin' => Cart::ORIGIN_USER,
|
||||
'current_purchase_id' => $purchase->id,
|
||||
'deleted_at' => null,
|
||||
]);
|
||||
$this->assertDatabaseCount('carrito_items', 1);
|
||||
$this->assertSame(1, $activeCart->items()->count());
|
||||
|
||||
$this->actingAs($user, 'sanctum')
|
||||
->postJson("/api/tenants/sonder/compras/{$purchase->id}/cancel")
|
||||
@@ -431,29 +490,134 @@ class StorePurchaseTest extends TestCase
|
||||
->assertJsonPath('data.status', Purchase::STATUS_CANCELLED);
|
||||
|
||||
$this->assertDatabaseHas('carritos', [
|
||||
'id' => $purchase->cart_id,
|
||||
'id' => $activeCart->id,
|
||||
'user_id' => $user->id,
|
||||
'status' => 'active',
|
||||
'current_purchase_id' => null,
|
||||
'deleted_at' => null,
|
||||
]);
|
||||
$this->assertDatabaseHas('carrito_items', [
|
||||
'cart_id' => $purchase->cart_id,
|
||||
'catalog_item_id' => $variant->catalog_item_id,
|
||||
'variant_id' => $variant->id,
|
||||
'cantidad' => 3,
|
||||
]);
|
||||
$this->assertDatabaseHas('inventories', [
|
||||
'id' => $variant->inventory_id,
|
||||
'reserved_stock' => 3,
|
||||
]);
|
||||
$this->assertDatabaseHas('stock_reservations', [
|
||||
'cart_item_id' => $cartItemId,
|
||||
'purchase_id' => null,
|
||||
'quantity' => 3,
|
||||
'status' => 'active',
|
||||
]);
|
||||
$this->assertSame(1, $activeCart->items()->count());
|
||||
}
|
||||
|
||||
public function test_it_restores_and_reserves_the_source_cart_when_an_expired_checkout_is_modified(): void
|
||||
public function test_it_reassigns_a_terminal_purchase_reservation_and_rejects_a_late_confirmation(): void
|
||||
{
|
||||
$this->createTenant('sonder', 'Sonder', 'sonder.com.ar');
|
||||
$user = User::factory()->create();
|
||||
$variant = $this->createVariantForTenant('sonder', 10, '50.00');
|
||||
$previousPurchase = $this->createCheckoutPurchase($user, 'sonder', $variant, 2);
|
||||
$cart = $previousPurchase->cart;
|
||||
|
||||
$previousPurchase->update([
|
||||
'status' => Purchase::STATUS_PENDING_PAYMENT,
|
||||
'payment_method' => 'transfer',
|
||||
'expires_at' => now()->addMinutes(30),
|
||||
]);
|
||||
|
||||
$currentPurchase = app(CheckoutService::class)->startCheckout(
|
||||
$previousPurchase->tenant,
|
||||
$user->id,
|
||||
['cart_id' => $cart->id],
|
||||
);
|
||||
|
||||
$this->assertDatabaseHas('compras', [
|
||||
'id' => $previousPurchase->id,
|
||||
'status' => Purchase::STATUS_SUPERSEDED,
|
||||
'expires_at' => null,
|
||||
]);
|
||||
$this->assertDatabaseHas('carritos', [
|
||||
'id' => $cart->id,
|
||||
'current_purchase_id' => $currentPurchase->id,
|
||||
]);
|
||||
$this->assertDatabaseHas('stock_reservations', [
|
||||
'purchase_id' => $currentPurchase->id,
|
||||
'quantity' => 2,
|
||||
'status' => 'active',
|
||||
]);
|
||||
|
||||
try {
|
||||
app(CheckoutService::class)->confirmPaidPurchase($previousPurchase->fresh());
|
||||
$this->fail('A superseded purchase was allowed to commit the current reservation.');
|
||||
} catch (ValidationException $exception) {
|
||||
$this->assertArrayHasKey('purchase', $exception->errors());
|
||||
}
|
||||
|
||||
$this->assertDatabaseHas('inventories', [
|
||||
'id' => $variant->inventory_id,
|
||||
'reserved_stock' => 2,
|
||||
'sold_units' => 0,
|
||||
]);
|
||||
$this->assertDatabaseHas('stock_reservations', [
|
||||
'purchase_id' => $currentPurchase->id,
|
||||
'quantity' => 2,
|
||||
'status' => 'active',
|
||||
]);
|
||||
}
|
||||
|
||||
public function test_removing_a_checkout_item_supersedes_the_purchase_and_restores_the_user_quota(): void
|
||||
{
|
||||
$this->createTenant('sonder', 'Sonder', 'sonder.com.ar');
|
||||
$user = User::factory()->create();
|
||||
$variant = $this->createVariantForTenant('sonder', 10, '50.00');
|
||||
$variant->catalogItem->update(['max_units_per_user' => 3]);
|
||||
$purchase = $this->createCheckoutPurchase($user, 'sonder', $variant, 2);
|
||||
$cart = $purchase->cart;
|
||||
$cartItem = $cart->items()->firstOrFail();
|
||||
|
||||
$cart->removeItem($cartItem->id);
|
||||
|
||||
$this->assertDatabaseHas('compras', [
|
||||
'id' => $purchase->id,
|
||||
'status' => Purchase::STATUS_SUPERSEDED,
|
||||
]);
|
||||
$this->assertDatabaseHas('compra_items', [
|
||||
'compra_id' => $purchase->id,
|
||||
'source_catalog_item_id' => $variant->catalog_item_id,
|
||||
'cantidad' => 2,
|
||||
]);
|
||||
$this->assertDatabaseHas('carritos', [
|
||||
'id' => $cart->id,
|
||||
'current_purchase_id' => null,
|
||||
]);
|
||||
$this->assertDatabaseHas('stock_reservations', [
|
||||
'inventory_id' => $variant->inventory_id,
|
||||
'cart_item_id' => null,
|
||||
'purchase_id' => null,
|
||||
'quantity' => 0,
|
||||
'status' => 'released',
|
||||
]);
|
||||
$this->assertDatabaseHas('inventories', [
|
||||
'id' => $variant->inventory_id,
|
||||
'reserved_stock' => 0,
|
||||
]);
|
||||
|
||||
$remaining = app(UserPurchaseLimitService::class)
|
||||
->remainingByCatalogItem(collect([$variant->catalogItem->fresh()]), $user->id)
|
||||
->get($variant->catalog_item_id);
|
||||
|
||||
$this->assertSame(3, $remaining);
|
||||
}
|
||||
|
||||
public function test_it_expires_the_purchase_without_mutating_the_active_cart(): void
|
||||
{
|
||||
$this->createTenant('sonder', 'Sonder', 'sonder.com.ar');
|
||||
$user = User::factory()->create();
|
||||
$variant = $this->createVariantForTenant('sonder', 10, '50.00');
|
||||
$purchase = $this->createCheckoutPurchase($user, 'sonder', $variant, 3);
|
||||
$activeCart = Cart::query()
|
||||
->where('user_id', $user->id)
|
||||
->where('status', 'active')
|
||||
->firstOrFail();
|
||||
$cartItemId = $purchase->cart->items()->firstOrFail()->id;
|
||||
$purchase->update(['expires_at' => now()->subMinute()]);
|
||||
|
||||
$this->artisan('reservations:expire')->assertSuccessful();
|
||||
@@ -462,66 +626,24 @@ class StorePurchaseTest extends TestCase
|
||||
'id' => $purchase->id,
|
||||
'status' => Purchase::STATUS_EXPIRED,
|
||||
]);
|
||||
$this->assertDatabaseHas('inventories', [
|
||||
'id' => $variant->inventory_id,
|
||||
'reserved_stock' => 0,
|
||||
]);
|
||||
|
||||
$this->actingAs($user, 'sanctum')
|
||||
->postJson("/api/tenants/sonder/compras/{$purchase->id}/cancel")
|
||||
->assertOk()
|
||||
->assertJsonPath('data.status', Purchase::STATUS_CANCELLED);
|
||||
|
||||
$this->assertDatabaseHas('carritos', [
|
||||
'id' => $purchase->cart_id,
|
||||
'user_id' => $user->id,
|
||||
'status' => 'active',
|
||||
'deleted_at' => null,
|
||||
]);
|
||||
$this->assertDatabaseHas('inventories', [
|
||||
'id' => $variant->inventory_id,
|
||||
'reserved_stock' => 3,
|
||||
]);
|
||||
}
|
||||
|
||||
public function test_it_merges_the_checkout_cart_when_the_user_created_another_active_cart(): void
|
||||
{
|
||||
$this->createTenant('sonder', 'Sonder', 'sonder.com.ar');
|
||||
$user = User::factory()->create();
|
||||
$variant = $this->createVariantForTenant('sonder', 10, '50.00');
|
||||
$purchase = $this->createCheckoutPurchase($user, 'sonder', $variant, 2);
|
||||
|
||||
$activeCartId = $this->actingAs($user, 'sanctum')
|
||||
->postJson('/api/tenants/sonder/cart/items', [
|
||||
'catalog_item_id' => $variant->catalog_item_id,
|
||||
'variant_id' => $variant->id,
|
||||
'cantidad' => 1,
|
||||
])
|
||||
->assertOk()
|
||||
->json('data.id');
|
||||
|
||||
$this->assertNotSame($purchase->cart_id, $activeCartId);
|
||||
|
||||
$this->actingAs($user, 'sanctum')
|
||||
->postJson("/api/tenants/sonder/compras/{$purchase->id}/cancel")
|
||||
->assertOk();
|
||||
|
||||
$this->assertDatabaseHas('carritos', [
|
||||
'id' => $activeCartId,
|
||||
'id' => $activeCart->id,
|
||||
'user_id' => $user->id,
|
||||
'status' => 'active',
|
||||
'current_purchase_id' => null,
|
||||
'deleted_at' => null,
|
||||
]);
|
||||
$this->assertDatabaseHas('carrito_items', [
|
||||
'cart_id' => $activeCartId,
|
||||
'catalog_item_id' => $variant->catalog_item_id,
|
||||
'variant_id' => $variant->id,
|
||||
'cantidad' => 3,
|
||||
]);
|
||||
$this->assertDatabaseHas('inventories', [
|
||||
'id' => $variant->inventory_id,
|
||||
'reserved_stock' => 3,
|
||||
$this->assertDatabaseHas('stock_reservations', [
|
||||
'cart_item_id' => $cartItemId,
|
||||
'purchase_id' => null,
|
||||
'quantity' => 3,
|
||||
'status' => 'active',
|
||||
]);
|
||||
$this->assertSame(1, $activeCart->items()->count());
|
||||
}
|
||||
|
||||
public function test_it_keeps_cart_items_during_checkout_and_updates_customer_data(): void
|
||||
@@ -541,7 +663,7 @@ class StorePurchaseTest extends TestCase
|
||||
],
|
||||
])
|
||||
->assertCreated()
|
||||
->assertJsonPath('data.items_source', 'cart')
|
||||
->assertJsonPath('data.items_source', 'purchase')
|
||||
->assertJsonCount(1, 'data.items')
|
||||
->assertJsonPath('data.items.0.quantity', 2)
|
||||
->assertJsonPath('data.dni', null)
|
||||
@@ -599,373 +721,40 @@ class StorePurchaseTest extends TestCase
|
||||
]);
|
||||
}
|
||||
|
||||
public function test_it_updates_a_checkout_cart_item_quantity_and_its_stock_reservation(): void
|
||||
{
|
||||
$tenant = $this->createTenant('sonder', 'Sonder', 'sonder.com.ar');
|
||||
$tenant->update(['checkout_editing_policy' => 'full']);
|
||||
$user = User::factory()->create();
|
||||
$variant = $this->createVariantForTenant('sonder', 10, '50.00');
|
||||
$purchase = $this->createCheckoutPurchase($user, 'sonder', $variant, 2);
|
||||
$itemId = $purchase->cart->items->firstOrFail()->id;
|
||||
|
||||
$this->actingAs($user, 'sanctum')
|
||||
->patchJson("/api/tenants/sonder/checkout-carts/{$purchase->cart_id}/items/{$itemId}", [
|
||||
'cantidad' => 4,
|
||||
])
|
||||
->assertOk()
|
||||
->assertJsonPath('data.items.0.cantidad', 4)
|
||||
->assertJsonPath('data.subtotal', '200.00');
|
||||
|
||||
$this->assertDatabaseHas('inventories', [
|
||||
'id' => $variant->inventory_id,
|
||||
'reserved_stock' => 4,
|
||||
]);
|
||||
$this->assertDatabaseHas('carrito_items', [
|
||||
'cart_id' => $purchase->cart_id,
|
||||
'catalog_item_id' => $variant->catalog_item_id,
|
||||
'variant_id' => $variant->id,
|
||||
'cantidad' => 4,
|
||||
]);
|
||||
|
||||
$this->actingAs($user, 'sanctum')
|
||||
->patchJson("/api/tenants/sonder/checkout-carts/{$purchase->cart_id}/items/{$itemId}", [
|
||||
'cantidad' => 1,
|
||||
])
|
||||
->assertOk()
|
||||
->assertJsonPath('data.items.0.cantidad', 1)
|
||||
->assertJsonPath('data.subtotal', '50.00');
|
||||
|
||||
$this->assertDatabaseHas('compras', [
|
||||
'id' => $purchase->id,
|
||||
'total' => '50.00',
|
||||
]);
|
||||
|
||||
$this->assertDatabaseHas('inventories', [
|
||||
'id' => $variant->inventory_id,
|
||||
'reserved_stock' => 1,
|
||||
]);
|
||||
}
|
||||
|
||||
public function test_checkout_cart_editing_uses_checkout_policy_independently_from_cart_policy(): void
|
||||
{
|
||||
$tenant = $this->createTenant('sonder', 'Sonder', 'sonder.com.ar');
|
||||
$tenant->update([
|
||||
'cart_editing_policy' => 'full',
|
||||
'checkout_editing_policy' => 'disabled',
|
||||
]);
|
||||
$user = User::factory()->create();
|
||||
$variant = $this->createVariantForTenant('sonder', 10, '50.00');
|
||||
$purchase = $this->createCheckoutPurchase($user, 'sonder', $variant, 2);
|
||||
$itemId = $purchase->cart->items->firstOrFail()->id;
|
||||
|
||||
$this->actingAs($user, 'sanctum')
|
||||
->patchJson("/api/tenants/sonder/checkout-carts/{$purchase->cart_id}/items/{$itemId}", [
|
||||
'cantidad' => 4,
|
||||
])
|
||||
->assertUnprocessable()
|
||||
->assertJsonValidationErrors('cantidad');
|
||||
|
||||
$this->assertDatabaseHas('carrito_items', [
|
||||
'id' => $itemId,
|
||||
'cantidad' => 2,
|
||||
]);
|
||||
}
|
||||
|
||||
public function test_it_removes_an_item_from_the_checkout_cart_when_the_policy_allows_it(): void
|
||||
{
|
||||
$tenant = $this->createTenant('sonder', 'Sonder', 'sonder.com.ar');
|
||||
$tenant->update(['checkout_editing_policy' => 'quantity_and_remove']);
|
||||
$user = User::factory()->create();
|
||||
$variant = $this->createVariantForTenant('sonder', 10, '50.00');
|
||||
$purchase = $this->createCheckoutPurchase($user, 'sonder', $variant, 2);
|
||||
$itemId = $purchase->cart->items->firstOrFail()->id;
|
||||
|
||||
$this->actingAs($user, 'sanctum')
|
||||
->deleteJson("/api/tenants/sonder/checkout-carts/{$purchase->cart_id}/items/{$itemId}")
|
||||
->assertOk()
|
||||
->assertJsonPath('data.items', [])
|
||||
->assertJsonPath('data.subtotal', '0.00');
|
||||
|
||||
$this->assertDatabaseMissing('carrito_items', ['id' => $itemId]);
|
||||
$this->assertDatabaseHas('compras', [
|
||||
'id' => $purchase->id,
|
||||
'total' => '0.00',
|
||||
]);
|
||||
$this->assertDatabaseHas('inventories', [
|
||||
'id' => $variant->inventory_id,
|
||||
'reserved_stock' => 0,
|
||||
]);
|
||||
}
|
||||
|
||||
public function test_it_changes_a_checkout_item_variant_and_moves_its_reservation(): void
|
||||
{
|
||||
$tenant = $this->createTenant('sonder', 'Sonder', 'sonder.com.ar');
|
||||
$tenant->update(['checkout_editing_policy' => 'full']);
|
||||
$user = User::factory()->create();
|
||||
$firstVariant = $this->createVariantForTenant('sonder', 10, '50.00');
|
||||
$secondInventory = Inventory::query()->create(['real_stock' => 10]);
|
||||
$secondVariant = $firstVariant->catalogItem->variants()->create([
|
||||
'inventory_id' => $secondInventory->id,
|
||||
'precio' => '70.00',
|
||||
]);
|
||||
$purchase = $this->createCheckoutPurchase($user, 'sonder', $firstVariant, 2);
|
||||
$itemId = $purchase->items->firstOrFail()->id;
|
||||
|
||||
$this->actingAs($user, 'sanctum')
|
||||
->patchJson("/api/tenants/sonder/compras/{$purchase->id}/items/{$itemId}", [
|
||||
'variant_id' => $secondVariant->id,
|
||||
])
|
||||
->assertOk()
|
||||
->assertJsonPath('data.items.0.source_variant_id', $secondVariant->id)
|
||||
->assertJsonPath('data.items.0.quantity', 2)
|
||||
->assertJsonPath('data.items.0.unit_price', '70.00')
|
||||
->assertJsonPath('data.items.0.line_total', '140.00')
|
||||
->assertJsonPath('data.total', '140.00')
|
||||
->assertJsonPath('data.items.0.variants.0.id', $firstVariant->id)
|
||||
->assertJsonPath('data.items.0.variants.1.id', $secondVariant->id);
|
||||
|
||||
$this->assertDatabaseHas('inventories', [
|
||||
'id' => $firstVariant->inventory_id,
|
||||
'reserved_stock' => 0,
|
||||
]);
|
||||
$this->assertDatabaseHas('inventories', [
|
||||
'id' => $secondInventory->id,
|
||||
'reserved_stock' => 2,
|
||||
]);
|
||||
$this->assertDatabaseHas('carrito_items', [
|
||||
'cart_id' => $purchase->cart_id,
|
||||
'catalog_item_id' => $firstVariant->catalog_item_id,
|
||||
'variant_id' => $secondVariant->id,
|
||||
'cantidad' => 2,
|
||||
]);
|
||||
$this->assertDatabaseMissing('carrito_items', [
|
||||
'cart_id' => $purchase->cart_id,
|
||||
'variant_id' => $firstVariant->id,
|
||||
]);
|
||||
}
|
||||
|
||||
public function test_it_rejects_checkout_variant_changes_when_the_policy_does_not_allow_them(): void
|
||||
{
|
||||
$tenant = $this->createTenant('sonder', 'Sonder', 'sonder.com.ar');
|
||||
$tenant->update(['checkout_editing_policy' => 'quantity_and_remove']);
|
||||
$user = User::factory()->create();
|
||||
$firstVariant = $this->createVariantForTenant('sonder', 10, '50.00');
|
||||
$secondInventory = Inventory::query()->create(['real_stock' => 10]);
|
||||
$secondVariant = $firstVariant->catalogItem->variants()->create([
|
||||
'inventory_id' => $secondInventory->id,
|
||||
]);
|
||||
$purchase = $this->createCheckoutPurchase($user, 'sonder', $firstVariant, 2);
|
||||
$itemId = $purchase->items->firstOrFail()->id;
|
||||
|
||||
$this->actingAs($user, 'sanctum')
|
||||
->patchJson("/api/tenants/sonder/compras/{$purchase->id}/items/{$itemId}", [
|
||||
'variant_id' => $secondVariant->id,
|
||||
])
|
||||
->assertUnprocessable()
|
||||
->assertJsonValidationErrors('variant_id');
|
||||
|
||||
$this->assertDatabaseHas('compra_items', [
|
||||
'id' => $itemId,
|
||||
'source_variant_id' => $firstVariant->id,
|
||||
'cantidad' => 2,
|
||||
]);
|
||||
$this->assertDatabaseHas('inventories', [
|
||||
'id' => $firstVariant->inventory_id,
|
||||
'reserved_stock' => 2,
|
||||
]);
|
||||
$this->assertDatabaseHas('inventories', [
|
||||
'id' => $secondInventory->id,
|
||||
'reserved_stock' => 0,
|
||||
]);
|
||||
}
|
||||
|
||||
public function test_checkout_variant_change_rolls_back_when_the_target_has_insufficient_stock(): void
|
||||
{
|
||||
$tenant = $this->createTenant('sonder', 'Sonder', 'sonder.com.ar');
|
||||
$tenant->update(['checkout_editing_policy' => 'full']);
|
||||
$user = User::factory()->create();
|
||||
$firstVariant = $this->createVariantForTenant('sonder', 10, '50.00');
|
||||
$secondInventory = Inventory::query()->create(['real_stock' => 1]);
|
||||
$secondVariant = $firstVariant->catalogItem->variants()->create([
|
||||
'inventory_id' => $secondInventory->id,
|
||||
'precio' => '70.00',
|
||||
]);
|
||||
$purchase = $this->createCheckoutPurchase($user, 'sonder', $firstVariant, 2);
|
||||
$itemId = $purchase->items->firstOrFail()->id;
|
||||
|
||||
$this->actingAs($user, 'sanctum')
|
||||
->patchJson("/api/tenants/sonder/compras/{$purchase->id}/items/{$itemId}", [
|
||||
'variant_id' => $secondVariant->id,
|
||||
])
|
||||
->assertUnprocessable()
|
||||
->assertJsonValidationErrors('variant_id');
|
||||
|
||||
$this->assertDatabaseHas('compra_items', [
|
||||
'id' => $itemId,
|
||||
'source_variant_id' => $firstVariant->id,
|
||||
'cantidad' => 2,
|
||||
'precio_unitario' => '50.00',
|
||||
]);
|
||||
$this->assertDatabaseHas('inventories', [
|
||||
'id' => $firstVariant->inventory_id,
|
||||
'reserved_stock' => 2,
|
||||
]);
|
||||
$this->assertDatabaseHas('inventories', [
|
||||
'id' => $secondInventory->id,
|
||||
'reserved_stock' => 0,
|
||||
]);
|
||||
$this->assertDatabaseHas('carrito_items', [
|
||||
'cart_id' => $purchase->cart_id,
|
||||
'variant_id' => $firstVariant->id,
|
||||
'cantidad' => 2,
|
||||
]);
|
||||
}
|
||||
|
||||
public function test_changing_to_an_existing_checkout_variant_merges_purchase_and_cart_rows(): void
|
||||
{
|
||||
$tenant = $this->createTenant('sonder', 'Sonder', 'sonder.com.ar');
|
||||
$tenant->update(['checkout_editing_policy' => 'full']);
|
||||
$user = User::factory()->create();
|
||||
$firstVariant = $this->createVariantForTenant('sonder', 10, '50.00');
|
||||
$secondInventory = Inventory::query()->create(['real_stock' => 10]);
|
||||
$secondVariant = $firstVariant->catalogItem->variants()->create([
|
||||
'inventory_id' => $secondInventory->id,
|
||||
'precio' => '70.00',
|
||||
]);
|
||||
$cart = Cart::query()->create([
|
||||
'tenant_codigo' => 'sonder',
|
||||
'user_id' => $user->id,
|
||||
'status' => 'active',
|
||||
]);
|
||||
$cart->addItem($firstVariant->catalog_item_id, $firstVariant->id, 2);
|
||||
$cart->addItem($secondVariant->catalog_item_id, $secondVariant->id, 3);
|
||||
$purchase = app(CheckoutService::class)->startCheckout($tenant, $user->id, [
|
||||
'cart_id' => $cart->id,
|
||||
]);
|
||||
$sourceItem = $purchase->items->firstWhere('source_variant_id', $firstVariant->id);
|
||||
$this->assertNotNull($sourceItem);
|
||||
|
||||
$this->actingAs($user, 'sanctum')
|
||||
->patchJson("/api/tenants/sonder/compras/{$purchase->id}/items/{$sourceItem->id}", [
|
||||
'variant_id' => $secondVariant->id,
|
||||
])
|
||||
->assertOk()
|
||||
->assertJsonCount(1, 'data.items')
|
||||
->assertJsonPath('data.items.0.source_variant_id', $secondVariant->id)
|
||||
->assertJsonPath('data.items.0.quantity', 5)
|
||||
->assertJsonPath('data.items.0.line_total', '350.00')
|
||||
->assertJsonPath('data.total', '350.00');
|
||||
|
||||
$this->assertDatabaseCount('compra_items', 1);
|
||||
$this->assertDatabaseHas('inventories', [
|
||||
'id' => $firstVariant->inventory_id,
|
||||
'reserved_stock' => 0,
|
||||
]);
|
||||
$this->assertDatabaseHas('inventories', [
|
||||
'id' => $secondInventory->id,
|
||||
'reserved_stock' => 5,
|
||||
]);
|
||||
$this->assertDatabaseCount('carrito_items', 1);
|
||||
$this->assertDatabaseHas('carrito_items', [
|
||||
'cart_id' => $cart->id,
|
||||
'variant_id' => $secondVariant->id,
|
||||
'cantidad' => 5,
|
||||
]);
|
||||
}
|
||||
|
||||
public function test_it_rejects_a_quantity_update_above_the_user_purchase_limit(): void
|
||||
{
|
||||
$tenant = $this->createTenant('sonder', 'Sonder', 'sonder.com.ar');
|
||||
$tenant->update(['checkout_editing_policy' => 'full']);
|
||||
$user = User::factory()->create();
|
||||
$variant = $this->createVariantForTenant('sonder', 10, '50.00');
|
||||
$variant->catalogItem->update(['max_units_per_user' => 3]);
|
||||
$purchase = $this->createCheckoutPurchase($user, 'sonder', $variant, 2);
|
||||
$itemId = $purchase->cart->items->firstOrFail()->id;
|
||||
|
||||
$this->actingAs($user, 'sanctum')
|
||||
->patchJson("/api/tenants/sonder/checkout-carts/{$purchase->cart_id}/items/{$itemId}", [
|
||||
'cantidad' => 4,
|
||||
])
|
||||
->assertUnprocessable()
|
||||
->assertJsonValidationErrors('cantidad');
|
||||
|
||||
$this->assertDatabaseHas('carrito_items', [
|
||||
'id' => $itemId,
|
||||
'cantidad' => 2,
|
||||
]);
|
||||
$this->assertDatabaseHas('inventories', [
|
||||
'id' => $variant->inventory_id,
|
||||
'reserved_stock' => 2,
|
||||
]);
|
||||
}
|
||||
|
||||
public function test_it_invalidates_a_pending_payment_when_the_checkout_cart_changes(): void
|
||||
{
|
||||
$tenant = $this->createTenant('sonder', 'Sonder', 'sonder.com.ar');
|
||||
$tenant->update(['checkout_editing_policy' => 'full']);
|
||||
$user = User::factory()->create();
|
||||
$variant = $this->createVariantForTenant('sonder', 10, '50.00');
|
||||
$purchase = $this->createCheckoutPurchase($user, 'sonder', $variant, 2);
|
||||
$purchase->update([
|
||||
'status' => Purchase::STATUS_PENDING_PAYMENT,
|
||||
'payment_method' => 'qr',
|
||||
]);
|
||||
$purchase->telepagosQr()->create([
|
||||
'qr_order_id' => 'stale-order',
|
||||
'qr_code' => 'stale-qr',
|
||||
]);
|
||||
$itemId = $purchase->cart->items->firstOrFail()->id;
|
||||
|
||||
$this->actingAs($user, 'sanctum')
|
||||
->patchJson("/api/tenants/sonder/checkout-carts/{$purchase->cart_id}/items/{$itemId}", [
|
||||
'cantidad' => 3,
|
||||
])
|
||||
->assertOk()
|
||||
->assertJsonPath('data.items.0.cantidad', 3);
|
||||
|
||||
$this->assertDatabaseHas('compras', [
|
||||
'id' => $purchase->id,
|
||||
'status' => Purchase::STATUS_CREATED,
|
||||
'payment_method' => null,
|
||||
'total' => '150.00',
|
||||
]);
|
||||
$this->assertDatabaseMissing('telepagos_qr', [
|
||||
'compra_id' => $purchase->id,
|
||||
'qr_order_id' => 'stale-order',
|
||||
]);
|
||||
}
|
||||
|
||||
public function test_a_no_op_checkout_cart_update_keeps_the_pending_payment_intact(): void
|
||||
public function test_checkout_items_are_immutable_and_editing_routes_are_unavailable(): void
|
||||
{
|
||||
$this->createTenant('sonder', 'Sonder', 'sonder.com.ar');
|
||||
$user = User::factory()->create();
|
||||
$variant = $this->createVariantForTenant('sonder', 10, '50.00');
|
||||
$purchase = $this->createCheckoutPurchase($user, 'sonder', $variant, 2);
|
||||
$purchase->update([
|
||||
'status' => Purchase::STATUS_PENDING_PAYMENT,
|
||||
'payment_method' => 'qr',
|
||||
]);
|
||||
$purchase->telepagosQr()->create([
|
||||
'qr_order_id' => 'current-order',
|
||||
'qr_code' => 'current-qr',
|
||||
]);
|
||||
$itemId = $purchase->cart->items->firstOrFail()->id;
|
||||
$cartItemId = $purchase->cart->items->firstOrFail()->id;
|
||||
$purchaseItemId = $purchase->items->firstOrFail()->id;
|
||||
|
||||
$this->actingAs($user, 'sanctum')
|
||||
->patchJson("/api/tenants/sonder/checkout-carts/{$purchase->cart_id}/items/{$itemId}", [
|
||||
'cantidad' => 2,
|
||||
->patchJson("/api/tenants/sonder/checkout-carts/{$purchase->cart_id}/items/{$cartItemId}", [
|
||||
'cantidad' => 3,
|
||||
])
|
||||
->assertOk();
|
||||
->assertNotFound();
|
||||
|
||||
$this->assertDatabaseHas('compras', [
|
||||
'id' => $purchase->id,
|
||||
'status' => Purchase::STATUS_PENDING_PAYMENT,
|
||||
'payment_method' => 'qr',
|
||||
$this->patchJson("/api/tenants/sonder/compras/{$purchase->id}/items/{$purchaseItemId}", [
|
||||
'quantity' => 3,
|
||||
])->assertNotFound();
|
||||
|
||||
$this->deleteJson("/api/tenants/sonder/compras/{$purchase->id}/items/{$purchaseItemId}")
|
||||
->assertNotFound();
|
||||
|
||||
$this->postJson("/api/tenants/sonder/compras/{$purchase->id}/edit-items")
|
||||
->assertNotFound();
|
||||
|
||||
$this->assertDatabaseHas('compra_items', [
|
||||
'id' => $purchaseItemId,
|
||||
'cantidad' => 2,
|
||||
'precio_unitario' => '50.00',
|
||||
'total' => '100.00',
|
||||
]);
|
||||
$this->assertDatabaseHas('telepagos_qr', [
|
||||
'compra_id' => $purchase->id,
|
||||
'qr_order_id' => 'current-order',
|
||||
$this->assertDatabaseHas('inventories', [
|
||||
'id' => $variant->inventory_id,
|
||||
'reserved_stock' => 2,
|
||||
]);
|
||||
}
|
||||
|
||||
@@ -1105,12 +894,16 @@ class StorePurchaseTest extends TestCase
|
||||
]);
|
||||
}
|
||||
|
||||
public function test_it_expires_an_abandoned_purchase_and_releases_its_checkout_cart(): void
|
||||
public function test_it_expires_an_abandoned_purchase_without_mutating_its_active_cart(): void
|
||||
{
|
||||
$this->createTenant('sonder', 'Sonder', 'sonder.com.ar');
|
||||
$user = User::factory()->create();
|
||||
$variant = $this->createVariantForTenant('sonder', 10, '50.00');
|
||||
$purchase = $this->createCheckoutPurchase($user, 'sonder', $variant, 3);
|
||||
$activeCart = Cart::query()
|
||||
->where('user_id', $user->id)
|
||||
->where('status', 'active')
|
||||
->firstOrFail();
|
||||
|
||||
$this->assertNotNull($purchase->expires_at);
|
||||
$this->assertDatabaseHas('inventories', [
|
||||
@@ -1129,23 +922,28 @@ class StorePurchaseTest extends TestCase
|
||||
'id' => $purchase->id,
|
||||
'status' => Purchase::STATUS_EXPIRED,
|
||||
]);
|
||||
$this->assertDatabaseMissing('compra_items', ['compra_id' => $purchase->id]);
|
||||
$this->assertDatabaseHas('compra_items', [
|
||||
'compra_id' => $purchase->id,
|
||||
'cantidad' => 3,
|
||||
]);
|
||||
$this->assertDatabaseHas('stock_reservations', [
|
||||
'purchase_id' => $purchase->id,
|
||||
'quantity' => 0,
|
||||
'status' => 'expired',
|
||||
'purchase_id' => null,
|
||||
'quantity' => 3,
|
||||
'status' => 'active',
|
||||
]);
|
||||
$this->assertDatabaseHas('inventories', [
|
||||
'id' => $variant->inventory_id,
|
||||
'real_stock' => 10,
|
||||
'reserved_stock' => 0,
|
||||
'reserved_stock' => 3,
|
||||
'sold_units' => 0,
|
||||
]);
|
||||
$this->assertSoftDeleted('carritos', [
|
||||
'id' => $purchase->cart_id,
|
||||
$this->assertDatabaseHas('carritos', [
|
||||
'id' => $activeCart->id,
|
||||
'user_id' => $user->id,
|
||||
'status' => 'converted',
|
||||
'status' => 'active',
|
||||
'deleted_at' => null,
|
||||
]);
|
||||
$this->assertSame(1, $activeCart->items()->count());
|
||||
|
||||
$this->artisan('reservations:expire')
|
||||
->expectsOutput('Expired purchases: 0')
|
||||
@@ -1153,13 +951,14 @@ class StorePurchaseTest extends TestCase
|
||||
->assertSuccessful();
|
||||
}
|
||||
|
||||
public function test_it_continues_expiring_purchases_after_an_inconsistent_reservation(): void
|
||||
public function test_it_expires_multiple_purchases_that_already_have_item_snapshots(): void
|
||||
{
|
||||
$this->createTenant('sonder', 'Sonder', 'sonder.com.ar');
|
||||
$user = User::factory()->create();
|
||||
$secondUser = User::factory()->create();
|
||||
$variant = $this->createVariantForTenant('sonder', 10, '50.00');
|
||||
$inconsistentPurchase = $this->createCheckoutPurchase($user, 'sonder', $variant, 1);
|
||||
$validPurchase = $this->createCheckoutPurchase($user, 'sonder', $variant, 1);
|
||||
$validPurchase = $this->createCheckoutPurchase($secondUser, 'sonder', $variant, 1);
|
||||
|
||||
$inconsistentPurchase->items()->create([
|
||||
'source_catalog_item_id' => $variant->catalog_item_id,
|
||||
@@ -1176,13 +975,13 @@ class StorePurchaseTest extends TestCase
|
||||
$this->travel(31)->minutes();
|
||||
|
||||
$this->artisan('reservations:expire')
|
||||
->expectsOutput('Expired purchases: 1')
|
||||
->expectsOutput('Expired purchases: 2')
|
||||
->expectsOutput('Expired cart items: 0')
|
||||
->assertSuccessful();
|
||||
|
||||
$this->assertDatabaseHas('compras', [
|
||||
'id' => $inconsistentPurchase->id,
|
||||
'status' => Purchase::STATUS_CREATED,
|
||||
'status' => Purchase::STATUS_EXPIRED,
|
||||
]);
|
||||
$this->assertDatabaseHas('compras', [
|
||||
'id' => $validPurchase->id,
|
||||
@@ -1190,7 +989,7 @@ class StorePurchaseTest extends TestCase
|
||||
]);
|
||||
}
|
||||
|
||||
public function test_purchase_detail_uses_cart_items_for_created_purchase(): void
|
||||
public function test_purchase_detail_uses_purchase_item_snapshot_for_created_purchase(): void
|
||||
{
|
||||
$this->createTenant('sonder', 'Sonder', 'sonder.com.ar');
|
||||
$user = User::factory()->create([
|
||||
@@ -1203,7 +1002,7 @@ class StorePurchaseTest extends TestCase
|
||||
->getJson("/api/tenants/sonder/compras/{$purchase->id}")
|
||||
->assertOk()
|
||||
->assertJsonPath('data.status', Purchase::STATUS_CREATED)
|
||||
->assertJsonPath('data.items_source', 'cart')
|
||||
->assertJsonPath('data.items_source', 'purchase')
|
||||
->assertJsonCount(1, 'data.items')
|
||||
->assertJsonPath('data.items.0.quantity', 2)
|
||||
->assertJsonPath('data.items.0.unit_price', '50.00')
|
||||
@@ -1242,7 +1041,7 @@ class StorePurchaseTest extends TestCase
|
||||
->assertJsonPath('data.items.0.item_details.imagen', null);
|
||||
}
|
||||
|
||||
public function test_purchase_detail_uses_cart_items_for_pending_payment_purchase(): void
|
||||
public function test_purchase_detail_uses_purchase_item_snapshot_for_pending_payment_purchase(): void
|
||||
{
|
||||
$this->createTenant('sonder', 'Sonder', 'sonder.com.ar');
|
||||
$user = User::factory()->create([
|
||||
@@ -1261,7 +1060,7 @@ class StorePurchaseTest extends TestCase
|
||||
->getJson("/api/tenants/sonder/compras/{$purchase->id}")
|
||||
->assertOk()
|
||||
->assertJsonPath('data.status', Purchase::STATUS_PENDING_PAYMENT)
|
||||
->assertJsonPath('data.items_source', 'cart')
|
||||
->assertJsonPath('data.items_source', 'purchase')
|
||||
->assertJsonCount(1, 'data.items')
|
||||
->assertJsonPath('data.items.0.quantity', 2)
|
||||
->assertJsonPath('data.items.0.unit_price', '50.00')
|
||||
@@ -1272,27 +1071,14 @@ class StorePurchaseTest extends TestCase
|
||||
->assertJsonPath('data.total', '100.00');
|
||||
}
|
||||
|
||||
public function test_created_and_pending_payment_purchase_details_use_the_current_cart_quantity(): void
|
||||
public function test_created_and_pending_payment_purchase_details_ignore_later_cart_changes(): void
|
||||
{
|
||||
$this->createTenant('sonder', 'Sonder', 'sonder.com.ar');
|
||||
$user = User::factory()->create([
|
||||
'email' => 'buyer@example.com',
|
||||
]);
|
||||
$variant = $this->createVariantForTenant('sonder', 10, '50.00');
|
||||
|
||||
foreach ([Purchase::STATUS_CREATED, Purchase::STATUS_PENDING_PAYMENT] as $status) {
|
||||
$user = User::factory()->create();
|
||||
$purchase = $this->createCheckoutPurchase($user, 'sonder', $variant, 2);
|
||||
$purchase->items()->create([
|
||||
'source_catalog_item_id' => $variant->catalog_item_id,
|
||||
'source_variant_id' => $variant->id,
|
||||
'item_nombre' => $variant->catalogItem->nombre,
|
||||
'descripcion' => $variant->catalogItem->descripcion,
|
||||
'slug' => $variant->catalogItem->slug,
|
||||
'variant_attributes' => [],
|
||||
'cantidad' => 1,
|
||||
'precio_unitario' => '50.00',
|
||||
'total' => '50.00',
|
||||
]);
|
||||
$purchase->cart->items()->update(['cantidad' => 3]);
|
||||
$purchase->update(['status' => $status]);
|
||||
|
||||
@@ -1300,11 +1086,11 @@ class StorePurchaseTest extends TestCase
|
||||
->getJson("/api/tenants/sonder/compras/{$purchase->id}")
|
||||
->assertOk()
|
||||
->assertJsonPath('data.status', $status)
|
||||
->assertJsonPath('data.items_source', 'cart')
|
||||
->assertJsonPath('data.items.0.quantity', 3)
|
||||
->assertJsonPath('data.items.0.line_total', '150.00')
|
||||
->assertJsonPath('data.subtotal', '150.00')
|
||||
->assertJsonPath('data.total', '150.00');
|
||||
->assertJsonPath('data.items_source', 'purchase')
|
||||
->assertJsonPath('data.items.0.quantity', 2)
|
||||
->assertJsonPath('data.items.0.line_total', '100.00')
|
||||
->assertJsonPath('data.subtotal', '100.00')
|
||||
->assertJsonPath('data.total', '100.00');
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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
|
||||
@@ -149,7 +178,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 +205,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 +224,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 +251,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 +263,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 +370,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 +440,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()
|
||||
|
||||
@@ -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');
|
||||
|
||||
@@ -20,6 +20,7 @@ class SaleFormServiceTest extends TestCase
|
||||
'Cancelada',
|
||||
'Rechazada',
|
||||
'Vencida',
|
||||
'Reemplazada',
|
||||
], array_column($form['statuses'], 'name'));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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']);
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user