feat(ticket): implement ticket generation on purchase payment and add related tests
This commit is contained in:
@@ -3,6 +3,8 @@
|
||||
namespace App\Domains\Ticket\Exceptions;
|
||||
|
||||
use App\Domains\Catalog\Models\CatalogItem;
|
||||
use App\Domains\Purchase\Models\Purchase;
|
||||
use App\Domains\Purchase\Models\PurchaseItem;
|
||||
use RuntimeException;
|
||||
|
||||
class TicketGenerationException extends RuntimeException
|
||||
@@ -26,4 +28,14 @@ class TicketGenerationException extends RuntimeException
|
||||
{
|
||||
return new self("El producto {$catalogItem->id} alcanzó su fecha máxima de uso.");
|
||||
}
|
||||
|
||||
public static function purchaseWithoutUser(Purchase $purchase): self
|
||||
{
|
||||
return new self("La compra {$purchase->id} no tiene un usuario asociado.");
|
||||
}
|
||||
|
||||
public static function catalogItemNotFound(PurchaseItem $purchaseItem): self
|
||||
{
|
||||
return new self("No se encontró el producto de la línea de compra {$purchaseItem->id}.");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,62 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Ticket\Listeners;
|
||||
|
||||
use App\Domains\Catalog\Models\CatalogItem;
|
||||
use App\Domains\Purchase\Events\PurchasePaid;
|
||||
use App\Domains\Ticket\Exceptions\TicketGenerationException;
|
||||
use App\Domains\Ticket\Services\TicketGeneratorService;
|
||||
|
||||
class GenerateTicketsForPaidPurchase
|
||||
{
|
||||
public function __construct(
|
||||
private readonly TicketGeneratorService $ticketGenerator,
|
||||
) {}
|
||||
|
||||
public function handle(PurchasePaid $event): void
|
||||
{
|
||||
$purchase = $event->purchase
|
||||
->newQuery()
|
||||
->with(['user', 'items'])
|
||||
->findOrFail($event->purchase->getKey());
|
||||
$user = $purchase->user;
|
||||
|
||||
foreach ($purchase->items as $purchaseItem) {
|
||||
$catalogItem = CatalogItem::query()
|
||||
->where('tenant_code', $purchase->tenant_codigo)
|
||||
->find($purchaseItem->source_catalog_item_id);
|
||||
|
||||
if ($catalogItem === null) {
|
||||
throw TicketGenerationException::catalogItemNotFound($purchaseItem);
|
||||
}
|
||||
|
||||
if (! $this->requiresTickets($catalogItem)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if ($user === null) {
|
||||
throw TicketGenerationException::purchaseWithoutUser($purchase);
|
||||
}
|
||||
|
||||
$this->ticketGenerator->generate(
|
||||
$catalogItem,
|
||||
$user,
|
||||
$purchaseItem->cantidad,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
private function requiresTickets(CatalogItem $catalogItem): bool
|
||||
{
|
||||
if (! $catalogItem->isBundle()) {
|
||||
return $catalogItem->has_tickets;
|
||||
}
|
||||
|
||||
return $catalogItem->bundleComponents()
|
||||
->whereHas(
|
||||
'catalogItem',
|
||||
fn ($query) => $query->where('has_tickets', true),
|
||||
)
|
||||
->exists();
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user