feat(ticket): implement ticket generation service, model, and exception handling with tests

This commit is contained in:
2026-07-21 11:20:52 -03:00
parent c3f54c79cb
commit a928a2e848
6 changed files with 526 additions and 0 deletions

View File

@@ -0,0 +1,29 @@
<?php
namespace App\Domains\Ticket\Exceptions;
use App\Domains\Catalog\Models\CatalogItem;
use RuntimeException;
class TicketGenerationException extends RuntimeException
{
public static function invalidQuantity(): self
{
return new self('La cantidad de tickets a generar debe ser mayor a cero.');
}
public static function emptyBundle(CatalogItem $bundle): self
{
return new self("El bundle {$bundle->id} no tiene componentes.");
}
public static function ticketsDisabled(CatalogItem $catalogItem): self
{
return new self("El producto {$catalogItem->id} no tiene tickets habilitados.");
}
public static function maximumUseDateReached(CatalogItem $catalogItem): self
{
return new self("El producto {$catalogItem->id} alcanzó su fecha máxima de uso.");
}
}

View File

@@ -0,0 +1,81 @@
<?php
namespace App\Domains\Ticket\Models;
use App\Domains\Auth\Models\User;
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;
#[Fillable([
'tenant_code',
'ticket',
'name',
'description',
'starts_at',
'expires_at',
'used_at',
'user_id',
])]
class Ticket extends Model
{
use HasFactory;
public $timestamps = false;
protected $appends = [
'is_valid',
'is_expired',
'is_used',
];
protected function casts(): array
{
return [
'starts_at' => 'datetime',
'expires_at' => 'datetime',
'used_at' => 'datetime',
'user_id' => 'integer',
];
}
/** @return BelongsTo<Tenant, $this> */
public function tenant(): BelongsTo
{
return $this->belongsTo(Tenant::class, 'tenant_code', 'codigo');
}
/** @return BelongsTo<User, $this> */
public function user(): BelongsTo
{
return $this->belongsTo(User::class);
}
public function isValid(): bool
{
$now = now();
return $this->used_at === null
&& ($this->starts_at === null || $this->starts_at->lessThanOrEqualTo($now))
&& ($this->expires_at === null || $this->expires_at->greaterThan($now));
}
public function getIsValidAttribute(): bool
{
return $this->isValid();
}
public function getIsExpiredAttribute(): bool
{
return $this->used_at === null
&& $this->expires_at !== null
&& $this->expires_at->lessThanOrEqualTo(now());
}
public function getIsUsedAttribute(): bool
{
return $this->used_at !== null;
}
}

View File

@@ -0,0 +1,86 @@
<?php
namespace App\Domains\Ticket\Services;
use App\Domains\Auth\Models\User;
use App\Domains\Catalog\Models\CatalogItem;
use App\Domains\Ticket\Exceptions\TicketGenerationException;
use App\Domains\Ticket\Models\Ticket;
use Carbon\CarbonInterface;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
class TicketGeneratorService
{
/**
* @return Collection<int, Ticket>
*/
public function generate(CatalogItem $catalogItem, User $user, int $quantity = 1): Collection
{
if ($quantity < 1) {
throw TicketGenerationException::invalidQuantity();
}
$now = now();
return DB::transaction(function () use ($catalogItem, $user, $quantity, $now): Collection {
$catalogItems = $this->resolveCatalogItems($catalogItem, $quantity, $now);
return $catalogItems->map(fn (CatalogItem $item): Ticket => Ticket::query()->create([
'tenant_code' => $item->tenant_code,
'ticket' => (string) Str::uuid(),
'name' => $item->nombre,
'description' => (string) ($item->descripcion ?? ''),
'starts_at' => $item->minimum_use_date,
'expires_at' => $item->maximum_use_date,
'used_at' => null,
'user_id' => $user->getKey(),
]));
});
}
/**
* @return Collection<int, CatalogItem>
*/
private function resolveCatalogItems(
CatalogItem $catalogItem,
int $quantity,
CarbonInterface $now,
): Collection {
if (! $catalogItem->isBundle()) {
$this->validateCatalogItem($catalogItem, $now);
return Collection::times($quantity, fn (): CatalogItem => $catalogItem);
}
$catalogItem->loadMissing('bundleComponents.catalogItem');
if ($catalogItem->bundleComponents->isEmpty()) {
throw TicketGenerationException::emptyBundle($catalogItem);
}
return $catalogItem->bundleComponents
->flatMap(function ($component) use ($quantity, $now): Collection {
$componentItem = $component->catalogItem;
$this->validateCatalogItem($componentItem, $now);
return Collection::times(
$quantity * $component->quantity,
fn (): CatalogItem => $componentItem,
);
})
->values();
}
private function validateCatalogItem(CatalogItem $catalogItem, CarbonInterface $now): void
{
if (! $catalogItem->has_tickets) {
throw TicketGenerationException::ticketsDisabled($catalogItem);
}
if ($catalogItem->maximum_use_date?->lessThanOrEqualTo($now)) {
throw TicketGenerationException::maximumUseDateReached($catalogItem);
}
}
}