Compare commits

...

4 Commits

18 changed files with 561 additions and 150 deletions

View File

@@ -0,0 +1,145 @@
<?php
namespace App\Domains\Bundle\Models;
use App\Domains\Tenant\Models\Tenant;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Casts\Attribute;
use App\Domains\Shared\Contracts\Buyable;
#[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 incrementRealStock(int $amount): void
{
if ($amount < 0) {
throw new \InvalidArgumentException('El monto a incrementar debe ser positivo.');
}
foreach ($this->items as $item) {
$item->variant->incrementRealStock($amount * $item->cantidad);
}
}
public function decrementRealStock(int $amount): void
{
if ($amount < 0) {
throw new \InvalidArgumentException('El monto a decrementar 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);
}
}
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 confirmReservedStock(int $amount): void
{
if ($amount < 0) {
throw new \InvalidArgumentException('El monto a confirmar debe ser positivo.');
}
foreach ($this->items as $item) {
$item->variant->confirmReservedStock($amount * $item->cantidad);
}
}
public function validateStock(): void
{
if ($this->stock_tecnico <= 0) {
throw new \InvalidArgumentException('El bundle no tiene stock técnico 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;
});
}
}

View 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');
}
}

View File

@@ -29,7 +29,8 @@ class CartController extends Controller
$result = $this->cartService->addItem( $result = $this->cartService->addItem(
$tenant, $tenant,
$request, $request,
(int) $request->validated('product_variant_id'), $request->mappedBuyableType(),
(int) $request->validated('buyable_id'),
(int) $request->validated('cantidad'), (int) $request->validated('cantidad'),
); );
@@ -47,22 +48,22 @@ class CartController extends Controller
public function updateItemQuantity( public function updateItemQuantity(
UpdateCartItemQuantityRequest $request, UpdateCartItemQuantityRequest $request,
Tenant $tenant, Tenant $tenant,
ProductVariant $productVariant, \App\Domains\Cart\Models\CartItem $cartItem,
): CartResource { ): CartResource {
return CartResource::make( return CartResource::make(
$this->cartService->updateItemQuantity( $this->cartService->updateItemQuantity(
$tenant, $tenant,
$request, $request,
$productVariant->getKey(), $cartItem->getKey(),
(int) $request->validated('cantidad'), (int) $request->validated('cantidad'),
) )
)->additional(['message' => 'Cantidad de producto actualizada.']); )->additional(['message' => 'Cantidad de producto actualizada.']);
} }
public function removeItem(Request $request, Tenant $tenant, ProductVariant $productVariant): CartResource public function removeItem(Request $request, Tenant $tenant, \App\Domains\Cart\Models\CartItem $cartItem): CartResource
{ {
return CartResource::make( return CartResource::make(
$this->cartService->removeItem($tenant, $request, $productVariant->getKey()) $this->cartService->removeItem($tenant, $request, $cartItem->getKey())
)->additional(['message' => 'Producto eliminado del carrito.']); )->additional(['message' => 'Producto eliminado del carrito.']);
} }
} }

View File

