Compare commits
5 Commits
18c80b075b
...
feature/va
| Author | SHA1 | Date | |
|---|---|---|---|
| 6fc6ed1fac | |||
| c05206cc51 | |||
| 480ee70393 | |||
| ceb1e2b04a | |||
| 1d56d27350 |
126
app/Domains/Bundle/Models/Bundle.php
Normal file
126
app/Domains/Bundle/Models/Bundle.php
Normal file
@@ -0,0 +1,126 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Bundle\Models;
|
||||
|
||||
use App\Domains\Shared\Contracts\Buyable;
|
||||
use App\Domains\Tenant\Models\Tenant;
|
||||
use Illuminate\Database\Eloquent\Attributes\Fillable;
|
||||
use Illuminate\Database\Eloquent\Casts\Attribute;
|
||||
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
use Illuminate\Database\Eloquent\Relations\HasMany;
|
||||
|
||||
#[Fillable([
|
||||
'tenant_codigo',
|
||||
'nombre',
|
||||
'descripcion',
|
||||
'precio',
|
||||
])]
|
||||
class Bundle extends Model implements Buyable
|
||||
{
|
||||
use HasFactory;
|
||||
|
||||
protected $table = 'bundles';
|
||||
|
||||
protected $appends = ['stock_tecnico'];
|
||||
|
||||
protected function casts(): array
|
||||
{
|
||||
return [
|
||||
'precio' => 'decimal:2',
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* @return BelongsTo<Tenant, $this>
|
||||
*/
|
||||
public function tenant(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(Tenant::class, 'tenant_codigo', 'codigo');
|
||||
}
|
||||
|
||||
/**
|
||||
* @return HasMany<BundleItem, $this>
|
||||
*/
|
||||
public function items(): HasMany
|
||||
{
|
||||
return $this->hasMany(BundleItem::class, 'bundle_id');
|
||||
}
|
||||
|
||||
public function getPrice(): float
|
||||
{
|
||||
return (float) $this->precio;
|
||||
}
|
||||
|
||||
public function getName(): string
|
||||
{
|
||||
return $this->nombre ?? 'Bundle';
|
||||
}
|
||||
|
||||
public function availableQuantity(): ?int
|
||||
{
|
||||
if ($this->items->isEmpty()) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
$availableQuantities = [];
|
||||
|
||||
foreach ($this->items as $item) {
|
||||
$variantQuantity = $item->variant?->availableQuantity();
|
||||
|
||||
if ($variantQuantity !== null) {
|
||||
$availableQuantities[] = intdiv($variantQuantity, $item->cantidad);
|
||||
}
|
||||
}
|
||||
|
||||
return $availableQuantities === [] ? null : min($availableQuantities);
|
||||
}
|
||||
|
||||
public function reserveStock(int $amount): void
|
||||
{
|
||||
if ($amount < 0) {
|
||||
throw new \InvalidArgumentException('El monto a reservar debe ser positivo.');
|
||||
}
|
||||
|
||||
foreach ($this->items as $item) {
|
||||
$item->variant->reserveStock($amount * $item->cantidad);
|
||||
}
|
||||
}
|
||||
|
||||
public function decrementReservedStock(int $amount): void
|
||||
{
|
||||
if ($amount < 0) {
|
||||
throw new \InvalidArgumentException('El monto a decrementar debe ser positivo.');
|
||||
}
|
||||
|
||||
foreach ($this->items as $item) {
|
||||
$item->variant->decrementReservedStock($amount * $item->cantidad);
|
||||
}
|
||||
}
|
||||
|
||||
public function buy(int $amount): void
|
||||
{
|
||||
if ($amount < 0) {
|
||||
throw new \InvalidArgumentException('El monto a comprar debe ser positivo.');
|
||||
}
|
||||
|
||||
foreach ($this->items as $item) {
|
||||
$item->variant->buy($amount * $item->cantidad);
|
||||
}
|
||||
}
|
||||
|
||||
public function validateStock(): void
|
||||
{
|
||||
$availableQuantity = $this->availableQuantity();
|
||||
|
||||
if ($availableQuantity !== null && $availableQuantity <= 0) {
|
||||
throw new \InvalidArgumentException('El bundle no tiene stock tecnico disponible.');
|
||||
}
|
||||
}
|
||||
|
||||
protected function stockTecnico(): Attribute
|
||||
{
|
||||
return Attribute::get(fn (): ?int => $this->availableQuantity());
|
||||
}
|
||||
}
|
||||
46
app/Domains/Bundle/Models/BundleItem.php
Normal file
46
app/Domains/Bundle/Models/BundleItem.php
Normal file
@@ -0,0 +1,46 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Bundle\Models;
|
||||
|
||||
use App\Domains\Catalog\Models\ProductVariant;
|
||||
use Illuminate\Database\Eloquent\Attributes\Fillable;
|
||||
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
|
||||
#[Fillable([
|
||||
'bundle_id',
|
||||
'producto_variante_id',
|
||||
'cantidad',
|
||||
])]
|
||||
class BundleItem extends Model
|
||||
{
|
||||
use HasFactory;
|
||||
|
||||
protected $table = 'bundle_items';
|
||||
|
||||
protected function casts(): array
|
||||
{
|
||||
return [
|
||||
'bundle_id' => 'integer',
|
||||
'producto_variante_id' => 'integer',
|
||||
'cantidad' => 'integer',
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* @return BelongsTo<Bundle, $this>
|
||||
*/
|
||||
public function bundle(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(Bundle::class, 'bundle_id');
|
||||
}
|
||||
|
||||
/**
|
||||
* @return BelongsTo<ProductVariant, $this>
|
||||
*/
|
||||
public function variant(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(ProductVariant::class, 'producto_variante_id');
|
||||
}
|
||||
}
|
||||
@@ -2,11 +2,11 @@
|
||||
|
||||
namespace App\Domains\Cart\Controllers;
|
||||
|
||||
use App\Domains\Cart\Models\CartItem;
|
||||
use App\Domains\Cart\Requests\AddCartItemRequest;
|
||||
use App\Domains\Cart\Requests\UpdateCartItemQuantityRequest;
|
||||
use App\Domains\Cart\Resources\CartResource;
|
||||
use App\Domains\Cart\Services\CartService;
|
||||
use App\Domains\Catalog\Models\ProductVariant;
|
||||
use App\Domains\Tenant\Models\Tenant;
|
||||
use App\Http\Controllers\Controller;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
@@ -16,8 +16,7 @@ class CartController extends Controller
|
||||
{
|
||||
public function __construct(
|
||||
protected CartService $cartService,
|
||||
) {
|
||||
}
|
||||
) {}
|
||||
|
||||
public function show(Request $request, Tenant $tenant): CartResource
|
||||
{
|
||||
@@ -29,7 +28,8 @@ class CartController extends Controller
|
||||
$result = $this->cartService->addItem(
|
||||
$tenant,
|
||||
$request,
|
||||
(int) $request->validated('product_variant_id'),
|
||||
$request->mappedBuyableType(),
|
||||
(int) $request->validated('buyable_id'),
|
||||
(int) $request->validated('cantidad'),
|
||||
);
|
||||
|
||||
@@ -47,22 +47,22 @@ class CartController extends Controller
|
||||
public function updateItemQuantity(
|
||||
UpdateCartItemQuantityRequest $request,
|
||||
Tenant $tenant,
|
||||
ProductVariant $productVariant,
|
||||
CartItem $cartItem,
|
||||
): CartResource {
|
||||
return CartResource::make(
|
||||
$this->cartService->updateItemQuantity(
|
||||
$tenant,
|
||||
$request,
|
||||
$productVariant->getKey(),
|
||||
$cartItem->getKey(),
|
||||
(int) $request->validated('cantidad'),
|
||||
)
|
||||
)->additional(['message' => 'Cantidad de producto actualizada.']);
|
||||
}
|
||||
|
||||
public function removeItem(Request $request, Tenant $tenant, ProductVariant $productVariant): CartResource
|
||||
public function removeItem(Request $request, Tenant $tenant, CartItem $cartItem): CartResource
|
||||
{
|
||||
return CartResource::make(
|
||||
$this->cartService->removeItem($tenant, $request, $productVariant->getKey())
|
||||
$this->cartService->removeItem($tenant, $request, $cartItem->getKey())
|
||||
)->additional(['message' => 'Producto eliminado del carrito.']);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,7 +3,9 @@
|
||||
namespace App\Domains\Cart\Models;
|
||||
|
||||
use App\Domains\Auth\Models\User;
|
||||
use App\Domains\Bundle\Models\Bundle;
|
||||
use App\Domains\Catalog\Models\ProductVariant;
|
||||
use App\Domains\Shared\Contracts\Buyable;
|
||||
use App\Domains\Tenant\Models\Tenant;
|
||||
use Illuminate\Database\Eloquent\Attributes\Fillable;
|
||||
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
||||
@@ -63,15 +65,15 @@ class Cart extends Model
|
||||
{
|
||||
$items = $this->relationLoaded('items')
|
||||
? $this->getRelation('items')
|
||||
: $this->items()->with('variant.product')->get();
|
||||
: $this->items()->with('buyable')->get();
|
||||
|
||||
return (float) $items->reduce(
|
||||
fn (float $carry, $item): float => $carry + ((float) ($item->variant?->product?->precio ?? 0) * $item->cantidad),
|
||||
fn (float $carry, $item): float => $carry + ($item->buyable?->getPrice() * $item->cantidad),
|
||||
0.0,
|
||||
);
|
||||
}
|
||||
|
||||
public function addItem(int $productVariantId, int $quantity): CartItem
|
||||
public function addItem(string $buyableType, int $buyableId, int $quantity): CartItem
|
||||
{
|
||||
if ($quantity <= 0) {
|
||||
throw ValidationException::withMessages([
|
||||
@@ -79,24 +81,28 @@ class Cart extends Model
|
||||
]);
|
||||
}
|
||||
|
||||
return DB::transaction(function () use ($productVariantId, $quantity): CartItem {
|
||||
$variant = $this->resolveScopedVariant($productVariantId, true);
|
||||
return DB::transaction(function () use ($buyableType, $buyableId, $quantity): CartItem {
|
||||
$buyable = $this->resolveScopedBuyable($buyableType, $buyableId, true);
|
||||
$canonicalType = $buyable::class;
|
||||
$availableQuantity = $buyable->availableQuantity();
|
||||
|
||||
if ($variant->tracksInventory() && $variant->availableQuantity() < $quantity) {
|
||||
if ($availableQuantity !== null && $availableQuantity < $quantity) {
|
||||
throw ValidationException::withMessages([
|
||||
'cantidad' => "Stock insuficiente para la variante solicitada. Maximo disponible: {$variant->availableQuantity()}.",
|
||||
'cantidad' => "Stock insuficiente para el producto solicitado. Maximo disponible: {$availableQuantity}.",
|
||||
]);
|
||||
}
|
||||
|
||||
/** @var CartItem|null $item */
|
||||
$item = $this->items()
|
||||
->where('producto_variante_id', $variant->getKey())
|
||||
->where('buyable_type', $canonicalType)
|
||||
->where('buyable_id', $buyable->getKey())
|
||||
->lockForUpdate()
|
||||
->first();
|
||||
|
||||
if ($item === null) {
|
||||
$item = $this->items()->create([
|
||||
'producto_variante_id' => $variant->getKey(),
|
||||
'buyable_type' => $canonicalType,
|
||||
'buyable_id' => $buyable->getKey(),
|
||||
'cantidad' => $quantity,
|
||||
]);
|
||||
} else {
|
||||
@@ -104,13 +110,13 @@ class Cart extends Model
|
||||
$item->save();
|
||||
}
|
||||
|
||||
$variant->reserveStock($quantity);
|
||||
$buyable->reserveStock($quantity);
|
||||
|
||||
return $item->fresh();
|
||||
});
|
||||
}
|
||||
|
||||
public function updateItem(int $productVariantId, int $quantity): CartItem
|
||||
public function updateItem(int $cartItemId, int $quantity): CartItem
|
||||
{
|
||||
if ($quantity <= 0) {
|
||||
throw ValidationException::withMessages([
|
||||
@@ -118,18 +124,19 @@ class Cart extends Model
|
||||
]);
|
||||
}
|
||||
|
||||
return DB::transaction(function () use ($productVariantId, $quantity): CartItem {
|
||||
return DB::transaction(function () use ($cartItemId, $quantity): CartItem {
|
||||
/** @var CartItem $item */
|
||||
$item = $this->items()
|
||||
->where('producto_variante_id', $productVariantId)
|
||||
->where('id', $cartItemId)
|
||||
->lockForUpdate()
|
||||
->firstOrFail();
|
||||
|
||||
$variant = $this->resolveScopedVariant($productVariantId, true);
|
||||
$buyable = $this->resolveScopedBuyable($item->buyable_type, $item->buyable_id, true);
|
||||
$delta = $quantity - $item->cantidad;
|
||||
$availableQuantity = $buyable->availableQuantity();
|
||||
|
||||
if ($delta > 0 && $variant->tracksInventory() && $variant->availableQuantity() < $delta) {
|
||||
$maxAvailable = $variant->availableQuantity() + $item->cantidad;
|
||||
if ($delta > 0 && $availableQuantity !== null && $availableQuantity < $delta) {
|
||||
$maxAvailable = $availableQuantity + $item->cantidad;
|
||||
throw ValidationException::withMessages([
|
||||
'cantidad' => "El máximo que se puede agregar es {$maxAvailable}.",
|
||||
]);
|
||||
@@ -139,49 +146,65 @@ class Cart extends Model
|
||||
$item->save();
|
||||
|
||||
if ($delta > 0) {
|
||||
$variant->reserveStock($delta);
|
||||
$buyable->reserveStock($delta);
|
||||
}
|
||||
|
||||
if ($delta < 0) {
|
||||
$variant->decrementReservedStock(abs($delta));
|
||||
$buyable->decrementReservedStock(abs($delta));
|
||||
}
|
||||
|
||||
return $item->fresh();
|
||||
});
|
||||
}
|
||||
|
||||
public function removeItem(int $productVariantId): void
|
||||
public function removeItem(int $cartItemId): void
|
||||
{
|
||||
DB::transaction(function () use ($productVariantId): void {
|
||||
DB::transaction(function () use ($cartItemId): void {
|
||||
/** @var CartItem $item */
|
||||
$item = $this->items()
|
||||
->where('producto_variante_id', $productVariantId)
|
||||
->where('id', $cartItemId)
|
||||
->lockForUpdate()
|
||||
->firstOrFail();
|
||||
|
||||
$variant = $this->resolveScopedVariant($productVariantId, true);
|
||||
$variant->decrementReservedStock($item->cantidad);
|
||||
$buyable = $this->resolveScopedBuyable($item->buyable_type, $item->buyable_id, true);
|
||||
$buyable->decrementReservedStock($item->cantidad);
|
||||
$item->delete();
|
||||
});
|
||||
}
|
||||
|
||||
protected function resolveScopedVariant(int $productVariantId, bool $lockForUpdate = false): ProductVariant
|
||||
protected function resolveScopedBuyable(string $buyableType, int $buyableId, bool $lockForUpdate = false): Buyable
|
||||
{
|
||||
$query = ProductVariant::query()
|
||||
->whereKey($productVariantId)
|
||||
->whereHas('product', fn ($query) => $query->where('tenant_codigo', $this->tenant_codigo));
|
||||
$buyableClass = $this->resolveBuyableClass($buyableType);
|
||||
|
||||
if ($buyableClass === ProductVariant::class) {
|
||||
$query = ProductVariant::query()
|
||||
->whereKey($buyableId)
|
||||
->whereHas('product', fn ($query) => $query->where('tenant_codigo', $this->tenant_codigo));
|
||||
} else {
|
||||
$query = Bundle::query()
|
||||
->whereKey($buyableId)
|
||||
->where('tenant_codigo', $this->tenant_codigo);
|
||||
}
|
||||
|
||||
if ($lockForUpdate) {
|
||||
$query->lockForUpdate();
|
||||
}
|
||||
|
||||
/** @var ProductVariant|null $variant */
|
||||
$variant = $query->first();
|
||||
$buyable = $query->first();
|
||||
|
||||
if ($variant === null) {
|
||||
throw new NotFoundHttpException('Product variant not found for tenant.');
|
||||
if ($buyable === null) {
|
||||
throw new NotFoundHttpException('Buyable not found for tenant.');
|
||||
}
|
||||
|
||||
return $variant;
|
||||
return $buyable;
|
||||
}
|
||||
|
||||
protected function resolveBuyableClass(string $buyableType): string
|
||||
{
|
||||
return match ($buyableType) {
|
||||
'variant', ProductVariant::class => ProductVariant::class,
|
||||
'bundle', Bundle::class => Bundle::class,
|
||||
default => throw new \InvalidArgumentException('Invalid buyable type'),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -10,7 +10,8 @@ use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
|
||||
#[Fillable([
|
||||
'cart_id',
|
||||
'producto_variante_id',
|
||||
'buyable_id',
|
||||
'buyable_type',
|
||||
'cantidad',
|
||||
])]
|
||||
class CartItem extends Model
|
||||
@@ -23,7 +24,8 @@ class CartItem extends Model
|
||||
{
|
||||
return [
|
||||
'cart_id' => 'integer',
|
||||
'producto_variante_id' => 'integer',
|
||||
'buyable_id' => 'integer',
|
||||
'buyable_type' => 'string',
|
||||
'cantidad' => 'integer',
|
||||
];
|
||||
}
|
||||
@@ -37,10 +39,10 @@ class CartItem extends Model
|
||||
}
|
||||
|
||||
/**
|
||||
* @return BelongsTo<ProductVariant, $this>
|
||||
* @return \Illuminate\Database\Eloquent\Relations\MorphTo
|
||||
*/
|
||||
public function variant(): BelongsTo
|
||||
public function buyable()
|
||||
{
|
||||
return $this->belongsTo(ProductVariant::class, 'producto_variante_id');
|
||||
return $this->morphTo();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,7 +2,10 @@
|
||||
|
||||
namespace App\Domains\Cart\Requests;
|
||||
|
||||
use App\Domains\Bundle\Models\Bundle;
|
||||
use App\Domains\Catalog\Models\ProductVariant;
|
||||
use Illuminate\Foundation\Http\FormRequest;
|
||||
use Illuminate\Validation\Rule;
|
||||
|
||||
class AddCartItemRequest extends FormRequest
|
||||
{
|
||||
@@ -17,8 +20,18 @@ class AddCartItemRequest extends FormRequest
|
||||
public function rules(): array
|
||||
{
|
||||
return [
|
||||
'product_variant_id' => ['required', 'integer'],
|
||||
'buyable_type' => ['required', 'string', Rule::in(['variant', 'bundle'])],
|
||||
'buyable_id' => ['required', 'integer'],
|
||||
'cantidad' => ['required', 'integer', 'min:1'],
|
||||
];
|
||||
}
|
||||
|
||||
public function mappedBuyableType(): string
|
||||
{
|
||||
return match ($this->input('buyable_type')) {
|
||||
'variant' => ProductVariant::class,
|
||||
'bundle' => Bundle::class,
|
||||
default => throw new \InvalidArgumentException('Invalid buyable type'),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -18,6 +18,8 @@ class UpdateCartItemQuantityRequest extends FormRequest
|
||||
{
|
||||
return [
|
||||
'cantidad' => ['required', 'integer', 'min:1'],
|
||||
'buyable_type' => ['prohibited'],
|
||||
'buyable_id' => ['prohibited'],
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
@@ -15,29 +15,15 @@ class CartItemResource extends JsonResource
|
||||
*/
|
||||
public function toArray(Request $request): array
|
||||
{
|
||||
$variant = $this->variant;
|
||||
$product = $variant?->product;
|
||||
|
||||
$attributesText = '';
|
||||
if ($variant && $variant->relationLoaded('definitions')) {
|
||||
$attributesText = $variant->definitions
|
||||
->map(function ($definition) {
|
||||
$attrName = $definition->productAttribute?->attribute?->nombre;
|
||||
$value = $definition->value;
|
||||
return $attrName ? "{$attrName}: {$value}" : $value;
|
||||
})
|
||||
->filter()
|
||||
->implode(', ');
|
||||
}
|
||||
|
||||
$productName = $product?->nombre;
|
||||
if ($productName && $attributesText !== '') {
|
||||
$productName .= " ({$attributesText})";
|
||||
}
|
||||
|
||||
/** @var \App\Domains\Shared\Contracts\Buyable|null $buyable */
|
||||
$buyable = $this->buyable;
|
||||
|
||||
$productName = $buyable?->getName();
|
||||
$precio = $buyable?->getPrice();
|
||||
|
||||
$imageUrl = null;
|
||||
if ($variant && $variant->relationLoaded('attachments')) {
|
||||
$firstAttachment = $variant->attachments->first();
|
||||
if ($this->buyable_type === \App\Domains\Catalog\Models\ProductVariant::class && $buyable && $buyable->relationLoaded('attachments')) {
|
||||
$firstAttachment = $buyable->attachments->first();
|
||||
if ($firstAttachment) {
|
||||
$imageUrl = $firstAttachment->getTemporaryUrl(1440);
|
||||
}
|
||||
@@ -46,16 +32,25 @@ class CartItemResource extends JsonResource
|
||||
return [
|
||||
'id' => $this->id,
|
||||
'cantidad' => $this->cantidad,
|
||||
'precio_unitario' => $this->formatMoney($product?->precio),
|
||||
'product_id' => $product?->id,
|
||||
'product_variant_id' => $this->producto_variante_id,
|
||||
'product' => $product === null ? null : [
|
||||
'precio_unitario' => $this->formatMoney($precio),
|
||||
'buyable_type' => $this->mapBuyableTypeToAlias($this->buyable_type),
|
||||
'buyable_id' => $this->buyable_id,
|
||||
'product' => $buyable === null ? null : [
|
||||
'nombre' => $productName,
|
||||
'imagen' => $imageUrl,
|
||||
],
|
||||
];
|
||||
}
|
||||
|
||||
protected function mapBuyableTypeToAlias(?string $type): string
|
||||
{
|
||||
return match ($type) {
|
||||
\App\Domains\Catalog\Models\ProductVariant::class => 'variant',
|
||||
\App\Domains\Bundle\Models\Bundle::class => 'bundle',
|
||||
default => 'unknown',
|
||||
};
|
||||
}
|
||||
|
||||
protected function formatMoney(float|int|string|null $amount): string
|
||||
{
|
||||
return number_format((float) ($amount ?? 0), 2, '.', '');
|
||||
|
||||
@@ -2,11 +2,12 @@
|
||||
|
||||
namespace App\Domains\Cart\Resources;
|
||||
|
||||
use App\Domains\Cart\Models\Cart;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Http\Resources\Json\JsonResource;
|
||||
|
||||
/**
|
||||
* @mixin \App\Domains\Cart\Models\Cart
|
||||
* @mixin Cart
|
||||
*/
|
||||
class CartResource extends JsonResource
|
||||
{
|
||||
@@ -20,7 +21,7 @@ class CartResource extends JsonResource
|
||||
: collect();
|
||||
|
||||
$subtotal = $items->reduce(
|
||||
fn (float $carry, $item): float => $carry + ((float) ($item->variant?->product?->precio ?? 0) * $item->cantidad),
|
||||
fn (float $carry, $item): float => $carry + ((float) ($item->buyable?->getPrice() ?? 0) * $item->cantidad),
|
||||
0.0,
|
||||
);
|
||||
|
||||
|
||||
@@ -2,10 +2,14 @@
|
||||
|
||||
namespace App\Domains\Cart\Services;
|
||||
|
||||
use App\Domains\Cart\Models\Cart;
|
||||
use App\Domains\Auth\Models\User;
|
||||
use App\Domains\Bundle\Models\Bundle;
|
||||
use App\Domains\Cart\Models\Cart;
|
||||
use App\Domains\Catalog\Models\ProductVariant;
|
||||
use App\Domains\Tenant\Models\Tenant;
|
||||
use Illuminate\Database\Eloquent\Relations\MorphTo;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\Auth;
|
||||
use Illuminate\Support\Str;
|
||||
use Symfony\Component\HttpFoundation\Cookie;
|
||||
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
|
||||
@@ -32,12 +36,12 @@ class CartService
|
||||
/**
|
||||
* @return array{cart: Cart, guest_token: ?string}
|
||||
*/
|
||||
public function addItem(Tenant $tenant, Request $request, int $productVariantId, int $quantity): array
|
||||
public function addItem(Tenant $tenant, Request $request, string $buyableType, int $buyableId, int $quantity): array
|
||||
{
|
||||
$resolvedIdentity = $this->resolveIdentity($request, true);
|
||||
$identity = $resolvedIdentity['identity'];
|
||||
$cart = $this->findOrCreateCart($tenant, $identity);
|
||||
$cart->addItem($productVariantId, $quantity);
|
||||
$cart->addItem($buyableType, $buyableId, $quantity);
|
||||
|
||||
return [
|
||||
'cart' => $this->loadCart($cart),
|
||||
@@ -45,20 +49,20 @@ class CartService
|
||||
];
|
||||
}
|
||||
|
||||
public function updateItemQuantity(Tenant $tenant, Request $request, int $productVariantId, int $quantity): Cart
|
||||
public function updateItemQuantity(Tenant $tenant, Request $request, int $cartItemId, int $quantity): Cart
|
||||
{
|
||||
$identity = $this->requireIdentity($request);
|
||||
$cart = $this->findCartOrFail($tenant, $identity);
|
||||
$cart->updateItem($productVariantId, $quantity);
|
||||
$cart->updateItem($cartItemId, $quantity);
|
||||
|
||||
return $this->loadCart($cart);
|
||||
}
|
||||
|
||||
public function removeItem(Tenant $tenant, Request $request, int $productVariantId): Cart
|
||||
public function removeItem(Tenant $tenant, Request $request, int $cartItemId): Cart
|
||||
{
|
||||
$identity = $this->requireIdentity($request);
|
||||
$cart = $this->findCartOrFail($tenant, $identity);
|
||||
$cart->removeItem($productVariantId);
|
||||
$cart->removeItem($cartItemId);
|
||||
|
||||
return $this->loadCart($cart);
|
||||
}
|
||||
@@ -93,9 +97,16 @@ class CartService
|
||||
protected function loadCart(Cart $cart): Cart
|
||||
{
|
||||
return $cart->fresh()->load([
|
||||
'items.variant.product',
|
||||
'items.variant.definitions.productAttribute.attribute',
|
||||
'items.variant.attachments',
|
||||
'items.buyable' => function (MorphTo $morphTo): void {
|
||||
$morphTo->morphWith([
|
||||
ProductVariant::class => [
|
||||
'product',
|
||||
'definitions.productAttribute.attribute',
|
||||
'attachments',
|
||||
],
|
||||
Bundle::class => ['items.variant'],
|
||||
]);
|
||||
},
|
||||
]);
|
||||
}
|
||||
|
||||
@@ -104,7 +115,7 @@ class CartService
|
||||
*/
|
||||
protected function resolveIdentity(Request $request, bool $generateGuestToken = false): ?array
|
||||
{
|
||||
$user = $request->user() ?? \Illuminate\Support\Facades\Auth::guard('sanctum')->user();
|
||||
$user = $request->user() ?? Auth::guard('sanctum')->user();
|
||||
|
||||
if ($user instanceof User) {
|
||||
return [
|
||||
@@ -201,5 +212,4 @@ class CartService
|
||||
|
||||
return Cart::query()->firstOrCreate($attributes, ['status' => 'active']);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -8,6 +8,6 @@ Route::prefix('tenants/{tenant:codigo}')
|
||||
->group(function (): void {
|
||||
Route::get('cart', [CartController::class, 'show']);
|
||||
Route::post('cart/items', [CartController::class, 'addItem']);
|
||||
Route::patch('cart/items/{productVariant}', [CartController::class, 'updateItemQuantity']);
|
||||
Route::delete('cart/items/{productVariant}', [CartController::class, 'removeItem']);
|
||||
Route::patch('cart/items/{cartItem}', [CartController::class, 'updateItemQuantity']);
|
||||
Route::delete('cart/items/{cartItem}', [CartController::class, 'removeItem']);
|
||||
});
|
||||
|
||||
@@ -4,6 +4,7 @@ namespace App\Domains\Catalog\Models;
|
||||
|
||||
use App\Domains\Attachable\Models\Attachment;
|
||||
use App\Domains\Catalog\Enums\InventoryPolicy;
|
||||
use App\Domains\Shared\Contracts\Buyable;
|
||||
use Illuminate\Database\Eloquent\Attributes\Fillable;
|
||||
use Illuminate\Database\Eloquent\Casts\Attribute;
|
||||
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
||||
@@ -23,7 +24,7 @@ use Illuminate\Database\Eloquent\Relations\HasMany;
|
||||
'minimum_use_date',
|
||||
'maximum_use_date',
|
||||
])]
|
||||
class ProductVariant extends Model
|
||||
class ProductVariant extends Model implements Buyable
|
||||
{
|
||||
use HasFactory;
|
||||
|
||||
@@ -87,6 +88,31 @@ class ProductVariant extends Model
|
||||
return ! $this->tracksInventory() || $this->availableQuantity() > 0;
|
||||
}
|
||||
|
||||
public function getPrice(): float
|
||||
{
|
||||
return (float) ($this->product->precio ?? 0.0);
|
||||
}
|
||||
|
||||
public function getName(): string
|
||||
{
|
||||
$name = $this->product?->nombre ?? 'Producto';
|
||||
|
||||
if ($this->relationLoaded('definitions') && $this->definitions->isNotEmpty()) {
|
||||
$definitions = $this->definitions->map(function ($def) {
|
||||
$attributeName = $def->productAttribute?->attribute?->nombre;
|
||||
$value = $def->value;
|
||||
|
||||
return $attributeName ? "{$attributeName}: {$value}" : $value;
|
||||
})->filter()->implode(', ');
|
||||
|
||||
if ($definitions !== '') {
|
||||
$name .= " ({$definitions})";
|
||||
}
|
||||
}
|
||||
|
||||
return $name;
|
||||
}
|
||||
|
||||
public function reserveStock(int $amount): void
|
||||
{
|
||||
if ($amount < 0) {
|
||||
|
||||
@@ -2,14 +2,20 @@
|
||||
|
||||
namespace App\Domains\Purchase\Controllers;
|
||||
|
||||
use App\Domains\Bundle\Models\Bundle;
|
||||
use App\Domains\Catalog\Models\ProductVariant;
|
||||
use App\Domains\Integration\Services\TelepagosIntegrationService;
|
||||
use App\Domains\Purchase\Models\Purchase;
|
||||
use App\Domains\Purchase\Requests\PaymentIntentRequest;
|
||||
use App\Domains\Purchase\Requests\StorePurchaseRequest;
|
||||
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\Database\Eloquent\Relations\MorphTo;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Collection;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
|
||||
|
||||
@@ -46,12 +52,17 @@ class PurchaseController extends Controller
|
||||
{
|
||||
$compra = $this->resolveScopedPurchase($tenant, $request->user()->id, $compra);
|
||||
|
||||
return PurchaseResource::make(
|
||||
$compra->loadMissing($this->purchaseDetailRelations())
|
||||
);
|
||||
$compra->loadMissing(['items', 'cart.items']);
|
||||
$this->loadBuyables($compra->items);
|
||||
|
||||
if ($compra->cart !== null) {
|
||||
$this->loadBuyables($compra->cart->items);
|
||||
}
|
||||
|
||||
return PurchaseResource::make($compra);
|
||||
}
|
||||
|
||||
public function paymentIntent(\App\Domains\Purchase\Requests\PaymentIntentRequest $request, Tenant $tenant, Purchase $compra): JsonResponse
|
||||
public function paymentIntent(PaymentIntentRequest $request, Tenant $tenant, Purchase $compra): JsonResponse
|
||||
{
|
||||
$compra = $this->resolveScopedPurchase($tenant, $request->user()->id, $compra);
|
||||
$method = $request->validated('method');
|
||||
@@ -63,7 +74,7 @@ class PurchaseController extends Controller
|
||||
]);
|
||||
|
||||
if ($method === 'transfer') {
|
||||
$telepagosService = new \App\Domains\Integration\Services\TelepagosIntegrationService();
|
||||
$telepagosService = new TelepagosIntegrationService;
|
||||
$telepagosService->forTenant($tenant->codigo);
|
||||
|
||||
try {
|
||||
@@ -81,13 +92,13 @@ class PurchaseController extends Controller
|
||||
]);
|
||||
} catch (\Exception $e) {
|
||||
return response()->json([
|
||||
'message' => 'Error getting account info: ' . $e->getMessage()
|
||||
'message' => 'Error getting account info: '.$e->getMessage(),
|
||||
], 500);
|
||||
}
|
||||
}
|
||||
|
||||
if ($method === 'qr') {
|
||||
$telepagosService = new \App\Domains\Integration\Services\TelepagosIntegrationService();
|
||||
$telepagosService = new TelepagosIntegrationService;
|
||||
$telepagosService->forTenant($tenant->codigo);
|
||||
|
||||
try {
|
||||
@@ -100,11 +111,11 @@ class PurchaseController extends Controller
|
||||
|
||||
$telepagosQr = $compra->telepagosQr()->create([
|
||||
'qr_order_id' => (string) ($qrResponse['qr_order_id'] ?? ''),
|
||||
'qr_code' => $qrResponse['qr_code'] ?? '',
|
||||
'qr_code' => $qrResponse['qr_code'] ?? '',
|
||||
]);
|
||||
} catch (\Exception $e) {
|
||||
return response()->json([
|
||||
'message' => 'Error generating QR: ' . $e->getMessage()
|
||||
'message' => 'Error generating QR: '.$e->getMessage(),
|
||||
], 500);
|
||||
}
|
||||
|
||||
@@ -143,15 +154,19 @@ class PurchaseController extends Controller
|
||||
/**
|
||||
* @return list<string>
|
||||
*/
|
||||
protected function purchaseDetailRelations(): array
|
||||
protected function loadBuyables(Collection $items): void
|
||||
{
|
||||
return [
|
||||
'items.variant.product',
|
||||
'items.variant.definitions.productAttribute.attribute',
|
||||
'items.variant.attachments',
|
||||
'cart.items.variant.product',
|
||||
'cart.items.variant.definitions.productAttribute.attribute',
|
||||
'cart.items.variant.attachments',
|
||||
];
|
||||
$items->load([
|
||||
'buyable' => function (MorphTo $morphTo): void {
|
||||
$morphTo->morphWith([
|
||||
ProductVariant::class => [
|
||||
'product',
|
||||
'definitions.productAttribute.attribute',
|
||||
'attachments',
|
||||
],
|
||||
Bundle::class => ['items.variant'],
|
||||
]);
|
||||
},
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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\Relations\HasOne;
|
||||
|
||||
#[Fillable([
|
||||
'cart_id',
|
||||
@@ -28,9 +29,13 @@ class Purchase extends Model
|
||||
use HasFactory;
|
||||
|
||||
public const STATUS_CREATED = 'created';
|
||||
|
||||
public const STATUS_PENDING_PAYMENT = 'pending_payment';
|
||||
|
||||
public const STATUS_PAID = 'paid';
|
||||
|
||||
public const STATUS_CANCELLED = 'cancelled';
|
||||
|
||||
public const STATUS_REJECTED = 'rejected';
|
||||
|
||||
protected $table = 'compras';
|
||||
@@ -77,7 +82,7 @@ class Purchase extends Model
|
||||
}
|
||||
|
||||
/**
|
||||
* @return \Illuminate\Database\Eloquent\Relations\HasOne<TelepagosQr, $this>
|
||||
* @return HasOne<TelepagosQr, $this>
|
||||
*/
|
||||
public function telepagosQr()
|
||||
{
|
||||
@@ -113,7 +118,7 @@ class Purchase extends Model
|
||||
|
||||
$cart = $this->relationLoaded('cart')
|
||||
? $this->getRelation('cart')
|
||||
: $this->cart()->with('items.variant.product')->first();
|
||||
: $this->cart()->with('items.buyable')->first();
|
||||
|
||||
if (! $cart) {
|
||||
return 0.0;
|
||||
|
||||
@@ -10,7 +10,8 @@ use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
|
||||
#[Fillable([
|
||||
'compra_id',
|
||||
'producto_variante_id',
|
||||
'buyable_id',
|
||||
'buyable_type',
|
||||
'cantidad',
|
||||
'precio_unitario',
|
||||
'discount_total',
|
||||
@@ -27,7 +28,8 @@ class PurchaseItem extends Model
|
||||
{
|
||||
return [
|
||||
'compra_id' => 'integer',
|
||||
'producto_variante_id' => 'integer',
|
||||
'buyable_id' => 'integer',
|
||||
'buyable_type' => 'string',
|
||||
'cantidad' => 'integer',
|
||||
'precio_unitario' => 'decimal:2',
|
||||
'discount_total' => 'decimal:2',
|
||||
@@ -45,10 +47,10 @@ class PurchaseItem extends Model
|
||||
}
|
||||
|
||||
/**
|
||||
* @return BelongsTo<ProductVariant, $this>
|
||||
* @return \Illuminate\Database\Eloquent\Relations\MorphTo
|
||||
*/
|
||||
public function variant(): BelongsTo
|
||||
public function buyable()
|
||||
{
|
||||
return $this->belongsTo(ProductVariant::class, 'producto_variante_id');
|
||||
return $this->morphTo();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,13 +2,16 @@
|
||||
|
||||
namespace App\Domains\Purchase\Resources;
|
||||
|
||||
use App\Domains\Bundle\Models\Bundle;
|
||||
use App\Domains\Cart\Models\CartItem;
|
||||
use App\Domains\Catalog\Models\ProductVariant;
|
||||
use App\Domains\Purchase\Models\PurchaseItem;
|
||||
use App\Domains\Shared\Contracts\Buyable;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Http\Resources\Json\JsonResource;
|
||||
|
||||
/**
|
||||
* @mixin \App\Domains\Purchase\Models\PurchaseItem|\App\Domains\Cart\Models\CartItem
|
||||
* @mixin PurchaseItem|CartItem
|
||||
*/
|
||||
class PurchaseItemResource extends JsonResource
|
||||
{
|
||||
@@ -17,30 +20,54 @@ class PurchaseItemResource extends JsonResource
|
||||
*/
|
||||
public function toArray(Request $request): array
|
||||
{
|
||||
$variant = $this->variant;
|
||||
$product = $variant?->product;
|
||||
/** @var Buyable|null $buyable */
|
||||
$buyable = $this->buyable;
|
||||
$quantity = (int) ($this->cantidad ?? 0);
|
||||
$unitPrice = $this->resolveUnitPrice();
|
||||
$lineTotal = $this->resolveLineTotal($unitPrice, $quantity);
|
||||
$variant = $buyable instanceof ProductVariant ? $buyable : null;
|
||||
|
||||
$imageUrl = null;
|
||||
$attributes = [];
|
||||
if ($this->buyable_type === ProductVariant::class && $buyable) {
|
||||
$imageUrl = $this->resolveImageUrl($buyable);
|
||||
$attributes = $this->resolveAttributes($buyable);
|
||||
}
|
||||
|
||||
return [
|
||||
'id' => $this->id,
|
||||
'quantity' => $quantity,
|
||||
'unit_price' => $this->formatMoney($unitPrice),
|
||||
'line_total' => $this->formatMoney($lineTotal),
|
||||
'product' => $product === null ? null : [
|
||||
'id' => $product->id,
|
||||
'nombre' => $product->nombre,
|
||||
'slug' => $product->slug,
|
||||
'imagen' => $this->resolveImageUrl(),
|
||||
'buyable_type' => $this->mapBuyableTypeToAlias($this->buyable_type),
|
||||
'buyable_id' => $this->buyable_id,
|
||||
'product' => $variant === null ? null : [
|
||||
'id' => $variant->product?->id,
|
||||
'nombre' => $variant->product?->nombre,
|
||||
'slug' => $variant->product?->slug,
|
||||
'imagen' => $imageUrl,
|
||||
],
|
||||
'variant' => $variant === null ? null : [
|
||||
'id' => $variant->id,
|
||||
'attributes' => $this->resolveAttributes(),
|
||||
'attributes' => $attributes,
|
||||
],
|
||||
'item_details' => $buyable === null ? null : [
|
||||
'nombre' => $buyable->getName(),
|
||||
'imagen' => $imageUrl,
|
||||
'attributes' => $attributes,
|
||||
],
|
||||
];
|
||||
}
|
||||
|
||||
protected function mapBuyableTypeToAlias(?string $type): string
|
||||
{
|
||||
return match ($type) {
|
||||
ProductVariant::class => 'variant',
|
||||
Bundle::class => 'bundle',
|
||||
default => 'unknown',
|
||||
};
|
||||
}
|
||||
|
||||
protected function resolveUnitPrice(): float
|
||||
{
|
||||
if ($this->resource instanceof PurchaseItem) {
|
||||
@@ -48,7 +75,7 @@ class PurchaseItemResource extends JsonResource
|
||||
}
|
||||
|
||||
if ($this->resource instanceof CartItem) {
|
||||
return (float) ($this->variant?->product?->precio ?? 0);
|
||||
return (float) ($this->buyable?->getPrice() ?? 0);
|
||||
}
|
||||
|
||||
return 0.0;
|
||||
@@ -63,15 +90,13 @@ class PurchaseItemResource extends JsonResource
|
||||
return $unitPrice * $quantity;
|
||||
}
|
||||
|
||||
protected function resolveImageUrl(): ?string
|
||||
protected function resolveImageUrl($buyable): ?string
|
||||
{
|
||||
$variant = $this->variant;
|
||||
|
||||
if ($variant === null || ! $variant->relationLoaded('attachments')) {
|
||||
if (! $buyable->relationLoaded('attachments')) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$attachment = $variant->attachments->first();
|
||||
$attachment = $buyable->attachments->first();
|
||||
|
||||
if ($attachment === null) {
|
||||
return null;
|
||||
@@ -83,15 +108,13 @@ class PurchaseItemResource extends JsonResource
|
||||
/**
|
||||
* @return array<int, array{name: string, value: mixed}>
|
||||
*/
|
||||
protected function resolveAttributes(): array
|
||||
protected function resolveAttributes($buyable): array
|
||||
{
|
||||
$variant = $this->variant;
|
||||
|
||||
if ($variant === null || ! $variant->relationLoaded('definitions')) {
|
||||
if (! $buyable->relationLoaded('definitions')) {
|
||||
return [];
|
||||
}
|
||||
|
||||
return $variant->definitions
|
||||
return $buyable->definitions
|
||||
->map(function ($definition): array {
|
||||
return [
|
||||
'name' => (string) ($definition->productAttribute?->attribute?->nombre ?? ''),
|
||||
|
||||
@@ -3,13 +3,14 @@
|
||||
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 \App\Domains\Purchase\Models\Purchase
|
||||
* @mixin Purchase
|
||||
*/
|
||||
class PurchaseResource extends JsonResource
|
||||
{
|
||||
@@ -87,7 +88,7 @@ class PurchaseResource extends JsonResource
|
||||
return (float) $item->precio_unitario * $item->cantidad;
|
||||
}
|
||||
|
||||
return (float) ($item->variant?->product?->precio ?? 0) * $item->cantidad;
|
||||
return (float) ($item->buyable?->getPrice() ?? 0) * $item->cantidad;
|
||||
}
|
||||
|
||||
protected function resolveItemTotal(PurchaseItem|CartItem $item): float
|
||||
|
||||
@@ -4,6 +4,7 @@ namespace App\Domains\Purchase\Services;
|
||||
|
||||
use App\Domains\Cart\Models\Cart;
|
||||
use App\Domains\Cart\Models\CartItem;
|
||||
use App\Domains\Bundle\Models\Bundle;
|
||||
use App\Domains\Catalog\Models\ProductVariant;
|
||||
use App\Domains\Purchase\Models\Purchase;
|
||||
use App\Domains\Tenant\Models\Tenant;
|
||||
@@ -29,7 +30,7 @@ class CheckoutService
|
||||
]);
|
||||
}
|
||||
|
||||
$cartItems->load('variant.product');
|
||||
$cartItems->load('buyable');
|
||||
$cart->setRelation('items', $cartItems);
|
||||
$totalAmount = $cart->getTotalAmount();
|
||||
|
||||
@@ -63,7 +64,7 @@ class CheckoutService
|
||||
$purchase->save();
|
||||
}
|
||||
|
||||
return $purchase->load(['items.variant.product', 'items.variant.definitions.productAttribute.attribute']);
|
||||
return $purchase->load(['items.buyable']);
|
||||
});
|
||||
}
|
||||
|
||||
@@ -82,7 +83,7 @@ class CheckoutService
|
||||
}
|
||||
|
||||
if (in_array($purchase->status, [Purchase::STATUS_PAID, Purchase::STATUS_CANCELLED, Purchase::STATUS_REJECTED], true)) {
|
||||
return $purchase->load(['items.variant.product', 'items.variant.definitions.productAttribute.attribute']);
|
||||
return $purchase->load(['items.buyable']);
|
||||
}
|
||||
|
||||
$purchase->update([
|
||||
@@ -90,7 +91,7 @@ class CheckoutService
|
||||
'total' => $purchase->calculateCurrentTotalAmount(),
|
||||
]);
|
||||
|
||||
return $purchase->load(['items.variant.product', 'items.variant.definitions.productAttribute.attribute']);
|
||||
return $purchase->load(['items.buyable']);
|
||||
});
|
||||
}
|
||||
|
||||
@@ -123,42 +124,37 @@ class CheckoutService
|
||||
]);
|
||||
}
|
||||
|
||||
$cartItems->load('variant.product');
|
||||
$variants = $this->resolveTenantVariants($purchase->tenant, $cartItems);
|
||||
$purchaseItemsPayload = $this->buildPurchaseItemsPayload($cartItems, $variants);
|
||||
$cartItems->load('buyable');
|
||||
$this->verifyTenantBuyables($purchase->tenant, $cartItems);
|
||||
$purchaseItemsPayload = $this->buildPurchaseItemsPayload($cartItems);
|
||||
|
||||
$purchase->items()->createMany($purchaseItemsPayload);
|
||||
$this->completeCartConversion($cart, $cartItems, $variants);
|
||||
$this->completeCartConversion($cart, $cartItems);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* @return Collection<int, ProductVariant>
|
||||
*/
|
||||
protected function resolveTenantVariants(Tenant $tenant, Collection $cartItems): Collection
|
||||
protected function verifyTenantBuyables(Tenant $tenant, Collection $cartItems): void
|
||||
{
|
||||
$variantIds = $cartItems
|
||||
->pluck('producto_variante_id')
|
||||
->map(static fn (mixed $id): int => (int) $id)
|
||||
->unique()
|
||||
->values();
|
||||
foreach ($cartItems as $item) {
|
||||
$buyable = $item->buyable;
|
||||
if ($buyable === null) {
|
||||
throw ValidationException::withMessages([
|
||||
'cart_id' => 'One or more buyables could not be loaded.',
|
||||
]);
|
||||
}
|
||||
|
||||
/** @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 ($item->buyable_type === ProductVariant::class && $buyable->product->tenant_codigo !== $tenant->codigo) {
|
||||
throw ValidationException::withMessages([
|
||||
'cart_id' => 'One or more product variants do not belong to the tenant.',
|
||||
]);
|
||||
}
|
||||
|
||||
if ($variants->count() !== $variantIds->count()) {
|
||||
throw ValidationException::withMessages([
|
||||
'cart_id' => 'One or more product variants do not belong to the tenant.',
|
||||
]);
|
||||
if ($item->buyable_type === Bundle::class && $buyable->tenant_codigo !== $tenant->codigo) {
|
||||
throw ValidationException::withMessages([
|
||||
'cart_id' => 'One or more bundles do not belong to the tenant.',
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
return $variants;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -187,20 +183,19 @@ class CheckoutService
|
||||
|
||||
/**
|
||||
* @param Collection<int, CartItem> $cartItems
|
||||
* @param Collection<int, ProductVariant> $variants
|
||||
* @return array<int, array<string, mixed>>
|
||||
*/
|
||||
protected function buildPurchaseItemsPayload(Collection $cartItems, Collection $variants): array
|
||||
protected function buildPurchaseItemsPayload(Collection $cartItems): array
|
||||
{
|
||||
return $cartItems
|
||||
->map(function (CartItem $item) use ($variants): array {
|
||||
/** @var ProductVariant $variant */
|
||||
$variant = $variants->get((int) $item['producto_variante_id']);
|
||||
->map(function (CartItem $item): array {
|
||||
$buyable = $item->buyable;
|
||||
$quantity = (int) $item['cantidad'];
|
||||
$unitPrice = (float) ($variant->product?->precio ?? 0);
|
||||
$unitPrice = $buyable?->getPrice() ?? 0;
|
||||
|
||||
return [
|
||||
'producto_variante_id' => $variant->getKey(),
|
||||
'buyable_type' => $item->buyable_type,
|
||||
'buyable_id' => $item->buyable_id,
|
||||
'cantidad' => $quantity,
|
||||
'precio_unitario' => $unitPrice,
|
||||
'discount_total' => null,
|
||||
@@ -213,17 +208,15 @@ class CheckoutService
|
||||
|
||||
/**
|
||||
* @param Collection<int, CartItem> $cartItems
|
||||
* @param Collection<int, ProductVariant> $variants
|
||||
*/
|
||||
protected function completeCartConversion(Cart $cart, Collection $cartItems, Collection $variants): void
|
||||
protected function completeCartConversion(Cart $cart, Collection $cartItems): void
|
||||
{
|
||||
foreach ($cartItems as $item) {
|
||||
/** @var ProductVariant $variant */
|
||||
$variant = $variants->get((int) $item->producto_variante_id);
|
||||
$buyable = $item->buyable;
|
||||
$quantity = (int) $item->cantidad;
|
||||
|
||||
try {
|
||||
$variant->buy($quantity);
|
||||
$buyable->buy($quantity);
|
||||
} catch (\InvalidArgumentException $exception) {
|
||||
throw ValidationException::withMessages([
|
||||
'cart_id' => 'The selected cart has inconsistent stock state.',
|
||||
|
||||
20
app/Domains/Shared/Contracts/Buyable.php
Normal file
20
app/Domains/Shared/Contracts/Buyable.php
Normal file
@@ -0,0 +1,20 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Shared\Contracts;
|
||||
|
||||
interface Buyable
|
||||
{
|
||||
public function getPrice(): float;
|
||||
|
||||
public function getName(): string;
|
||||
|
||||
public function availableQuantity(): ?int;
|
||||
|
||||
public function reserveStock(int $amount): void;
|
||||
|
||||
public function decrementReservedStock(int $amount): void;
|
||||
|
||||
public function buy(int $amount): void;
|
||||
|
||||
public function validateStock(): void;
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Database\Migrations\Migration;
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
|
||||
return new class extends Migration
|
||||
{
|
||||
/**
|
||||
* Run the migrations.
|
||||
*/
|
||||
public function up(): void
|
||||
{
|
||||
Schema::create('bundles', function (Blueprint $table) {
|
||||
$table->id();
|
||||
$table->string('tenant_codigo', 10);
|
||||
$table->string('nombre');
|
||||
$table->text('descripcion')->nullable();
|
||||
$table->decimal('precio', 10, 2);
|
||||
$table->timestamps();
|
||||
|
||||
$table->foreign('tenant_codigo')->references('codigo')->on('tenants')->onDelete('cascade');
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Reverse the migrations.
|
||||
*/
|
||||
public function down(): void
|
||||
{
|
||||
Schema::dropIfExists('bundles');
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,30 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Database\Migrations\Migration;
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
|
||||
return new class extends Migration
|
||||
{
|
||||
/**
|
||||
* Run the migrations.
|
||||
*/
|
||||
public function up(): void
|
||||
{
|
||||
Schema::create('bundle_items', function (Blueprint $table) {
|
||||
$table->id();
|
||||
$table->foreignId('bundle_id')->constrained('bundles')->onDelete('cascade');
|
||||
$table->foreignId('producto_variante_id')->constrained('productos_variantes')->onDelete('cascade');
|
||||
$table->integer('cantidad');
|
||||
$table->timestamps();
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Reverse the migrations.
|
||||
*/
|
||||
public function down(): void
|
||||
{
|
||||
Schema::dropIfExists('bundle_items');
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,58 @@
|
||||
<?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
|
||||
{
|
||||
/**
|
||||
* Run the migrations.
|
||||
*/
|
||||
public function up(): void
|
||||
{
|
||||
Schema::table('carrito_items', function (Blueprint $table) {
|
||||
$table->string('buyable_type')->nullable();
|
||||
$table->unsignedBigInteger('buyable_id')->nullable();
|
||||
$table->index('cart_id');
|
||||
});
|
||||
|
||||
// Copy existing data
|
||||
DB::table('carrito_items')->update([
|
||||
'buyable_type' => 'App\Domains\Catalog\Models\ProductVariant',
|
||||
'buyable_id' => DB::raw('producto_variante_id'),
|
||||
]);
|
||||
|
||||
Schema::table('carrito_items', function (Blueprint $table) {
|
||||
$table->dropForeign(['producto_variante_id']);
|
||||
});
|
||||
|
||||
Schema::table('carrito_items', function (Blueprint $table) {
|
||||
$table->dropUnique(['cart_id', 'producto_variante_id']);
|
||||
$table->dropColumn('producto_variante_id');
|
||||
$table->unique(['cart_id', 'buyable_type', 'buyable_id']);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Reverse the migrations.
|
||||
*/
|
||||
public function down(): void
|
||||
{
|
||||
Schema::table('carrito_items', function (Blueprint $table) {
|
||||
$table->dropUnique(['cart_id', 'buyable_type', 'buyable_id']);
|
||||
$table->foreignId('producto_variante_id')->nullable()->constrained('productos_variantes')->onDelete('cascade');
|
||||
});
|
||||
|
||||
DB::table('carrito_items')->update([
|
||||
'producto_variante_id' => DB::raw('buyable_id'),
|
||||
]);
|
||||
|
||||
Schema::table('carrito_items', function (Blueprint $table) {
|
||||
$table->dropColumn(['buyable_type', 'buyable_id']);
|
||||
$table->dropIndex(['cart_id']);
|
||||
$table->unique(['cart_id', 'producto_variante_id']);
|
||||
});
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,48 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Database\Migrations\Migration;
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
|
||||
return new class extends Migration
|
||||
{
|
||||
/**
|
||||
* Run the migrations.
|
||||
*/
|
||||
public function up(): void
|
||||
{
|
||||
Schema::table('compra_items', function (Blueprint $table) {
|
||||
$table->string('buyable_type')->nullable();
|
||||
$table->unsignedBigInteger('buyable_id')->nullable();
|
||||
});
|
||||
|
||||
// Copy existing data
|
||||
\Illuminate\Support\Facades\DB::table('compra_items')->update([
|
||||
'buyable_type' => 'App\Domains\Catalog\Models\ProductVariant',
|
||||
'buyable_id' => \Illuminate\Support\Facades\DB::raw('producto_variante_id'),
|
||||
]);
|
||||
|
||||
Schema::table('compra_items', function (Blueprint $table) {
|
||||
$table->dropForeign(['producto_variante_id']);
|
||||
$table->dropColumn('producto_variante_id');
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Reverse the migrations.
|
||||
*/
|
||||
public function down(): void
|
||||
{
|
||||
Schema::table('compra_items', function (Blueprint $table) {
|
||||
$table->foreignId('producto_variante_id')->nullable()->constrained('productos_variantes')->onDelete('cascade');
|
||||
});
|
||||
|
||||
\Illuminate\Support\Facades\DB::table('compra_items')->update([
|
||||
'producto_variante_id' => \Illuminate\Support\Facades\DB::raw('buyable_id'),
|
||||
]);
|
||||
|
||||
Schema::table('compra_items', function (Blueprint $table) {
|
||||
$table->dropColumn(['buyable_type', 'buyable_id']);
|
||||
});
|
||||
}
|
||||
};
|
||||
@@ -60,7 +60,8 @@ class CartControllerTest extends TestCase
|
||||
]);
|
||||
|
||||
$response = $this->postJson('/api/tenants/acme/cart/items', [
|
||||
'product_variant_id' => $variant->id,
|
||||
'buyable_type' => 'variant',
|
||||
'buyable_id' => $variant->id,
|
||||
'cantidad' => 2,
|
||||
]);
|
||||
|
||||
@@ -70,7 +71,8 @@ class CartControllerTest extends TestCase
|
||||
->assertJsonPath('data.tenant_codigo', 'acme')
|
||||
->assertJsonPath('data.items.0.cantidad', 2)
|
||||
->assertJsonPath('data.items.0.precio_unitario', '49.90')
|
||||
->assertJsonPath('data.items.0.product_id', $variant->product->id)
|
||||
->assertJsonPath('data.items.0.buyable_type', 'variant')
|
||||
->assertJsonPath('data.items.0.buyable_id', $variant->id)
|
||||
->assertJsonPath('data.items.0.product.nombre', 'Shirt acme (Color: Red)')
|
||||
->assertJsonPath('data.items.0.product.imagen', null)
|
||||
->assertJsonPath('data.subtotal', '99.80');
|
||||
@@ -82,7 +84,8 @@ class CartControllerTest extends TestCase
|
||||
]);
|
||||
|
||||
$this->assertDatabaseHas('carrito_items', [
|
||||
'producto_variante_id' => $variant->id,
|
||||
'buyable_type' => ProductVariant::class,
|
||||
'buyable_id' => $variant->id,
|
||||
'cantidad' => 2,
|
||||
]);
|
||||
|
||||
@@ -98,7 +101,8 @@ class CartControllerTest extends TestCase
|
||||
$variant = $this->createVariantForTenant('acme', 12, '25.00');
|
||||
|
||||
$firstResponse = $this->postJson('/api/tenants/acme/cart/items', [
|
||||
'product_variant_id' => $variant->id,
|
||||
'buyable_type' => 'variant',
|
||||
'buyable_id' => $variant->id,
|
||||
'cantidad' => 2,
|
||||
]);
|
||||
|
||||
@@ -112,7 +116,8 @@ class CartControllerTest extends TestCase
|
||||
[],
|
||||
['HTTP_Accept' => 'application/json', 'CONTENT_TYPE' => 'application/json'],
|
||||
json_encode([
|
||||
'product_variant_id' => $variant->id,
|
||||
'buyable_type' => 'variant',
|
||||
'buyable_id' => $variant->id,
|
||||
'cantidad' => 3,
|
||||
])
|
||||
);
|
||||
@@ -125,7 +130,8 @@ class CartControllerTest extends TestCase
|
||||
$this->assertDatabaseCount('carritos', 1);
|
||||
$this->assertDatabaseCount('carrito_items', 1);
|
||||
$this->assertDatabaseHas('carrito_items', [
|
||||
'producto_variante_id' => $variant->id,
|
||||
'buyable_type' => ProductVariant::class,
|
||||
'buyable_id' => $variant->id,
|
||||
'cantidad' => 5,
|
||||
]);
|
||||
$this->assertDatabaseHas('productos_variantes', [
|
||||
@@ -140,15 +146,17 @@ class CartControllerTest extends TestCase
|
||||
$variant = $this->createVariantForTenant('acme', 10, '15.00');
|
||||
|
||||
$createResponse = $this->postJson('/api/tenants/acme/cart/items', [
|
||||
'product_variant_id' => $variant->id,
|
||||
'buyable_type' => 'variant',
|
||||
'buyable_id' => $variant->id,
|
||||
'cantidad' => 2,
|
||||
]);
|
||||
|
||||
$guestToken = $createResponse->getCookie('guest_token', false)?->getValue();
|
||||
$cartItemId = $createResponse->json('data.items.0.id');
|
||||
|
||||
$response = $this->call(
|
||||
'PATCH',
|
||||
"/api/tenants/acme/cart/items/{$variant->id}",
|
||||
"/api/tenants/acme/cart/items/{$cartItemId}",
|
||||
[],
|
||||
['guest_token' => $guestToken],
|
||||
[],
|
||||
@@ -164,7 +172,8 @@ class CartControllerTest extends TestCase
|
||||
->assertJsonPath('data.subtotal', '75.00');
|
||||
|
||||
$this->assertDatabaseHas('carrito_items', [
|
||||
'producto_variante_id' => $variant->id,
|
||||
'buyable_type' => ProductVariant::class,
|
||||
'buyable_id' => $variant->id,
|
||||
'cantidad' => 5,
|
||||
]);
|
||||
$this->assertDatabaseHas('productos_variantes', [
|
||||
@@ -179,15 +188,17 @@ class CartControllerTest extends TestCase
|
||||
$variant = $this->createVariantForTenant('acme', 10, '15.00');
|
||||
|
||||
$createResponse = $this->postJson('/api/tenants/acme/cart/items', [
|
||||
'product_variant_id' => $variant->id,
|
||||
'buyable_type' => 'variant',
|
||||
'buyable_id' => $variant->id,
|
||||
'cantidad' => 4,
|
||||
]);
|
||||
|
||||
$guestToken = $createResponse->getCookie('guest_token', false)?->getValue();
|
||||
$cartItemId = $createResponse->json('data.items.0.id');
|
||||
|
||||
$response = $this->call(
|
||||
'DELETE',
|
||||
"/api/tenants/acme/cart/items/{$variant->id}",
|
||||
"/api/tenants/acme/cart/items/{$cartItemId}",
|
||||
[],
|
||||
['guest_token' => $guestToken],
|
||||
[],
|
||||
@@ -216,14 +227,16 @@ class CartControllerTest extends TestCase
|
||||
|
||||
$this->actingAs($user)
|
||||
->postJson('/api/tenants/acme/cart/items', [
|
||||
'product_variant_id' => $acmeVariantA->id,
|
||||
'buyable_type' => 'variant',
|
||||
'buyable_id' => $acmeVariantA->id,
|
||||
'cantidad' => 1,
|
||||
])
|
||||
->assertOk();
|
||||
|
||||
$this->actingAs($user)
|
||||
->postJson('/api/tenants/acme/cart/items', [
|
||||
'product_variant_id' => $acmeVariantB->id,
|
||||
'buyable_type' => 'variant',
|
||||
'buyable_id' => $acmeVariantB->id,
|
||||
'cantidad' => 2,
|
||||
])
|
||||
->assertOk()
|
||||
@@ -231,7 +244,8 @@ class CartControllerTest extends TestCase
|
||||
|
||||
$this->actingAs($user)
|
||||
->postJson('/api/tenants/globex/cart/items', [
|
||||
'product_variant_id' => $globexVariant->id,
|
||||
'buyable_type' => 'variant',
|
||||
'buyable_id' => $globexVariant->id,
|
||||
'cantidad' => 1,
|
||||
])
|
||||
->assertOk();
|
||||
@@ -253,7 +267,8 @@ class CartControllerTest extends TestCase
|
||||
$otherVariant = $this->createVariantForTenant('globex', 10, '20.00');
|
||||
|
||||
$this->postJson('/api/tenants/acme/cart/items', [
|
||||
'product_variant_id' => $otherVariant->id,
|
||||
'buyable_type' => 'variant',
|
||||
'buyable_id' => $otherVariant->id,
|
||||
'cantidad' => 1,
|
||||
])->assertNotFound();
|
||||
}
|
||||
@@ -275,16 +290,19 @@ class CartControllerTest extends TestCase
|
||||
$variant = $this->createVariantForTenant('acme', 2, '10.00');
|
||||
|
||||
$this->postJson('/api/tenants/acme/cart/items', [
|
||||
'product_variant_id' => $variant->id,
|
||||
'buyable_type' => 'variant',
|
||||
'buyable_id' => $variant->id,
|
||||
'cantidad' => 0,
|
||||
])->assertUnprocessable()->assertJsonValidationErrors(['cantidad']);
|
||||
|
||||
$response = $this->postJson('/api/tenants/acme/cart/items', [
|
||||
'product_variant_id' => $variant->id,
|
||||
'buyable_type' => 'variant',
|
||||
'buyable_id' => $variant->id,
|
||||
'cantidad' => 2,
|
||||
]);
|
||||
|
||||
$guestToken = $response->getCookie('guest_token', false)?->getValue();
|
||||
$cartItemId = $response->json('data.items.0.id');
|
||||
|
||||
$response1 = $this->call(
|
||||
'POST',
|
||||
@@ -294,7 +312,8 @@ class CartControllerTest extends TestCase
|
||||
[],
|
||||
['HTTP_Accept' => 'application/json', 'CONTENT_TYPE' => 'application/json'],
|
||||
json_encode([
|
||||
'product_variant_id' => $variant->id,
|
||||
'buyable_type' => 'variant',
|
||||
'buyable_id' => $variant->id,
|
||||
'cantidad' => 1,
|
||||
])
|
||||
);
|
||||
@@ -305,7 +324,7 @@ class CartControllerTest extends TestCase
|
||||
|
||||
$response2 = $this->call(
|
||||
'PATCH',
|
||||
"/api/tenants/acme/cart/items/{$variant->id}",
|
||||
"/api/tenants/acme/cart/items/{$cartItemId}",
|
||||
[],
|
||||
['guest_token' => $guestToken],
|
||||
[],
|
||||
@@ -320,6 +339,32 @@ class CartControllerTest extends TestCase
|
||||
->assertJsonValidationErrors(['cantidad' => 'El máximo que se puede agregar es 2.']);
|
||||
}
|
||||
|
||||
public function test_it_only_accepts_buyable_identity_when_adding_an_item(): void
|
||||
{
|
||||
$variant = $this->createVariantForTenant('acme', 10, '10.00');
|
||||
|
||||
$this->postJson('/api/tenants/acme/cart/items', [
|
||||
'product_variant_id' => $variant->id,
|
||||
'cantidad' => 1,
|
||||
])->assertUnprocessable()
|
||||
->assertJsonValidationErrors(['buyable_type', 'buyable_id']);
|
||||
|
||||
$createResponse = $this->postJson('/api/tenants/acme/cart/items', [
|
||||
'buyable_type' => 'variant',
|
||||
'buyable_id' => $variant->id,
|
||||
'cantidad' => 1,
|
||||
])->assertOk();
|
||||
|
||||
$cartItemId = $createResponse->json('data.items.0.id');
|
||||
|
||||
$this->patchJson("/api/tenants/acme/cart/items/{$cartItemId}", [
|
||||
'cantidad' => 2,
|
||||
'buyable_type' => 'variant',
|
||||
'buyable_id' => $variant->id,
|
||||
])->assertUnprocessable()
|
||||
->assertJsonValidationErrors(['buyable_type', 'buyable_id']);
|
||||
}
|
||||
|
||||
public function test_unlimited_inventory_can_be_reserved_updated_and_released_without_real_stock(): void
|
||||
{
|
||||
$variant = $this->createVariantForTenant(
|
||||
@@ -331,11 +376,13 @@ class CartControllerTest extends TestCase
|
||||
);
|
||||
|
||||
$response = $this->postJson('/api/tenants/acme/cart/items', [
|
||||
'product_variant_id' => $variant->id,
|
||||
'buyable_type' => 'variant',
|
||||
'buyable_id' => $variant->id,
|
||||
'cantidad' => 100,
|
||||
])->assertOk();
|
||||
|
||||
$guestToken = $response->getCookie('guest_token', false)?->getValue();
|
||||
$cartItemId = $response->json('data.items.0.id');
|
||||
$this->assertDatabaseHas('productos_variantes', [
|
||||
'id' => $variant->id,
|
||||
'stock_real' => 0,
|
||||
@@ -344,7 +391,7 @@ class CartControllerTest extends TestCase
|
||||
|
||||
$this->call(
|
||||
'PATCH',
|
||||
"/api/tenants/acme/cart/items/{$variant->id}",
|
||||
"/api/tenants/acme/cart/items/{$cartItemId}",
|
||||
[],
|
||||
['guest_token' => $guestToken],
|
||||
[],
|
||||
@@ -360,7 +407,7 @@ class CartControllerTest extends TestCase
|
||||
|
||||
$this->call(
|
||||
'DELETE',
|
||||
"/api/tenants/acme/cart/items/{$variant->id}",
|
||||
"/api/tenants/acme/cart/items/{$cartItemId}",
|
||||
[],
|
||||
['guest_token' => $guestToken],
|
||||
[],
|
||||
|
||||
@@ -113,7 +113,8 @@ class TelepagosWebhookTest extends TestCase
|
||||
|
||||
$this->assertDatabaseHas('compra_items', [
|
||||
'compra_id' => $matchingPurchase->id,
|
||||
'producto_variante_id' => $variant->id,
|
||||
'buyable_type' => ProductVariant::class,
|
||||
'buyable_id' => $variant->id,
|
||||
'cantidad' => 1,
|
||||
'total' => 50,
|
||||
]);
|
||||
@@ -201,7 +202,7 @@ class TelepagosWebhookTest extends TestCase
|
||||
'status' => 'active',
|
||||
]);
|
||||
|
||||
$cart->addItem($variantId, $quantity);
|
||||
$cart->addItem(ProductVariant::class, $variantId, $quantity);
|
||||
|
||||
/** @var CheckoutService $checkoutService */
|
||||
$checkoutService = app(CheckoutService::class);
|
||||
|
||||
@@ -51,7 +51,8 @@ class StorePurchaseTest extends TestCase
|
||||
|
||||
$cartResponse = $this->actingAs($user, 'sanctum')
|
||||
->postJson('/api/tenants/sonder/cart/items', [
|
||||
'product_variant_id' => $variant->id,
|
||||
'buyable_type' => 'variant',
|
||||
'buyable_id' => $variant->id,
|
||||
'cantidad' => 2,
|
||||
])
|
||||
->assertOk();
|
||||
@@ -111,7 +112,8 @@ class StorePurchaseTest extends TestCase
|
||||
]);
|
||||
$this->assertDatabaseHas('carrito_items', [
|
||||
'cart_id' => $cartId,
|
||||
'producto_variante_id' => $variant->id,
|
||||
'buyable_type' => ProductVariant::class,
|
||||
'buyable_id' => $variant->id,
|
||||
'cantidad' => 2,
|
||||
]);
|
||||
$this->assertDatabaseHas('productos_variantes', [
|
||||
@@ -131,7 +133,8 @@ class StorePurchaseTest extends TestCase
|
||||
|
||||
$cartId = $this->actingAs($user, 'sanctum')
|
||||
->postJson('/api/tenants/sonder/cart/items', [
|
||||
'product_variant_id' => $variant->id,
|
||||
'buyable_type' => 'variant',
|
||||
'buyable_id' => $variant->id,
|
||||
'cantidad' => 2,
|
||||
])
|
||||
->assertOk()
|
||||
@@ -280,7 +283,8 @@ class StorePurchaseTest extends TestCase
|
||||
$purchase = $this->createCheckoutPurchase($user, 'sonder', $variant, 2);
|
||||
|
||||
$purchase->items()->create([
|
||||
'producto_variante_id' => $variant->id,
|
||||
'buyable_type' => ProductVariant::class,
|
||||
'buyable_id' => $variant->id,
|
||||
'cantidad' => 1,
|
||||
'precio_unitario' => '50.00',
|
||||
'discount_total' => null,
|
||||
@@ -326,7 +330,8 @@ class StorePurchaseTest extends TestCase
|
||||
|
||||
$cartId = $this->actingAs($owner, 'sanctum')
|
||||
->postJson('/api/tenants/sonder/cart/items', [
|
||||
'product_variant_id' => $variant->id,
|
||||
'buyable_type' => 'variant',
|
||||
'buyable_id' => $variant->id,
|
||||
'cantidad' => 1,
|
||||
])
|
||||
->assertOk()
|
||||
@@ -352,7 +357,8 @@ class StorePurchaseTest extends TestCase
|
||||
|
||||
$cartId = $this->actingAs($user, 'sanctum')
|
||||
->postJson('/api/tenants/globex/cart/items', [
|
||||
'product_variant_id' => $variant->id,
|
||||
'buyable_type' => 'variant',
|
||||
'buyable_id' => $variant->id,
|
||||
'cantidad' => 1,
|
||||
])
|
||||
->assertOk()
|
||||
@@ -492,7 +498,7 @@ class StorePurchaseTest extends TestCase
|
||||
'status' => 'active',
|
||||
]);
|
||||
|
||||
$cart->addItem($variant->id, $quantity);
|
||||
$cart->addItem(ProductVariant::class, $variant->id, $quantity);
|
||||
|
||||
return app(CheckoutService::class)->startCheckout($tenant, $user->id, [
|
||||
'cart_id' => $cart->id,
|
||||
|
||||
Reference in New Issue
Block a user