feat(purchase): add checkout expiration settings and reservation status to purchase items
- Introduced a new configuration file for purchase settings, including checkout and payment expiration times. - Added a migration to include a `reservation_status` column in the `compra_items` table, defaulting to 'active' and updating existing records based on purchase status. - Created a migration to add an `expires_at` timestamp to the `compras` table, updating it for existing records based on their status. - Scoped unique indexes in the `carritos` table to only active carts, adding virtual columns for active user and guest tokens. - Implemented a console command to expire overdue purchases and release stock reservations, scheduled to run every minute. - Added tests for Google token exchange and login functionality, ensuring proper cart handling and user authentication. - Updated purchase-related tests to reflect changes in item handling and customer data validation.
This commit is contained in:
@@ -5,22 +5,46 @@ namespace App\Domains\Auth\Controllers;
|
||||
use App\Domains\Auth\Requests\GoogleTokenExchangeRequest;
|
||||
use App\Domains\Auth\Resources\UserResource;
|
||||
use App\Domains\Auth\Services\GoogleAuthService;
|
||||
use App\Domains\Cart\Services\GuestCartMergeService;
|
||||
use App\Http\Controllers\Controller;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Support\Facades\Cookie;
|
||||
|
||||
class GoogleTokenExchangeController extends Controller
|
||||
{
|
||||
public function __construct(private readonly GoogleAuthService $googleAuthService) {}
|
||||
public function __construct(
|
||||
private readonly GoogleAuthService $googleAuthService,
|
||||
private readonly GuestCartMergeService $guestCartMergeService,
|
||||
) {}
|
||||
|
||||
public function __invoke(GoogleTokenExchangeRequest $request): JsonResponse
|
||||
{
|
||||
$authentication = $this->googleAuthService->exchange($request->validated('oauth_code'));
|
||||
$authentication = $this->googleAuthService->exchange(
|
||||
$request->validated('oauth_code'),
|
||||
$request->validated('tenant_codigo'),
|
||||
);
|
||||
|
||||
return response()->json([
|
||||
$guestTokenCookie = $request->cookie('guest_token');
|
||||
$guestToken = is_string($guestTokenCookie) && $guestTokenCookie !== ''
|
||||
? $guestTokenCookie
|
||||
: null;
|
||||
$this->guestCartMergeService->merge(
|
||||
$authentication['tenant_codigo'],
|
||||
$authentication['user'],
|
||||
$guestToken,
|
||||
);
|
||||
|
||||
$response = response()->json([
|
||||
'message' => 'Sesion iniciada correctamente.',
|
||||
'token' => $authentication['token'],
|
||||
'token_type' => 'Bearer',
|
||||
'user' => UserResource::make($authentication['user']),
|
||||
]);
|
||||
|
||||
if ($guestToken !== null) {
|
||||
$response->withCookie(Cookie::forget('guest_token'));
|
||||
}
|
||||
|
||||
return $response;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,16 +2,22 @@
|
||||
|
||||
namespace App\Domains\Auth\Controllers;
|
||||
|
||||
use App\Domains\Auth\Requests\LoginUserRequest;
|
||||
use App\Domains\Auth\Models\User;
|
||||
use App\Domains\Auth\Requests\LoginUserRequest;
|
||||
use App\Domains\Auth\Resources\UserResource;
|
||||
use App\Domains\Cart\Services\GuestCartMergeService;
|
||||
use App\Http\Controllers\Controller;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Support\Facades\Cookie;
|
||||
use Illuminate\Support\Facades\Hash;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
|
||||
class LoginController extends Controller
|
||||
{
|
||||
public function __construct(
|
||||
private readonly GuestCartMergeService $guestCartMergeService,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* @throws ValidationException
|
||||
*/
|
||||
@@ -33,11 +39,27 @@ class LoginController extends Controller
|
||||
now()->addMinutes($expirationMinutes),
|
||||
)->plainTextToken;
|
||||
|
||||
return response()->json([
|
||||
$guestTokenCookie = $request->cookie('guest_token');
|
||||
$guestToken = is_string($guestTokenCookie) && $guestTokenCookie !== ''
|
||||
? $guestTokenCookie
|
||||
: null;
|
||||
$this->guestCartMergeService->merge(
|
||||
$credentials['tenant_codigo'],
|
||||
$user,
|
||||
$guestToken,
|
||||
);
|
||||
|
||||
$response = response()->json([
|
||||
'message' => 'Sesion iniciada correctamente.',
|
||||
'token' => $token,
|
||||
'token_type' => 'Bearer',
|
||||
'user' => UserResource::make($user),
|
||||
]);
|
||||
|
||||
if ($guestToken !== null) {
|
||||
$response->withCookie(Cookie::forget('guest_token'));
|
||||
}
|
||||
|
||||
return $response;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -16,6 +16,7 @@ class GoogleTokenExchangeRequest extends FormRequest
|
||||
{
|
||||
return [
|
||||
'oauth_code' => ['required', 'uuid'],
|
||||
'tenant_codigo' => ['required', 'string', 'exists:tenants,codigo'],
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
@@ -19,6 +19,7 @@ class LoginUserRequest extends FormRequest
|
||||
return [
|
||||
'email' => ['required', 'string', 'email', 'max:255'],
|
||||
'password' => ['required', 'string'],
|
||||
'tenant_codigo' => ['required', 'string', 'exists:tenants,codigo'],
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
@@ -72,6 +72,7 @@ class GoogleAuthService
|
||||
Cache::put("google-oauth-exchange:{$exchangeCode}", [
|
||||
'user_id' => $user->id,
|
||||
'token' => $token,
|
||||
'tenant_codigo' => $tenant->codigo,
|
||||
], now()->addMinutes(5));
|
||||
|
||||
return redirect()->to($context['return_url'].'/login?'.http_build_query([
|
||||
@@ -79,10 +80,10 @@ class GoogleAuthService
|
||||
]));
|
||||
}
|
||||
|
||||
/** @return array{user: User, token: string} */
|
||||
public function exchange(string $exchangeCode): array
|
||||
/** @return array{user: User, token: string, tenant_codigo: string} */
|
||||
public function exchange(string $exchangeCode, string $tenantCodigo): array
|
||||
{
|
||||
/** @var array{user_id: int, token: string}|null $authentication */
|
||||
/** @var array{user_id: int, token: string, tenant_codigo?: string}|null $authentication */
|
||||
$authentication = Cache::pull("google-oauth-exchange:{$exchangeCode}");
|
||||
|
||||
if (! $authentication) {
|
||||
@@ -91,9 +92,16 @@ class GoogleAuthService
|
||||
]);
|
||||
}
|
||||
|
||||
if (($authentication['tenant_codigo'] ?? null) !== $tenantCodigo) {
|
||||
throw ValidationException::withMessages([
|
||||
'tenant_codigo' => 'El tenant no coincide con la solicitud de autenticacion.',
|
||||
]);
|
||||
}
|
||||
|
||||
return [
|
||||
'user' => User::query()->findOrFail($authentication['user_id']),
|
||||
'token' => $authentication['token'],
|
||||
'tenant_codigo' => $tenantCodigo,
|
||||
];
|
||||
}
|
||||
|
||||
|
||||
@@ -1,73 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Cart\Middleware;
|
||||
|
||||
use App\Domains\Cart\Models\Cart;
|
||||
use App\Domains\Tenant\Models\Tenant;
|
||||
use Closure;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\Auth;
|
||||
use Illuminate\Support\Facades\Cookie;
|
||||
use Symfony\Component\HttpFoundation\Response;
|
||||
|
||||
class MergeGuestCartMiddleware
|
||||
{
|
||||
public function handle(Request $request, Closure $next): Response
|
||||
{
|
||||
$guestToken = $request->cookie('guest_token');
|
||||
|
||||
// Resolve authenticated user optionally (from default guard or sanctum guard)
|
||||
$user = $request->user() ?? Auth::guard('sanctum')->user();
|
||||
$userId = $user?->getKey();
|
||||
|
||||
\Illuminate\Support\Facades\Log::info('MergeGuestCartMiddleware processed', [
|
||||
'user_id' => $userId,
|
||||
'guest_token' => $guestToken,
|
||||
]);
|
||||
|
||||
if ($user !== null && is_string($guestToken) && $guestToken !== '') {
|
||||
$tenantParam = $request->route('tenant');
|
||||
$tenantCodigo = null;
|
||||
|
||||
if ($tenantParam instanceof Tenant) {
|
||||
$tenantCodigo = $tenantParam->codigo;
|
||||
} elseif (is_string($tenantParam)) {
|
||||
$tenantCodigo = $tenantParam;
|
||||
}
|
||||
|
||||
if ($tenantCodigo !== null) {
|
||||
$guestCart = Cart::query()
|
||||
->where('tenant_codigo', $tenantCodigo)
|
||||
->where('guest_token', $guestToken)
|
||||
->first();
|
||||
|
||||
if ($guestCart !== null && $guestCart->items()->exists()) {
|
||||
$userCart = Cart::query()
|
||||
->where('tenant_codigo', $tenantCodigo)
|
||||
->where('user_id', $userId)
|
||||
->first();
|
||||
|
||||
if ($userCart !== null) {
|
||||
$userCart->delete();
|
||||
}
|
||||
|
||||
$guestCart->update([
|
||||
'user_id' => $userId,
|
||||
'guest_token' => null,
|
||||
]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
$response = $next($request);
|
||||
|
||||
if ($user !== null && is_string($guestToken) && $guestToken !== '') {
|
||||
// Remove the cookie from the response since the user is authenticated.
|
||||
if (method_exists($response, 'withCookie')) {
|
||||
$response->withCookie(Cookie::forget('guest_token'));
|
||||
}
|
||||
}
|
||||
|
||||
return $response;
|
||||
}
|
||||
}
|
||||
@@ -172,6 +172,7 @@ class CartService
|
||||
{
|
||||
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']),
|
||||
@@ -199,7 +200,10 @@ class CartService
|
||||
*/
|
||||
protected function findOrCreateCart(Tenant $tenant, array $identity): Cart
|
||||
{
|
||||
$attributes = ['tenant_codigo' => $tenant->codigo];
|
||||
$attributes = [
|
||||
'tenant_codigo' => $tenant->codigo,
|
||||
'status' => 'active',
|
||||
];
|
||||
|
||||
if ($identity['user_id'] !== null) {
|
||||
$attributes['user_id'] = $identity['user_id'];
|
||||
@@ -207,6 +211,6 @@ class CartService
|
||||
$attributes['guest_token'] = $identity['guest_token'];
|
||||
}
|
||||
|
||||
return Cart::query()->firstOrCreate($attributes, ['status' => 'active']);
|
||||
return Cart::query()->firstOrCreate($attributes);
|
||||
}
|
||||
}
|
||||
|
||||
49
app/Domains/Cart/Services/GuestCartMergeService.php
Normal file
49
app/Domains/Cart/Services/GuestCartMergeService.php
Normal file
@@ -0,0 +1,49 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Cart\Services;
|
||||
|
||||
use App\Domains\Auth\Models\User;
|
||||
use App\Domains\Cart\Models\Cart;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
|
||||
class GuestCartMergeService
|
||||
{
|
||||
public function merge(string $tenantCodigo, User $user, ?string $guestToken): void
|
||||
{
|
||||
if ($guestToken === null || $guestToken === '') {
|
||||
return;
|
||||
}
|
||||
|
||||
DB::transaction(function () use ($tenantCodigo, $user, $guestToken): void {
|
||||
$guestCart = Cart::query()
|
||||
->where('tenant_codigo', $tenantCodigo)
|
||||
->where('guest_token', $guestToken)
|
||||
->where('status', 'active')
|
||||
->lockForUpdate()
|
||||
->first();
|
||||
|
||||
if ($guestCart === null || ! $guestCart->items()->exists()) {
|
||||
return;
|
||||
}
|
||||
|
||||
$userCart = Cart::query()
|
||||
->where('tenant_codigo', $tenantCodigo)
|
||||
->where('user_id', $user->getKey())
|
||||
->where('status', 'active')
|
||||
->lockForUpdate()
|
||||
->first();
|
||||
|
||||
if ($userCart !== null) {
|
||||
$userCart->update([
|
||||
'status' => 'converted',
|
||||
]);
|
||||
$userCart->delete();
|
||||
}
|
||||
|
||||
$guestCart->update([
|
||||
'user_id' => $user->getKey(),
|
||||
'guest_token' => null,
|
||||
]);
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -4,7 +4,6 @@ use App\Domains\Cart\Controllers\CartController;
|
||||
use Illuminate\Support\Facades\Route;
|
||||
|
||||
Route::prefix('tenants/{tenant:codigo}')
|
||||
->middleware(\App\Domains\Cart\Middleware\MergeGuestCartMiddleware::class)
|
||||
->group(function (): void {
|
||||
Route::get('cart', [CartController::class, 'show']);
|
||||
Route::post('cart/items', [CartController::class, 'addItem']);
|
||||
|
||||
@@ -4,16 +4,19 @@ 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\StorePurchaseRequest;
|
||||
use App\Domains\Purchase\Requests\StartCheckoutRequest;
|
||||
use App\Domains\Purchase\Requests\UpdatePurchaseCustomerRequest;
|
||||
use App\Domains\Purchase\Requests\UpdatePurchaseItemQuantityRequest;
|
||||
use App\Domains\Purchase\Resources\PurchaseResource;
|
||||
use App\Domains\Purchase\Services\CheckoutService;
|
||||
use App\Domains\Tenant\Models\Tenant;
|
||||
use App\Http\Controllers\Controller;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Collection;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
|
||||
|
||||
class PurchaseController extends Controller
|
||||
@@ -32,8 +35,11 @@ class PurchaseController extends Controller
|
||||
)->response();
|
||||
}
|
||||
|
||||
public function store(StorePurchaseRequest $request, Tenant $tenant, CheckoutService $checkoutService): JsonResponse
|
||||
{
|
||||
public function startCheckout(
|
||||
StartCheckoutRequest $request,
|
||||
Tenant $tenant,
|
||||
CheckoutService $checkoutService,
|
||||
): JsonResponse {
|
||||
$data = $request->validated();
|
||||
|
||||
$purchase = $checkoutService->startCheckout(
|
||||
@@ -49,16 +55,56 @@ class PurchaseController extends Controller
|
||||
{
|
||||
$compra = $this->resolveScopedPurchase($tenant, $request->user()->id, $compra);
|
||||
|
||||
$compra->loadMissing(['items', 'cart.items']);
|
||||
$compra->loadMissing('items');
|
||||
$compra->items->load('imageAttachment');
|
||||
|
||||
if ($compra->cart !== null) {
|
||||
$this->loadCartCatalogEntries($compra->cart->items);
|
||||
}
|
||||
|
||||
return PurchaseResource::make($compra);
|
||||
}
|
||||
|
||||
public function updateCustomerData(
|
||||
UpdatePurchaseCustomerRequest $request,
|
||||
Tenant $tenant,
|
||||
Purchase $compra,
|
||||
CheckoutService $checkoutService,
|
||||
): PurchaseResource {
|
||||
$compra = $this->resolveScopedPurchase($tenant, $request->user()->id, $compra);
|
||||
|
||||
return PurchaseResource::make(
|
||||
$checkoutService->updateCustomerData($compra, $request->validated()),
|
||||
);
|
||||
}
|
||||
|
||||
public function updateItemQuantity(
|
||||
UpdatePurchaseItemQuantityRequest $request,
|
||||
Tenant $tenant,
|
||||
Purchase $compra,
|
||||
PurchaseItem $item,
|
||||
CheckoutService $checkoutService,
|
||||
): PurchaseResource {
|
||||
$compra = $this->resolveScopedPurchase($tenant, $request->user()->id, $compra);
|
||||
|
||||
return PurchaseResource::make(
|
||||
$checkoutService->updateItemQuantity(
|
||||
$compra,
|
||||
$item,
|
||||
(int) $request->validated('quantity'),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
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 paymentIntent(PaymentIntentRequest $request, Tenant $tenant, Purchase $compra): JsonResponse
|
||||
{
|
||||
$compra = $this->resolveScopedPurchase($tenant, $request->user()->id, $compra);
|
||||
@@ -68,6 +114,9 @@ class PurchaseController extends Controller
|
||||
$purchaseUpdate = [
|
||||
'payment_method' => $method,
|
||||
'status' => Purchase::STATUS_PENDING_PAYMENT,
|
||||
'expires_at' => now()->addMinutes(
|
||||
max(1, (int) config("purchase.payment_expiration_minutes.{$method}", 30))
|
||||
),
|
||||
'total' => $totalAmount,
|
||||
];
|
||||
|
||||
@@ -75,7 +124,22 @@ class PurchaseController extends Controller
|
||||
$purchaseUpdate['transfer_payer_dni'] = preg_replace('/\D+/', '', (string) $request->validated('transfer_payer_dni'));
|
||||
}
|
||||
|
||||
$compra->update($purchaseUpdate);
|
||||
$updated = Purchase::query()
|
||||
->whereKey($compra->getKey())
|
||||
->whereIn('status', [Purchase::STATUS_CREATED, Purchase::STATUS_PENDING_PAYMENT])
|
||||
->where(function ($query): void {
|
||||
$query->whereNull('expires_at')
|
||||
->orWhere('expires_at', '>', now());
|
||||
})
|
||||
->update($purchaseUpdate);
|
||||
|
||||
if ($updated === 0) {
|
||||
throw ValidationException::withMessages([
|
||||
'purchase' => 'The purchase is no longer available for payment.',
|
||||
]);
|
||||
}
|
||||
|
||||
$compra->refresh();
|
||||
|
||||
if ($method === 'transfer') {
|
||||
$telepagosService = new TelepagosIntegrationService;
|
||||
@@ -146,6 +210,15 @@ class PurchaseController extends Controller
|
||||
);
|
||||
}
|
||||
|
||||
public function cancel(Request $request, Tenant $tenant, Purchase $compra, CheckoutService $checkoutService): PurchaseResource
|
||||
{
|
||||
$compra = $this->resolveScopedPurchase($tenant, $request->user()->id, $compra);
|
||||
|
||||
return PurchaseResource::make(
|
||||
$checkoutService->cancelPurchase($compra)
|
||||
);
|
||||
}
|
||||
|
||||
protected function resolveScopedPurchase(Tenant $tenant, int $userId, Purchase $purchase): Purchase
|
||||
{
|
||||
if ($purchase->tenant_codigo !== $tenant->codigo || $purchase->user_id !== $userId) {
|
||||
@@ -154,17 +227,4 @@ class PurchaseController extends Controller
|
||||
|
||||
return $purchase;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return list<string>
|
||||
*/
|
||||
protected function loadCartCatalogEntries(Collection $items): void
|
||||
{
|
||||
$items->load([
|
||||
'catalogItem.attachments',
|
||||
'variant.attachments',
|
||||
'variant.catalogItem.attachments',
|
||||
'variant.definitions.itemAttribute.attribute',
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -20,6 +20,7 @@ use Illuminate\Support\Facades\DB;
|
||||
'user_id',
|
||||
'status',
|
||||
'payment_method',
|
||||
'expires_at',
|
||||
'total',
|
||||
'dni',
|
||||
'transfer_payer_dni',
|
||||
@@ -41,6 +42,8 @@ class Purchase extends Model
|
||||
|
||||
public const STATUS_REJECTED = 'rejected';
|
||||
|
||||
public const STATUS_EXPIRED = 'expired';
|
||||
|
||||
protected $table = 'compras';
|
||||
|
||||
protected function casts(): array
|
||||
@@ -48,6 +51,7 @@ class Purchase extends Model
|
||||
return [
|
||||
'cart_id' => 'integer',
|
||||
'user_id' => 'integer',
|
||||
'expires_at' => 'datetime',
|
||||
'total' => 'decimal:2',
|
||||
];
|
||||
}
|
||||
@@ -111,23 +115,11 @@ class Purchase extends Model
|
||||
|
||||
public function calculateCurrentTotalAmount(): float
|
||||
{
|
||||
if ($this->relationLoaded('items') && $this->getRelation('items')->isNotEmpty()) {
|
||||
if ($this->relationLoaded('items')) {
|
||||
return (float) $this->getRelation('items')->sum('total');
|
||||
}
|
||||
|
||||
if ($this->items()->exists()) {
|
||||
return (float) $this->items()->sum('total');
|
||||
}
|
||||
|
||||
$cart = $this->relationLoaded('cart')
|
||||
? $this->getRelation('cart')
|
||||
: $this->cart()->with(['items.catalogItem', 'items.variant'])->first();
|
||||
|
||||
if (! $cart) {
|
||||
return 0.0;
|
||||
}
|
||||
|
||||
return $cart->getTotalAmount();
|
||||
return (float) $this->items()->sum('total');
|
||||
}
|
||||
|
||||
public function markAsPendingPayment(): void
|
||||
|
||||
@@ -23,11 +23,18 @@ use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
'discount_total',
|
||||
'tax_total',
|
||||
'total',
|
||||
'reservation_status',
|
||||
])]
|
||||
class PurchaseItem extends Model
|
||||
{
|
||||
use HasFactory;
|
||||
|
||||
public const RESERVATION_ACTIVE = 'active';
|
||||
|
||||
public const RESERVATION_COMMITTED = 'committed';
|
||||
|
||||
public const RESERVATION_RELEASED = 'released';
|
||||
|
||||
protected $table = 'compra_items';
|
||||
|
||||
protected function casts(): array
|
||||
|
||||
51
app/Domains/Purchase/Requests/StartCheckoutRequest.php
Normal file
51
app/Domains/Purchase/Requests/StartCheckoutRequest.php
Normal file
@@ -0,0 +1,51 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Purchase\Requests;
|
||||
|
||||
use Illuminate\Foundation\Http\FormRequest;
|
||||
use Illuminate\Validation\Rule;
|
||||
|
||||
class StartCheckoutRequest extends FormRequest
|
||||
{
|
||||
public function authorize(): bool
|
||||
{
|
||||
return $this->user() !== null;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
public function rules(): array
|
||||
{
|
||||
return [
|
||||
'cart_id' => [
|
||||
'required_without:direct_item',
|
||||
Rule::prohibitedIf(fn (): bool => $this->has('direct_item')),
|
||||
'integer',
|
||||
'exists:carritos,id',
|
||||
],
|
||||
'direct_item' => [
|
||||
'required_without:cart_id',
|
||||
Rule::prohibitedIf(fn (): bool => $this->has('cart_id')),
|
||||
'array',
|
||||
],
|
||||
'direct_item.catalog_item_id' => [
|
||||
'required_with:direct_item',
|
||||
'integer',
|
||||
],
|
||||
'direct_item.variant_id' => [
|
||||
'nullable',
|
||||
'integer',
|
||||
],
|
||||
'direct_item.cantidad' => [
|
||||
'required_with:direct_item',
|
||||
'integer',
|
||||
'min:1',
|
||||
],
|
||||
'dni' => ['prohibited'],
|
||||
'telefono' => ['prohibited'],
|
||||
'nombre_apellido' => ['prohibited'],
|
||||
'email' => ['prohibited'],
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -4,7 +4,7 @@ namespace App\Domains\Purchase\Requests;
|
||||
|
||||
use Illuminate\Foundation\Http\FormRequest;
|
||||
|
||||
class StorePurchaseRequest extends FormRequest
|
||||
class UpdatePurchaseCustomerRequest extends FormRequest
|
||||
{
|
||||
public function authorize(): bool
|
||||
{
|
||||
@@ -17,7 +17,6 @@ class StorePurchaseRequest extends FormRequest
|
||||
public function rules(): array
|
||||
{
|
||||
return [
|
||||
'cart_id' => ['required', 'integer', 'exists:carritos,id'],
|
||||
'dni' => ['required', 'string'],
|
||||
'telefono' => ['required', 'string'],
|
||||
'nombre_apellido' => ['required', 'string'],
|
||||
@@ -0,0 +1,23 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Purchase\Requests;
|
||||
|
||||
use Illuminate\Foundation\Http\FormRequest;
|
||||
|
||||
class UpdatePurchaseItemQuantityRequest extends FormRequest
|
||||
{
|
||||
public function authorize(): bool
|
||||
{
|
||||
return $this->user() !== null;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
public function rules(): array
|
||||
{
|
||||
return [
|
||||
'quantity' => ['required', 'integer', 'min:1', 'max:100'],
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -2,12 +2,10 @@
|
||||
|
||||
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;
|
||||
use Illuminate\Http\Resources\Json\JsonResource;
|
||||
use Illuminate\Support\Collection;
|
||||
|
||||
/**
|
||||
* @mixin Purchase
|
||||
@@ -19,18 +17,20 @@ class PurchaseResource extends JsonResource
|
||||
*/
|
||||
public function toArray(Request $request): array
|
||||
{
|
||||
[$items, $itemsSource] = $this->resolveItems();
|
||||
$items = $this->resource->relationLoaded('items')
|
||||
? $this->resource->getRelation('items')
|
||||
: collect();
|
||||
|
||||
$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);
|
||||
|
||||
$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);
|
||||
@@ -43,62 +43,27 @@ class PurchaseResource extends JsonResource
|
||||
'created_at' => $this->created_at,
|
||||
'status' => $this->status,
|
||||
'payment_method' => $this->payment_method,
|
||||
'expires_at' => $this->expires_at,
|
||||
'dni' => $this->dni,
|
||||
'transfer_payer_dni' => $this->transfer_payer_dni,
|
||||
'telefono' => $this->telefono,
|
||||
'nombre_apellido' => $this->nombre_apellido,
|
||||
'email' => $this->email,
|
||||
'items_source' => $itemsSource,
|
||||
'items_source' => $items->isNotEmpty() ? 'purchase' : null,
|
||||
'items' => PurchaseItemResource::collection($items),
|
||||
'subtotal' => $this->formatMoney($subtotal),
|
||||
'total' => $this->formatMoney($total),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array{0: Collection<int, PurchaseItem|CartItem>, 1: string|null}
|
||||
*/
|
||||
protected function resolveItems(): array
|
||||
protected function resolveItemSubtotal(PurchaseItem $item): float
|
||||
{
|
||||
if (! $this->resource->relationLoaded('items')) {
|
||||
return [collect(), null];
|
||||
}
|
||||
|
||||
$purchaseItems = $this->resource->getRelation('items');
|
||||
|
||||
if ($purchaseItems->isNotEmpty()) {
|
||||
return [$purchaseItems, 'purchase'];
|
||||
}
|
||||
|
||||
if (! $this->resource->relationLoaded('cart')) {
|
||||
return [collect(), null];
|
||||
}
|
||||
|
||||
$cart = $this->resource->getRelation('cart');
|
||||
|
||||
if ($cart === null || ! $cart->relationLoaded('items')) {
|
||||
return [collect(), null];
|
||||
}
|
||||
|
||||
return [$cart->getRelation('items'), 'cart'];
|
||||
return (float) $item->precio_unitario * $item->cantidad;
|
||||
}
|
||||
|
||||
protected function resolveItemSubtotal(PurchaseItem|CartItem $item): float
|
||||
protected function resolveItemTotal(PurchaseItem $item): float
|
||||
{
|
||||
if ($item instanceof PurchaseItem) {
|
||||
return (float) $item->precio_unitario * $item->cantidad;
|
||||
}
|
||||
|
||||
return (float) ($item->selectedItem()?->getPrice() ?? 0) * $item->cantidad;
|
||||
}
|
||||
|
||||
protected function resolveItemTotal(PurchaseItem|CartItem $item): float
|
||||
{
|
||||
if ($item instanceof PurchaseItem) {
|
||||
return (float) ($item->total ?? 0);
|
||||
}
|
||||
|
||||
return $this->resolveItemSubtotal($item);
|
||||
return (float) ($item->total ?? 0);
|
||||
}
|
||||
|
||||
protected function formatMoney(float|int|string|null $amount): string
|
||||
|
||||
@@ -3,77 +3,54 @@
|
||||
namespace App\Domains\Purchase\Services;
|
||||
|
||||
use App\Domains\Attachable\Models\Attachment;
|
||||
use App\Domains\Attachable\Services\AttachmentService;
|
||||
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\Catalog\Services\CatalogInventoryService;
|
||||
use App\Domains\Purchase\Models\Purchase;
|
||||
use App\Domains\Purchase\Models\PurchaseItem;
|
||||
use App\Domains\Tenant\Models\Tenant;
|
||||
use Illuminate\Support\Collection;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Storage;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
|
||||
use Throwable;
|
||||
|
||||
class CheckoutService
|
||||
{
|
||||
public function __construct(
|
||||
private readonly AttachmentService $attachmentService,
|
||||
private readonly CatalogInventoryService $catalogInventoryService,
|
||||
) {}
|
||||
|
||||
public function startCheckout(Tenant $tenant, int $userId, array $purchaseData): Purchase
|
||||
{
|
||||
$cartId = (int) $purchaseData['cart_id'];
|
||||
unset($purchaseData['cart_id']);
|
||||
return DB::transaction(function () use ($tenant, $userId, $purchaseData): Purchase {
|
||||
$directItem = $purchaseData['direct_item'] ?? null;
|
||||
$cartId = isset($purchaseData['cart_id']) ? (int) $purchaseData['cart_id'] : null;
|
||||
unset($purchaseData['direct_item'], $purchaseData['cart_id']);
|
||||
|
||||
return DB::transaction(function () use ($tenant, $userId, $purchaseData, $cartId): Purchase {
|
||||
$cart = $this->resolveCheckoutCart($tenant, $userId, $cartId);
|
||||
$cartItems = $cart->items()->lockForUpdate()->get();
|
||||
if (is_array($directItem)) {
|
||||
return $this->startDirectCheckout(
|
||||
$tenant,
|
||||
$userId,
|
||||
$purchaseData,
|
||||
$directItem,
|
||||
);
|
||||
}
|
||||
|
||||
if ($cartItems->isEmpty()) {
|
||||
if ($cartId === null) {
|
||||
throw ValidationException::withMessages([
|
||||
'cart_id' => 'The selected cart does not contain items.',
|
||||
'cart_id' => 'A cart or direct item is required.',
|
||||
]);
|
||||
}
|
||||
|
||||
$this->loadCartItems($cartItems);
|
||||
$cart->setRelation('items', $cartItems);
|
||||
$totalAmount = $cart->getTotalAmount();
|
||||
|
||||
/** @var Purchase|null $purchase */
|
||||
$purchase = Purchase::query()
|
||||
->where('cart_id', $cart->getKey())
|
||||
->where('tenant_codigo', $tenant->codigo)
|
||||
->where('user_id', $userId)
|
||||
->whereIn('status', [Purchase::STATUS_CREATED, Purchase::STATUS_PENDING_PAYMENT])
|
||||
->latest('id')
|
||||
->first();
|
||||
|
||||
if ($purchase === null) {
|
||||
/** @var Purchase $purchase */
|
||||
$purchase = Purchase::query()->create([
|
||||
...$purchaseData,
|
||||
'cart_id' => $cart->getKey(),
|
||||
'tenant_codigo' => $tenant->codigo,
|
||||
'user_id' => $userId,
|
||||
'status' => Purchase::STATUS_CREATED,
|
||||
'payment_method' => null,
|
||||
'total' => $totalAmount,
|
||||
]);
|
||||
} else {
|
||||
$purchase->fill([
|
||||
...$purchaseData,
|
||||
'status' => Purchase::STATUS_CREATED,
|
||||
'payment_method' => null,
|
||||
'total' => $totalAmount,
|
||||
]);
|
||||
$purchase->save();
|
||||
}
|
||||
|
||||
return $this->loadPurchase($purchase);
|
||||
return $this->startCartCheckout(
|
||||
$tenant,
|
||||
$userId,
|
||||
$purchaseData,
|
||||
$cartId,
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
@@ -91,7 +68,12 @@ class CheckoutService
|
||||
]);
|
||||
}
|
||||
|
||||
if (in_array($purchase->status, [Purchase::STATUS_PAID, Purchase::STATUS_CANCELLED, Purchase::STATUS_REJECTED], true)) {
|
||||
if (in_array($purchase->status, [
|
||||
Purchase::STATUS_PAID,
|
||||
Purchase::STATUS_CANCELLED,
|
||||
Purchase::STATUS_REJECTED,
|
||||
Purchase::STATUS_EXPIRED,
|
||||
], true)) {
|
||||
return $this->loadPurchase($purchase);
|
||||
}
|
||||
|
||||
@@ -104,59 +86,515 @@ class CheckoutService
|
||||
});
|
||||
}
|
||||
|
||||
public function confirmPurchase(Purchase $purchase): void
|
||||
/**
|
||||
* @param array<string, string> $customerData
|
||||
*/
|
||||
public function updateCustomerData(Purchase $purchase, array $customerData): Purchase
|
||||
{
|
||||
$snapshotPaths = [];
|
||||
return DB::transaction(function () use ($purchase, $customerData): Purchase {
|
||||
/** @var Purchase $purchase */
|
||||
$purchase = Purchase::query()
|
||||
->lockForUpdate()
|
||||
->findOrFail($purchase->getKey());
|
||||
|
||||
try {
|
||||
DB::transaction(function () use ($purchase, &$snapshotPaths): void {
|
||||
/** @var Purchase $purchase */
|
||||
$purchase = Purchase::query()
|
||||
->lockForUpdate()
|
||||
->findOrFail($purchase->getKey());
|
||||
|
||||
if ($purchase->items()->exists()) {
|
||||
return;
|
||||
}
|
||||
|
||||
/** @var Cart|null $cart */
|
||||
$cart = $purchase->cart()->lockForUpdate()->first();
|
||||
|
||||
if ($cart === null) {
|
||||
throw ValidationException::withMessages([
|
||||
'cart_id' => 'The purchase cart is no longer available.',
|
||||
]);
|
||||
}
|
||||
|
||||
$cartItems = $cart->items()->lockForUpdate()->get();
|
||||
|
||||
if ($cartItems->isEmpty()) {
|
||||
throw ValidationException::withMessages([
|
||||
'cart_id' => 'The purchase cart does not contain items.',
|
||||
]);
|
||||
}
|
||||
|
||||
$this->loadCartItems($cartItems);
|
||||
$this->verifyTenantItems($purchase->tenant, $cartItems);
|
||||
$purchaseItemsPayload = $this->buildPurchaseItemsPayload($purchase, $cartItems, $snapshotPaths);
|
||||
|
||||
$purchase->items()->createMany($purchaseItemsPayload);
|
||||
$this->completeCartConversion($cart, $cartItems);
|
||||
});
|
||||
} catch (Throwable $throwable) {
|
||||
foreach ($snapshotPaths as $snapshotPath) {
|
||||
Storage::disk('s3')->delete($snapshotPath);
|
||||
if (
|
||||
$purchase->status !== Purchase::STATUS_CREATED
|
||||
|| ($purchase->expires_at !== null && $purchase->expires_at->isPast())
|
||||
) {
|
||||
throw ValidationException::withMessages([
|
||||
'purchase' => 'The purchase is no longer editable.',
|
||||
]);
|
||||
}
|
||||
|
||||
throw $throwable;
|
||||
$purchase->update($customerData);
|
||||
|
||||
return $this->loadPurchase($purchase);
|
||||
});
|
||||
}
|
||||
|
||||
public function updateItemQuantity(
|
||||
Purchase $purchase,
|
||||
PurchaseItem $purchaseItem,
|
||||
int $quantity,
|
||||
): Purchase {
|
||||
return DB::transaction(function () use ($purchase, $purchaseItem, $quantity): Purchase {
|
||||
/** @var Purchase $purchase */
|
||||
$purchase = Purchase::query()
|
||||
->lockForUpdate()
|
||||
->findOrFail($purchase->getKey());
|
||||
|
||||
if (
|
||||
$purchase->status !== Purchase::STATUS_CREATED
|
||||
|| ($purchase->expires_at !== null && $purchase->expires_at->isPast())
|
||||
) {
|
||||
throw ValidationException::withMessages([
|
||||
'purchase' => 'The purchase is no longer editable.',
|
||||
]);
|
||||
}
|
||||
|
||||
/** @var PurchaseItem|null $purchaseItem */
|
||||
$purchaseItem = $purchase->items()
|
||||
->whereKey($purchaseItem->getKey())
|
||||
->lockForUpdate()
|
||||
->first();
|
||||
|
||||
if ($purchaseItem === null) {
|
||||
throw new NotFoundHttpException('Purchase item not found.');
|
||||
}
|
||||
|
||||
if ($purchaseItem->reservation_status !== PurchaseItem::RESERVATION_ACTIVE) {
|
||||
throw ValidationException::withMessages([
|
||||
'item' => 'The purchase item is no longer editable.',
|
||||
]);
|
||||
}
|
||||
|
||||
$currentQuantity = (int) $purchaseItem->cantidad;
|
||||
$difference = $quantity - $currentQuantity;
|
||||
|
||||
if ($difference !== 0) {
|
||||
$selection = $this->resolvePurchaseItemSelection($purchase->tenant, $purchaseItem);
|
||||
|
||||
try {
|
||||
if ($difference > 0) {
|
||||
$this->catalogInventoryService->reserve($selection, $difference);
|
||||
} else {
|
||||
$this->catalogInventoryService->release($selection, abs($difference));
|
||||
}
|
||||
} catch (\InvalidArgumentException $exception) {
|
||||
throw ValidationException::withMessages([
|
||||
'quantity' => 'No hay suficiente stock disponible.',
|
||||
]);
|
||||
}
|
||||
|
||||
$purchaseItem->update([
|
||||
'cantidad' => $quantity,
|
||||
'total' => (float) $purchaseItem->precio_unitario * $quantity,
|
||||
]);
|
||||
$this->syncSourceCartItemQuantity($purchase, $purchaseItem, $quantity);
|
||||
}
|
||||
|
||||
$purchase->update([
|
||||
'total' => $purchase->calculateCurrentTotalAmount(),
|
||||
]);
|
||||
|
||||
return $this->loadPurchase($purchase);
|
||||
});
|
||||
}
|
||||
|
||||
public function prepareItemEditing(Purchase $purchase): Purchase
|
||||
{
|
||||
return DB::transaction(function () use ($purchase): Purchase {
|
||||
/** @var Purchase $purchase */
|
||||
$purchase = Purchase::query()
|
||||
->lockForUpdate()
|
||||
->findOrFail($purchase->getKey());
|
||||
|
||||
if (
|
||||
! in_array($purchase->status, [
|
||||
Purchase::STATUS_CREATED,
|
||||
Purchase::STATUS_PENDING_PAYMENT,
|
||||
], true)
|
||||
|| ($purchase->expires_at !== null && $purchase->expires_at->isPast())
|
||||
) {
|
||||
throw ValidationException::withMessages([
|
||||
'purchase' => 'The purchase is no longer editable.',
|
||||
]);
|
||||
}
|
||||
|
||||
$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 confirmPurchase(Purchase $purchase): void
|
||||
{
|
||||
DB::transaction(function () use ($purchase): void {
|
||||
/** @var Purchase $purchase */
|
||||
$purchase = Purchase::query()
|
||||
->lockForUpdate()
|
||||
->findOrFail($purchase->getKey());
|
||||
|
||||
if ($purchase->status === Purchase::STATUS_PAID) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (in_array($purchase->status, [
|
||||
Purchase::STATUS_CANCELLED,
|
||||
Purchase::STATUS_REJECTED,
|
||||
Purchase::STATUS_EXPIRED,
|
||||
], true)) {
|
||||
throw ValidationException::withMessages([
|
||||
'purchase' => 'A cancelled, rejected or expired purchase cannot be confirmed.',
|
||||
]);
|
||||
}
|
||||
|
||||
$items = $purchase->items()
|
||||
->where('reservation_status', PurchaseItem::RESERVATION_ACTIVE)
|
||||
->lockForUpdate()
|
||||
->get();
|
||||
|
||||
foreach ($items as $item) {
|
||||
$selection = $this->resolvePurchaseItemSelection($purchase->tenant, $item);
|
||||
|
||||
try {
|
||||
$this->catalogInventoryService->commit($selection, (int) $item->cantidad);
|
||||
} catch (\InvalidArgumentException $exception) {
|
||||
throw ValidationException::withMessages([
|
||||
'items' => 'The purchase has an inconsistent stock reservation.',
|
||||
]);
|
||||
}
|
||||
|
||||
$item->update([
|
||||
'reservation_status' => PurchaseItem::RESERVATION_COMMITTED,
|
||||
]);
|
||||
}
|
||||
|
||||
$this->finalizeSourceCart($purchase);
|
||||
});
|
||||
}
|
||||
|
||||
public function cancelPurchase(Purchase $purchase): Purchase
|
||||
{
|
||||
return $this->releasePurchase($purchase, Purchase::STATUS_CANCELLED);
|
||||
}
|
||||
|
||||
public function expirePurchase(Purchase $purchase): Purchase
|
||||
{
|
||||
return $this->releasePurchase($purchase, Purchase::STATUS_EXPIRED);
|
||||
}
|
||||
|
||||
public function expireOverduePurchases(): int
|
||||
{
|
||||
$expiredCount = 0;
|
||||
|
||||
Purchase::query()
|
||||
->whereIn('status', [Purchase::STATUS_CREATED, Purchase::STATUS_PENDING_PAYMENT])
|
||||
->whereNotNull('expires_at')
|
||||
->where('expires_at', '<=', now())
|
||||
->orderBy('id')
|
||||
->eachById(function (Purchase $purchase) use (&$expiredCount): void {
|
||||
$purchase = $this->expirePurchase($purchase);
|
||||
|
||||
if ($purchase->status === Purchase::STATUS_EXPIRED) {
|
||||
$expiredCount++;
|
||||
}
|
||||
});
|
||||
|
||||
return $expiredCount;
|
||||
}
|
||||
|
||||
private function releasePurchase(Purchase $purchase, string $targetStatus): Purchase
|
||||
{
|
||||
return DB::transaction(function () use ($purchase, $targetStatus): Purchase {
|
||||
/** @var Purchase $purchase */
|
||||
$purchase = Purchase::query()
|
||||
->lockForUpdate()
|
||||
->findOrFail($purchase->getKey());
|
||||
|
||||
if ($purchase->status === Purchase::STATUS_PAID) {
|
||||
if ($targetStatus === Purchase::STATUS_EXPIRED) {
|
||||
return $this->loadPurchase($purchase);
|
||||
}
|
||||
|
||||
throw ValidationException::withMessages([
|
||||
'purchase' => 'A paid purchase cannot be cancelled.',
|
||||
]);
|
||||
}
|
||||
|
||||
if (in_array($purchase->status, [
|
||||
Purchase::STATUS_CANCELLED,
|
||||
Purchase::STATUS_REJECTED,
|
||||
Purchase::STATUS_EXPIRED,
|
||||
], true)) {
|
||||
return $this->loadPurchase($purchase);
|
||||
}
|
||||
|
||||
if (
|
||||
$targetStatus === Purchase::STATUS_EXPIRED
|
||||
&& ($purchase->expires_at === null || $purchase->expires_at->isFuture())
|
||||
) {
|
||||
return $this->loadPurchase($purchase);
|
||||
}
|
||||
|
||||
$items = $purchase->items()
|
||||
->where('reservation_status', PurchaseItem::RESERVATION_ACTIVE)
|
||||
->lockForUpdate()
|
||||
->get();
|
||||
$reservationReturnedToCart = $this->restoreSourceCart($purchase);
|
||||
|
||||
foreach ($items as $item) {
|
||||
if (! $reservationReturnedToCart) {
|
||||
$selection = $this->resolvePurchaseItemSelection($purchase->tenant, $item);
|
||||
|
||||
try {
|
||||
$this->catalogInventoryService->release($selection, (int) $item->cantidad);
|
||||
} catch (\InvalidArgumentException $exception) {
|
||||
throw ValidationException::withMessages([
|
||||
'items' => 'The purchase has an inconsistent stock reservation.',
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
$item->update([
|
||||
'reservation_status' => PurchaseItem::RESERVATION_RELEASED,
|
||||
]);
|
||||
}
|
||||
|
||||
$purchase->update([
|
||||
'status' => $targetStatus,
|
||||
]);
|
||||
|
||||
return $this->loadPurchase($purchase);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $purchaseData
|
||||
* @param array<string, mixed> $directItem
|
||||
*/
|
||||
private function startDirectCheckout(
|
||||
Tenant $tenant,
|
||||
int $userId,
|
||||
array $purchaseData,
|
||||
array $directItem,
|
||||
): Purchase {
|
||||
$catalogItemId = (int) $directItem['catalog_item_id'];
|
||||
$variantId = isset($directItem['variant_id']) ? (int) $directItem['variant_id'] : null;
|
||||
$quantity = (int) $directItem['cantidad'];
|
||||
$selection = $this->resolveSelection($tenant, $catalogItemId, $variantId);
|
||||
$availableQuantity = $this->catalogInventoryService->availableQuantity($selection);
|
||||
|
||||
if ($availableQuantity !== null && $availableQuantity < $quantity) {
|
||||
throw ValidationException::withMessages([
|
||||
'direct_item.cantidad' => "Stock insuficiente. Maximo disponible: {$availableQuantity}.",
|
||||
]);
|
||||
}
|
||||
|
||||
try {
|
||||
$this->catalogInventoryService->reserve($selection, $quantity);
|
||||
} catch (\InvalidArgumentException $exception) {
|
||||
throw ValidationException::withMessages([
|
||||
'direct_item.cantidad' => 'No hay suficiente stock disponible.',
|
||||
]);
|
||||
}
|
||||
|
||||
$purchase = $this->createPurchase(
|
||||
$tenant,
|
||||
$userId,
|
||||
$purchaseData,
|
||||
$selection->getPrice() * $quantity,
|
||||
null,
|
||||
);
|
||||
$cartItem = $this->makeDirectCartItem($selection, $catalogItemId, $variantId, $quantity);
|
||||
$purchase->items()->createMany(
|
||||
$this->buildPurchaseItemsPayload(collect([$cartItem])),
|
||||
);
|
||||
|
||||
return $this->loadPurchase($purchase);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $purchaseData
|
||||
*/
|
||||
private function startCartCheckout(
|
||||
Tenant $tenant,
|
||||
int $userId,
|
||||
array $purchaseData,
|
||||
int $cartId,
|
||||
): Purchase {
|
||||
$cart = $this->resolveCheckoutCart($tenant, $userId, $cartId);
|
||||
$cartItems = $cart->items()->lockForUpdate()->get();
|
||||
|
||||
if ($cartItems->isEmpty()) {
|
||||
throw ValidationException::withMessages([
|
||||
'cart_id' => 'The selected cart does not contain items.',
|
||||
]);
|
||||
}
|
||||
|
||||
$this->loadCartItems($cartItems);
|
||||
$this->verifyTenantItems($tenant, $cartItems);
|
||||
$cart->setRelation('items', $cartItems);
|
||||
|
||||
$purchase = $this->createPurchase(
|
||||
$tenant,
|
||||
$userId,
|
||||
$purchaseData,
|
||||
$cart->getTotalAmount(),
|
||||
$cart->getKey(),
|
||||
);
|
||||
$purchase->items()->createMany(
|
||||
$this->buildPurchaseItemsPayload($cartItems),
|
||||
);
|
||||
|
||||
// PurchaseItem owns the reservation during checkout. The source cart is
|
||||
// kept with its owner so it can be restored if the purchase is cancelled
|
||||
// or expires. Only active carts participate in the identity constraint.
|
||||
$cart->update([
|
||||
'status' => 'checkout',
|
||||
'guest_token' => null,
|
||||
]);
|
||||
|
||||
return $this->loadPurchase($purchase);
|
||||
}
|
||||
|
||||
private function restoreSourceCart(Purchase $purchase): bool
|
||||
{
|
||||
if ($purchase->cart_id === null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
/** @var Cart|null $sourceCart */
|
||||
$sourceCart = Cart::withTrashed()
|
||||
->whereKey($purchase->cart_id)
|
||||
->lockForUpdate()
|
||||
->first();
|
||||
|
||||
if ($sourceCart === null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
/** @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) {
|
||||
$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) {
|
||||
$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);
|
||||
}
|
||||
}
|
||||
|
||||
$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 syncSourceCartItemQuantity(
|
||||
Purchase $purchase,
|
||||
PurchaseItem $purchaseItem,
|
||||
int $quantity,
|
||||
): void {
|
||||
if ($purchase->cart_id === null) {
|
||||
return;
|
||||
}
|
||||
|
||||
$sourceCart = Cart::withTrashed()
|
||||
->whereKey($purchase->cart_id)
|
||||
->lockForUpdate()
|
||||
->first();
|
||||
|
||||
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,
|
||||
]);
|
||||
}
|
||||
|
||||
private function finalizeSourceCart(Purchase $purchase): void
|
||||
{
|
||||
if ($purchase->cart_id === null) {
|
||||
return;
|
||||
}
|
||||
|
||||
/** @var Cart|null $sourceCart */
|
||||
$sourceCart = Cart::withTrashed()
|
||||
->whereKey($purchase->cart_id)
|
||||
->lockForUpdate()
|
||||
->first();
|
||||
|
||||
if ($sourceCart === null || $sourceCart->trashed()) {
|
||||
return;
|
||||
}
|
||||
|
||||
$sourceCart->update([
|
||||
'status' => 'converted',
|
||||
'guest_token' => null,
|
||||
]);
|
||||
$sourceCart->delete();
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $purchaseData
|
||||
*/
|
||||
private function createPurchase(
|
||||
Tenant $tenant,
|
||||
int $userId,
|
||||
array $purchaseData,
|
||||
float $total,
|
||||
?int $cartId,
|
||||
): Purchase {
|
||||
return Purchase::query()->create([
|
||||
...$purchaseData,
|
||||
'cart_id' => $cartId,
|
||||
'tenant_codigo' => $tenant->codigo,
|
||||
'user_id' => $userId,
|
||||
'status' => Purchase::STATUS_CREATED,
|
||||
'payment_method' => null,
|
||||
'expires_at' => now()->addMinutes(
|
||||
max(1, (int) config('purchase.checkout_expiration_minutes', 30)),
|
||||
),
|
||||
'total' => $total,
|
||||
]);
|
||||
}
|
||||
|
||||
protected function verifyTenantItems(Tenant $tenant, Collection $cartItems): void
|
||||
{
|
||||
foreach ($cartItems as $item) {
|
||||
$selectedItem = $item->selectedItem();
|
||||
if ($selectedItem === null) {
|
||||
if ($item->selectedItem() === null) {
|
||||
throw ValidationException::withMessages([
|
||||
'cart_id' => 'One or more catalog items could not be loaded.',
|
||||
]);
|
||||
@@ -170,10 +608,6 @@ class CheckoutService
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param Collection<int, CartItem> $cartItems
|
||||
* @return Collection<int, CartItem>
|
||||
*/
|
||||
protected function resolveCheckoutCart(Tenant $tenant, int $userId, int $cartId): Cart
|
||||
{
|
||||
/** @var Cart|null $cart */
|
||||
@@ -198,21 +632,14 @@ class CheckoutService
|
||||
* @param Collection<int, CartItem> $cartItems
|
||||
* @return array<int, array<string, mixed>>
|
||||
*/
|
||||
protected function buildPurchaseItemsPayload(
|
||||
Purchase $purchase,
|
||||
Collection $cartItems,
|
||||
array &$snapshotPaths = [],
|
||||
): array {
|
||||
protected function buildPurchaseItemsPayload(Collection $cartItems): array
|
||||
{
|
||||
return $cartItems
|
||||
->map(function (CartItem $item) use ($purchase, &$snapshotPaths): array {
|
||||
->map(function (CartItem $item): array {
|
||||
$selectedItem = $item->selectedItem();
|
||||
$quantity = (int) $item['cantidad'];
|
||||
$quantity = (int) $item->cantidad;
|
||||
$unitPrice = $selectedItem?->getPrice() ?? 0;
|
||||
$imageAttachment = $this->snapshotFirstImage($purchase, $item);
|
||||
|
||||
if ($imageAttachment !== null) {
|
||||
$snapshotPaths[] = $imageAttachment->path;
|
||||
}
|
||||
$imageAttachment = $this->firstImageAttachment($item);
|
||||
|
||||
return [
|
||||
'source_catalog_item_id' => $item->catalog_item_id,
|
||||
@@ -230,37 +657,117 @@ class CheckoutService
|
||||
'discount_total' => null,
|
||||
'tax_total' => null,
|
||||
'total' => $unitPrice * $quantity,
|
||||
'reservation_status' => PurchaseItem::RESERVATION_ACTIVE,
|
||||
];
|
||||
})
|
||||
->all();
|
||||
}
|
||||
|
||||
/**
|
||||
* @param Collection<int, CartItem> $cartItems
|
||||
*/
|
||||
protected function completeCartConversion(Cart $cart, Collection $cartItems): void
|
||||
{
|
||||
foreach ($cartItems as $item) {
|
||||
$selectedItem = $item->selectedItem();
|
||||
$quantity = (int) $item->cantidad;
|
||||
private function resolveSelection(
|
||||
Tenant $tenant,
|
||||
int $catalogItemId,
|
||||
?int $variantId,
|
||||
): CatalogItem|Variant {
|
||||
/** @var CatalogItem|null $catalogItem */
|
||||
$catalogItem = CatalogItem::query()
|
||||
->whereKey($catalogItemId)
|
||||
->where('tenant_code', $tenant->codigo)
|
||||
->lockForUpdate()
|
||||
->first();
|
||||
|
||||
try {
|
||||
$this->catalogInventoryService->commit(
|
||||
$selectedItem,
|
||||
$quantity,
|
||||
);
|
||||
} catch (\InvalidArgumentException $exception) {
|
||||
throw ValidationException::withMessages([
|
||||
'cart_id' => 'The selected cart has inconsistent stock state.',
|
||||
]);
|
||||
}
|
||||
if ($catalogItem === null) {
|
||||
throw new NotFoundHttpException('Catalog item not found for tenant.');
|
||||
}
|
||||
|
||||
$cart->status = 'converted';
|
||||
$cart->user_id = null;
|
||||
$cart->guest_token = null;
|
||||
$cart->save();
|
||||
$cart->delete();
|
||||
if ($catalogItem->isBundle()) {
|
||||
if ($variantId !== null) {
|
||||
throw ValidationException::withMessages([
|
||||
'direct_item.variant_id' => 'Un bundle no admite una variante.',
|
||||
]);
|
||||
}
|
||||
|
||||
if (! $catalogItem->bundleComponents()->exists()) {
|
||||
throw ValidationException::withMessages([
|
||||
'direct_item.catalog_item_id' => 'El bundle no tiene componentes.',
|
||||
]);
|
||||
}
|
||||
|
||||
return $catalogItem;
|
||||
}
|
||||
|
||||
if ($variantId === null) {
|
||||
if ($catalogItem->inventory_id === null) {
|
||||
throw ValidationException::withMessages([
|
||||
'direct_item.variant_id' => 'Debe seleccionar una variante para este item.',
|
||||
]);
|
||||
}
|
||||
|
||||
$catalogItem->setRelation(
|
||||
'inventory',
|
||||
Inventory::query()->whereKey($catalogItem->inventory_id)->lockForUpdate()->firstOrFail(),
|
||||
);
|
||||
|
||||
return $catalogItem;
|
||||
}
|
||||
|
||||
/** @var Variant|null $variant */
|
||||
$variant = Variant::query()
|
||||
->whereKey($variantId)
|
||||
->where('catalog_item_id', $catalogItem->id)
|
||||
->lockForUpdate()
|
||||
->first();
|
||||
|
||||
if ($variant === null) {
|
||||
throw new NotFoundHttpException('Variant not found for catalog item.');
|
||||
}
|
||||
|
||||
$variant->setRelation('catalogItem', $catalogItem);
|
||||
$variant->setRelation(
|
||||
'inventory',
|
||||
Inventory::query()->whereKey($variant->inventory_id)->lockForUpdate()->firstOrFail(),
|
||||
);
|
||||
|
||||
return $variant;
|
||||
}
|
||||
|
||||
private function resolvePurchaseItemSelection(Tenant $tenant, PurchaseItem $item): CatalogItem|Variant
|
||||
{
|
||||
return $this->resolveSelection(
|
||||
$tenant,
|
||||
(int) $item->source_catalog_item_id,
|
||||
$item->source_variant_id === null ? null : (int) $item->source_variant_id,
|
||||
);
|
||||
}
|
||||
|
||||
private function makeDirectCartItem(
|
||||
CatalogItem|Variant $selection,
|
||||
int $catalogItemId,
|
||||
?int $variantId,
|
||||
int $quantity,
|
||||
): CartItem {
|
||||
$catalogItem = $selection instanceof Variant
|
||||
? $selection->catalogItem
|
||||
: $selection;
|
||||
$catalogItem->loadMissing(['inventory', 'attachments']);
|
||||
|
||||
if ($selection instanceof Variant) {
|
||||
$selection->loadMissing([
|
||||
'inventory',
|
||||
'attachments',
|
||||
'catalogItem',
|
||||
'definitions.itemAttribute.attribute',
|
||||
]);
|
||||
}
|
||||
|
||||
$item = new CartItem([
|
||||
'catalog_item_id' => $catalogItemId,
|
||||
'variant_id' => $variantId,
|
||||
'cantidad' => $quantity,
|
||||
]);
|
||||
$item->setRelation('catalogItem', $catalogItem);
|
||||
$item->setRelation('variant', $selection instanceof Variant ? $selection : null);
|
||||
|
||||
return $item;
|
||||
}
|
||||
|
||||
/** @param Collection<int, CartItem> $cartItems */
|
||||
@@ -283,19 +790,10 @@ class CheckoutService
|
||||
]);
|
||||
}
|
||||
|
||||
private function snapshotFirstImage(Purchase $purchase, CartItem $item): ?Attachment
|
||||
private function firstImageAttachment(CartItem $item): ?Attachment
|
||||
{
|
||||
$source = $item->variant?->attachments->first()
|
||||
return $item->variant?->attachments->first()
|
||||
?? $item->catalogItem?->attachments->first();
|
||||
|
||||
if ($source === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return $this->attachmentService->copy(
|
||||
$source,
|
||||
"purchase/{$purchase->id}",
|
||||
);
|
||||
}
|
||||
|
||||
/** @return array<int, array{name: string, value: mixed}> */
|
||||
|
||||
@@ -3,8 +3,14 @@
|
||||
use App\Domains\Purchase\Controllers\PurchaseController;
|
||||
use Illuminate\Support\Facades\Route;
|
||||
|
||||
Route::prefix('tenants/{tenant:codigo}')->middleware(['auth:sanctum', \App\Domains\Cart\Middleware\MergeGuestCartMiddleware::class])->group(function (): void {
|
||||
Route::apiResource('compras', PurchaseController::class)->only(['index', 'store', 'show']);
|
||||
Route::prefix('tenants/{tenant:codigo}')->middleware('auth:sanctum')->group(function (): void {
|
||||
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, 'updateItemQuantity']);
|
||||
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']);
|
||||
Route::post('compras/{compra}/cancel', [PurchaseController::class, 'cancel']);
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user