@@ -63,15 +63,15 @@ class Cart extends Model
{ {
$items = $this->relationLoaded('items') $items = $this->relationLoaded('items')
? $this->getRelation('items') ? $this->getRelation('items')
: $this->items()->with('variant.product')->get(); : $this->items()->with('buyable')->get();
return (float) $items->reduce( 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, 0.0,
); );
} }
public function addItem(int $productVariantId, int $quantity): CartItem public function addItem(string $buyableType, int $buyableId, int $quantity): CartItem
{ {
if ($quantity <= 0) { if ($quantity <= 0) {
throw ValidationException::withMessages([ throw ValidationException::withMessages([
@@ -79,24 +79,26 @@ class Cart extends Model
]); ]);
} }
return DB::transaction(function () use ($productVariantId, $quantity): CartItem { return DB::transaction(function () use ($buyableType, $buyableId, $quantity): CartItem {
$variant = $this->resolveScopedVariant($productVariantId, true); $buyable = $this->resolveScopedBuyable($buyableType, $buyableId, true);
if ($variant->stock_tecnico < $quantity) { if ($buyable->stock_tecnico < $quantity) {
throw ValidationException::withMessages([ throw ValidationException::withMessages([
'cantidad' => "Stock insuficiente para la variante solicitada. Maximo disponible: {$variant->stock_tecnico}.", 'cantidad' => "Stock insuficiente para la variante/bundle solicitado. Maximo disponible: {$buyable->stock_tecnico}.",
]); ]);
} }
/** @var CartItem|null $item */ /** @var CartItem|null $item */
$item = $this->items() $item = $this->items()
->where('producto_variante_id', $variant->getKey()) ->where('buyable_type', $buyableType)
->where('buyable_id', $buyable->getKey())
->lockForUpdate() ->lockForUpdate()
->first(); ->first();
if ($item === null) { if ($item === null) {
$item = $this->items()->create([ $item = $this->items()->create([
'producto_variante_id' => $variant->getKey(), 'buyable_type' => $buyableType,
'buyable_id' => $buyable->getKey(),
'cantidad' => $quantity, 'cantidad' => $quantity,
]); ]);
} else { } else {
@@ -104,13 +106,13 @@ class Cart extends Model
$item->save(); $item->save();
} }
$variant->incrementReservedStock($quantity); $buyable->incrementReservedStock($quantity);
return $item->fresh(); return $item->fresh();
}); });
} }
public function updateItem(int $productVariantId, int $quantity): CartItem public function updateItem(int $cartItemId, int $quantity): CartItem
{ {
if ($quantity <= 0) { if ($quantity <= 0) {
throw ValidationException::withMessages([ throw ValidationException::withMessages([
@@ -118,18 +120,18 @@ class Cart extends Model
]); ]);
} }
return DB::transaction(function () use ($productVariantId, $quantity): CartItem { return DB::transaction(function () use ($cartItemId, $quantity): CartItem {
/** @var CartItem $item */ /** @var CartItem $item */
$item = $this->items() $item = $this->items()
->where('producto_variante_id', $productVariantId) ->where('id', $cartItemId)
->lockForUpdate() ->lockForUpdate()
->firstOrFail(); ->firstOrFail();
$variant = $this->resolveScopedVariant($productVariantId, true); $buyable = $this->resolveScopedBuyable($item->buyable_type, $item->buyable_id, true);
$delta = $quantity - $item->cantidad; $delta = $quantity - $item->cantidad;
if ($delta > 0 && $variant->stock_tecnico < $delta) { if ($delta > 0 && $buyable->stock_tecnico < $delta) {
$maxAvailable = $variant->stock_tecnico + $item->cantidad; $maxAvailable = $buyable->stock_tecnico + $item->cantidad;
throw ValidationException::withMessages([ throw ValidationException::withMessages([
'cantidad' => "El máximo que se puede agregar es {$maxAvailable}.", 'cantidad' => "El máximo que se puede agregar es {$maxAvailable}.",
]); ]);
@@ -139,49 +141,56 @@ class Cart extends Model
$item->save(); $item->save();
if ($delta > 0) { if ($delta > 0) {
$variant->incrementReservedStock($delta); $buyable->incrementReservedStock($delta);
} }
if ($delta < 0) { if ($delta < 0) {
$variant->decrementReservedStock(abs($delta)); $buyable->decrementReservedStock(abs($delta));
} }
return $item->fresh(); 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 */ /** @var CartItem $item */
$item = $this->items() $item = $this->items()
->where('producto_variante_id', $productVariantId) ->where('id', $cartItemId)
->lockForUpdate() ->lockForUpdate()
->firstOrFail(); ->firstOrFail();
$variant = $this->resolveScopedVariant($productVariantId, true); $buyable = $this->resolveScopedBuyable($item->buyable_type, $item->buyable_id, true);
$variant->decrementReservedStock($item->cantidad); $buyable->decrementReservedStock($item->cantidad);
$item->delete(); $item->delete();
}); });
} }
protected function resolveScopedVariant(int $productVariantId, bool $lockForUpdate = false): ProductVariant protected function resolveScopedBuyable(string $buyableType, int $buyableId, bool $lockForUpdate = false)
{ {
$query = ProductVariant::query() if ($buyableType === \App\Domains\Catalog\Models\ProductVariant::class) {
->whereKey($productVariantId) $query = \App\Domains\Catalog\Models\ProductVariant::query()
->whereKey($buyableId)
->whereHas('product', fn ($query) => $query->where('tenant_codigo', $this->tenant_codigo)); ->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()
->whereKey($buyableId)
->where('tenant_codigo', $this->tenant_codigo);
} else {
throw new \InvalidArgumentException('Invalid buyable type');
}
if ($lockForUpdate) { if ($lockForUpdate) {
$query->lockForUpdate(); $query->lockForUpdate();
} }
/** @var ProductVariant|null $variant */ $buyable = $query->first();
$variant = $query->first();
if ($variant === null) { if ($buyable === null) {
throw new NotFoundHttpException('Product variant not found for tenant.'); throw new NotFoundHttpException('Buyable not found for tenant.');
} }
return $variant; return $buyable;
} }
} }

