refactor(catalog): Complete catalog refactor to simplify its data model and its querying.

source commits: refactor/catalog
This commit is contained in:
2026-07-21 09:23:19 -03:00
parent d3182fbd13
commit 29a2ca19a3
116 changed files with 5141 additions and 5217 deletions

View File

@@ -2,8 +2,6 @@
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;
@@ -12,7 +10,6 @@ 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;
@@ -53,10 +50,10 @@ class PurchaseController extends Controller
$compra = $this->resolveScopedPurchase($tenant, $request->user()->id, $compra);
$compra->loadMissing(['items', 'cart.items']);
$this->loadBuyables($compra->items);
$compra->items->load('imageAttachment');
if ($compra->cart !== null) {
$this->loadBuyables($compra->cart->items);
$this->loadCartCatalogEntries($compra->cart->items);
}
return PurchaseResource::make($compra);
@@ -161,19 +158,13 @@ class PurchaseController extends Controller
/**
* @return list<string>
*/
protected function loadBuyables(Collection $items): void
protected function loadCartCatalogEntries(Collection $items): void
{
$items->load([
'buyable' => function (MorphTo $morphTo): void {
$morphTo->morphWith([
ProductVariant::class => [
'product',
'definitions.productAttribute.attribute',
'attachments',
],
Bundle::class => ['items.variant'],
]);
},
'catalogItem.attachments',
'variant.attachments',
'variant.catalogItem.attachments',
'variant.definitions.itemAttribute.attribute',
]);
}
}

View File

