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,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();
}
}