Compare commits
8 Commits
341cc16ee8
...
feature/va
| Author | SHA1 | Date | |
|---|---|---|---|
| 6fc6ed1fac | |||
| c05206cc51 | |||
| 480ee70393 | |||
| ceb1e2b04a | |||
| 1d56d27350 | |||
| 18c80b075b | |||
| 10157d7c63 | |||
| 716d8e447c |
@@ -2,15 +2,14 @@
|
||||
|
||||
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;
|
||||
use Illuminate\Database\Eloquent\Casts\Attribute;
|
||||
|
||||
use App\Domains\Shared\Contracts\Buyable;
|
||||
|
||||
#[Fillable([
|
||||
'tenant_codigo',
|
||||
@@ -59,36 +58,33 @@ class Bundle extends Model implements Buyable
|
||||
return $this->nombre ?? 'Bundle';
|
||||
}
|
||||
|
||||
public function incrementRealStock(int $amount): void
|
||||
public function availableQuantity(): ?int
|
||||
{
|
||||
if ($amount < 0) {
|
||||
throw new \InvalidArgumentException('El monto a incrementar debe ser positivo.');
|
||||
if ($this->items->isEmpty()) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
$availableQuantities = [];
|
||||
|
||||
foreach ($this->items as $item) {
|
||||
$item->variant->incrementRealStock($amount * $item->cantidad);
|
||||
$variantQuantity = $item->variant?->availableQuantity();
|
||||
|
||||
if ($variantQuantity !== null) {
|
||||
$availableQuantities[] = intdiv($variantQuantity, $item->cantidad);
|
||||
}
|
||||
}
|
||||
|
||||
return $availableQuantities === [] ? null : min($availableQuantities);
|
||||
}
|
||||
|
||||
public function decrementRealStock(int $amount): void
|
||||
public function reserveStock(int $amount): void
|
||||
{
|
||||
if ($amount < 0) {
|
||||
throw new \InvalidArgumentException('El monto a decrementar debe ser positivo.');
|
||||
throw new \InvalidArgumentException('El monto a reservar debe ser positivo.');
|
||||
}
|
||||
|
||||
foreach ($this->items as $item) {
|
||||
$item->variant->decrementRealStock($amount * $item->cantidad);
|
||||
}
|
||||
}
|
||||
|
||||
public function incrementReservedStock(int $amount): void
|
||||
{
|
||||
if ($amount < 0) {
|
||||
throw new \InvalidArgumentException('El monto a incrementar debe ser positivo.');
|
||||
}
|
||||
|
||||
foreach ($this->items as $item) {
|
||||
$item->variant->incrementReservedStock($amount * $item->cantidad);
|
||||
$item->variant->reserveStock($amount * $item->cantidad);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -103,43 +99,28 @@ class Bundle extends Model implements Buyable
|
||||
}
|
||||
}
|
||||
|
||||
public function confirmReservedStock(int $amount): void
|
||||
public function buy(int $amount): void
|
||||
{
|
||||
if ($amount < 0) {
|
||||
throw new \InvalidArgumentException('El monto a confirmar debe ser positivo.');
|
||||
throw new \InvalidArgumentException('El monto a comprar debe ser positivo.');
|
||||
}
|
||||
|
||||
foreach ($this->items as $item) {
|
||||
$item->variant->confirmReservedStock($amount * $item->cantidad);
|
||||
$item->variant->buy($amount * $item->cantidad);
|
||||
}
|
||||
}
|
||||
|
||||
public function validateStock(): void
|
||||
{
|
||||
if ($this->stock_tecnico <= 0) {
|
||||
throw new \InvalidArgumentException('El bundle no tiene stock técnico disponible.');
|
||||
$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(function () {
|
||||
if ($this->items->isEmpty()) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
$minStock = PHP_INT_MAX;
|
||||
foreach ($this->items as $item) {
|
||||
// Ensure variant is loaded
|
||||
if ($item->variant) {
|
||||
$itemStock = floor($item->variant->stock_tecnico / $item->cantidad);
|
||||
if ($itemStock < $minStock) {
|
||||
$minStock = $itemStock;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return $minStock === PHP_INT_MAX ? 0 : (int) $minStock;
|
||||
});
|
||||
return Attribute::get(fn (): ?int => $this->availableQuantity());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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
|
||||
{
|
||||
@@ -48,7 +47,7 @@ class CartController extends Controller
|
||||
public function updateItemQuantity(
|
||||
UpdateCartItemQuantityRequest $request,
|
||||
Tenant $tenant,
|
||||
\App\Domains\Cart\Models\CartItem $cartItem,
|
||||
CartItem $cartItem,
|
||||
): CartResource {
|
||||
return CartResource::make(
|
||||
$this->cartService->updateItemQuantity(
|
||||
@@ -60,7 +59,7 @@ class CartController extends Controller
|
||||
)->additional(['message' => 'Cantidad de producto actualizada.']);
|
||||
}
|
||||
|
||||
public function removeItem(Request $request, Tenant $tenant, \App\Domains\Cart\Models\CartItem $cartItem): CartResource
|
||||
public function removeItem(Request $request, Tenant $tenant, CartItem $cartItem): CartResource
|
||||
{
|
||||
return CartResource::make(
|
||||
$this->cartService->removeItem($tenant, $request, $cartItem->getKey())
|
||||
|
||||
@@ -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;
|
||||
@@ -81,23 +83,25 @@ class Cart extends Model
|
||||
|
||||
return DB::transaction(function () use ($buyableType, $buyableId, $quantity): CartItem {
|
||||
$buyable = $this->resolveScopedBuyable($buyableType, $buyableId, true);
|
||||
$canonicalType = $buyable::class;
|
||||
$availableQuantity = $buyable->availableQuantity();
|
||||
|
||||
if ($buyable->stock_tecnico < $quantity) {
|
||||
if ($availableQuantity !== null && $availableQuantity < $quantity) {
|
||||
throw ValidationException::withMessages([
|
||||
'cantidad' => "Stock insuficiente para la variante/bundle solicitado. Maximo disponible: {$buyable->stock_tecnico}.",
|
||||
'cantidad' => "Stock insuficiente para el producto solicitado. Maximo disponible: {$availableQuantity}.",
|
||||
]);
|
||||
}
|
||||
|
||||
/** @var CartItem|null $item */
|
||||
$item = $this->items()
|
||||
->where('buyable_type', $buyableType)
|
||||
->where('buyable_type', $canonicalType)
|
||||
->where('buyable_id', $buyable->getKey())
|
||||
->lockForUpdate()
|
||||
->first();
|
||||
|
||||
if ($item === null) {
|
||||
$item = $this->items()->create([
|
||||
'buyable_type' => $buyableType,
|
||||
'buyable_type' => $canonicalType,
|
||||
'buyable_id' => $buyable->getKey(),
|
||||
'cantidad' => $quantity,
|
||||
]);
|
||||
@@ -106,7 +110,7 @@ class Cart extends Model
|
||||
$item->save();
|
||||
}
|
||||
|
||||
$buyable->incrementReservedStock($quantity);
|
||||
$buyable->reserveStock($quantity);
|
||||
|
||||
return $item->fresh();
|
||||
});
|
||||
@@ -129,9 +133,10 @@ class Cart extends Model
|
||||
|
||||
$buyable = $this->resolveScopedBuyable($item->buyable_type, $item->buyable_id, true);
|
||||
$delta = $quantity - $item->cantidad;
|
||||
$availableQuantity = $buyable->availableQuantity();
|
||||
|
||||
if ($delta > 0 && $buyable->stock_tecnico < $delta) {
|
||||
$maxAvailable = $buyable->stock_tecnico + $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}.",
|
||||
]);
|
||||
@@ -141,7 +146,7 @@ class Cart extends Model
|
||||
$item->save();
|
||||
|
||||
if ($delta > 0) {
|
||||
$buyable->incrementReservedStock($delta);
|
||||
$buyable->reserveStock($delta);
|
||||
}
|
||||
|
||||
if ($delta < 0) {
|
||||
@@ -167,18 +172,18 @@ class Cart extends Model
|
||||
});
|
||||
}
|
||||
|
||||
protected function resolveScopedBuyable(string $buyableType, int $buyableId, bool $lockForUpdate = false)
|
||||
protected function resolveScopedBuyable(string $buyableType, int $buyableId, bool $lockForUpdate = false): Buyable
|
||||
{
|
||||
if ($buyableType === \App\Domains\Catalog\Models\ProductVariant::class) {
|
||||
$query = \App\Domains\Catalog\Models\ProductVariant::query()
|
||||
$buyableClass = $this->resolveBuyableClass($buyableType);
|
||||
|
||||
if ($buyableClass === ProductVariant::class) {
|
||||
$query = ProductVariant::query()
|
||||
->whereKey($buyableId)
|
||||
->whereHas('product', fn ($query) => $query->where('tenant_codigo', $this->tenant_codigo));
|
||||
} elseif ($buyableType === \App\Domains\Bundle\Models\Bundle::class) {
|
||||
$query = \App\Domains\Bundle\Models\Bundle::query()
|
||||
} else {
|
||||
$query = Bundle::query()
|
||||
->whereKey($buyableId)
|
||||
->where('tenant_codigo', $this->tenant_codigo);
|
||||
} else {
|
||||
throw new \InvalidArgumentException('Invalid buyable type');
|
||||
}
|
||||
|
||||
if ($lockForUpdate) {
|
||||
@@ -193,4 +198,13 @@ class Cart extends Model
|
||||
|
||||
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'),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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,7 +20,7 @@ class AddCartItemRequest extends FormRequest
|
||||
public function rules(): array
|
||||
{
|
||||
return [
|
||||
'buyable_type' => ['required', 'string', \Illuminate\Validation\Rule::in(['variant', 'bundle'])],
|
||||
'buyable_type' => ['required', 'string', Rule::in(['variant', 'bundle'])],
|
||||
'buyable_id' => ['required', 'integer'],
|
||||
'cantidad' => ['required', 'integer', 'min:1'],
|
||||
];
|
||||
@@ -26,8 +29,8 @@ class AddCartItemRequest extends FormRequest
|
||||
public function mappedBuyableType(): string
|
||||
{
|
||||
return match ($this->input('buyable_type')) {
|
||||
'variant' => \App\Domains\Catalog\Models\ProductVariant::class,
|
||||
'bundle' => \App\Domains\Bundle\Models\Bundle::class,
|
||||
'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'],
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
@@ -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']);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
9
app/Domains/Catalog/Enums/InventoryPolicy.php
Normal file
9
app/Domains/Catalog/Enums/InventoryPolicy.php
Normal file
@@ -0,0 +1,9 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Catalog\Enums;
|
||||
|
||||
enum InventoryPolicy: string
|
||||
{
|
||||
case Tracked = 'tracked';
|
||||
case Unlimited = 'unlimited';
|
||||
}
|
||||
@@ -3,19 +3,19 @@
|
||||
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;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
|
||||
use Illuminate\Database\Eloquent\Relations\HasMany;
|
||||
|
||||
use Illuminate\Database\Eloquent\Casts\Attribute;
|
||||
|
||||
use App\Domains\Shared\Contracts\Buyable;
|
||||
|
||||
#[Fillable([
|
||||
'producto_id',
|
||||
'inventory_policy',
|
||||
'stock_real',
|
||||
'stock_reservado',
|
||||
'stock',
|
||||
@@ -32,9 +32,20 @@ class ProductVariant extends Model implements Buyable
|
||||
|
||||
protected $appends = ['stock_tecnico'];
|
||||
|
||||
protected $attributes = [
|
||||
'inventory_policy' => 'tracked',
|
||||
'stock_real' => 0,
|
||||
'stock_reservado' => 0,
|
||||
'cantidad_vendida' => 0,
|
||||
];
|
||||
|
||||
protected static function booted(): void
|
||||
{
|
||||
static::saving(function (ProductVariant $variant) {
|
||||
if ($variant->exists && $variant->isDirty('inventory_policy')) {
|
||||
throw new \InvalidArgumentException('La politica de inventario no puede modificarse.');
|
||||
}
|
||||
|
||||
$variant->validateStock();
|
||||
});
|
||||
}
|
||||
@@ -49,11 +60,34 @@ class ProductVariant extends Model implements Buyable
|
||||
throw new \InvalidArgumentException('El stock reservado no puede ser negativo.');
|
||||
}
|
||||
|
||||
if ($this->stock_reservado > $this->stock_real) {
|
||||
if ($this->cantidad_vendida < 0) {
|
||||
throw new \InvalidArgumentException('La cantidad vendida no puede ser negativa.');
|
||||
}
|
||||
|
||||
if ($this->tracksInventory() && $this->stock_reservado > $this->stock_real) {
|
||||
throw new \InvalidArgumentException('El stock reservado no puede ser mayor que el stock real.');
|
||||
}
|
||||
}
|
||||
|
||||
public function tracksInventory(): bool
|
||||
{
|
||||
return $this->inventory_policy === InventoryPolicy::Tracked;
|
||||
}
|
||||
|
||||
public function availableQuantity(): ?int
|
||||
{
|
||||
if (! $this->tracksInventory()) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return $this->stock_real - $this->stock_reservado;
|
||||
}
|
||||
|
||||
public function isAvailableForSale(): bool
|
||||
{
|
||||
return ! $this->tracksInventory() || $this->availableQuantity() > 0;
|
||||
}
|
||||
|
||||
public function getPrice(): float
|
||||
{
|
||||
return (float) ($this->product->precio ?? 0.0);
|
||||
@@ -61,44 +95,34 @@ class ProductVariant extends Model implements Buyable
|
||||
|
||||
public function getName(): string
|
||||
{
|
||||
$name = $this->product->nombre ?? 'Producto';
|
||||
|
||||
$name = $this->product?->nombre ?? 'Producto';
|
||||
|
||||
if ($this->relationLoaded('definitions') && $this->definitions->isNotEmpty()) {
|
||||
$definitions = $this->definitions->map(function ($def) {
|
||||
return $def->value ?? $def->productAttribute?->attribute?->nombre;
|
||||
$attributeName = $def->productAttribute?->attribute?->nombre;
|
||||
$value = $def->value;
|
||||
|
||||
return $attributeName ? "{$attributeName}: {$value}" : $value;
|
||||
})->filter()->implode(', ');
|
||||
|
||||
|
||||
if ($definitions !== '') {
|
||||
$name .= " ({$definitions})";
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
return $name;
|
||||
}
|
||||
|
||||
public function incrementRealStock(int $amount): void
|
||||
public function reserveStock(int $amount): void
|
||||
{
|
||||
if ($amount < 0) {
|
||||
throw new \InvalidArgumentException('El monto a incrementar debe ser positivo.');
|
||||
}
|
||||
$this->stock_real += $amount;
|
||||
$this->save();
|
||||
}
|
||||
|
||||
public function decrementRealStock(int $amount): void
|
||||
{
|
||||
if ($amount < 0) {
|
||||
throw new \InvalidArgumentException('El monto a decrementar debe ser positivo.');
|
||||
if ($this->tracksInventory() && $this->availableQuantity() < $amount) {
|
||||
throw new \InvalidArgumentException('No hay suficiente stock disponible para reservar.');
|
||||
}
|
||||
$this->stock_real -= $amount;
|
||||
$this->save();
|
||||
}
|
||||
|
||||
public function incrementReservedStock(int $amount): void
|
||||
{
|
||||
if ($amount < 0) {
|
||||
throw new \InvalidArgumentException('El monto a incrementar debe ser positivo.');
|
||||
}
|
||||
$this->stock_reservado += $amount;
|
||||
$this->save();
|
||||
}
|
||||
@@ -112,13 +136,13 @@ class ProductVariant extends Model implements Buyable
|
||||
$this->save();
|
||||
}
|
||||
|
||||
public function confirmReservedStock(int $amount): void
|
||||
public function buy(int $amount): void
|
||||
{
|
||||
if ($amount < 0) {
|
||||
throw new \InvalidArgumentException('El monto a confirmar debe ser positivo.');
|
||||
}
|
||||
|
||||
if ($this->stock_real < $amount) {
|
||||
if ($this->tracksInventory() && $this->stock_real < $amount) {
|
||||
throw new \InvalidArgumentException('No hay suficiente stock real para confirmar la reserva.');
|
||||
}
|
||||
|
||||
@@ -126,14 +150,18 @@ class ProductVariant extends Model implements Buyable
|
||||
throw new \InvalidArgumentException('No hay suficiente stock reservado para confirmar la reserva.');
|
||||
}
|
||||
|
||||
$this->stock_real -= $amount;
|
||||
if ($this->tracksInventory()) {
|
||||
$this->stock_real -= $amount;
|
||||
}
|
||||
|
||||
$this->stock_reservado -= $amount;
|
||||
$this->cantidad_vendida += $amount;
|
||||
$this->save();
|
||||
}
|
||||
|
||||
protected function stockTecnico(): Attribute
|
||||
{
|
||||
return Attribute::get(fn () => $this->stock_real - $this->stock_reservado);
|
||||
return Attribute::get(fn (): ?int => $this->availableQuantity());
|
||||
}
|
||||
|
||||
protected function stock(): Attribute
|
||||
@@ -150,8 +178,10 @@ class ProductVariant extends Model implements Buyable
|
||||
{
|
||||
return [
|
||||
'producto_id' => 'integer',
|
||||
'inventory_policy' => InventoryPolicy::class,
|
||||
'stock_real' => 'integer',
|
||||
'stock_reservado' => 'integer',
|
||||
'cantidad_vendida' => 'integer',
|
||||
'is_placeholder' => 'boolean',
|
||||
'has_tickets' => 'boolean',
|
||||
'minimum_use_date' => 'datetime',
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
namespace App\Domains\Catalog\Requests;
|
||||
|
||||
use App\Domains\Catalog\Enums\InventoryPolicy;
|
||||
use App\Domains\Shared\Rules\ImageOrBase64Rule;
|
||||
use Illuminate\Foundation\Http\FormRequest;
|
||||
use Illuminate\Validation\Rule;
|
||||
@@ -32,6 +33,8 @@ class StoreProductRequest extends FormRequest
|
||||
'descripcion' => ['nullable', 'string'],
|
||||
'precio' => ['required', 'numeric', 'min:0'],
|
||||
'stock' => ['sometimes', 'integer', 'min:0'],
|
||||
'inventory_policy' => ['sometimes', Rule::enum(InventoryPolicy::class)],
|
||||
'cantidad_vendida' => ['prohibited'],
|
||||
'attribute_ids' => ['sometimes', 'array'],
|
||||
'attribute_ids.*' => [
|
||||
'required',
|
||||
@@ -41,7 +44,7 @@ class StoreProductRequest extends FormRequest
|
||||
),
|
||||
],
|
||||
'images' => ['sometimes', 'nullable', 'array'],
|
||||
'images.*' => ['required', new ImageOrBase64Rule()],
|
||||
'images.*' => ['required', new ImageOrBase64Rule],
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
namespace App\Domains\Catalog\Requests;
|
||||
|
||||
use App\Domains\Catalog\Enums\InventoryPolicy;
|
||||
use App\Domains\Shared\Rules\ImageOrBase64Rule;
|
||||
use Illuminate\Foundation\Http\FormRequest;
|
||||
use Illuminate\Validation\Rule;
|
||||
@@ -20,6 +21,8 @@ class StoreProductVariantRequest extends FormRequest
|
||||
{
|
||||
return [
|
||||
'stock' => ['sometimes', 'integer', 'min:0'],
|
||||
'inventory_policy' => ['sometimes', Rule::enum(InventoryPolicy::class)],
|
||||
'cantidad_vendida' => ['prohibited'],
|
||||
'definitions' => ['sometimes', 'array'],
|
||||
'definitions.*.products_attribute_id' => [
|
||||
'required',
|
||||
@@ -31,7 +34,7 @@ class StoreProductVariantRequest extends FormRequest
|
||||
],
|
||||
'definitions.*.value' => ['nullable', 'string'],
|
||||
'images' => ['sometimes', 'nullable', 'array'],
|
||||
'images.*' => ['required', new ImageOrBase64Rule()],
|
||||
'images.*' => ['required', new ImageOrBase64Rule],
|
||||
'has_tickets' => ['boolean'],
|
||||
'minimum_use_date' => ['nullable', 'date'],
|
||||
'maximum_use_date' => ['nullable', 'date', 'after_or_equal:minimum_use_date'],
|
||||
|
||||
@@ -20,6 +20,8 @@ class UpdateProductVariantRequest extends FormRequest
|
||||
{
|
||||
return [
|
||||
'stock' => ['sometimes', 'integer', 'min:0'],
|
||||
'inventory_policy' => ['prohibited'],
|
||||
'cantidad_vendida' => ['prohibited'],
|
||||
'definitions' => ['sometimes', 'array'],
|
||||
'definitions.*.products_attribute_id' => [
|
||||
'required',
|
||||
@@ -31,7 +33,7 @@ class UpdateProductVariantRequest extends FormRequest
|
||||
],
|
||||
'definitions.*.value' => ['nullable', 'string'],
|
||||
'images' => ['sometimes', 'nullable', 'array'],
|
||||
'images.*' => ['required', new ImageOrBase64Rule()],
|
||||
'images.*' => ['required', new ImageOrBase64Rule],
|
||||
'has_tickets' => ['boolean'],
|
||||
'minimum_use_date' => ['nullable', 'date'],
|
||||
'maximum_use_date' => ['nullable', 'date', 'after_or_equal:minimum_use_date'],
|
||||
|
||||
@@ -35,7 +35,9 @@ class ProductResource extends JsonResource
|
||||
'variants_map' => $this->whenLoaded('variants', fn () => $this->variants
|
||||
->map(fn ($variant) => [
|
||||
'variant_id' => $variant->id,
|
||||
'inventory_policy' => $variant->inventory_policy->value,
|
||||
'cantidad_maxima' => $variant->stock_tecnico,
|
||||
'cantidad_vendida' => $variant->cantidad_vendida,
|
||||
'attributes' => $variant->definitions
|
||||
->mapWithKeys(fn ($definition) => [
|
||||
$definition->productAttribute?->attribute?->codigo => $definition->value,
|
||||
|
||||
@@ -18,7 +18,9 @@ class ProductVariantResource extends JsonResource
|
||||
{
|
||||
return [
|
||||
'id' => $this->id,
|
||||
'inventory_policy' => $this->inventory_policy->value,
|
||||
'cantidad_maxima' => $this->stock_tecnico,
|
||||
'cantidad_vendida' => $this->cantidad_vendida,
|
||||
'has_tickets' => $this->has_tickets,
|
||||
'minimum_use_date' => $this->minimum_use_date,
|
||||
'maximum_use_date' => $this->maximum_use_date,
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
namespace App\Domains\Catalog\Services;
|
||||
|
||||
use App\Domains\Attachable\Services\AttachmentService;
|
||||
use App\Domains\Catalog\Enums\InventoryPolicy;
|
||||
use App\Domains\Catalog\Models\Attribute;
|
||||
use App\Domains\Catalog\Models\Product;
|
||||
use App\Domains\Catalog\Models\ProductVariant;
|
||||
@@ -28,7 +29,8 @@ class ProductService
|
||||
$attributeIds = $data['attribute_ids'] ?? [];
|
||||
$images = $data['images'] ?? [];
|
||||
$stock = $data['stock'] ?? 0;
|
||||
unset($data['attribute_ids'], $data['images'], $data['stock']);
|
||||
$inventoryPolicy = $data['inventory_policy'] ?? InventoryPolicy::Tracked->value;
|
||||
unset($data['attribute_ids'], $data['images'], $data['stock'], $data['inventory_policy']);
|
||||
|
||||
/** @var Product $product */
|
||||
$product = Product::query()->create([
|
||||
@@ -45,6 +47,7 @@ class ProductService
|
||||
// Create default variant with stock
|
||||
$this->createVariant($product, [
|
||||
'stock' => $stock,
|
||||
'inventory_policy' => $inventoryPolicy,
|
||||
'is_placeholder' => true,
|
||||
'definitions' => [],
|
||||
]);
|
||||
@@ -179,6 +182,7 @@ class ProductService
|
||||
if ($product->variants()->count() === 0) {
|
||||
$product->createVariant([
|
||||
'stock' => 0,
|
||||
'inventory_policy' => InventoryPolicy::Tracked->value,
|
||||
'is_placeholder' => true,
|
||||
'definitions' => [],
|
||||
]);
|
||||
@@ -327,13 +331,13 @@ class ProductService
|
||||
|
||||
$selectedVariant = $variantId !== null
|
||||
? $product->variants->firstWhere('id', $variantId)
|
||||
: $product->variants->first(fn (ProductVariant $variant) => $variant->stock_tecnico > 0);
|
||||
: $product->variants->first(fn (ProductVariant $variant) => $variant->isAvailableForSale());
|
||||
|
||||
if ($variantId !== null && $selectedVariant === null) {
|
||||
throw new NotFoundHttpException('Product variant not found for product.');
|
||||
}
|
||||
|
||||
if ($variantId !== null && $selectedVariant->stock_tecnico <= 0) {
|
||||
if ($variantId !== null && ! $selectedVariant->isAvailableForSale()) {
|
||||
throw ValidationException::withMessages([
|
||||
'variant_id' => 'La variante seleccionada no tiene stock.',
|
||||
]);
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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,15 +20,16 @@ class PurchaseItemResource extends JsonResource
|
||||
*/
|
||||
public function toArray(Request $request): array
|
||||
{
|
||||
/** @var \App\Domains\Shared\Contracts\Buyable|null $buyable */
|
||||
/** @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 === \App\Domains\Catalog\Models\ProductVariant::class && $buyable) {
|
||||
if ($this->buyable_type === ProductVariant::class && $buyable) {
|
||||
$imageUrl = $this->resolveImageUrl($buyable);
|
||||
$attributes = $this->resolveAttributes($buyable);
|
||||
}
|
||||
@@ -37,6 +41,16 @@ class PurchaseItemResource extends JsonResource
|
||||
'line_total' => $this->formatMoney($lineTotal),
|
||||
'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' => $attributes,
|
||||
],
|
||||
'item_details' => $buyable === null ? null : [
|
||||
'nombre' => $buyable->getName(),
|
||||
'imagen' => $imageUrl,
|
||||
@@ -48,8 +62,8 @@ class PurchaseItemResource extends JsonResource
|
||||
protected function mapBuyableTypeToAlias(?string $type): string
|
||||
{
|
||||
return match ($type) {
|
||||
\App\Domains\Catalog\Models\ProductVariant::class => 'variant',
|
||||
\App\Domains\Bundle\Models\Bundle::class => 'bundle',
|
||||
ProductVariant::class => 'variant',
|
||||
Bundle::class => 'bundle',
|
||||
default => 'unknown',
|
||||
};
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
@@ -97,6 +98,15 @@ class CheckoutService
|
||||
public function confirmPurchase(Purchase $purchase): void
|
||||
{
|
||||
DB::transaction(function () use ($purchase): 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();
|
||||
|
||||
@@ -114,10 +124,6 @@ class CheckoutService
|
||||
]);
|
||||
}
|
||||
|
||||
if ($purchase->items()->exists()) {
|
||||
return;
|
||||
}
|
||||
|
||||
$cartItems->load('buyable');
|
||||
$this->verifyTenantBuyables($purchase->tenant, $cartItems);
|
||||
$purchaseItemsPayload = $this->buildPurchaseItemsPayload($cartItems);
|
||||
@@ -136,13 +142,14 @@ class CheckoutService
|
||||
'cart_id' => 'One or more buyables could not be loaded.',
|
||||
]);
|
||||
}
|
||||
|
||||
// Check tenant relation depending on type
|
||||
if ($item->buyable_type === \App\Domains\Catalog\Models\ProductVariant::class && $buyable->product->tenant_codigo !== $tenant->codigo) {
|
||||
|
||||
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.',
|
||||
]);
|
||||
} elseif ($item->buyable_type === \App\Domains\Bundle\Models\Bundle::class && $buyable->tenant_codigo !== $tenant->codigo) {
|
||||
}
|
||||
|
||||
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.',
|
||||
]);
|
||||
@@ -152,7 +159,7 @@ class CheckoutService
|
||||
|
||||
/**
|
||||
* @param Collection<int, CartItem> $cartItems
|
||||
* @return \Illuminate\Support\Collection<int, ProductVariant>
|
||||
* @return Collection<int, ProductVariant>
|
||||
*/
|
||||
protected function resolveCheckoutCart(Tenant $tenant, int $userId, int $cartId): Cart
|
||||
{
|
||||
@@ -209,7 +216,7 @@ class CheckoutService
|
||||
$quantity = (int) $item->cantidad;
|
||||
|
||||
try {
|
||||
$buyable->confirmReservedStock($quantity);
|
||||
$buyable->buy($quantity);
|
||||
} catch (\InvalidArgumentException $exception) {
|
||||
throw ValidationException::withMessages([
|
||||
'cart_id' => 'The selected cart has inconsistent stock state.',
|
||||
|
||||
@@ -5,14 +5,16 @@ namespace App\Domains\Shared\Contracts;
|
||||
interface Buyable
|
||||
{
|
||||
public function getPrice(): float;
|
||||
|
||||
public function getName(): string;
|
||||
|
||||
public function incrementRealStock(int $amount): void;
|
||||
public function decrementRealStock(int $amount): void;
|
||||
|
||||
public function incrementReservedStock(int $amount): void;
|
||||
public function availableQuantity(): ?int;
|
||||
|
||||
public function reserveStock(int $amount): void;
|
||||
|
||||
public function decrementReservedStock(int $amount): void;
|
||||
public function confirmReservedStock(int $amount): void;
|
||||
|
||||
|
||||
public function buy(int $amount): void;
|
||||
|
||||
public function validateStock(): void;
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
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
|
||||
@@ -14,17 +15,23 @@ return new class extends Migration
|
||||
Schema::table('carrito_items', function (Blueprint $table) {
|
||||
$table->string('buyable_type')->nullable();
|
||||
$table->unsignedBigInteger('buyable_id')->nullable();
|
||||
$table->index('cart_id');
|
||||
});
|
||||
|
||||
// Copy existing data
|
||||
\Illuminate\Support\Facades\DB::table('carrito_items')->update([
|
||||
DB::table('carrito_items')->update([
|
||||
'buyable_type' => 'App\Domains\Catalog\Models\ProductVariant',
|
||||
'buyable_id' => \Illuminate\Support\Facades\DB::raw('producto_variante_id'),
|
||||
'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']);
|
||||
});
|
||||
}
|
||||
|
||||
@@ -34,15 +41,18 @@ return new class extends Migration
|
||||
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');
|
||||
});
|
||||
|
||||
\Illuminate\Support\Facades\DB::table('carrito_items')->update([
|
||||
'producto_variante_id' => \Illuminate\Support\Facades\DB::raw('buyable_id'),
|
||||
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,29 @@
|
||||
<?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('productos_variantes', function (Blueprint $table) {
|
||||
$table->string('inventory_policy')->default('tracked')->after('producto_id');
|
||||
$table->unsignedBigInteger('cantidad_vendida')->default(0)->after('stock_reservado');
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Reverse the migrations.
|
||||
*/
|
||||
public function down(): void
|
||||
{
|
||||
Schema::table('productos_variantes', function (Blueprint $table) {
|
||||
$table->dropColumn(['inventory_policy', 'cantidad_vendida']);
|
||||
});
|
||||
}
|
||||
};
|
||||
@@ -110,6 +110,29 @@ class AttributeSeeder extends Seeder
|
||||
],
|
||||
]);
|
||||
|
||||
// Seed Fecha attribute
|
||||
$existingFecha = Attribute::query()
|
||||
->where('tenant_codigo', $tenant->codigo)
|
||||
->where('codigo', 'fecha')
|
||||
->first();
|
||||
|
||||
if ($existingFecha) {
|
||||
Product::deleteAttribute($existingFecha);
|
||||
}
|
||||
|
||||
Product::createAttribute($tenant, [
|
||||
'codigo' => 'fecha',
|
||||
'nombre' => 'Fecha',
|
||||
'type' => FieldType::Select->value,
|
||||
'is_required' => true,
|
||||
'options' => [
|
||||
['value' => '2026-10-09', 'label' => '09/10/2026', 'sort_order' => 1],
|
||||
['value' => '2026-10-10', 'label' => '10/10/2026', 'sort_order' => 2],
|
||||
['value' => '2026-10-11', 'label' => '11/10/2026', 'sort_order' => 3],
|
||||
['value' => '2026-10-12', 'label' => '12/10/2026', 'sort_order' => 4],
|
||||
],
|
||||
]);
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -28,6 +28,7 @@ class DatabaseSeeder extends Seeder
|
||||
CategorySeeder::class,
|
||||
BrandSeeder::class,
|
||||
ProductCatalogFromImagesSeeder::class,
|
||||
FiestaFutbolInfantilProductSeeder::class,
|
||||
TelepagosIntegrationSeeder::class,
|
||||
MenuSeeder::class,
|
||||
]);
|
||||
|
||||
95
database/seeders/FiestaFutbolInfantilProductSeeder.php
Normal file
95
database/seeders/FiestaFutbolInfantilProductSeeder.php
Normal file
@@ -0,0 +1,95 @@
|
||||
<?php
|
||||
|
||||
namespace Database\Seeders;
|
||||
|
||||
use App\Domains\Catalog\Enums\InventoryPolicy;
|
||||
use App\Domains\Catalog\Models\Attribute;
|
||||
use App\Domains\Catalog\Models\Category;
|
||||
use App\Domains\Catalog\Models\Product;
|
||||
use App\Domains\Catalog\Services\ProductService;
|
||||
use App\Domains\Tenant\Models\Tenant;
|
||||
use Illuminate\Database\Seeder;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use RuntimeException;
|
||||
|
||||
class FiestaFutbolInfantilProductSeeder extends Seeder
|
||||
{
|
||||
public function __construct(private readonly ProductService $productService) {}
|
||||
|
||||
public function run(): void
|
||||
{
|
||||
$tenant = Tenant::query()->where('codigo', 'fiesta_futbol_infantil')->first();
|
||||
|
||||
if (! $tenant) {
|
||||
throw new RuntimeException("Tenant 'fiesta_futbol_infantil' no encontrado.");
|
||||
}
|
||||
|
||||
// Delete existing products for this tenant
|
||||
$existingProducts = Product::query()
|
||||
->where('tenant_codigo', $tenant->codigo)
|
||||
->get();
|
||||
|
||||
foreach ($existingProducts as $product) {
|
||||
$this->productService->delete($product);
|
||||
}
|
||||
|
||||
// We need a category, let's just use 'Accesorios' or create an 'Entradas' category
|
||||
$category = Category::firstOrCreate(['nombre' => 'Entradas', 'tenant_code' => null]);
|
||||
|
||||
$dates = ['2026-10-09', '2026-10-10', '2026-10-11', '2026-10-12'];
|
||||
|
||||
// 1. Entrada General
|
||||
$entrada = $this->productService->create($tenant, [
|
||||
'categoria_id' => $category->id,
|
||||
'slug' => 'entrada-general',
|
||||
'nombre' => 'Entrada General',
|
||||
'descripcion' => 'Acceso total al predio. No incluye acceso a estacionamiento. Niños menores de 5 años ingresan gratis.',
|
||||
'precio' => 10000,
|
||||
'stock' => 0,
|
||||
'inventory_policy' => InventoryPolicy::Unlimited->value,
|
||||
'attribute_ids' => [Attribute::where('codigo', 'fecha')->where('tenant_codigo', $tenant->codigo)->first()?->id],
|
||||
]);
|
||||
|
||||
foreach ($dates as $date) {
|
||||
$this->productService->createVariant($entrada, [
|
||||
'stock' => 0,
|
||||
'inventory_policy' => InventoryPolicy::Unlimited->value,
|
||||
'has_tickets' => true,
|
||||
'minimum_use_date' => $date.' 00:00:00',
|
||||
'maximum_use_date' => $date.' 23:59:59',
|
||||
'definitions' => [
|
||||
[
|
||||
'products_attribute_id' => DB::table('products_attributes')
|
||||
->where('product_id', $entrada->id)
|
||||
->first()?->id,
|
||||
'value' => $date,
|
||||
],
|
||||
],
|
||||
]);
|
||||
}
|
||||
|
||||
// Other products without variants
|
||||
$gastronomiaCategory = Category::firstOrCreate(['nombre' => 'Gastronomía', 'tenant_code' => null]);
|
||||
|
||||
$simpleProducts = [
|
||||
['slug' => 'hamburguesa-papa-frita', 'nombre' => 'Hamburguesa con papa frita', 'precio' => 8000, 'cat' => $gastronomiaCategory->id],
|
||||
['slug' => 'pancho', 'nombre' => 'Pancho', 'precio' => 4000, 'cat' => $gastronomiaCategory->id],
|
||||
['slug' => 'coca-cola-500ml', 'nombre' => 'Coca Cola 500ml', 'precio' => 3000, 'cat' => $gastronomiaCategory->id],
|
||||
['slug' => 'agua-mineral-1l', 'nombre' => 'Agua Mineral 1L', 'precio' => 2500, 'cat' => $gastronomiaCategory->id],
|
||||
['slug' => 'estacionamiento-auto', 'nombre' => 'Estacionamiento Auto', 'precio' => 5000, 'cat' => $category->id],
|
||||
['slug' => 'estacionamiento-moto', 'nombre' => 'Estacionamiento Moto', 'precio' => 2000, 'cat' => $category->id],
|
||||
];
|
||||
|
||||
foreach ($simpleProducts as $p) {
|
||||
$this->productService->create($tenant, [
|
||||
'categoria_id' => $p['cat'],
|
||||
'slug' => $p['slug'],
|
||||
'nombre' => $p['nombre'],
|
||||
'descripcion' => $p['nombre'],
|
||||
'precio' => $p['precio'],
|
||||
'stock' => 0,
|
||||
'inventory_policy' => InventoryPolicy::Unlimited->value,
|
||||
]);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
namespace Database\Seeders;
|
||||
|
||||
use App\Domains\Catalog\Enums\InventoryPolicy;
|
||||
use App\Domains\Catalog\Models\Attribute;
|
||||
use App\Domains\Catalog\Models\Brand;
|
||||
use App\Domains\Catalog\Models\Category;
|
||||
@@ -64,9 +65,7 @@ class ProductCatalogFromImagesSeeder extends Seeder
|
||||
'istockphoto-1675347112-2048x2048.jpg',
|
||||
];
|
||||
|
||||
public function __construct(private readonly ProductService $productService)
|
||||
{
|
||||
}
|
||||
public function __construct(private readonly ProductService $productService) {}
|
||||
|
||||
/**
|
||||
* Run the database seeds.
|
||||
@@ -162,9 +161,9 @@ class ProductCatalogFromImagesSeeder extends Seeder
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array{attribute_codes: array<int, string>, brand_name: string|null, category_name: string, color: string|null, description: string, product_name: string, product_slug: string, type: string} $metadata
|
||||
* @param array{price: int} $pricing
|
||||
* @param array<int, array{files: array<int, \SplFileInfo>, group_key: string, metadata: array{attribute_codes: array<int, string>, brand_name: string|null, category_name: string, color: string|null, description: string, product_name: string, product_slug: string, type: string}, stock: int}> $variantGroups
|
||||
* @param array{attribute_codes: array<int, string>, brand_name: string|null, category_name: string, color: string|null, description: string, product_name: string, product_slug: string, type: string} $metadata
|
||||
* @param array{price: int} $pricing
|
||||
* @param array<int, array{files: array<int, \SplFileInfo>, group_key: string, metadata: array{attribute_codes: array<int, string>, brand_name: string|null, category_name: string, color: string|null, description: string, product_name: string, product_slug: string, type: string}, stock: int}> $variantGroups
|
||||
*/
|
||||
private function seedProduct(Tenant $tenant, array $metadata, array $pricing, array $variantGroups): void
|
||||
{
|
||||
@@ -206,6 +205,7 @@ class ProductCatalogFromImagesSeeder extends Seeder
|
||||
'nombre' => $metadata['product_name'],
|
||||
'descripcion' => $metadata['description'],
|
||||
'precio' => $pricing['price'],
|
||||
'inventory_policy' => InventoryPolicy::Tracked->value,
|
||||
'attribute_ids' => array_values($attributeIds->all()),
|
||||
]);
|
||||
|
||||
@@ -226,9 +226,11 @@ class ProductCatalogFromImagesSeeder extends Seeder
|
||||
if ($attributeIds->isEmpty()) {
|
||||
$this->productService->createVariant($product, [
|
||||
'stock' => $variantGroup['stock'],
|
||||
'inventory_policy' => InventoryPolicy::Tracked->value,
|
||||
'definitions' => [],
|
||||
'images' => $images,
|
||||
]);
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -280,6 +282,7 @@ class ProductCatalogFromImagesSeeder extends Seeder
|
||||
|
||||
$this->productService->createVariant($product, [
|
||||
'stock' => $stock,
|
||||
'inventory_policy' => InventoryPolicy::Tracked->value,
|
||||
'definitions' => $definitions,
|
||||
'images' => $images,
|
||||
]);
|
||||
@@ -288,7 +291,7 @@ class ProductCatalogFromImagesSeeder extends Seeder
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<int, array{files: array<int, \SplFileInfo>, group_key: string, metadata: array{attribute_codes: array<int, string>, brand_name: string|null, category_name: string, color: string|null, description: string, product_name: string, product_slug: string, type: string}, stock: int}> $variantGroups
|
||||
* @param array<int, array{files: array<int, \SplFileInfo>, group_key: string, metadata: array{attribute_codes: array<int, string>, brand_name: string|null, category_name: string, color: string|null, description: string, product_name: string, product_slug: string, type: string}, stock: int}> $variantGroups
|
||||
* @return array{attribute_codes: array<int, string>, brand_name: string|null, category_name: string, color: string|null, description: string, product_name: string, product_slug: string, type: string}
|
||||
*/
|
||||
private function buildProductMetadata(string $productKey, array $variantGroups): array
|
||||
|
||||
@@ -2,14 +2,19 @@
|
||||
|
||||
namespace Tests\Feature\Cart;
|
||||
|
||||
use App\Domains\Attachable\Enums\AttachmentType;
|
||||
use App\Domains\Attachable\Models\Attachment;
|
||||
use App\Domains\Auth\Models\User;
|
||||
use App\Domains\Catalog\Models\Product;
|
||||
use App\Domains\Catalog\Enums\InventoryPolicy;
|
||||
use App\Domains\Catalog\Models\Attribute;
|
||||
use App\Domains\Catalog\Models\ProductVariant;
|
||||
use App\Domains\Catalog\Models\Category;
|
||||
use App\Domains\Catalog\Models\Product;
|
||||
use App\Domains\Catalog\Models\ProductAttribute;
|
||||
use App\Domains\Catalog\Models\ProductVariant;
|
||||
use App\Domains\Catalog\Models\ProductVariantDefinition;
|
||||
use App\Domains\Tenant\Models\Tenant;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Illuminate\Support\Str;
|
||||
use Tests\TestCase;
|
||||
|
||||
class CartControllerTest extends TestCase
|
||||
@@ -29,7 +34,7 @@ class CartControllerTest extends TestCase
|
||||
'status' => 'active',
|
||||
'items' => [],
|
||||
'subtotal' => '0.00',
|
||||
]
|
||||
],
|
||||
]);
|
||||
}
|
||||
|
||||
@@ -55,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,
|
||||
]);
|
||||
|
||||
@@ -65,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');
|
||||
@@ -77,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,
|
||||
]);
|
||||
|
||||
@@ -93,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,
|
||||
]);
|
||||
|
||||
@@ -107,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,
|
||||
])
|
||||
);
|
||||
@@ -120,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', [
|
||||
@@ -135,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],
|
||||
[],
|
||||
@@ -159,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', [
|
||||
@@ -174,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],
|
||||
[],
|
||||
@@ -211,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()
|
||||
@@ -226,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();
|
||||
@@ -248,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();
|
||||
}
|
||||
@@ -270,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',
|
||||
@@ -289,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,
|
||||
])
|
||||
);
|
||||
@@ -300,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],
|
||||
[],
|
||||
@@ -315,18 +339,101 @@ 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(
|
||||
'acme',
|
||||
0,
|
||||
'10.00',
|
||||
'unlimited',
|
||||
InventoryPolicy::Unlimited,
|
||||
);
|
||||
|
||||
$response = $this->postJson('/api/tenants/acme/cart/items', [
|
||||
'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,
|
||||
'stock_reservado' => 100,
|
||||
]);
|
||||
|
||||
$this->call(
|
||||
'PATCH',
|
||||
"/api/tenants/acme/cart/items/{$cartItemId}",
|
||||
[],
|
||||
['guest_token' => $guestToken],
|
||||
[],
|
||||
['HTTP_Accept' => 'application/json', 'CONTENT_TYPE' => 'application/json'],
|
||||
json_encode(['cantidad' => 150]),
|
||||
)->assertOk();
|
||||
|
||||
$this->assertDatabaseHas('productos_variantes', [
|
||||
'id' => $variant->id,
|
||||
'stock_real' => 0,
|
||||
'stock_reservado' => 150,
|
||||
]);
|
||||
|
||||
$this->call(
|
||||
'DELETE',
|
||||
"/api/tenants/acme/cart/items/{$cartItemId}",
|
||||
[],
|
||||
['guest_token' => $guestToken],
|
||||
[],
|
||||
['HTTP_Accept' => 'application/json'],
|
||||
)->assertOk();
|
||||
|
||||
$this->assertDatabaseHas('productos_variantes', [
|
||||
'id' => $variant->id,
|
||||
'stock_real' => 0,
|
||||
'stock_reservado' => 0,
|
||||
]);
|
||||
}
|
||||
|
||||
protected function createVariantForTenant(
|
||||
string $tenantCode,
|
||||
int $stock,
|
||||
string $price,
|
||||
string $slugPrefix = 'shirt',
|
||||
InventoryPolicy $inventoryPolicy = InventoryPolicy::Tracked,
|
||||
): ProductVariant {
|
||||
$tenant = Tenant::query()->where('codigo', $tenantCode)->first();
|
||||
if (! $tenant) {
|
||||
$this->createTenant($tenantCode, ucfirst($tenantCode), "{$tenantCode}.com");
|
||||
}
|
||||
|
||||
$category = \App\Domains\Catalog\Models\Category::query()->create([
|
||||
$category = Category::query()->create([
|
||||
'tenant_code' => $tenantCode,
|
||||
'nombre' => "{$slugPrefix} category {$tenantCode}",
|
||||
]);
|
||||
@@ -342,6 +449,7 @@ class CartControllerTest extends TestCase
|
||||
|
||||
return ProductVariant::query()->create([
|
||||
'producto_id' => $product->id,
|
||||
'inventory_policy' => $inventoryPolicy->value,
|
||||
'slug' => "{$slugPrefix}-variant-".ProductVariant::query()->count(),
|
||||
'nombre' => ucfirst($slugPrefix).' Variant',
|
||||
'stock' => $stock,
|
||||
@@ -352,21 +460,21 @@ class CartControllerTest extends TestCase
|
||||
|
||||
protected function createTenant(string $codigo, string $nombre, string $dominio): Tenant
|
||||
{
|
||||
$hdrKey = (string) \Illuminate\Support\Str::uuid();
|
||||
$ftrKey = (string) \Illuminate\Support\Str::uuid();
|
||||
$hdrKey = (string) Str::uuid();
|
||||
$ftrKey = (string) Str::uuid();
|
||||
|
||||
$headerAttachment = \App\Domains\Attachable\Models\Attachment::create([
|
||||
$headerAttachment = Attachment::create([
|
||||
'key' => $hdrKey,
|
||||
'path' => 'tenants/' . $hdrKey . '.png',
|
||||
'path' => 'tenants/'.$hdrKey.'.png',
|
||||
'filename' => 'logo_header.png',
|
||||
'type' => \App\Domains\Attachable\Enums\AttachmentType::Image,
|
||||
'type' => AttachmentType::Image,
|
||||
'mime_type' => 'image/png',
|
||||
]);
|
||||
$footerAttachment = \App\Domains\Attachable\Models\Attachment::create([
|
||||
$footerAttachment = Attachment::create([
|
||||
'key' => $ftrKey,
|
||||
'path' => 'tenants/' . $ftrKey . '.png',
|
||||
'path' => 'tenants/'.$ftrKey.'.png',
|
||||
'filename' => 'logo_footer.png',
|
||||
'type' => \App\Domains\Attachable\Enums\AttachmentType::Image,
|
||||
'type' => AttachmentType::Image,
|
||||
'mime_type' => 'image/png',
|
||||
]);
|
||||
|
||||
|
||||
@@ -4,6 +4,7 @@ namespace Tests\Feature\Catalog;
|
||||
|
||||
use App\Domains\Attachable\Enums\AttachmentType;
|
||||
use App\Domains\Attachable\Models\Attachment;
|
||||
use App\Domains\Catalog\Enums\InventoryPolicy;
|
||||
use App\Domains\Catalog\Models\Attribute;
|
||||
use App\Domains\Catalog\Models\Brand;
|
||||
use App\Domains\Catalog\Models\Product;
|
||||
@@ -768,6 +769,67 @@ class ProductControllerTest extends TestCase
|
||||
$response->assertJsonValidationErrors(['variant_id']);
|
||||
}
|
||||
|
||||
public function test_it_creates_an_unlimited_default_variant_and_exposes_inventory_fields(): void
|
||||
{
|
||||
$response = $this->postJson("/api/tenants/{$this->tenant->codigo}/productos", [
|
||||
'categoria_id' => 1,
|
||||
'brand_id' => $this->brand->id,
|
||||
'slug' => 'unlimited-product',
|
||||
'nombre' => 'Unlimited Product',
|
||||
'precio' => 100,
|
||||
'stock' => 0,
|
||||
'inventory_policy' => InventoryPolicy::Unlimited->value,
|
||||
]);
|
||||
|
||||
$response->assertCreated();
|
||||
|
||||
$product = Product::query()->where('slug', 'unlimited-product')->firstOrFail();
|
||||
$variant = $product->variants()->firstOrFail();
|
||||
$this->assertSame(InventoryPolicy::Unlimited, $variant->inventory_policy);
|
||||
|
||||
$this->getJson("/api/tenants/{$this->tenant->codigo}/productos/{$product->id}")
|
||||
->assertOk()
|
||||
->assertJsonPath('data.variant.id', $variant->id)
|
||||
->assertJsonPath('data.variant.inventory_policy', InventoryPolicy::Unlimited->value)
|
||||
->assertJsonPath('data.variant.cantidad_maxima', null)
|
||||
->assertJsonPath('data.variant.cantidad_vendida', 0)
|
||||
->assertJsonPath('data.variants_map.0.inventory_policy', InventoryPolicy::Unlimited->value)
|
||||
->assertJsonPath('data.variants_map.0.cantidad_maxima', null)
|
||||
->assertJsonPath('data.variants_map.0.cantidad_vendida', 0);
|
||||
}
|
||||
|
||||
public function test_it_rejects_invalid_or_updated_inventory_policies(): void
|
||||
{
|
||||
$this->postJson("/api/tenants/{$this->tenant->codigo}/productos", [
|
||||
'categoria_id' => 1,
|
||||
'brand_id' => $this->brand->id,
|
||||
'slug' => 'invalid-policy',
|
||||
'nombre' => 'Invalid Policy',
|
||||
'precio' => 100,
|
||||
'inventory_policy' => 'sometimes',
|
||||
])->assertUnprocessable()->assertJsonValidationErrors(['inventory_policy']);
|
||||
|
||||
$product = Product::query()->create([
|
||||
'tenant_codigo' => $this->tenant->codigo,
|
||||
'categoria_id' => 1,
|
||||
'brand_id' => $this->brand->id,
|
||||
'slug' => 'immutable-policy',
|
||||
'nombre' => 'Immutable Policy',
|
||||
'precio' => 100,
|
||||
]);
|
||||
$variant = $product->variants()->create([
|
||||
'stock' => 0,
|
||||
'inventory_policy' => InventoryPolicy::Unlimited->value,
|
||||
]);
|
||||
|
||||
$this->putJson(
|
||||
"/api/tenants/{$this->tenant->codigo}/productos/{$product->id}/variants/{$variant->id}",
|
||||
['inventory_policy' => InventoryPolicy::Tracked->value],
|
||||
)->assertUnprocessable()->assertJsonValidationErrors(['inventory_policy']);
|
||||
|
||||
$this->assertSame(InventoryPolicy::Unlimited, $variant->fresh()->inventory_policy);
|
||||
}
|
||||
|
||||
private function createAttachment(string $path): Attachment
|
||||
{
|
||||
return Attachment::create([
|
||||
|
||||
@@ -2,8 +2,12 @@
|
||||
|
||||
namespace Tests\Feature\Integration;
|
||||
|
||||
use App\Domains\Attachable\Enums\AttachmentType;
|
||||
use App\Domains\Attachable\Models\Attachment;
|
||||
use App\Domains\Auth\Models\User;
|
||||
use App\Domains\Cart\Models\Cart;
|
||||
use App\Domains\Catalog\Enums\InventoryPolicy;
|
||||
use App\Domains\Catalog\Models\Category;
|
||||
use App\Domains\Catalog\Models\Product;
|
||||
use App\Domains\Catalog\Models\ProductVariant;
|
||||
use App\Domains\Integration\Models\Integration;
|
||||
@@ -14,6 +18,7 @@ use App\Domains\Tenant\Models\Tenant;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Illuminate\Support\Facades\Cache;
|
||||
use Illuminate\Support\Facades\Http;
|
||||
use Illuminate\Support\Str;
|
||||
use Tests\TestCase;
|
||||
|
||||
class TelepagosWebhookTest extends TestCase
|
||||
@@ -24,7 +29,7 @@ class TelepagosWebhookTest extends TestCase
|
||||
{
|
||||
parent::setUp();
|
||||
|
||||
config(['services.integrations.secret' => 'base64:' . base64_encode(random_bytes(32))]);
|
||||
config(['services.integrations.secret' => 'base64:'.base64_encode(random_bytes(32))]);
|
||||
Cache::flush();
|
||||
}
|
||||
|
||||
@@ -108,11 +113,19 @@ 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,
|
||||
]);
|
||||
|
||||
$this->assertDatabaseHas('productos_variantes', [
|
||||
'id' => $variant->id,
|
||||
'stock_real' => 9,
|
||||
'stock_reservado' => 2,
|
||||
'cantidad_vendida' => 1,
|
||||
]);
|
||||
|
||||
$this->assertDatabaseMissing('compra_items', [
|
||||
'compra_id' => $newerPurchase->id,
|
||||
]);
|
||||
@@ -122,6 +135,60 @@ class TelepagosWebhookTest extends TestCase
|
||||
]);
|
||||
}
|
||||
|
||||
public function test_transfer_webhook_buys_unlimited_inventory_without_reducing_real_stock(): void
|
||||
{
|
||||
$tenant = $this->createTenant('unlimited', 'Unlimited', 'unlimited.com.ar');
|
||||
$this->configureTelepagosIntegration($tenant);
|
||||
$user = User::factory()->create();
|
||||
$variant = $this->createVariantForTenant(
|
||||
'unlimited',
|
||||
0,
|
||||
'50.00',
|
||||
'service',
|
||||
InventoryPolicy::Unlimited,
|
||||
);
|
||||
$purchase = $this->createPendingTransferPurchase(
|
||||
$tenant,
|
||||
$user->id,
|
||||
$variant->id,
|
||||
3,
|
||||
'87654321',
|
||||
);
|
||||
|
||||
Http::fake([
|
||||
'https://api.telepagos.com.ar/v2/auth/token' => Http::response([
|
||||
'status' => 'ok',
|
||||
'token' => 'test-token',
|
||||
'expires_at' => now()->addHour()->toIso8601String(),
|
||||
]),
|
||||
'https://api.telepagos.com.ar/v2/payment/cashin/7000' => Http::response([
|
||||
'status' => 'ok',
|
||||
'data' => [
|
||||
'amount' => 150,
|
||||
'operation_id' => 1,
|
||||
'transaction_id' => 'tx-unlimited',
|
||||
'buyer' => ['cuit' => '20876543219'],
|
||||
],
|
||||
]),
|
||||
]);
|
||||
|
||||
$this->postJson('/api/webhooks/telepagos/unlimited', ['id' => '7000'])
|
||||
->assertOk()
|
||||
->assertJsonPath('status', 'success');
|
||||
|
||||
$this->assertDatabaseHas('compras', [
|
||||
'id' => $purchase->id,
|
||||
'status' => Purchase::STATUS_PAID,
|
||||
]);
|
||||
$this->assertDatabaseHas('productos_variantes', [
|
||||
'id' => $variant->id,
|
||||
'inventory_policy' => InventoryPolicy::Unlimited->value,
|
||||
'stock_real' => 0,
|
||||
'stock_reservado' => 0,
|
||||
'cantidad_vendida' => 3,
|
||||
]);
|
||||
}
|
||||
|
||||
private function createPendingTransferPurchase(
|
||||
Tenant $tenant,
|
||||
int $userId,
|
||||
@@ -135,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);
|
||||
@@ -184,8 +251,9 @@ class TelepagosWebhookTest extends TestCase
|
||||
int $stock,
|
||||
string $price,
|
||||
string $slugPrefix = 'shirt',
|
||||
InventoryPolicy $inventoryPolicy = InventoryPolicy::Tracked,
|
||||
): ProductVariant {
|
||||
$category = \App\Domains\Catalog\Models\Category::query()->create([
|
||||
$category = Category::query()->create([
|
||||
'tenant_code' => $tenantCode,
|
||||
'nombre' => "{$slugPrefix} category {$tenantCode}",
|
||||
]);
|
||||
@@ -201,6 +269,7 @@ class TelepagosWebhookTest extends TestCase
|
||||
|
||||
return ProductVariant::query()->create([
|
||||
'producto_id' => $product->id,
|
||||
'inventory_policy' => $inventoryPolicy->value,
|
||||
'slug' => "{$slugPrefix}-variant-".ProductVariant::query()->count(),
|
||||
'nombre' => ucfirst($slugPrefix).' Variant',
|
||||
'stock' => $stock,
|
||||
@@ -211,21 +280,21 @@ class TelepagosWebhookTest extends TestCase
|
||||
|
||||
private function createTenant(string $codigo, string $nombre, string $dominio): Tenant
|
||||
{
|
||||
$hdrKey = (string) \Illuminate\Support\Str::uuid();
|
||||
$ftrKey = (string) \Illuminate\Support\Str::uuid();
|
||||
$hdrKey = (string) Str::uuid();
|
||||
$ftrKey = (string) Str::uuid();
|
||||
|
||||
$headerAttachment = \App\Domains\Attachable\Models\Attachment::create([
|
||||
$headerAttachment = Attachment::create([
|
||||
'key' => $hdrKey,
|
||||
'path' => 'tenants/' . $hdrKey . '.png',
|
||||
'path' => 'tenants/'.$hdrKey.'.png',
|
||||
'filename' => 'logo_header.png',
|
||||
'type' => \App\Domains\Attachable\Enums\AttachmentType::Image,
|
||||
'type' => AttachmentType::Image,
|
||||
'mime_type' => 'image/png',
|
||||
]);
|
||||
$footerAttachment = \App\Domains\Attachable\Models\Attachment::create([
|
||||
$footerAttachment = Attachment::create([
|
||||
'key' => $ftrKey,
|
||||
'path' => 'tenants/' . $ftrKey . '.png',
|
||||
'path' => 'tenants/'.$ftrKey.'.png',
|
||||
'filename' => 'logo_footer.png',
|
||||
'type' => \App\Domains\Attachable\Enums\AttachmentType::Image,
|
||||
'type' => AttachmentType::Image,
|
||||
'mime_type' => 'image/png',
|
||||
]);
|
||||
|
||||
|
||||
@@ -2,14 +2,19 @@
|
||||
|
||||
namespace Tests\Feature\Purchase;
|
||||
|
||||
use App\Domains\Attachable\Enums\AttachmentType;
|
||||
use App\Domains\Attachable\Models\Attachment;
|
||||
use App\Domains\Auth\Models\User;
|
||||
use App\Domains\Cart\Models\Cart;
|
||||
use App\Domains\Catalog\Enums\InventoryPolicy;
|
||||
use App\Domains\Catalog\Models\Category;
|
||||
use App\Domains\Catalog\Models\Product;
|
||||
use App\Domains\Catalog\Models\ProductVariant;
|
||||
use App\Domains\Purchase\Models\Purchase;
|
||||
use App\Domains\Purchase\Services\CheckoutService;
|
||||
use App\Domains\Tenant\Models\Tenant;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Illuminate\Support\Str;
|
||||
use Tests\TestCase;
|
||||
|
||||
class StorePurchaseTest extends TestCase
|
||||
@@ -22,7 +27,7 @@ class StorePurchaseTest extends TestCase
|
||||
$user = User::factory()->create([
|
||||
'email' => 'buyer@example.com',
|
||||
]);
|
||||
$category = \App\Domains\Catalog\Models\Category::query()->create([
|
||||
$category = Category::query()->create([
|
||||
'tenant_code' => 'sonder',
|
||||
'nombre' => 'Test Category',
|
||||
]);
|
||||
@@ -46,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();
|
||||
@@ -106,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', [
|
||||
@@ -126,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()
|
||||
@@ -237,6 +245,13 @@ class StorePurchaseTest extends TestCase
|
||||
$checkoutService->confirmPurchase($purchase);
|
||||
$purchase->refresh()->markAsPaid();
|
||||
|
||||
$this->assertDatabaseHas('productos_variantes', [
|
||||
'id' => $variant->id,
|
||||
'stock_real' => 8,
|
||||
'stock_reservado' => 0,
|
||||
'cantidad_vendida' => 2,
|
||||
]);
|
||||
|
||||
$this->assertSoftDeleted('carritos', [
|
||||
'id' => $purchase->cart_id,
|
||||
]);
|
||||
@@ -268,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,
|
||||
@@ -314,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()
|
||||
@@ -340,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()
|
||||
@@ -401,18 +419,48 @@ class StorePurchaseTest extends TestCase
|
||||
->assertJsonValidationErrors(['cart_id']);
|
||||
}
|
||||
|
||||
public function test_it_confirms_unlimited_inventory_without_reducing_real_stock_and_is_idempotent(): void
|
||||
{
|
||||
$this->createTenant('sonder', 'Sonder', 'sonder.com.ar');
|
||||
$user = User::factory()->create();
|
||||
$variant = $this->createVariantForTenant(
|
||||
'sonder',
|
||||
0,
|
||||
'50.00',
|
||||
'unlimited',
|
||||
InventoryPolicy::Unlimited,
|
||||
);
|
||||
$purchase = $this->createCheckoutPurchase($user, 'sonder', $variant, 25);
|
||||
$purchase->update(['payment_method' => 'transfer']);
|
||||
|
||||
$checkoutService = app(CheckoutService::class);
|
||||
$purchase = $checkoutService->completePurchase($purchase);
|
||||
$checkoutService->confirmPurchase($purchase);
|
||||
$checkoutService->confirmPurchase($purchase);
|
||||
|
||||
$this->assertDatabaseHas('productos_variantes', [
|
||||
'id' => $variant->id,
|
||||
'inventory_policy' => InventoryPolicy::Unlimited->value,
|
||||
'stock_real' => 0,
|
||||
'stock_reservado' => 0,
|
||||
'cantidad_vendida' => 25,
|
||||
]);
|
||||
$this->assertDatabaseCount('compra_items', 1);
|
||||
}
|
||||
|
||||
protected function createVariantForTenant(
|
||||
string $tenantCode,
|
||||
int $stock,
|
||||
string $price,
|
||||
string $slugPrefix = 'shirt',
|
||||
InventoryPolicy $inventoryPolicy = InventoryPolicy::Tracked,
|
||||
): ProductVariant {
|
||||
$tenant = Tenant::query()->where('codigo', $tenantCode)->first();
|
||||
if (! $tenant) {
|
||||
$this->createTenant($tenantCode, ucfirst($tenantCode), "{$tenantCode}.com");
|
||||
}
|
||||
|
||||
$category = \App\Domains\Catalog\Models\Category::query()->create([
|
||||
$category = Category::query()->create([
|
||||
'tenant_code' => $tenantCode,
|
||||
'nombre' => "{$slugPrefix} category {$tenantCode}",
|
||||
]);
|
||||
@@ -428,6 +476,7 @@ class StorePurchaseTest extends TestCase
|
||||
|
||||
return ProductVariant::query()->create([
|
||||
'producto_id' => $product->id,
|
||||
'inventory_policy' => $inventoryPolicy->value,
|
||||
'slug' => "{$slugPrefix}-variant-".ProductVariant::query()->count(),
|
||||
'nombre' => ucfirst($slugPrefix).' Variant',
|
||||
'stock' => $stock,
|
||||
@@ -449,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,
|
||||
@@ -462,21 +511,21 @@ class StorePurchaseTest extends TestCase
|
||||
|
||||
protected function createTenant(string $codigo, string $nombre, string $dominio): Tenant
|
||||
{
|
||||
$hdrKey = (string) \Illuminate\Support\Str::uuid();
|
||||
$ftrKey = (string) \Illuminate\Support\Str::uuid();
|
||||
$hdrKey = (string) Str::uuid();
|
||||
$ftrKey = (string) Str::uuid();
|
||||
|
||||
$headerAttachment = \App\Domains\Attachable\Models\Attachment::create([
|
||||
$headerAttachment = Attachment::create([
|
||||
'key' => $hdrKey,
|
||||
'path' => 'tenants/' . $hdrKey . '.png',
|
||||
'path' => 'tenants/'.$hdrKey.'.png',
|
||||
'filename' => 'logo_header.png',
|
||||
'type' => \App\Domains\Attachable\Enums\AttachmentType::Image,
|
||||
'type' => AttachmentType::Image,
|
||||
'mime_type' => 'image/png',
|
||||
]);
|
||||
$footerAttachment = \App\Domains\Attachable\Models\Attachment::create([
|
||||
$footerAttachment = Attachment::create([
|
||||
'key' => $ftrKey,
|
||||
'path' => 'tenants/' . $ftrKey . '.png',
|
||||
'path' => 'tenants/'.$ftrKey.'.png',
|
||||
'filename' => 'logo_footer.png',
|
||||
'type' => \App\Domains\Attachable\Enums\AttachmentType::Image,
|
||||
'type' => AttachmentType::Image,
|
||||
'mime_type' => 'image/png',
|
||||
]);
|
||||
|
||||
|
||||
153
tests/Unit/Catalog/ProductVariantInventoryTest.php
Normal file
153
tests/Unit/Catalog/ProductVariantInventoryTest.php
Normal file
@@ -0,0 +1,153 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Unit\Catalog;
|
||||
|
||||
use App\Domains\Attachable\Enums\AttachmentType;
|
||||
use App\Domains\Attachable\Models\Attachment;
|
||||
use App\Domains\Catalog\Enums\InventoryPolicy;
|
||||
use App\Domains\Catalog\Models\Category;
|
||||
use App\Domains\Catalog\Models\Product;
|
||||
use App\Domains\Catalog\Models\ProductVariant;
|
||||
use App\Domains\Tenant\Models\Tenant;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Illuminate\Support\Str;
|
||||
use Tests\TestCase;
|
||||
|
||||
class ProductVariantInventoryTest extends TestCase
|
||||
{
|
||||
use RefreshDatabase;
|
||||
|
||||
private Product $product;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
|
||||
$headerAttachment = $this->createAttachment('header.png');
|
||||
$footerAttachment = $this->createAttachment('footer.png');
|
||||
|
||||
$tenant = Tenant::query()->create([
|
||||
'codigo' => 'inventory-test',
|
||||
'nombre' => 'Inventory Test',
|
||||
'dominio' => 'inventory.test',
|
||||
'primary_color' => '#111111',
|
||||
'secondary_color' => '#222222',
|
||||
'danger_color' => '#333333',
|
||||
'success_color' => '#28a745',
|
||||
'header_bg_color' => '#444444',
|
||||
'footer_bg_color' => '#444444',
|
||||
'header_logo_id' => $headerAttachment->id,
|
||||
'footer_logo_id' => $footerAttachment->id,
|
||||
]);
|
||||
|
||||
$category = Category::query()->create([
|
||||
'tenant_code' => $tenant->codigo,
|
||||
'nombre' => 'Inventory',
|
||||
]);
|
||||
|
||||
$this->product = Product::query()->create([
|
||||
'tenant_codigo' => $tenant->codigo,
|
||||
'categoria_id' => $category->id,
|
||||
'slug' => 'inventory-product',
|
||||
'nombre' => 'Inventory Product',
|
||||
'precio' => 100,
|
||||
]);
|
||||
}
|
||||
|
||||
public function test_it_defaults_to_tracked_inventory_with_no_sales(): void
|
||||
{
|
||||
$variant = $this->createVariant(5);
|
||||
|
||||
$this->assertSame(InventoryPolicy::Tracked, $variant->inventory_policy);
|
||||
$this->assertSame(5, $variant->availableQuantity());
|
||||
$this->assertSame(0, $variant->cantidad_vendida);
|
||||
$this->assertTrue($variant->isAvailableForSale());
|
||||
}
|
||||
|
||||
public function test_tracked_inventory_cannot_reserve_more_than_available_stock(): void
|
||||
{
|
||||
$variant = $this->createVariant(5);
|
||||
$variant->reserveStock(3);
|
||||
|
||||
$this->assertSame(2, $variant->fresh()->availableQuantity());
|
||||
|
||||
$this->expectException(\InvalidArgumentException::class);
|
||||
$variant->reserveStock(3);
|
||||
}
|
||||
|
||||
public function test_unlimited_inventory_can_reserve_more_than_real_stock(): void
|
||||
{
|
||||
$variant = $this->createVariant(0, InventoryPolicy::Unlimited);
|
||||
$variant->reserveStock(50);
|
||||
|
||||
$variant->refresh();
|
||||
$this->assertNull($variant->availableQuantity());
|
||||
$this->assertSame(50, $variant->stock_reservado);
|
||||
$this->assertTrue($variant->isAvailableForSale());
|
||||
}
|
||||
|
||||
public function test_buying_tracked_inventory_consumes_stock_and_records_the_sale(): void
|
||||
{
|
||||
$variant = $this->createVariant(10);
|
||||
$variant->reserveStock(4);
|
||||
$variant->buy(3);
|
||||
|
||||
$variant->refresh();
|
||||
$this->assertSame(7, $variant->stock_real);
|
||||
$this->assertSame(1, $variant->stock_reservado);
|
||||
$this->assertSame(3, $variant->cantidad_vendida);
|
||||
}
|
||||
|
||||
public function test_buying_unlimited_inventory_preserves_real_stock_and_records_the_sale(): void
|
||||
{
|
||||
$variant = $this->createVariant(0, InventoryPolicy::Unlimited);
|
||||
$variant->reserveStock(4);
|
||||
$variant->buy(3);
|
||||
|
||||
$variant->refresh();
|
||||
$this->assertSame(0, $variant->stock_real);
|
||||
$this->assertSame(1, $variant->stock_reservado);
|
||||
$this->assertSame(3, $variant->cantidad_vendida);
|
||||
}
|
||||
|
||||
public function test_buy_requires_enough_reserved_stock(): void
|
||||
{
|
||||
$variant = $this->createVariant(10);
|
||||
$variant->reserveStock(1);
|
||||
|
||||
$this->expectException(\InvalidArgumentException::class);
|
||||
$variant->buy(2);
|
||||
}
|
||||
|
||||
public function test_inventory_policy_cannot_change_after_creation(): void
|
||||
{
|
||||
$variant = $this->createVariant(10);
|
||||
$variant->inventory_policy = InventoryPolicy::Unlimited;
|
||||
|
||||
$this->expectException(\InvalidArgumentException::class);
|
||||
$this->expectExceptionMessage('La politica de inventario no puede modificarse.');
|
||||
$variant->save();
|
||||
}
|
||||
|
||||
private function createVariant(
|
||||
int $stock,
|
||||
InventoryPolicy $inventoryPolicy = InventoryPolicy::Tracked,
|
||||
): ProductVariant {
|
||||
return ProductVariant::query()->create([
|
||||
'producto_id' => $this->product->id,
|
||||
'stock' => $stock,
|
||||
'inventory_policy' => $inventoryPolicy->value,
|
||||
]);
|
||||
}
|
||||
|
||||
private function createAttachment(string $filename): Attachment
|
||||
{
|
||||
return Attachment::query()->create([
|
||||
'key' => (string) Str::uuid(),
|
||||
'path' => 'tests/'.$filename,
|
||||
'filename' => $filename,
|
||||
'type' => AttachmentType::Image,
|
||||
'mime_type' => 'image/png',
|
||||
]);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user