@@ -119,7 +119,7 @@ class Purchase extends Model
$cart = $this->relationLoaded('cart')
? $this->getRelation('cart')
: $this->cart()->with('items.buyable')->first();
: $this->cart()->with(['items.catalogItem', 'items.variant'])->first();
if (! $cart) {
return 0.0;

View File

@@ -2,7 +2,7 @@
namespace App\Domains\Purchase\Models;
use App\Domains\Catalog\Models\ProductVariant;
use App\Domains\Attachable\Models\Attachment;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
@@ -10,8 +10,14 @@ use Illuminate\Database\Eloquent\Relations\BelongsTo;
#[Fillable([
'compra_id',
'buyable_id',
'buyable_type',
'source_catalog_item_id',
'source_variant_id',
'image_attachment_id',
'nombre',
'descripcion',
'slug',
'item_nombre',
'variant_attributes',
'cantidad',
'precio_unitario',
'discount_total',
@@ -28,8 +34,10 @@ class PurchaseItem extends Model
{
return [
'compra_id' => 'integer',
'buyable_id' => 'integer',
'buyable_type' => 'string',
'source_catalog_item_id' => 'integer',
'source_variant_id' => 'integer',
'image_attachment_id' => 'integer',
'variant_attributes' => 'array',
'cantidad' => 'integer',
'precio_unitario' => 'decimal:2',
'discount_total' => 'decimal:2',
@@ -46,11 +54,9 @@ class PurchaseItem extends Model
return $this->belongsTo(Purchase::class, 'compra_id');
}
/**
* @return \Illuminate\Database\Eloquent\Relations\MorphTo
*/
public function buyable()
/** @return BelongsTo<Attachment, $this> */
public function imageAttachment(): BelongsTo
{
return $this->morphTo();
return $this->belongsTo(Attachment::class, 'image_attachment_id');
}
}

View File

@@ -2,136 +2,114 @@
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\Catalog\Models\CatalogItem;
use App\Domains\Catalog\Models\Variant;
use App\Domains\Purchase\Models\PurchaseItem;
use App\Domains\Shared\Contracts\Buyable;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;
/**
* @mixin PurchaseItem|CartItem
*/
/** @mixin PurchaseItem|CartItem */
class PurchaseItemResource extends JsonResource
{
/**
* @return array<string, mixed>
*/
/** @return array<string, mixed> */
public function toArray(Request $request): array
{
/** @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;
if ($this->resource instanceof PurchaseItem) {
$imageUrl = $this->imageAttachment?->getTemporaryUrl(1440);
$attributes = $this->variant_attributes ?? [];
$imageUrl = null;
$attributes = [];
if ($this->buyable_type === ProductVariant::class && $buyable) {
$imageUrl = $this->resolveImageUrl($buyable);
$attributes = $this->resolveAttributes($buyable);
return [
'id' => $this->id,
'quantity' => (int) $this->cantidad,
'unit_price' => $this->formatMoney($this->precio_unitario),
'line_total' => $this->formatMoney($this->total),
'source_catalog_item_id' => $this->source_catalog_item_id,
'source_variant_id' => $this->source_variant_id,
'item_details' => [
'nombre' => $this->item_nombre,
'descripcion' => $this->descripcion,
'slug' => $this->slug,
'imagen' => $imageUrl,
'attributes' => $attributes,
],
];
}
$selectedItem = $this->selectedItem();
$catalogItem = $this->catalogItem;
$variant = $this->variant;
$quantity = (int) ($this->cantidad ?? 0);
$unitPrice = $this->resolveUnitPrice($selectedItem);
$lineTotal = $unitPrice * $quantity;
$imageUrl = $this->resolveImageUrl($selectedItem, $catalogItem);
return [
'id' => $this->id,
'quantity' => $quantity,
'unit_price' => $this->formatMoney($unitPrice),
'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,
'catalog_item_id' => $this->catalog_item_id,
'variant_id' => $this->variant_id,
'product' => $catalogItem === null ? null : [
'id' => $catalogItem->id,
'nombre' => $catalogItem->nombre,
'descripcion' => $catalogItem->descripcion,
'slug' => $catalogItem->slug,
'imagen' => $imageUrl,
],
'variant' => $variant === null ? null : [
'id' => $variant->id,
'attributes' => $attributes,
'attributes' => $this->resolveAttributes($variant),
],
'item_details' => $buyable === null ? null : [
'nombre' => $buyable->getName(),
'item_details' => $selectedItem === null ? null : [
'nombre' => $selectedItem->getName(),
'descripcion' => $catalogItem?->descripcion,
'imagen' => $imageUrl,
'attributes' => $attributes,
'attributes' => $variant === null ? [] : $this->resolveAttributes($variant),
],
];
}
protected function mapBuyableTypeToAlias(?string $type): string
private function resolveUnitPrice(CatalogItem|Variant|null $selectedItem): float
{
return match ($type) {
ProductVariant::class => 'variant',
Bundle::class => 'bundle',
default => 'unknown',
};
return (float) ($selectedItem?->getPrice() ?? 0);
}
protected function resolveUnitPrice(): float
{
if ($this->resource instanceof PurchaseItem) {
return (float) ($this->precio_unitario ?? 0);
private function resolveImageUrl(
CatalogItem|Variant|null $selectedItem,
?CatalogItem $catalogItem,
): ?string {
$attachment = $selectedItem?->relationLoaded('attachments')
? $selectedItem->attachments->first()
: null;
if ($attachment === null && $catalogItem?->relationLoaded('attachments')) {
$attachment = $catalogItem->attachments->first();
}
if ($this->resource instanceof CartItem) {
return (float) ($this->buyable?->getPrice() ?? 0);
}
return 0.0;
return $attachment?->getTemporaryUrl(1440);
}
protected function resolveLineTotal(float $unitPrice, int $quantity): float
/** @return array<int, array{name: string, value: mixed}> */
private function resolveAttributes(Variant $variant): array
{
if ($this->resource instanceof PurchaseItem) {
return (float) ($this->total ?? 0);
}
return $unitPrice * $quantity;
}
protected function resolveImageUrl($buyable): ?string
{
if (! $buyable->relationLoaded('attachments')) {
return null;
}
$attachment = $buyable->attachments->first();
if ($attachment === null) {
return null;
}
return $attachment->getTemporaryUrl(1440);
}
/**
* @return array<int, array{name: string, value: mixed}>
*/
protected function resolveAttributes($buyable): array
{
if (! $buyable->relationLoaded('definitions')) {
if (! $variant->relationLoaded('definitions')) {
return [];
}
return $buyable->definitions
->map(function ($definition): array {
return [
'name' => (string) ($definition->productAttribute?->attribute?->nombre ?? ''),
'value' => $definition->value,
];
})
return $variant->definitions
->map(fn ($definition): array => [
'name' => (string) ($definition->itemAttribute?->attribute?->nombre ?? ''),
'value' => $definition->value,
])
->filter(fn (array $attribute): bool => $attribute['name'] !== '' || $attribute['value'] !== null)
->values()
->all();
}
protected function formatMoney(float|int|string|null $amount): ?string
private function formatMoney(float|int|string|null $amount): string
{
if ($amount === null) {
return null;
}
return number_format((float) $amount, 2, '.', '');
return number_format((float) ($amount ?? 0), 2, '.', '');
}
}

View File

@@ -89,7 +89,7 @@ class PurchaseResource extends JsonResource
return (float) $item->precio_unitario * $item->cantidad;
}
return (float) ($item->buyable?->getPrice() ?? 0) * $item->cantidad;
return (float) ($item->selectedItem()?->getPrice() ?? 0) * $item->cantidad;
}
protected function resolveItemTotal(PurchaseItem|CartItem $item): float

View File

@@ -2,19 +2,28 @@
namespace App\Domains\Purchase\Services;
use App\Domains\Attachable\Models\Attachment;
use App\Domains\Attachable\Services\AttachmentService;
use App\Domains\Cart\Models\Cart;
use App\Domains\Cart\Models\CartItem;
use App\Domains\Bundle\Models\Bundle;
use App\Domains\Catalog\Models\ProductVariant;
use App\Domains\Catalog\Models\Variant;
use App\Domains\Catalog\Services\CatalogInventoryService;
use App\Domains\Purchase\Models\Purchase;
use App\Domains\Tenant\Models\Tenant;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;
use Illuminate\Validation\ValidationException;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Throwable;
class CheckoutService
{
public function __construct(
private readonly AttachmentService $attachmentService,
private readonly CatalogInventoryService $catalogInventoryService,
) {}
public function startCheckout(Tenant $tenant, int $userId, array $purchaseData): Purchase
{
$cartId = (int) $purchaseData['cart_id'];
@@ -30,7 +39,7 @@ class CheckoutService
]);
}
$cartItems->load('buyable');
$this->loadCartItems($cartItems);
$cart->setRelation('items', $cartItems);
$totalAmount = $cart->getTotalAmount();
@@ -64,7 +73,7 @@ class CheckoutService
$purchase->save();
}
return $purchase->load(['items.buyable']);
return $this->loadPurchase($purchase);
});
}
@@ -83,7 +92,7 @@ class CheckoutService
}
if (in_array($purchase->status, [Purchase::STATUS_PAID, Purchase::STATUS_CANCELLED, Purchase::STATUS_REJECTED], true)) {
return $purchase->load(['items.buyable']);
return $this->loadPurchase($purchase);
}
$purchase->update([
@@ -91,67 +100,71 @@ class CheckoutService
'total' => $purchase->calculateCurrentTotalAmount(),
]);
return $purchase->load(['items.buyable']);
return $this->loadPurchase($purchase);
});
}
public function confirmPurchase(Purchase $purchase): void
{
DB::transaction(function () use ($purchase): void {
/** @var Purchase $purchase */
$purchase = Purchase::query()
->lockForUpdate()
->findOrFail($purchase->getKey());
$snapshotPaths = [];
if ($purchase->items()->exists()) {
return;
try {
DB::transaction(function () use ($purchase, &$snapshotPaths): void {
/** @var Purchase $purchase */
$purchase = Purchase::query()
->lockForUpdate()
->findOrFail($purchase->getKey());
if ($purchase->items()->exists()) {
return;
}
/** @var Cart|null $cart */
$cart = $purchase->cart()->lockForUpdate()->first();
if ($cart === null) {
throw ValidationException::withMessages([
'cart_id' => 'The purchase cart is no longer available.',
]);
}
$cartItems = $cart->items()->lockForUpdate()->get();
if ($cartItems->isEmpty()) {
throw ValidationException::withMessages([
'cart_id' => 'The purchase cart does not contain items.',
]);
}
$this->loadCartItems($cartItems);
$this->verifyTenantItems($purchase->tenant, $cartItems);
$purchaseItemsPayload = $this->buildPurchaseItemsPayload($purchase, $cartItems, $snapshotPaths);
$purchase->items()->createMany($purchaseItemsPayload);
$this->completeCartConversion($cart, $cartItems);
});
} catch (Throwable $throwable) {
foreach ($snapshotPaths as $snapshotPath) {
Storage::disk('s3')->delete($snapshotPath);
}
/** @var Cart|null $cart */
$cart = $purchase->cart()->lockForUpdate()->first();
if ($cart === null) {
throw ValidationException::withMessages([
'cart_id' => 'The purchase cart is no longer available.',
]);
}
$cartItems = $cart->items()->lockForUpdate()->get();
if ($cartItems->isEmpty()) {
throw ValidationException::withMessages([
'cart_id' => 'The purchase cart does not contain items.',
]);
}
$cartItems->load('buyable');
$this->verifyTenantBuyables($purchase->tenant, $cartItems);
$purchaseItemsPayload = $this->buildPurchaseItemsPayload($cartItems);
$purchase->items()->createMany($purchaseItemsPayload);
$this->completeCartConversion($cart, $cartItems);
});
throw $throwable;
}
}
protected function verifyTenantBuyables(Tenant $tenant, Collection $cartItems): void
protected function verifyTenantItems(Tenant $tenant, Collection $cartItems): void
{
foreach ($cartItems as $item) {
$buyable = $item->buyable;
if ($buyable === null) {
$selectedItem = $item->selectedItem();
if ($selectedItem === null) {
throw ValidationException::withMessages([
'cart_id' => 'One or more buyables could not be loaded.',
'cart_id' => 'One or more catalog items could not be loaded.',
]);
}
if ($item->buyable_type === ProductVariant::class && $buyable->product->tenant_codigo !== $tenant->codigo) {
if ($item->catalogItem?->tenant_code !== $tenant->codigo) {
throw ValidationException::withMessages([
'cart_id' => 'One or more product variants do not belong to the tenant.',
]);
}
if ($item->buyable_type === Bundle::class && $buyable->tenant_codigo !== $tenant->codigo) {
throw ValidationException::withMessages([
'cart_id' => 'One or more bundles do not belong to the tenant.',
'cart_id' => 'One or more catalog items do not belong to the tenant.',
]);
}
}
@@ -159,7 +172,7 @@ class CheckoutService
/**
* @param Collection<int, CartItem> $cartItems
* @return Collection<int, ProductVariant>
* @return Collection<int, CartItem>
*/
protected function resolveCheckoutCart(Tenant $tenant, int $userId, int $cartId): Cart
{
@@ -185,17 +198,33 @@ class CheckoutService
* @param Collection<int, CartItem> $cartItems
* @return array<int, array<string, mixed>>
*/
protected function buildPurchaseItemsPayload(Collection $cartItems): array
{
protected function buildPurchaseItemsPayload(
Purchase $purchase,
Collection $cartItems,
array &$snapshotPaths = [],
): array {
return $cartItems
->map(function (CartItem $item): array {
$buyable = $item->buyable;
->map(function (CartItem $item) use ($purchase, &$snapshotPaths): array {
$selectedItem = $item->selectedItem();
$quantity = (int) $item['cantidad'];
$unitPrice = $buyable?->getPrice() ?? 0;
$unitPrice = $selectedItem?->getPrice() ?? 0;
$imageAttachment = $this->snapshotFirstImage($purchase, $item);
if ($imageAttachment !== null) {
$snapshotPaths[] = $imageAttachment->path;
}
return [
'buyable_type' => $item->buyable_type,
'buyable_id' => $item->buyable_id,
'source_catalog_item_id' => $item->catalog_item_id,
'source_variant_id' => $item->variant_id,
'image_attachment_id' => $imageAttachment?->id,
'nombre' => $item->catalogItem->nombre,
'descripcion' => $item->catalogItem->descripcion,
'slug' => $item->catalogItem->slug,
'item_nombre' => $selectedItem->getName(),
'variant_attributes' => $item->variant === null
? []
: $this->snapshotAttributes($item->variant),
'cantidad' => $quantity,
'precio_unitario' => $unitPrice,
'discount_total' => null,
@@ -212,11 +241,14 @@ class CheckoutService
protected function completeCartConversion(Cart $cart, Collection $cartItems): void
{
foreach ($cartItems as $item) {
$buyable = $item->buyable;
$selectedItem = $item->selectedItem();
$quantity = (int) $item->cantidad;
try {
$buyable->buy($quantity);
$this->catalogInventoryService->commit(
$selectedItem,
$quantity,
);
} catch (\InvalidArgumentException $exception) {
throw ValidationException::withMessages([
'cart_id' => 'The selected cart has inconsistent stock state.',
@@ -230,4 +262,52 @@ class CheckoutService
$cart->save();
$cart->delete();
}
/** @param Collection<int, CartItem> $cartItems */
private function loadCartItems(Collection $cartItems): void
{
$cartItems->load([
'catalogItem.inventory',
'catalogItem.attachments',
'variant.inventory',
'variant.attachments',
'variant.catalogItem',
'variant.definitions.itemAttribute.attribute',
]);
}
private function loadPurchase(Purchase $purchase): Purchase
{
return $purchase->load([
'items.imageAttachment',
]);
}
private function snapshotFirstImage(Purchase $purchase, CartItem $item): ?Attachment
{
$source = $item->variant?->attachments->first()
?? $item->catalogItem?->attachments->first();
if ($source === null) {
return null;
}
return $this->attachmentService->copy(
$source,
"purchase/{$purchase->id}",
);
}
/** @return array<int, array{name: string, value: mixed}> */
private function snapshotAttributes(Variant $variant): array
{
return $variant->definitions
->map(fn ($definition): array => [
'name' => (string) ($definition->itemAttribute?->attribute?->nombre ?? ''),
'value' => $definition->value,
])
->filter(fn (array $attribute): bool => $attribute['name'] !== '' || $attribute['value'] !== null)
->values()
->all();
}
}