Compare commits
4 Commits
c3f54c79cb
...
e1a67fd9f3
| Author | SHA1 | Date | |
|---|---|---|---|
| e1a67fd9f3 | |||
| 38f74739da | |||
| c0978033c1 | |||
| a928a2e848 |
14
app/Domains/Purchase/Events/PurchasePaid.php
Normal file
14
app/Domains/Purchase/Events/PurchasePaid.php
Normal file
@@ -0,0 +1,14 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Purchase\Events;
|
||||
|
||||
use App\Domains\Purchase\Models\Purchase;
|
||||
use Illuminate\Foundation\Events\Dispatchable;
|
||||
use Illuminate\Queue\SerializesModels;
|
||||
|
||||
class PurchasePaid
|
||||
{
|
||||
use Dispatchable, SerializesModels;
|
||||
|
||||
public function __construct(public readonly Purchase $purchase) {}
|
||||
}
|
||||
@@ -4,6 +4,7 @@ namespace App\Domains\Purchase\Models;
|
||||
|
||||
use App\Domains\Auth\Models\User;
|
||||
use App\Domains\Cart\Models\Cart;
|
||||
use App\Domains\Purchase\Events\PurchasePaid;
|
||||
use App\Domains\Tenant\Models\Tenant;
|
||||
use Illuminate\Database\Eloquent\Attributes\Fillable;
|
||||
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
||||
@@ -11,6 +12,7 @@ use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
use Illuminate\Database\Eloquent\Relations\HasMany;
|
||||
use Illuminate\Database\Eloquent\Relations\HasOne;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
|
||||
#[Fillable([
|
||||
'cart_id',
|
||||
@@ -137,8 +139,23 @@ class Purchase extends Model
|
||||
|
||||
public function markAsPaid(): void
|
||||
{
|
||||
$this->update([
|
||||
'status' => self::STATUS_PAID,
|
||||
]);
|
||||
DB::transaction(function (): void {
|
||||
$currentStatus = self::query()
|
||||
->whereKey($this->getKey())
|
||||
->lockForUpdate()
|
||||
->value('status');
|
||||
|
||||
if ($currentStatus === self::STATUS_PAID) {
|
||||
$this->status = self::STATUS_PAID;
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$this->update([
|
||||
'status' => self::STATUS_PAID,
|
||||
]);
|
||||
|
||||
PurchasePaid::dispatch($this);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
24
app/Domains/Ticket/Controllers/TicketController.php
Normal file
24
app/Domains/Ticket/Controllers/TicketController.php
Normal file
@@ -0,0 +1,24 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Ticket\Controllers;
|
||||
|
||||
use App\Domains\Tenant\Models\Tenant;
|
||||
use App\Domains\Ticket\Models\Ticket;
|
||||
use App\Domains\Ticket\Resources\TicketResource;
|
||||
use App\Http\Controllers\Controller;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\Request;
|
||||
|
||||
class TicketController extends Controller
|
||||
{
|
||||
public function index(Request $request, Tenant $tenant): JsonResponse
|
||||
{
|
||||
$tickets = Ticket::query()
|
||||
->where('tenant_code', $tenant->codigo)
|
||||
->where('user_id', $request->user()->getKey())
|
||||
->orderByDesc('id')
|
||||
->get();
|
||||
|
||||
return TicketResource::collection($tickets)->response();
|
||||
}
|
||||
}
|
||||
41
app/Domains/Ticket/Exceptions/TicketGenerationException.php
Normal file
41
app/Domains/Ticket/Exceptions/TicketGenerationException.php
Normal file
@@ -0,0 +1,41 @@
|
||||
<?php
|
||||
|
||||
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
|
||||
{
|
||||
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.");
|
||||
}
|
||||
|
||||
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,63 @@
|
||||
<?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,
|
||||
$purchaseItem->source_variant_id,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
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();
|
||||
}
|
||||
}
|
||||
85
app/Domains/Ticket/Models/Ticket.php
Normal file
85
app/Domains/Ticket/Models/Ticket.php
Normal file
@@ -0,0 +1,85 @@
|
||||
<?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',
|
||||
'source_catalog_item_id',
|
||||
'source_variant_id',
|
||||
'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 [
|
||||
'source_catalog_item_id' => 'integer',
|
||||
'source_variant_id' => 'integer',
|
||||
'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;
|
||||
}
|
||||
}
|
||||
31
app/Domains/Ticket/Resources/TicketResource.php
Normal file
31
app/Domains/Ticket/Resources/TicketResource.php
Normal file
@@ -0,0 +1,31 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Ticket\Resources;
|
||||
|
||||
use App\Domains\Ticket\Models\Ticket;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Http\Resources\Json\JsonResource;
|
||||
|
||||
/** @mixin Ticket */
|
||||
class TicketResource extends JsonResource
|
||||
{
|
||||
/** @return array<string, mixed> */
|
||||
public function toArray(Request $request): array
|
||||
{
|
||||
return [
|
||||
'id' => $this->id,
|
||||
'tenant_code' => $this->tenant_code,
|
||||
'ticket' => $this->ticket,
|
||||
'name' => $this->name,
|
||||
'description' => $this->description,
|
||||
'source_catalog_item_id' => $this->source_catalog_item_id,
|
||||
'source_variant_id' => $this->source_variant_id,
|
||||
'starts_at' => $this->starts_at,
|
||||
'expires_at' => $this->expires_at,
|
||||
'used_at' => $this->used_at,
|
||||
'is_valid' => $this->is_valid,
|
||||
'is_expired' => $this->is_expired,
|
||||
'is_used' => $this->is_used,
|
||||
];
|
||||
}
|
||||
}
|
||||
92
app/Domains/Ticket/Services/TicketGeneratorService.php
Normal file
92
app/Domains/Ticket/Services/TicketGeneratorService.php
Normal file
@@ -0,0 +1,92 @@
|
||||
<?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,
|
||||
?int $sourceVariantId = null,
|
||||
): Collection {
|
||||
if ($quantity < 1) {
|
||||
throw TicketGenerationException::invalidQuantity();
|
||||
}
|
||||
|
||||
$now = now();
|
||||
|
||||
return DB::transaction(function () use ($catalogItem, $user, $quantity, $sourceVariantId, $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 ?? ''),
|
||||
'source_catalog_item_id' => $catalogItem->getKey(),
|
||||
'source_variant_id' => $sourceVariantId,
|
||||
'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);
|
||||
}
|
||||
}
|
||||
}
|
||||
10
app/Domains/Ticket/routes/api.php
Normal file
10
app/Domains/Ticket/routes/api.php
Normal file
@@ -0,0 +1,10 @@
|
||||
<?php
|
||||
|
||||
use App\Domains\Ticket\Controllers\TicketController;
|
||||
use Illuminate\Support\Facades\Route;
|
||||
|
||||
Route::prefix('tenants/{tenant:codigo}')
|
||||
->middleware('auth:sanctum')
|
||||
->group(function (): void {
|
||||
Route::get('tickets', [TicketController::class, 'index']);
|
||||
});
|
||||
@@ -2,7 +2,10 @@
|
||||
|
||||
namespace App\Providers;
|
||||
|
||||
use App\Domains\Purchase\Events\PurchasePaid;
|
||||
use App\Domains\Ticket\Listeners\GenerateTicketsForPaidPurchase;
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
use Illuminate\Support\Facades\Event;
|
||||
use Illuminate\Support\ServiceProvider;
|
||||
|
||||
class AppServiceProvider extends ServiceProvider
|
||||
@@ -20,6 +23,8 @@ class AppServiceProvider extends ServiceProvider
|
||||
*/
|
||||
public function boot(): void
|
||||
{
|
||||
Event::listen(PurchasePaid::class, GenerateTicketsForPaidPurchase::class);
|
||||
|
||||
Builder::macro('paginateFromRequest', function (int $defaultPerPage = 15, int $maxPerPage = 100, ?int $page = null) {
|
||||
/** @var Builder $this */
|
||||
$perPage = (int) request()->query('per_page', $defaultPerPage);
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Database\Migrations\Migration;
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
|
||||
return new class extends Migration
|
||||
{
|
||||
public function up(): void
|
||||
{
|
||||
Schema::create('tickets', function (Blueprint $table): void {
|
||||
$table->id();
|
||||
$table->string('tenant_code');
|
||||
$table->uuid('ticket');
|
||||
$table->string('name');
|
||||
$table->text('description');
|
||||
$table->dateTime('starts_at')->nullable();
|
||||
$table->dateTime('expires_at')->nullable();
|
||||
$table->dateTime('used_at')->nullable();
|
||||
$table->foreignId('user_id')->constrained()->cascadeOnUpdate()->restrictOnDelete();
|
||||
|
||||
$table->foreign('tenant_code')
|
||||
->references('codigo')
|
||||
->on('tenants')
|
||||
->cascadeOnUpdate()
|
||||
->restrictOnDelete();
|
||||
});
|
||||
}
|
||||
|
||||
public function down(): void
|
||||
{
|
||||
Schema::dropIfExists('tickets');
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,23 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Database\Migrations\Migration;
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
|
||||
return new class extends Migration
|
||||
{
|
||||
public function up(): void
|
||||
{
|
||||
Schema::table('tickets', function (Blueprint $table): void {
|
||||
$table->unsignedBigInteger('source_catalog_item_id')->nullable()->after('description');
|
||||
$table->unsignedBigInteger('source_variant_id')->nullable()->after('source_catalog_item_id');
|
||||
});
|
||||
}
|
||||
|
||||
public function down(): void
|
||||
{
|
||||
Schema::table('tickets', function (Blueprint $table): void {
|
||||
$table->dropColumn(['source_catalog_item_id', 'source_variant_id']);
|
||||
});
|
||||
}
|
||||
};
|
||||
@@ -8,3 +8,4 @@ require __DIR__.'/../app/Domains/Purchase/routes/api.php';
|
||||
require __DIR__.'/../app/Domains/Tenant/routes/api.php';
|
||||
require __DIR__.'/../app/Domains/Integration/routes/api.php';
|
||||
require __DIR__.'/../app/Domains/Menu/routes/api.php';
|
||||
require __DIR__.'/../app/Domains/Ticket/routes/api.php';
|
||||
|
||||
104
tests/Feature/Ticket/TicketControllerTest.php
Normal file
104
tests/Feature/Ticket/TicketControllerTest.php
Normal file
@@ -0,0 +1,104 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature\Ticket;
|
||||
|
||||
use App\Domains\Attachable\Enums\AttachmentType;
|
||||
use App\Domains\Attachable\Models\Attachment;
|
||||
use App\Domains\Auth\Models\User;
|
||||
use App\Domains\Tenant\Models\Tenant;
|
||||
use App\Domains\Ticket\Models\Ticket;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Illuminate\Support\Str;
|
||||
use Tests\TestCase;
|
||||
|
||||
class TicketControllerTest extends TestCase
|
||||
{
|
||||
use RefreshDatabase;
|
||||
|
||||
public function test_an_authenticated_user_can_list_their_tickets_for_the_tenant(): void
|
||||
{
|
||||
$tenant = $this->createTenant('current');
|
||||
$user = User::factory()->create();
|
||||
$olderTicket = $this->createTicket($tenant, $user, 'Older ticket');
|
||||
$newerTicket = $this->createTicket($tenant, $user, 'Newer ticket');
|
||||
|
||||
$this->actingAs($user, 'sanctum')
|
||||
->getJson("/api/tenants/{$tenant->codigo}/tickets")
|
||||
->assertOk()
|
||||
->assertJsonCount(2, 'data')
|
||||
->assertJsonPath('data.0.id', $newerTicket->id)
|
||||
->assertJsonPath('data.0.name', 'Newer ticket')
|
||||
->assertJsonPath('data.0.is_valid', true)
|
||||
->assertJsonPath('data.0.is_expired', false)
|
||||
->assertJsonPath('data.0.is_used', false)
|
||||
->assertJsonPath('data.1.id', $olderTicket->id)
|
||||
->assertJsonMissingPath('meta')
|
||||
->assertJsonMissingPath('links');
|
||||
}
|
||||
|
||||
public function test_it_does_not_include_tickets_from_other_users_or_tenants(): void
|
||||
{
|
||||
$tenant = $this->createTenant('current');
|
||||
$otherTenant = $this->createTenant('other');
|
||||
$user = User::factory()->create();
|
||||
$otherUser = User::factory()->create();
|
||||
$visibleTicket = $this->createTicket($tenant, $user, 'Visible');
|
||||
$this->createTicket($tenant, $otherUser, 'Other user');
|
||||
$this->createTicket($otherTenant, $user, 'Other tenant');
|
||||
|
||||
$this->actingAs($user, 'sanctum')
|
||||
->getJson("/api/tenants/{$tenant->codigo}/tickets")
|
||||
->assertOk()
|
||||
->assertJsonCount(1, 'data')
|
||||
->assertJsonPath('data.0.id', $visibleTicket->id);
|
||||
}
|
||||
|
||||
public function test_authentication_is_required_to_list_tickets(): void
|
||||
{
|
||||
$tenant = $this->createTenant('current');
|
||||
|
||||
$this->getJson("/api/tenants/{$tenant->codigo}/tickets")
|
||||
->assertUnauthorized();
|
||||
}
|
||||
|
||||
private function createTicket(Tenant $tenant, User $user, string $name): Ticket
|
||||
{
|
||||
return Ticket::query()->create([
|
||||
'tenant_code' => $tenant->codigo,
|
||||
'ticket' => (string) Str::uuid(),
|
||||
'name' => $name,
|
||||
'description' => "Description for {$name}",
|
||||
'user_id' => $user->id,
|
||||
]);
|
||||
}
|
||||
|
||||
private function createTenant(string $code): Tenant
|
||||
{
|
||||
$headerLogo = $this->createAttachment("{$code}-header");
|
||||
$footerLogo = $this->createAttachment("{$code}-footer");
|
||||
|
||||
return Tenant::query()->create([
|
||||
'codigo' => $code,
|
||||
'nombre' => ucfirst($code),
|
||||
'dominio' => "{$code}.local",
|
||||
'primary_color' => '#000000',
|
||||
'secondary_color' => '#000000',
|
||||
'danger_color' => '#000000',
|
||||
'success_color' => '#000000',
|
||||
'header_bg_color' => '#000000',
|
||||
'footer_bg_color' => '#000000',
|
||||
'header_logo_id' => $headerLogo->id,
|
||||
'footer_logo_id' => $footerLogo->id,
|
||||
]);
|
||||
}
|
||||
|
||||
private function createAttachment(string $name): Attachment
|
||||
{
|
||||
return Attachment::query()->create([
|
||||
'path' => "test/{$name}.png",
|
||||
'filename' => "{$name}.png",
|
||||
'type' => AttachmentType::Image,
|
||||
'mime_type' => 'image/png',
|
||||
]);
|
||||
}
|
||||
}
|
||||
275
tests/Feature/Ticket/TicketGeneratorServiceTest.php
Normal file
275
tests/Feature/Ticket/TicketGeneratorServiceTest.php
Normal file
@@ -0,0 +1,275 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature\Ticket;
|
||||
|
||||
use App\Domains\Attachable\Enums\AttachmentType;
|
||||
use App\Domains\Attachable\Models\Attachment;
|
||||
use App\Domains\Auth\Models\User;
|
||||
use App\Domains\Catalog\Enums\CatalogItemType;
|
||||
use App\Domains\Catalog\Models\CatalogItem;
|
||||
use App\Domains\Purchase\Models\Purchase;
|
||||
use App\Domains\Tenant\Models\Tenant;
|
||||
use App\Domains\Ticket\Exceptions\TicketGenerationException;
|
||||
use App\Domains\Ticket\Services\TicketGeneratorService;
|
||||
use Illuminate\Database\Eloquent\Collection as EloquentCollection;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Illuminate\Support\Carbon;
|
||||
use Illuminate\Support\Str;
|
||||
use Tests\TestCase;
|
||||
|
||||
class TicketGeneratorServiceTest extends TestCase
|
||||
{
|
||||
use RefreshDatabase;
|
||||
|
||||
private TicketGeneratorService $service;
|
||||
|
||||
private Tenant $tenant;
|
||||
|
||||
private User $user;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
|
||||
Carbon::setTestNow('2026-07-21 10:00:00');
|
||||
$this->service = app(TicketGeneratorService::class);
|
||||
$this->tenant = $this->createTenant();
|
||||
$this->user = User::factory()->create();
|
||||
}
|
||||
|
||||
protected function tearDown(): void
|
||||
{
|
||||
Carbon::setTestNow();
|
||||
|
||||
parent::tearDown();
|
||||
}
|
||||
|
||||
public function test_it_generates_tickets_from_a_standard_catalog_item(): void
|
||||
{
|
||||
$item = $this->createTicketableItem(
|
||||
'single-day',
|
||||
now()->subHour(),
|
||||
now()->addDay(),
|
||||
);
|
||||
|
||||
$tickets = $this->service->generate($item, $this->user, 2);
|
||||
|
||||
$this->assertCount(2, $tickets);
|
||||
foreach ($tickets as $ticket) {
|
||||
$this->assertTrue(Str::isUuid($ticket->ticket));
|
||||
$this->assertSame($this->tenant->codigo, $ticket->tenant_code);
|
||||
$this->assertSame($this->user->id, $ticket->user_id);
|
||||
$this->assertSame($item->nombre, $ticket->name);
|
||||
$this->assertSame($item->descripcion, $ticket->description);
|
||||
$this->assertSame($item->id, $ticket->source_catalog_item_id);
|
||||
$this->assertNull($ticket->source_variant_id);
|
||||
$this->assertTrue($ticket->starts_at->equalTo($item->minimum_use_date));
|
||||
$this->assertTrue($ticket->expires_at->equalTo($item->maximum_use_date));
|
||||
}
|
||||
}
|
||||
|
||||
public function test_it_rejects_an_item_without_tickets_enabled(): void
|
||||
{
|
||||
$item = $this->createTicketableItem('disabled');
|
||||
$item->update(['has_tickets' => false]);
|
||||
|
||||
$this->expectException(TicketGenerationException::class);
|
||||
$this->expectExceptionMessage('no tiene tickets habilitados');
|
||||
|
||||
$this->service->generate($item->fresh(), $this->user);
|
||||
}
|
||||
|
||||
public function test_it_rejects_an_item_when_its_maximum_use_date_was_reached(): void
|
||||
{
|
||||
$item = $this->createTicketableItem('expired', maximumUseDate: now());
|
||||
|
||||
$this->expectException(TicketGenerationException::class);
|
||||
$this->expectExceptionMessage('alcanzó su fecha máxima de uso');
|
||||
|
||||
$this->service->generate($item, $this->user);
|
||||
}
|
||||
|
||||
public function test_it_generates_tickets_for_every_bundle_component_and_quantity(): void
|
||||
{
|
||||
$first = $this->createTicketableItem('first', maximumUseDate: now()->addDay());
|
||||
$second = $this->createTicketableItem('second', maximumUseDate: now()->addDays(2));
|
||||
$bundle = $this->createBundle('bundle');
|
||||
$bundle->bundleComponents()->createMany([
|
||||
['component_catalog_item_id' => $first->id, 'quantity' => 2],
|
||||
['component_catalog_item_id' => $second->id, 'quantity' => 1],
|
||||
]);
|
||||
|
||||
$tickets = $this->service->generate($bundle, $this->user, 2);
|
||||
|
||||
$this->assertCount(6, $tickets);
|
||||
$this->assertCount(6, $tickets->where('source_catalog_item_id', $bundle->id));
|
||||
$this->assertCount(4, $tickets->where('name', $first->nombre));
|
||||
$this->assertCount(2, $tickets->where('name', $second->nombre));
|
||||
}
|
||||
|
||||
public function test_bundle_generation_is_rolled_back_when_a_component_is_invalid(): void
|
||||
{
|
||||
$valid = $this->createTicketableItem('valid');
|
||||
$invalid = $this->createTicketableItem('invalid');
|
||||
$invalid->update(['has_tickets' => false]);
|
||||
$bundle = $this->createBundle('invalid-bundle');
|
||||
$bundle->bundleComponents()->createMany([
|
||||
['component_catalog_item_id' => $valid->id, 'quantity' => 1],
|
||||
['component_catalog_item_id' => $invalid->id, 'quantity' => 1],
|
||||
]);
|
||||
|
||||
try {
|
||||
$this->service->generate($bundle, $this->user);
|
||||
$this->fail('La generación debería haber fallado.');
|
||||
} catch (TicketGenerationException) {
|
||||
$this->assertDatabaseCount('tickets', 0);
|
||||
}
|
||||
}
|
||||
|
||||
public function test_marking_a_purchase_as_paid_generates_its_tickets_once(): void
|
||||
{
|
||||
$item = $this->createTicketableItem('paid-ticket');
|
||||
$purchase = $this->createPurchase($item, 2);
|
||||
$purchase->setRelation('items', new EloquentCollection);
|
||||
|
||||
$purchase->markAsPaid();
|
||||
|
||||
$this->assertSame(Purchase::STATUS_PAID, $purchase->status);
|
||||
$this->assertDatabaseCount('tickets', 2);
|
||||
|
||||
$purchase->markAsPaid();
|
||||
|
||||
$this->assertDatabaseCount('tickets', 2);
|
||||
}
|
||||
|
||||
public function test_a_ticket_generated_from_a_purchase_keeps_its_source_ids(): void
|
||||
{
|
||||
$item = $this->createTicketableItem('sourced-ticket');
|
||||
$purchase = $this->createPurchase($item, 1, 1234);
|
||||
|
||||
$purchase->markAsPaid();
|
||||
|
||||
$this->assertDatabaseHas('tickets', [
|
||||
'source_catalog_item_id' => $item->id,
|
||||
'source_variant_id' => 1234,
|
||||
]);
|
||||
}
|
||||
|
||||
public function test_marking_a_purchase_as_paid_ignores_items_without_tickets(): void
|
||||
{
|
||||
$item = $this->createTicketableItem('regular-product');
|
||||
$item->update(['has_tickets' => false]);
|
||||
$purchase = $this->createPurchase($item->fresh(), 1);
|
||||
|
||||
$purchase->markAsPaid();
|
||||
|
||||
$this->assertSame(Purchase::STATUS_PAID, $purchase->status);
|
||||
$this->assertDatabaseCount('tickets', 0);
|
||||
}
|
||||
|
||||
public function test_paid_status_is_rolled_back_when_ticket_generation_fails(): void
|
||||
{
|
||||
$item = $this->createTicketableItem('expired-paid-ticket', maximumUseDate: now());
|
||||
$purchase = $this->createPurchase($item, 1);
|
||||
|
||||
try {
|
||||
$purchase->markAsPaid();
|
||||
$this->fail('La generación debería haber fallado.');
|
||||
} catch (TicketGenerationException) {
|
||||
$this->assertSame(Purchase::STATUS_PENDING_PAYMENT, $purchase->fresh()->status);
|
||||
$this->assertDatabaseCount('tickets', 0);
|
||||
}
|
||||
}
|
||||
|
||||
private function createTicketableItem(
|
||||
string $slug,
|
||||
mixed $minimumUseDate = null,
|
||||
mixed $maximumUseDate = null,
|
||||
): CatalogItem {
|
||||
return CatalogItem::query()->create([
|
||||
'tenant_code' => $this->tenant->codigo,
|
||||
'slug' => $slug,
|
||||
'nombre' => ucfirst($slug),
|
||||
'descripcion' => "Descripción de {$slug}",
|
||||
'precio' => 10,
|
||||
'has_tickets' => true,
|
||||
'minimum_use_date' => $minimumUseDate,
|
||||
'maximum_use_date' => $maximumUseDate,
|
||||
]);
|
||||
}
|
||||
|
||||
private function createBundle(string $slug): CatalogItem
|
||||
{
|
||||
return CatalogItem::query()->create([
|
||||
'tenant_code' => $this->tenant->codigo,
|
||||
'type' => CatalogItemType::Bundle,
|
||||
'inventory_policy' => null,
|
||||
'slug' => $slug,
|
||||
'nombre' => ucfirst($slug),
|
||||
'descripcion' => "Descripción de {$slug}",
|
||||
'precio' => 20,
|
||||
]);
|
||||
}
|
||||
|
||||
private function createPurchase(
|
||||
CatalogItem $catalogItem,
|
||||
int $quantity,
|
||||
?int $sourceVariantId = null,
|
||||
): Purchase {
|
||||
$purchase = Purchase::query()->create([
|
||||
'tenant_codigo' => $this->tenant->codigo,
|
||||
'user_id' => $this->user->id,
|
||||
'status' => Purchase::STATUS_PENDING_PAYMENT,
|
||||
'payment_method' => 'transfer',
|
||||
'total' => 10 * $quantity,
|
||||
]);
|
||||
|
||||
$purchase->items()->create([
|
||||
'source_catalog_item_id' => $catalogItem->id,
|
||||
'source_variant_id' => $sourceVariantId,
|
||||
'image_attachment_id' => null,
|
||||
'nombre' => $catalogItem->nombre,
|
||||
'descripcion' => $catalogItem->descripcion,
|
||||
'slug' => $catalogItem->slug,
|
||||
'item_nombre' => $catalogItem->nombre,
|
||||
'variant_attributes' => [],
|
||||
'cantidad' => $quantity,
|
||||
'precio_unitario' => 10,
|
||||
'discount_total' => null,
|
||||
'tax_total' => null,
|
||||
'total' => 10 * $quantity,
|
||||
]);
|
||||
|
||||
return $purchase;
|
||||
}
|
||||
|
||||
private function createTenant(): Tenant
|
||||
{
|
||||
$header = Attachment::query()->create([
|
||||
'path' => 'test/ticket-header.png',
|
||||
'filename' => 'header.png',
|
||||
'type' => AttachmentType::Image,
|
||||
'mime_type' => 'image/png',
|
||||
]);
|
||||
$footer = Attachment::query()->create([
|
||||
'path' => 'test/ticket-footer.png',
|
||||
'filename' => 'footer.png',
|
||||
'type' => AttachmentType::Image,
|
||||
'mime_type' => 'image/png',
|
||||
]);
|
||||
|
||||
return Tenant::query()->create([
|
||||
'codigo' => 'ticket-tenant',
|
||||
'nombre' => 'Ticket Tenant',
|
||||
'dominio' => 'ticket.local',
|
||||
'primary_color' => '#000000',
|
||||
'secondary_color' => '#000000',
|
||||
'danger_color' => '#000000',
|
||||
'success_color' => '#000000',
|
||||
'header_bg_color' => '#000000',
|
||||
'footer_bg_color' => '#000000',
|
||||
'header_logo_id' => $header->id,
|
||||
'footer_logo_id' => $footer->id,
|
||||
]);
|
||||
}
|
||||
}
|
||||
117
tests/Unit/Ticket/TicketTest.php
Normal file
117
tests/Unit/Ticket/TicketTest.php
Normal file
@@ -0,0 +1,117 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Unit\Ticket;
|
||||
|
||||
use App\Domains\Auth\Models\User;
|
||||
use App\Domains\Tenant\Models\Tenant;
|
||||
use App\Domains\Ticket\Models\Ticket;
|
||||
use Illuminate\Support\Carbon;
|
||||
use Tests\TestCase;
|
||||
|
||||
class TicketTest extends TestCase
|
||||
{
|
||||
protected function tearDown(): void
|
||||
{
|
||||
Carbon::setTestNow();
|
||||
|
||||
parent::tearDown();
|
||||
}
|
||||
|
||||
public function test_it_maps_its_dates_and_relations(): void
|
||||
{
|
||||
$ticket = new Ticket;
|
||||
$ticket->setRawAttributes([
|
||||
'source_catalog_item_id' => '20',
|
||||
'source_variant_id' => '30',
|
||||
'starts_at' => '2026-07-21 10:00:00',
|
||||
'expires_at' => '2026-07-22 10:00:00',
|
||||
'used_at' => null,
|
||||
'user_id' => '10',
|
||||
]);
|
||||
|
||||
$this->assertSame('tickets', $ticket->getTable());
|
||||
$this->assertFalse($ticket->usesTimestamps());
|
||||
$this->assertSame(20, $ticket->source_catalog_item_id);
|
||||
$this->assertSame(30, $ticket->source_variant_id);
|
||||
$this->assertInstanceOf(Carbon::class, $ticket->starts_at);
|
||||
$this->assertInstanceOf(Carbon::class, $ticket->expires_at);
|
||||
$this->assertNull($ticket->used_at);
|
||||
$this->assertSame(10, $ticket->user_id);
|
||||
$this->assertInstanceOf(Tenant::class, $ticket->tenant()->getRelated());
|
||||
$this->assertInstanceOf(User::class, $ticket->user()->getRelated());
|
||||
}
|
||||
|
||||
public function test_unused_ticket_without_date_restrictions_is_valid(): void
|
||||
{
|
||||
$this->assertTrue((new Ticket)->isValid());
|
||||
}
|
||||
|
||||
public function test_ticket_is_invalid_before_its_start_date(): void
|
||||
{
|
||||
Carbon::setTestNow('2026-07-21 10:00:00');
|
||||
$ticket = new Ticket(['starts_at' => now()->addSecond()]);
|
||||
|
||||
$this->assertFalse($ticket->isValid());
|
||||
}
|
||||
|
||||
public function test_ticket_is_valid_when_its_start_date_is_reached(): void
|
||||
{
|
||||
Carbon::setTestNow('2026-07-21 10:00:00');
|
||||
$ticket = new Ticket(['starts_at' => now()]);
|
||||
|
||||
$this->assertTrue($ticket->isValid());
|
||||
}
|
||||
|
||||
public function test_ticket_is_invalid_when_it_expires(): void
|
||||
{
|
||||
Carbon::setTestNow('2026-07-21 10:00:00');
|
||||
$ticket = new Ticket(['expires_at' => now()]);
|
||||
|
||||
$this->assertFalse($ticket->isValid());
|
||||
}
|
||||
|
||||
public function test_used_ticket_is_invalid(): void
|
||||
{
|
||||
$ticket = new Ticket(['used_at' => now()->subSecond()]);
|
||||
|
||||
$this->assertFalse($ticket->isValid());
|
||||
}
|
||||
|
||||
public function test_it_appends_computed_status_fields(): void
|
||||
{
|
||||
Carbon::setTestNow('2026-07-21 10:00:00');
|
||||
$ticket = new Ticket([
|
||||
'starts_at' => now()->subHour(),
|
||||
'expires_at' => now()->addHour(),
|
||||
]);
|
||||
|
||||
$attributes = $ticket->toArray();
|
||||
|
||||
$this->assertTrue($attributes['is_valid']);
|
||||
$this->assertFalse($attributes['is_expired']);
|
||||
$this->assertFalse($attributes['is_used']);
|
||||
}
|
||||
|
||||
public function test_unused_ticket_is_expired_when_its_expiration_date_is_reached(): void
|
||||
{
|
||||
Carbon::setTestNow('2026-07-21 10:00:00');
|
||||
$ticket = new Ticket(['expires_at' => now()]);
|
||||
|
||||
$this->assertFalse($ticket->is_valid);
|
||||
$this->assertTrue($ticket->is_expired);
|
||||
$this->assertFalse($ticket->is_used);
|
||||
}
|
||||
|
||||
public function test_used_ticket_is_not_reported_as_expired(): void
|
||||
{
|
||||
Carbon::setTestNow('2026-07-21 10:00:00');
|
||||
$ticket = new Ticket([
|
||||
'expires_at' => now()->subHour(),
|
||||
'used_at' => now()->subDay(),
|
||||
]);
|
||||
|
||||
$this->assertFalse($ticket->is_valid);
|
||||
$this->assertFalse($ticket->is_expired);
|
||||
$this->assertTrue($ticket->is_used);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user