refactor(checkout): split checkout workflows into focused services
This commit is contained in:
@@ -0,0 +1,65 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Purchase\Services\Checkout;
|
||||
|
||||
use App\Domains\Attachable\Models\Attachment;
|
||||
use App\Domains\Cart\Models\CartItem;
|
||||
use App\Domains\Catalog\Models\Variant;
|
||||
use App\Domains\Purchase\Models\PurchaseItem;
|
||||
use Illuminate\Support\Collection;
|
||||
|
||||
class PurchaseItemSnapshotFactory
|
||||
{
|
||||
/**
|
||||
* @param Collection<int, CartItem> $cartItems
|
||||
* @return array<int, array<string, mixed>>
|
||||
*/
|
||||
public function fromCartItems(Collection $cartItems): array
|
||||
{
|
||||
return $cartItems
|
||||
->map(function (CartItem $item): array {
|
||||
$selectedItem = $item->selectedItem();
|
||||
$quantity = (int) $item->cantidad;
|
||||
$unitPrice = $selectedItem?->getPrice() ?? 0;
|
||||
|
||||
return [
|
||||
'source_catalog_item_id' => $item->catalog_item_id,
|
||||
'source_variant_id' => $item->variant_id,
|
||||
'image_attachment_id' => $this->firstImageAttachment($item)?->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,
|
||||
'tax_total' => null,
|
||||
'total' => $unitPrice * $quantity,
|
||||
'reservation_status' => PurchaseItem::RESERVATION_ACTIVE,
|
||||
];
|
||||
})
|
||||
->all();
|
||||
}
|
||||
|
||||
private function firstImageAttachment(CartItem $item): ?Attachment
|
||||
{
|
||||
return $item->variant?->attachments->first()
|
||||
?? $item->catalogItem?->attachments->first();
|
||||
}
|
||||
|
||||
/** @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();
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user