feat: enhance checkout process with cart integration and stock confirmation
This commit is contained in:
@@ -10,6 +10,7 @@ use Illuminate\Database\Eloquent\Factories\HasFactory;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
use Illuminate\Database\Eloquent\Relations\HasMany;
|
||||
use Illuminate\Database\Eloquent\SoftDeletes;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
|
||||
@@ -23,6 +24,7 @@ use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
|
||||
class Cart extends Model
|
||||
{
|
||||
use HasFactory;
|
||||
use SoftDeletes;
|
||||
|
||||
protected $table = 'carritos';
|
||||
|
||||
|
||||
@@ -85,6 +85,25 @@ class ProductVariant extends Model
|
||||
$this->save();
|
||||
}
|
||||
|
||||
public function confirmReservedStock(int $amount): void
|
||||
{
|
||||
if ($amount < 0) {
|
||||
throw new \InvalidArgumentException('El monto a confirmar debe ser positivo.');
|
||||
}
|
||||
|
||||
if ($this->stock_real < $amount) {
|
||||
throw new \InvalidArgumentException('No hay suficiente stock real para confirmar la reserva.');
|
||||
}
|
||||
|
||||
if ($this->stock_reservado < $amount) {
|
||||
throw new \InvalidArgumentException('No hay suficiente stock reservado para confirmar la reserva.');
|
||||
}
|
||||
|
||||
$this->stock_real -= $amount;
|
||||
$this->stock_reservado -= $amount;
|
||||
$this->save();
|
||||
}
|
||||
|
||||
protected function stockTecnico(): Attribute
|
||||
{
|
||||
return Attribute::get(fn () => $this->stock_real - $this->stock_reservado);
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
namespace App\Domains\Integration\Services;
|
||||
|
||||
use App\Domains\Purchase\Services\CheckoutService;
|
||||
use App\Domains\Purchase\Models\TelepagosPayment;
|
||||
use App\Domains\Purchase\Models\TelepagosQr;
|
||||
use App\Domains\Tenant\Models\Tenant;
|
||||
@@ -10,6 +11,10 @@ use Illuminate\Support\Facades\Log;
|
||||
|
||||
class TelepagosWebhookService
|
||||
{
|
||||
public function __construct(
|
||||
private readonly CheckoutService $checkoutService,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* Handle the Telepagos webhook notification.
|
||||
*
|
||||
@@ -79,6 +84,7 @@ class TelepagosWebhookService
|
||||
|
||||
\Illuminate\Support\Facades\DB::transaction(function () use ($compra, $paymentData) {
|
||||
TelepagosPayment::create($paymentData);
|
||||
$this->checkoutService->confirmPurchase($compra);
|
||||
$compra->finalize();
|
||||
});
|
||||
|
||||
|
||||
@@ -32,7 +32,7 @@ class PurchaseController extends Controller
|
||||
{
|
||||
$data = $request->validated();
|
||||
|
||||
$purchase = $checkoutService->processCheckout(
|
||||
$purchase = $checkoutService->startCheckout(
|
||||
$tenant,
|
||||
$request->user()->id,
|
||||
$data
|
||||
|
||||
@@ -3,14 +3,17 @@
|
||||
namespace App\Domains\Purchase\Models;
|
||||
|
||||
use App\Domains\Auth\Models\User;
|
||||
use App\Domains\Cart\Models\Cart;
|
||||
use App\Domains\Tenant\Models\Tenant;
|
||||
use Illuminate\Database\Eloquent\Attributes\Fillable;
|
||||
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
use Illuminate\Database\Eloquent\Relations\HasMany;
|
||||
use Illuminate\Support\Collection;
|
||||
|
||||
#[Fillable([
|
||||
'cart_id',
|
||||
'tenant_codigo',
|
||||
'user_id',
|
||||
'status',
|
||||
@@ -30,6 +33,7 @@ class Purchase extends Model
|
||||
protected function casts(): array
|
||||
{
|
||||
return [
|
||||
'cart_id' => 'integer',
|
||||
'user_id' => 'integer',
|
||||
];
|
||||
}
|
||||
@@ -50,6 +54,14 @@ class Purchase extends Model
|
||||
return $this->belongsTo(User::class);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return BelongsTo<Cart, $this>
|
||||
*/
|
||||
public function cart(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(Cart::class, 'cart_id')->withTrashed();
|
||||
}
|
||||
|
||||
/**
|
||||
* @return HasMany<PurchaseItem, $this>
|
||||
*/
|
||||
@@ -76,7 +88,25 @@ class Purchase extends Model
|
||||
|
||||
public function getTotalAmount(): float
|
||||
{
|
||||
return (float) $this->items()->sum('total');
|
||||
if ($this->items()->exists()) {
|
||||
return (float) $this->items()->sum('total');
|
||||
}
|
||||
|
||||
$cart = $this->relationLoaded('cart') ? $this->getRelation('cart') : $this->cart;
|
||||
|
||||
if ($cart === null) {
|
||||
return 0.0;
|
||||
}
|
||||
|
||||
/** @var Collection<int, mixed> $items */
|
||||
$items = $cart->relationLoaded('items')
|
||||
? $cart->getRelation('items')
|
||||
: $cart->items()->with('variant.product')->get();
|
||||
|
||||
return $items->reduce(
|
||||
static fn (float $carry, $item): float => $carry + ((float) ($item->variant?->product?->precio ?? 0) * (int) $item->cantidad),
|
||||
0.0,
|
||||
);
|
||||
}
|
||||
|
||||
public function finalize(): void
|
||||
|
||||
@@ -19,13 +19,11 @@ class StorePurchaseRequest extends FormRequest
|
||||
{
|
||||
return [
|
||||
'status' => ['sometimes', 'string', Rule::in(['pending', 'paid', 'cancelled'])],
|
||||
'cart_id' => ['required', 'integer', 'exists:carritos,id'],
|
||||
'dni' => ['required', 'string'],
|
||||
'telefono' => ['required', 'string'],
|
||||
'nombre_apellido' => ['required', 'string'],
|
||||
'email' => ['required', 'string', 'email'],
|
||||
'items' => ['required', 'array', 'min:1'],
|
||||
'items.*.producto_variante_id' => ['required', 'integer', 'exists:productos_variantes,id'],
|
||||
'items.*.cantidad' => ['required', 'integer', 'min:1'],
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
@@ -31,6 +31,7 @@ class PurchaseResource extends JsonResource
|
||||
|
||||
return [
|
||||
'id' => $this->id,
|
||||
'cart_id' => $this->cart_id,
|
||||
'tenant_codigo' => $this->tenant_codigo,
|
||||
'user_id' => $this->user_id,
|
||||
'status' => $this->status,
|
||||
|
||||
@@ -2,28 +2,37 @@
|
||||
|
||||
namespace App\Domains\Purchase\Services;
|
||||
|
||||
use App\Domains\Cart\Models\Cart;
|
||||
use App\Domains\Cart\Models\CartItem;
|
||||
use App\Domains\Catalog\Models\ProductVariant;
|
||||
use App\Domains\Purchase\Models\Purchase;
|
||||
use App\Domains\Tenant\Models\Tenant;
|
||||
use Illuminate\Support\Collection;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
|
||||
|
||||
class CheckoutService
|
||||
{
|
||||
public function processCheckout(Tenant $tenant, int $userId, array $purchaseData): Purchase
|
||||
public function startCheckout(Tenant $tenant, int $userId, array $purchaseData): Purchase
|
||||
{
|
||||
// 1. Preparar items de la compra
|
||||
$items = $purchaseData['items'];
|
||||
unset($purchaseData['items']);
|
||||
$cartId = (int) $purchaseData['cart_id'];
|
||||
unset($purchaseData['cart_id']);
|
||||
|
||||
$variants = $this->resolveTenantVariants($tenant, $items);
|
||||
$purchaseItemsPayload = $this->buildPurchaseItemsPayload($items, $variants);
|
||||
return DB::transaction(function () use ($tenant, $userId, $purchaseData, $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.',
|
||||
]);
|
||||
}
|
||||
|
||||
// 2. Crear la orden de compra y vaciar carrito
|
||||
return DB::transaction(function () use ($tenant, $userId, $purchaseData, $purchaseItemsPayload): Purchase {
|
||||
/** @var Purchase $purchase */
|
||||
$purchase = Purchase::query()->create([
|
||||
...$purchaseData,
|
||||
'cart_id' => $cart->getKey(),
|
||||
'tenant_codigo' => $tenant->codigo,
|
||||
'user_id' => $userId,
|
||||
'status' => 'pending',
|
||||
@@ -31,45 +40,66 @@ class CheckoutService
|
||||
'payment_method' => null,
|
||||
]);
|
||||
|
||||
$purchase->items()->createMany($purchaseItemsPayload);
|
||||
|
||||
// Vaciar y eliminar el carrito activo del usuario
|
||||
$cart = \App\Domains\Cart\Models\Cart::query()
|
||||
->where('tenant_codigo', $tenant->codigo)
|
||||
->where('user_id', $userId)
|
||||
->first();
|
||||
if ($cart) {
|
||||
$cart->items()->delete();
|
||||
$cart->delete();
|
||||
}
|
||||
|
||||
return $purchase->load(['items.variant.product', 'items.variant.definitions.productAttribute.attribute']);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<int, array<string, mixed>> $items
|
||||
* @return \Illuminate\Support\Collection<int, ProductVariant>
|
||||
*/
|
||||
protected function resolveTenantVariants(Tenant $tenant, array $items)
|
||||
public function confirmPurchase(Purchase $purchase): void
|
||||
{
|
||||
$variantIds = collect($items)
|
||||
DB::transaction(function () use ($purchase): void {
|
||||
/** @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.',
|
||||
]);
|
||||
}
|
||||
|
||||
if ($purchase->items()->exists()) {
|
||||
return;
|
||||
}
|
||||
|
||||
$cartItems->load('variant.product');
|
||||
$variants = $this->resolveTenantVariants($purchase->tenant, $cartItems);
|
||||
$purchaseItemsPayload = $this->buildPurchaseItemsPayload($cartItems, $variants);
|
||||
|
||||
$purchase->items()->createMany($purchaseItemsPayload);
|
||||
$this->completeCartConversion($cart, $cartItems, $variants);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* @return Collection<int, ProductVariant>
|
||||
*/
|
||||
protected function resolveTenantVariants(Tenant $tenant, Collection $cartItems): Collection
|
||||
{
|
||||
$variantIds = $cartItems
|
||||
->pluck('producto_variante_id')
|
||||
->filter()
|
||||
->map(static fn (mixed $id): int => (int) $id)
|
||||
->unique()
|
||||
->values();
|
||||
|
||||
/** @var Collection<int, ProductVariant> $variants */
|
||||
$variants = ProductVariant::query()
|
||||
->with('product')
|
||||
->whereIn('id', $variantIds)
|
||||
->whereHas('product', fn ($query) => $query->where('tenant_codigo', $tenant->codigo))
|
||||
->lockForUpdate()
|
||||
->get()
|
||||
->keyBy('id');
|
||||
|
||||
if ($variants->count() !== $variantIds->count()) {
|
||||
throw ValidationException::withMessages([
|
||||
'items' => 'One or more product variants do not belong to the tenant.',
|
||||
'cart_id' => 'One or more product variants do not belong to the tenant.',
|
||||
]);
|
||||
}
|
||||
|
||||
@@ -77,14 +107,38 @@ class CheckoutService
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<int, array<string, mixed>> $items
|
||||
* @param \Illuminate\Support\Collection<int, ProductVariant> $variants
|
||||
* @param Collection<int, CartItem> $cartItems
|
||||
* @return \Illuminate\Support\Collection<int, ProductVariant>
|
||||
*/
|
||||
protected function resolveCheckoutCart(Tenant $tenant, int $userId, int $cartId): Cart
|
||||
{
|
||||
/** @var Cart|null $cart */
|
||||
$cart = Cart::query()
|
||||
->lockForUpdate()
|
||||
->find($cartId);
|
||||
|
||||
if ($cart === null || $cart->tenant_codigo !== $tenant->codigo || $cart->user_id !== $userId) {
|
||||
throw new NotFoundHttpException('Cart not found for tenant.');
|
||||
}
|
||||
|
||||
if ($cart->status !== 'active') {
|
||||
throw ValidationException::withMessages([
|
||||
'cart_id' => 'The selected cart is no longer active.',
|
||||
]);
|
||||
}
|
||||
|
||||
return $cart;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param Collection<int, CartItem> $cartItems
|
||||
* @param Collection<int, ProductVariant> $variants
|
||||
* @return array<int, array<string, mixed>>
|
||||
*/
|
||||
protected function buildPurchaseItemsPayload(array $items, $variants): array
|
||||
protected function buildPurchaseItemsPayload(Collection $cartItems, Collection $variants): array
|
||||
{
|
||||
return collect($items)
|
||||
->map(function (array $item) use ($variants): array {
|
||||
return $cartItems
|
||||
->map(function (CartItem $item) use ($variants): array {
|
||||
/** @var ProductVariant $variant */
|
||||
$variant = $variants->get((int) $item['producto_variante_id']);
|
||||
$quantity = (int) $item['cantidad'];
|
||||
@@ -101,4 +155,31 @@ class CheckoutService
|
||||
})
|
||||
->all();
|
||||
}
|
||||
|
||||
/**
|
||||
* @param Collection<int, CartItem> $cartItems
|
||||
* @param Collection<int, ProductVariant> $variants
|
||||
*/
|
||||
protected function completeCartConversion(Cart $cart, Collection $cartItems, Collection $variants): void
|
||||
{
|
||||
foreach ($cartItems as $item) {
|
||||
/** @var ProductVariant $variant */
|
||||
$variant = $variants->get((int) $item->producto_variante_id);
|
||||
$quantity = (int) $item->cantidad;
|
||||
|
||||
try {
|
||||
$variant->confirmReservedStock($quantity);
|
||||
} catch (\InvalidArgumentException $exception) {
|
||||
throw ValidationException::withMessages([
|
||||
'cart_id' => 'The selected cart has inconsistent stock state.',
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
$cart->status = 'converted';
|
||||
$cart->user_id = null;
|
||||
$cart->guest_token = null;
|
||||
$cart->save();
|
||||
$cart->delete();
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user