View File

@@ -10,7 +10,8 @@ use Illuminate\Database\Eloquent\Relations\BelongsTo;
#[Fillable([ #[Fillable([
'cart_id', 'cart_id',
'producto_variante_id', 'buyable_id',
'buyable_type',
'cantidad', 'cantidad',
])] ])]
class CartItem extends Model class CartItem extends Model
@@ -23,7 +24,8 @@ class CartItem extends Model
{ {
return [ return [
'cart_id' => 'integer', 'cart_id' => 'integer',
'producto_variante_id' => 'integer', 'buyable_id' => 'integer',
'buyable_type' => 'string',
'cantidad' => 'integer', '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();
} }
} }

View File

@@ -17,8 +17,18 @@ class AddCartItemRequest extends FormRequest
public function rules(): array public function rules(): array
{ {
return [ return [
'product_variant_id' => ['required', 'integer'], 'buyable_type' => ['required', 'string', \Illuminate\Validation\Rule::in(['variant', 'bundle'])],
'buyable_id' => ['required', 'integer'],
'cantidad' => ['required', 'integer', 'min:1'], 'cantidad' => ['required', 'integer', 'min:1'],
]; ];
} }
public function mappedBuyableType(): string
{
return match ($this->input('buyable_type')) {
'variant' => \App\Domains\Catalog\Models\ProductVariant::class,
'bundle' => \App\Domains\Bundle\Models\Bundle::class,
default => throw new \InvalidArgumentException('Invalid buyable type'),
};
}
} }

View File

