commit1dc4e29c69Author: ncoronel <ncoronel@quo.ar> Date: Wed Aug 19 13:58:03 2026 -0300 refactor(reservations): unify expiration command commit093e894cc3Author: ncoronel <ncoronel@quo.ar> Date: Wed Aug 19 13:48:09 2026 -0300 feat(cart): expire abandoned stock reservations commitfdf0f3328fAuthor: ncoronel <ncoronel@quo.ar> Date: Wed Aug 19 12:53:12 2026 -0300 refactor(stock): implement expiration for stock reservations and add configuration commit8d6bcdcc43Author: ncoronel <ncoronel@quo.ar> Date: Wed Aug 19 12:38:21 2026 -0300 refactor(cart): invalidate payment on actual changes commit3206e293ebAuthor: ncoronel <ncoronel@quo.ar> Date: Wed Aug 19 12:24:48 2026 -0300 refactor(cart): own checkout item editing commitaed99bd05eAuthor: ncoronel <ncoronel@quo.ar> Date: Wed Aug 19 12:14:57 2026 -0300 refactor(checkout): remove legacy purchase item reservations commitf1649e0e4bAuthor: ncoronel <ncoronel@quo.ar> Date: Wed Aug 19 12:06:29 2026 -0300 refactor(checkout): materialize purchase items on confirmation commite6c4b40a37Author: ncoronel <ncoronel@quo.ar> Date: Wed Aug 19 12:06:19 2026 -0300 feat(inventory): add traceable cart stock reservations
336 lines
9.9 KiB
PHP
336 lines
9.9 KiB
PHP
<?php
|
|
|
|
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\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;
|
|
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
|
|
|
|
class CartService
|
|
{
|
|
public function __construct(
|
|
private readonly StockReservationService $reservations,
|
|
) {}
|
|
|
|
public function show(Tenant $tenant, Request $request): Cart
|
|
{
|
|
$resolvedIdentity = $this->resolveIdentity($request);
|
|
|
|
if ($resolvedIdentity === null) {
|
|
return $this->makeEmptyCart($tenant);
|
|
}
|
|
|
|
$cart = $this->findCart($tenant, $resolvedIdentity['identity']);
|
|
|
|
if ($cart === null) {
|
|
return $this->makeEmptyCart($tenant);
|
|
}
|
|
|
|
return $this->loadCart($cart);
|
|
}
|
|
|
|
/**
|
|
* @return array{cart: Cart, guest_token: ?string}
|
|
*/
|
|
public function addItem(
|
|
Tenant $tenant,
|
|
Request $request,
|
|
int $catalogItemId,
|
|
?int $variantId,
|
|
int $quantity,
|
|
): array {
|
|
$resolvedIdentity = $this->resolveIdentity($request, true);
|
|
$identity = $resolvedIdentity['identity'];
|
|
$cart = $this->findOrCreateCart($tenant, $identity);
|
|
$cart->addItem($catalogItemId, $variantId, $quantity);
|
|
|
|
return [
|
|
'cart' => $this->loadCart($cart),
|
|
'guest_token' => $resolvedIdentity['generated_guest_token'],
|
|
];
|
|
}
|
|
|
|
public function updateItem(
|
|
Tenant $tenant,
|
|
Request $request,
|
|
int $cartItemId,
|
|
int $quantity,
|
|
?int $variantId,
|
|
bool $updateVariant,
|
|
): Cart {
|
|
$identity = $this->requireIdentity($request);
|
|
$cart = $this->findCartOrFail($tenant, $identity);
|
|
$cart->updateItem($cartItemId, $quantity, $variantId, $updateVariant);
|
|
|
|
return $this->loadCart($cart);
|
|
}
|
|
|
|
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())
|
|
->whereIn('status', [
|
|
Purchase::STATUS_CREATED,
|
|
Purchase::STATUS_PENDING_PAYMENT,
|
|
])
|
|
->whereDoesntHave('items')
|
|
->lockForUpdate()
|
|
->first();
|
|
|
|
if ($purchase === null) {
|
|
throw new NotFoundHttpException('Checkout cart not found.');
|
|
}
|
|
|
|
if ($purchase->expires_at !== null && $purchase->expires_at->isPast()) {
|
|
throw ValidationException::withMessages([
|
|
'cart' => __('api.purchase.not_editable'),
|
|
]);
|
|
}
|
|
|
|
/** @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);
|
|
}
|
|
|
|
$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);
|
|
});
|
|
}
|
|
|
|
public function removeItem(Tenant $tenant, Request $request, int $cartItemId): Cart
|
|
{
|
|
$identity = $this->requireIdentity($request);
|
|
$cart = $this->findCartOrFail($tenant, $identity);
|
|
$cart->removeItem($cartItemId);
|
|
|
|
return $this->loadCart($cart);
|
|
}
|
|
|
|
public function makeGuestTokenCookie(string $guestToken): Cookie
|
|
{
|
|
return cookie(
|
|
'guest_token',
|
|
$guestToken,
|
|
60 * 24 * 180,
|
|
'/',
|
|
config('session.domain'),
|
|
(bool) config('session.secure'),
|
|
true,
|
|
false,
|
|
config('session.same_site'),
|
|
);
|
|
}
|
|
|
|
protected function makeEmptyCart(Tenant $tenant): Cart
|
|
{
|
|
$cart = new Cart([
|
|
'tenant_codigo' => $tenant->codigo,
|
|
'status' => 'active',
|
|
]);
|
|
|
|
$cart->setRelation('items', collect());
|
|
|
|
return $cart;
|
|
}
|
|
|
|
protected function loadCart(Cart $cart): Cart
|
|
{
|
|
return $cart->fresh()->load([
|
|
'items.catalogItem.attachments',
|
|
'items.catalogItem.inventory',
|
|
'items.catalogItem.itemAttributes.attribute',
|
|
'items.variant.attachments',
|
|
'items.variant.inventory',
|
|
'items.variant.definitions.itemAttribute.attribute.options',
|
|
'items.variant.eventDates',
|
|
'items.variant.eventDate',
|
|
]);
|
|
}
|
|
|
|
/**
|
|
* @return array{identity: array{user_id: ?int, guest_token: ?string}, generated_guest_token: ?string}|null
|
|
*/
|
|
protected function resolveIdentity(Request $request, bool $generateGuestToken = false): ?array
|
|
{
|
|
$user = $request->user() ?? Auth::guard('sanctum')->user();
|
|
|
|
if ($user instanceof User) {
|
|
return [
|
|
'identity' => [
|
|
'user_id' => $user->getKey(),
|
|
'guest_token' => null,
|
|
],
|
|
'generated_guest_token' => null,
|
|
];
|
|
}
|
|
|
|
$guestToken = $request->cookie('guest_token');
|
|
|
|
if (is_string($guestToken) && $guestToken !== '') {
|
|
return [
|
|
'identity' => [
|
|
'user_id' => null,
|
|
'guest_token' => $guestToken,
|
|
],
|
|
'generated_guest_token' => null,
|
|
];
|
|
}
|
|
|
|
if (! $generateGuestToken) {
|
|
return null;
|
|
}
|
|
|
|
$generatedGuestToken = (string) Str::uuid();
|
|
|
|
return [
|
|
'identity' => [
|
|
'user_id' => null,
|
|
'guest_token' => $generatedGuestToken,
|
|
],
|
|
'generated_guest_token' => $generatedGuestToken,
|
|
];
|
|
}
|
|
|
|
/**
|
|
* @return array{user_id: ?int, guest_token: ?string}
|
|
*/
|
|
protected function requireIdentity(Request $request): array
|
|
{
|
|
$resolvedIdentity = $this->resolveIdentity($request);
|
|
|
|
if ($resolvedIdentity === null) {
|
|
throw new NotFoundHttpException('Cart not found.');
|
|
}
|
|
|
|
return $resolvedIdentity['identity'];
|
|
}
|
|
|
|
/**
|
|
* @param array{user_id: ?int, guest_token: ?string} $identity
|
|
*/
|
|
protected function findCart(Tenant $tenant, array $identity): ?Cart
|
|
{
|
|
return Cart::query()
|
|
->where('tenant_codigo', $tenant->codigo)
|
|
->where('status', 'active')
|
|
->when(
|
|
$identity['user_id'] !== null,
|
|
fn ($query) => $query->where('user_id', $identity['user_id']),
|
|
fn ($query) => $query->where('guest_token', $identity['guest_token']),
|
|
)
|
|
->first();
|
|
}
|
|
|
|
/**
|
|
* @param array{user_id: ?int, guest_token: ?string} $identity
|
|
*/
|
|
protected function findCartOrFail(Tenant $tenant, array $identity): Cart
|
|
{
|
|
$cart = $this->findCart($tenant, $identity);
|
|
|
|
if ($cart === null) {
|
|
throw new NotFoundHttpException('Cart not found.');
|
|
}
|
|
|
|
return $cart;
|
|
}
|
|
|
|
/**
|
|
* @param array{user_id: ?int, guest_token: ?string} $identity
|
|
*/
|
|
protected function findOrCreateCart(Tenant $tenant, array $identity): Cart
|
|
{
|
|
$attributes = [
|
|
'tenant_codigo' => $tenant->codigo,
|
|
'status' => 'active',
|
|
];
|
|
|
|
if ($identity['user_id'] !== null) {
|
|
$attributes['user_id'] = $identity['user_id'];
|
|
} else {
|
|
$attributes['guest_token'] = $identity['guest_token'];
|
|
}
|
|
|
|
return Cart::query()->firstOrCreate($attributes);
|
|
}
|
|
}
|