@@ -15,29 +15,15 @@ class CartItemResource extends JsonResource
*/ */
public function toArray(Request $request): array public function toArray(Request $request): array
{ {
$variant = $this->variant; /** @var \App\Domains\Shared\Contracts\Buyable|null $buyable */
$product = $variant?->product; $buyable = $this->buyable;
$attributesText = ''; $productName = $buyable?->getName();
if ($variant && $variant->relationLoaded('definitions')) { $precio = $buyable?->getPrice();
$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})";
}
$imageUrl = null; $imageUrl = null;
if ($variant && $variant->relationLoaded('attachments')) { if ($this->buyable_type === \App\Domains\Catalog\Models\ProductVariant::class && $buyable && $buyable->relationLoaded('attachments')) {
$firstAttachment = $variant->attachments->first(); $firstAttachment = $buyable->attachments->first();
if ($firstAttachment) { if ($firstAttachment) {
$imageUrl = $firstAttachment->getTemporaryUrl(1440); $imageUrl = $firstAttachment->getTemporaryUrl(1440);
} }
@@ -46,16 +32,25 @@ class CartItemResource extends JsonResource
return [ return [
'id' => $this->id, 'id' => $this->id,
'cantidad' => $this->cantidad, 'cantidad' => $this->cantidad,
'precio_unitario' => $this->formatMoney($product?->precio), 'precio_unitario' => $this->formatMoney($precio),
'product_id' => $product?->id, 'buyable_type' => $this->mapBuyableTypeToAlias($this->buyable_type),
'product_variant_id' => $this->producto_variante_id, 'buyable_id' => $this->buyable_id,
'product' => $product === null ? null : [ 'product' => $buyable === null ? null : [
'nombre' => $productName, 'nombre' => $productName,
'imagen' => $imageUrl, '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 protected function formatMoney(float|int|string|null $amount): string
{ {
return number_format((float) ($amount ?? 0), 2, '.', ''); return number_format((float) ($amount ?? 0), 2, '.', '');

View File

@@ -32,12 +32,12 @@ class CartService
/** /**
* @return array{cart: Cart, guest_token: ?string} * @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); $resolvedIdentity = $this->resolveIdentity($request, true);
$identity = $resolvedIdentity['identity']; $identity = $resolvedIdentity['identity'];
$cart = $this->findOrCreateCart($tenant, $identity); $cart = $this->findOrCreateCart($tenant, $identity);
$cart->addItem($productVariantId, $quantity); $cart->addItem($buyableType, $buyableId, $quantity);
return [ return [
'cart' => $this->loadCart($cart), 'cart' => $this->loadCart($cart),
@@ -45,20 +45,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); $identity = $this->requireIdentity($request);
$cart = $this->findCartOrFail($tenant, $identity); $cart = $this->findCartOrFail($tenant, $identity);
$cart->updateItem($productVariantId, $quantity); $cart->updateItem($cartItemId, $quantity);
return $this->loadCart($cart); 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); $identity = $this->requireIdentity($request);
$cart = $this->findCartOrFail($tenant, $identity); $cart = $this->findCartOrFail($tenant, $identity);
$cart->removeItem($productVariantId); $cart->removeItem($cartItemId);
return $this->loadCart($cart); return $this->loadCart($cart);
} }

View File

@@ -8,6 +8,6 @@ Route::prefix('tenants/{tenant:codigo}')
->group(function (): void { ->group(function (): void {
Route::get('cart', [CartController::class, 'show']); Route::get('cart', [CartController::class, 'show']);
Route::post('cart/items', [CartController::class, 'addItem']); Route::post('cart/items', [CartController::class, 'addItem']);
Route::patch('cart/items/{productVariant}', [CartController::class, 'updateItemQuantity']); Route::patch('cart/items/{cartItem}', [CartController::class, 'updateItemQuantity']);
Route::delete('cart/items/{productVariant}', [CartController::class, 'removeItem']); Route::delete('cart/items/{cartItem}', [CartController::class, 'removeItem']);
}); });

View File

@@ -12,6 +12,8 @@ use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Casts\Attribute; use Illuminate\Database\Eloquent\Casts\Attribute;
use App\Domains\Shared\Contracts\Buyable;
#[Fillable([ #[Fillable([
'producto_id', 'producto_id',
'stock_real', 'stock_real',
@@ -22,7 +24,7 @@ use Illuminate\Database\Eloquent\Casts\Attribute;
'minimum_use_date', 'minimum_use_date',
'maximum_use_date', 'maximum_use_date',
])] ])]
class ProductVariant extends Model class ProductVariant extends Model implements Buyable
{ {
use HasFactory; use HasFactory;
@@ -52,6 +54,28 @@ class ProductVariant extends Model
} }
} }
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) {
return $def->value ?? $def->productAttribute?->attribute?->nombre;
})->filter()->implode(', ');
if ($definitions !== '') {
$name .= " ({$definitions})";
}
}
return $name;
}
public function incrementRealStock(int $amount): void public function incrementRealStock(int $amount): void
{ {
if ($amount < 0) { if ($amount < 0) {

View File

@@ -10,7 +10,8 @@ use Illuminate\Database\Eloquent\Relations\BelongsTo;
#[Fillable([ #[Fillable([
'compra_id', 'compra_id',
'producto_variante_id', 'buyable_id',
'buyable_type',
'cantidad', 'cantidad',
'precio_unitario', 'precio_unitario',
'discount_total', 'discount_total',
@@ -27,7 +28,8 @@ class PurchaseItem extends Model
{ {
return [ return [
'compra_id' => 'integer', 'compra_id' => 'integer',
'producto_variante_id' => 'integer', 'buyable_id' => 'integer',
'buyable_type' => 'string',
'cantidad' => 'integer', 'cantidad' => 'integer',
'precio_unitario' => 'decimal:2', 'precio_unitario' => 'decimal:2',
'discount_total' => '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();
} }
} }

View File

@@ -17,30 +17,43 @@ class PurchaseItemResource extends JsonResource
*/ */
public function toArray(Request $request): array public function toArray(Request $request): array
{ {
$variant = $this->variant; /** @var \App\Domains\Shared\Contracts\Buyable|null $buyable */
$product = $variant?->product; $buyable = $this->buyable;
$quantity = (int) ($this->cantidad ?? 0); $quantity = (int) ($this->cantidad ?? 0);
$unitPrice = $this->resolveUnitPrice(); $unitPrice = $this->resolveUnitPrice();
$lineTotal = $this->resolveLineTotal($unitPrice, $quantity); $lineTotal = $this->resolveLineTotal($unitPrice, $quantity);
$imageUrl = null;
$attributes = [];
if ($this->buyable_type === \App\Domains\Catalog\Models\ProductVariant::class && $buyable) {
$imageUrl = $this->resolveImageUrl($buyable);
$attributes = $this->resolveAttributes($buyable);
}
return [ return [
'id' => $this->id, 'id' => $this->id,
'quantity' => $quantity, 'quantity' => $quantity,
'unit_price' => $this->formatMoney($unitPrice), 'unit_price' => $this->formatMoney($unitPrice),
'line_total' => $this->formatMoney($lineTotal), 'line_total' => $this->formatMoney($lineTotal),
'product' => $product === null ? null : [ 'buyable_type' => $this->mapBuyableTypeToAlias($this->buyable_type),
'id' => $product->id, 'buyable_id' => $this->buyable_id,
'nombre' => $product->nombre, 'item_details' => $buyable === null ? null : [
'slug' => $product->slug, 'nombre' => $buyable->getName(),
'imagen' => $this->resolveImageUrl(), 'imagen' => $imageUrl,
], 'attributes' => $attributes,
'variant' => $variant === null ? null : [
'id' => $variant->id,
'attributes' => $this->resolveAttributes(),
], ],
]; ];
} }
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 resolveUnitPrice(): float protected function resolveUnitPrice(): float
{ {
if ($this->resource instanceof PurchaseItem) { if ($this->resource instanceof PurchaseItem) {
@@ -48,7 +61,7 @@ class PurchaseItemResource extends JsonResource
} }
if ($this->resource instanceof CartItem) { if ($this->resource instanceof CartItem) {
return (float) ($this->variant?->product?->precio ?? 0); return (float) ($this->buyable?->getPrice() ?? 0);
} }
return 0.0; return 0.0;
@@ -63,15 +76,13 @@ class PurchaseItemResource extends JsonResource
return $unitPrice * $quantity; return $unitPrice * $quantity;
} }
protected function resolveImageUrl(): ?string protected function resolveImageUrl($buyable): ?string
{ {
$variant = $this->variant; if (! $buyable->relationLoaded('attachments')) {
if ($variant === null || ! $variant->relationLoaded('attachments')) {
return null; return null;
} }
$attachment = $variant->attachments->first(); $attachment = $buyable->attachments->first();
if ($attachment === null) { if ($attachment === null) {
return null; return null;
@@ -83,15 +94,13 @@ class PurchaseItemResource extends JsonResource
/** /**
* @return array<int, array{name: string, value: mixed}> * @return array<int, array{name: string, value: mixed}>
*/ */
protected function resolveAttributes(): array protected function resolveAttributes($buyable): array
{ {
$variant = $this->variant; if (! $buyable->relationLoaded('definitions')) {
if ($variant === null || ! $variant->relationLoaded('definitions')) {
return []; return [];
} }
return $variant->definitions return $buyable->definitions
->map(function ($definition): array { ->map(function ($definition): array {
return [ return [
'name' => (string) ($definition->productAttribute?->attribute?->nombre ?? ''), 'name' => (string) ($definition->productAttribute?->attribute?->nombre ?? ''),

View File

@@ -29,7 +29,7 @@ class CheckoutService
]); ]);
} }
$cartItems->load('variant.product'); $cartItems->load('buyable');
$cart->setRelation('items', $cartItems); $cart->setRelation('items', $cartItems);
$totalAmount = $cart->getTotalAmount(); $totalAmount = $cart->getTotalAmount();
@@ -63,7 +63,7 @@ class CheckoutService
$purchase->save(); $purchase->save();
} }
return $purchase->load(['items.variant.product', 'items.variant.definitions.productAttribute.attribute']); return $purchase->load(['items.buyable']);
}); });
} }
@@ -82,7 +82,7 @@ class CheckoutService
} }
if (in_array($purchase->status, [Purchase::STATUS_PAID, Purchase::STATUS_CANCELLED, Purchase::STATUS_REJECTED], true)) { if (in_array($purchase->status, [Purchase::STATUS_PAID, Purchase::STATUS_CANCELLED, Purchase::STATUS_REJECTED], true)) {
return $purchase->load(['items.variant.product', 'items.variant.definitions.productAttribute.attribute']); return $purchase->load(['items.buyable']);
} }
$purchase->update([ $purchase->update([
@@ -90,7 +90,7 @@ class CheckoutService
'total' => $purchase->calculateCurrentTotalAmount(), 'total' => $purchase->calculateCurrentTotalAmount(),
]); ]);
return $purchase->load(['items.variant.product', 'items.variant.definitions.productAttribute.attribute']); return $purchase->load(['items.buyable']);
}); });
} }
@@ -118,42 +118,36 @@ class CheckoutService
return; return;
} }
$cartItems->load('variant.product'); $cartItems->load('buyable');
$variants = $this->resolveTenantVariants($purchase->tenant, $cartItems); $this->verifyTenantBuyables($purchase->tenant, $cartItems);
$purchaseItemsPayload = $this->buildPurchaseItemsPayload($cartItems, $variants); $purchaseItemsPayload = $this->buildPurchaseItemsPayload($cartItems);
$purchase->items()->createMany($purchaseItemsPayload); $purchase->items()->createMany($purchaseItemsPayload);
$this->completeCartConversion($cart, $cartItems, $variants); $this->completeCartConversion($cart, $cartItems);
}); });
} }
/** protected function verifyTenantBuyables(Tenant $tenant, Collection $cartItems): void
* @return Collection<int, ProductVariant>
*/
protected function resolveTenantVariants(Tenant $tenant, Collection $cartItems): Collection
{ {
$variantIds = $cartItems foreach ($cartItems as $item) {
->pluck('producto_variante_id') $buyable = $item->buyable;
->map(static fn (mixed $id): int => (int) $id) if ($buyable === null) {
->unique()
->values();
/** @var Collection<int, ProductVariant> $variants */
$variants = ProductVariant::query()
->with('product')
->whereIn('id', $variantIds)
->whereHas('product', fn ($query) => $query->where('tenant_codigo', $tenant->codigo))
->lockForUpdate()
->get()
->keyBy('id');
if ($variants->count() !== $variantIds->count()) {
throw ValidationException::withMessages([ throw ValidationException::withMessages([
'cart_id' => 'One or more product variants do not belong to the tenant.', 'cart_id' => 'One or more buyables could not be loaded.',
]); ]);
} }
return $variants; // Check tenant relation depending on type
if ($item->buyable_type === \App\Domains\Catalog\Models\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) {
throw ValidationException::withMessages([
'cart_id' => 'One or more bundles do not belong to the tenant.',
]);
}
}
} }
/** /**
@@ -182,20 +176,19 @@ class CheckoutService
/** /**
* @param Collection<int, CartItem> $cartItems * @param Collection<int, CartItem> $cartItems
* @param Collection<int, ProductVariant> $variants
* @return array<int, array<string, mixed>> * @return array<int, array<string, mixed>>
*/ */
protected function buildPurchaseItemsPayload(Collection $cartItems, Collection $variants): array protected function buildPurchaseItemsPayload(Collection $cartItems): array
{ {
return $cartItems return $cartItems
->map(function (CartItem $item) use ($variants): array { ->map(function (CartItem $item): array {
/** @var ProductVariant $variant */ $buyable = $item->buyable;
$variant = $variants->get((int) $item['producto_variante_id']);
$quantity = (int) $item['cantidad']; $quantity = (int) $item['cantidad'];
$unitPrice = (float) ($variant->product?->precio ?? 0); $unitPrice = $buyable?->getPrice() ?? 0;
return [ return [
'producto_variante_id' => $variant->getKey(), 'buyable_type' => $item->buyable_type,
'buyable_id' => $item->buyable_id,
'cantidad' => $quantity, 'cantidad' => $quantity,
'precio_unitario' => $unitPrice, 'precio_unitario' => $unitPrice,
'discount_total' => null, 'discount_total' => null,
@@ -208,17 +201,15 @@ class CheckoutService
/** /**
* @param Collection<int, CartItem> $cartItems * @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) { foreach ($cartItems as $item) {
/** @var ProductVariant $variant */ $buyable = $item->buyable;
$variant = $variants->get((int) $item->producto_variante_id);
$quantity = (int) $item->cantidad; $quantity = (int) $item->cantidad;
try { try {
$variant->confirmReservedStock($quantity); $buyable->confirmReservedStock($quantity);
} catch (\InvalidArgumentException $exception) { } catch (\InvalidArgumentException $exception) {
throw ValidationException::withMessages([ throw ValidationException::withMessages([
'cart_id' => 'The selected cart has inconsistent stock state.', 'cart_id' => 'The selected cart has inconsistent stock state.',

View File

@@ -0,0 +1,18 @@
<?php
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 decrementReservedStock(int $amount): void;
public function confirmReservedStock(int $amount): void;
public function validateStock(): void;
}

View File

@@ -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');
}
};

View File

@@ -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');
}
};

View File

@@ -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('carrito_items', function (Blueprint $table) {
$table->string('buyable_type')->nullable();
$table->unsignedBigInteger('buyable_id')->nullable();
});
// Copy existing data
\Illuminate\Support\Facades\DB::table('carrito_items')->update([
'buyable_type' => 'App\Domains\Catalog\Models\ProductVariant',
'buyable_id' => \Illuminate\Support\Facades\DB::raw('producto_variante_id'),
]);
Schema::table('carrito_items', function (Blueprint $table) {
$table->dropForeign(['producto_variante_id']);
$table->dropColumn('producto_variante_id');
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::table('carrito_items', function (Blueprint $table) {
$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'),
]);
Schema::table('carrito_items', function (Blueprint $table) {
$table->dropColumn(['buyable_type', 'buyable_id']);
});
}
};

View File

@@ -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']);
});
}
};