feat(desfile): add administrative entry reservations
This commit is contained in:
@@ -0,0 +1,19 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Ticketing\Desfile\Controllers;
|
||||
|
||||
use App\Domains\Ticketing\Desfile\Requests\StoreEntryReservationsRequest;
|
||||
use App\Domains\Ticketing\Desfile\Resources\EntryReservationResource;
|
||||
use App\Domains\Ticketing\Desfile\Services\EntryReservationService;
|
||||
use App\Http\Controllers\Controller;
|
||||
use Illuminate\Http\Resources\Json\AnonymousResourceCollection;
|
||||
|
||||
class EntryReservationController extends Controller
|
||||
{
|
||||
public function store(StoreEntryReservationsRequest $request, EntryReservationService $service): AnonymousResourceCollection
|
||||
{
|
||||
return EntryReservationResource::collection($service->reserve(
|
||||
$request->user(), $request->validated('idempotency_key'), $request->validated('rows'),
|
||||
));
|
||||
}
|
||||
}
|
||||
@@ -2,14 +2,19 @@
|
||||
|
||||
namespace App\Domains\Ticketing\Desfile\Models;
|
||||
|
||||
use App\Domains\Commerce\Catalog\Models\Inventory;
|
||||
use App\Domains\Commerce\Catalog\Models\Variant;
|
||||
use App\Domains\Ticketing\Desfile\Enums\EntryReservationPaymentType;
|
||||
use App\Domains\Ticketing\Ticket\Models\Ticket;
|
||||
use Illuminate\Database\Eloquent\Attributes\Fillable;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
|
||||
#[Fillable([
|
||||
'variant_id',
|
||||
'ticket_id',
|
||||
'inventory_id',
|
||||
'batch_id',
|
||||
'fecha_reserva',
|
||||
'importe',
|
||||
'tipo_pago',
|
||||
@@ -33,4 +38,14 @@ class EntryReservation extends Model
|
||||
{
|
||||
return $this->belongsTo(Variant::class)->withTrashed();
|
||||
}
|
||||
|
||||
public function ticket(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(Ticket::class);
|
||||
}
|
||||
|
||||
public function inventory(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(Inventory::class);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Ticketing\Desfile\Requests;
|
||||
|
||||
use App\Domains\Ticketing\Desfile\Enums\EntryReservationPaymentType;
|
||||
use Illuminate\Foundation\Http\FormRequest;
|
||||
use Illuminate\Validation\Rule;
|
||||
|
||||
class StoreEntryReservationsRequest extends FormRequest
|
||||
{
|
||||
public function authorize(): bool
|
||||
{
|
||||
return $this->user()?->tenant_codigo === 'desfile_pura_tendencia';
|
||||
}
|
||||
|
||||
public function rules(): array
|
||||
{
|
||||
return [
|
||||
'idempotency_key' => ['required', 'uuid'],
|
||||
'rows' => ['required', 'array', 'min:1', 'max:100'],
|
||||
'rows.*' => ['required', 'array:variant_id,tipo_pago'],
|
||||
'rows.*.variant_id' => ['required', 'integer', 'min:1', 'distinct'],
|
||||
'rows.*.tipo_pago' => ['required', Rule::enum(EntryReservationPaymentType::class)],
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Ticketing\Desfile\Resources;
|
||||
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Http\Resources\Json\JsonResource;
|
||||
|
||||
class EntryReservationResource extends JsonResource
|
||||
{
|
||||
public function toArray(Request $request): array
|
||||
{
|
||||
return [
|
||||
'id' => $this->id,
|
||||
'variant_id' => $this->variant_id,
|
||||
'ticket_id' => $this->ticket_id,
|
||||
'fecha_reserva' => $this->fecha_reserva->toIso8601String(),
|
||||
'tipo_pago' => $this->tipo_pago->value,
|
||||
'importe' => $this->importe,
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,132 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Ticketing\Desfile\Services;
|
||||
|
||||
use App\Domains\Commerce\Catalog\Enums\InventoryPolicy;
|
||||
use App\Domains\Commerce\Catalog\Models\CatalogItem;
|
||||
use App\Domains\Commerce\Catalog\Models\Inventory;
|
||||
use App\Domains\Commerce\Catalog\Models\Variant;
|
||||
use App\Domains\Core\Auth\Models\User;
|
||||
use App\Domains\Ticketing\Desfile\Enums\EntryReservationPaymentType;
|
||||
use App\Domains\Ticketing\Desfile\Models\EntryReservation;
|
||||
use App\Domains\Ticketing\Ticket\Exceptions\TicketGenerationException;
|
||||
use App\Domains\Ticketing\Ticket\Services\TicketGeneratorService;
|
||||
use Illuminate\Support\Collection;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
|
||||
class EntryReservationService
|
||||
{
|
||||
public function __construct(private readonly TicketGeneratorService $tickets) {}
|
||||
|
||||
/** @param list<array{variant_id: int, tipo_pago: string}> $rows */
|
||||
public function reserve(User $user, string $key, array $rows): Collection
|
||||
{
|
||||
abort_unless($user->tenant_codigo === 'desfile_pura_tendencia', 403);
|
||||
$normalized = collect($rows)->map(fn (array $row): array => [
|
||||
'variant_id' => (int) $row['variant_id'], 'tipo_pago' => $row['tipo_pago'],
|
||||
])->sortBy('variant_id')->values()->all();
|
||||
$hash = hash('sha256', json_encode($normalized, JSON_THROW_ON_ERROR));
|
||||
|
||||
return DB::transaction(function () use ($user, $key, $rows, $hash): Collection {
|
||||
// Serialize retries by the same administrator, including the first insert.
|
||||
User::query()->whereKey($user->id)->lockForUpdate()->firstOrFail();
|
||||
$batch = DB::table('desfile_reservation_batches')
|
||||
->where('user_id', $user->id)->where('idempotency_key', $key)->lockForUpdate()->first();
|
||||
if ($batch !== null) {
|
||||
abort_unless($batch->tenant_code === $user->tenant_codigo && hash_equals($batch->request_hash, $hash), 409,
|
||||
'La clave de envío ya fue utilizada con otras entradas.');
|
||||
|
||||
return EntryReservation::query()->where('batch_id', $batch->id)->with('ticket')->orderBy('id')->get();
|
||||
}
|
||||
|
||||
$tenant = $user->tenant()->firstOrFail();
|
||||
$entry = CatalogItem::query()->forTenantCatalog($tenant)->where('slug', 'entrada')
|
||||
->lockForUpdate()->firstOrFail();
|
||||
$ids = array_column($rows, 'variant_id');
|
||||
$variants = $entry->variants()->whereKey($ids)->orderBy('id')->lockForUpdate()->get();
|
||||
$inventories = Inventory::query()->whereKey($variants->pluck('inventory_id')->filter()->unique())
|
||||
->orderBy('id')->lockForUpdate()->get()->keyBy('id');
|
||||
$variants->load([
|
||||
'eventDates', 'eventDate',
|
||||
'desfileEntryReservations' => fn ($query) => $query->lockForUpdate(),
|
||||
]);
|
||||
foreach ($variants as $variant) {
|
||||
$variant->setRelation('inventory', $inventories->get($variant->inventory_id));
|
||||
}
|
||||
$entry->setRelation('variants', $variants);
|
||||
$available = $entry->visibleVariants()->keyBy('id');
|
||||
$requirements = [];
|
||||
$errors = [];
|
||||
foreach ($rows as $index => $row) {
|
||||
$variant = $available->get($row['variant_id']);
|
||||
if ($variant === null || $variant->inventory === null) {
|
||||
$errors["rows.{$index}.variant_id"] = $this->entryLabel($variants->firstWhere('id', $row['variant_id']), $index).': la entrada ya no está disponible.';
|
||||
|
||||
continue;
|
||||
}
|
||||
$requirements[$variant->inventory_id] = ($requirements[$variant->inventory_id] ?? 0) + 1;
|
||||
}
|
||||
if ($errors !== []) {
|
||||
throw ValidationException::withMessages($errors);
|
||||
}
|
||||
$tracked = $entry->inventory_policy !== InventoryPolicy::Unlimited;
|
||||
foreach ($requirements as $inventoryId => $quantity) {
|
||||
if ($tracked && $inventories[$inventoryId]->availableStock() < $quantity) {
|
||||
foreach ($rows as $index => $row) {
|
||||
$variant = $available[$row['variant_id']];
|
||||
if ($variant->inventory_id === $inventoryId) {
|
||||
$errors["rows.{$index}.variant_id"] = $this->entryLabel($variant, $index).': no hay stock suficiente para reservar las entradas seleccionadas.';
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if ($errors !== []) {
|
||||
throw ValidationException::withMessages($errors);
|
||||
}
|
||||
|
||||
$batchId = DB::table('desfile_reservation_batches')->insertGetId([
|
||||
'user_id' => $user->id, 'tenant_code' => $tenant->codigo,
|
||||
'idempotency_key' => $key, 'request_hash' => $hash,
|
||||
'created_at' => now(), 'updated_at' => now(),
|
||||
]);
|
||||
foreach ($requirements as $inventoryId => $quantity) {
|
||||
$inventories[$inventoryId]->reserveEntry($quantity, $tracked);
|
||||
}
|
||||
$reservations = collect();
|
||||
foreach ($rows as $index => $row) {
|
||||
$variant = $available[$row['variant_id']];
|
||||
$payment = EntryReservationPaymentType::from($row['tipo_pago']);
|
||||
try {
|
||||
$ticket = $this->tickets->generate($entry, $user, 1, $variant->id)->sole();
|
||||
} catch (TicketGenerationException $exception) {
|
||||
throw ValidationException::withMessages([
|
||||
"rows.{$index}.variant_id" => $this->entryLabel($variant, $index).': no se pudo emitir el ticket. '.$exception->getMessage(),
|
||||
]);
|
||||
}
|
||||
$reservation = EntryReservation::query()->create([
|
||||
'batch_id' => $batchId, 'ticket_id' => $ticket->id,
|
||||
'variant_id' => $variant->id, 'inventory_id' => $variant->inventory_id,
|
||||
'fecha_reserva' => now(), 'tipo_pago' => $payment,
|
||||
'importe' => $payment === EntryReservationPaymentType::Free ? 0 : $variant->getPrice(),
|
||||
]);
|
||||
$reservations->push($reservation->setRelation('ticket', $ticket));
|
||||
}
|
||||
|
||||
return $reservations;
|
||||
}, 3);
|
||||
}
|
||||
|
||||
private function entryLabel(?Variant $variant, int $index): string
|
||||
{
|
||||
if ($variant === null) {
|
||||
return 'Entrada '.($index + 1);
|
||||
}
|
||||
|
||||
$values = $variant->selectionValues();
|
||||
|
||||
return collect(['tipo' => 'Tipo', 'sector' => 'Sector', 'fila' => 'Fila', 'asiento' => 'Asiento'])
|
||||
->map(fn (string $label, string $key): string => $label.': '.($values->get($key) ?? 'sin especificar'))
|
||||
->implode(', ');
|
||||
}
|
||||
}
|
||||
@@ -1,8 +1,13 @@
|
||||
<?php
|
||||
|
||||
use App\Domains\Ticketing\Desfile\Controllers\EntryController;
|
||||
use App\Domains\Ticketing\Desfile\Controllers\EntryReservationController;
|
||||
use Illuminate\Support\Facades\Route;
|
||||
|
||||
Route::post('v1/adminapp/tenant/desfile/entry-reservations', [EntryReservationController::class, 'store'])
|
||||
->middleware(['auth:sanctum', 'adminapp.tenant', 'tenant.menu:adminapp.desfile.reservas'])
|
||||
->name('adminapp.desfile.entry-reservations.store');
|
||||
|
||||
Route::prefix('v1/adminapp/tenant/desfile')
|
||||
->middleware(['auth:sanctum', 'adminapp.tenant', 'tenant.menu:adminapp.desfile.entradas'])
|
||||
->group(function (): void {
|
||||
|
||||
291
tests/Feature/Desfile/EntryReservationServiceTest.php
Normal file
291
tests/Feature/Desfile/EntryReservationServiceTest.php
Normal file
@@ -0,0 +1,291 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature\Desfile;
|
||||
|
||||
use App\Domains\Commerce\Catalog\Models\Inventory;
|
||||
use App\Domains\Core\Auth\Models\User;
|
||||
use App\Domains\Ticketing\Desfile\Requests\StoreEntryReservationsRequest;
|
||||
use App\Domains\Ticketing\Desfile\Services\EntryReservationService;
|
||||
use App\Domains\Ticketing\Ticket\Models\Ticket;
|
||||
use App\Domains\Ticketing\Ticket\Services\ResolvedTicketValidity;
|
||||
use App\Domains\Ticketing\Ticket\Services\TicketGeneratorService;
|
||||
use App\Domains\Ticketing\Ticket\Services\TicketValidityResolver;
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
use Illuminate\Support\Facades\Validator;
|
||||
use Illuminate\Support\Str;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
use Mockery;
|
||||
use Symfony\Component\HttpKernel\Exception\HttpException;
|
||||
use Tests\TestCase;
|
||||
|
||||
/** Exercises real transactions on the guarded SQLite :memory: connection. */
|
||||
class EntryReservationServiceTest extends TestCase
|
||||
{
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
// Minimal domain schema isolates this workflow from unrelated legacy migrations.
|
||||
Schema::create('users', function (Blueprint $table): void {
|
||||
$table->id();
|
||||
$table->string('tenant_codigo');
|
||||
$table->softDeletes();
|
||||
});
|
||||
Schema::create('tenants', function (Blueprint $table): void {
|
||||
$table->id();
|
||||
$table->string('codigo')->unique();
|
||||
$table->unsignedBigInteger('active_event_id')->nullable();
|
||||
});
|
||||
Schema::create('catalog_items', function (Blueprint $table): void {
|
||||
$table->id();
|
||||
$table->string('tenant_code');
|
||||
$table->string('slug');
|
||||
$table->string('inventory_policy');
|
||||
$table->decimal('precio', 10, 2);
|
||||
$table->timestamp('sales_end_at')->nullable();
|
||||
$table->softDeletes();
|
||||
$table->boolean('has_tickets')->default(true);
|
||||
$table->unsignedBigInteger('event_id')->nullable();
|
||||
});
|
||||
Schema::create('inventories', function (Blueprint $table): void {
|
||||
$table->id();
|
||||
foreach (['real_stock', 'reserved_stock', 'sold_units', 'refunded_units'] as $column) {
|
||||
$table->integer($column)->default(0);
|
||||
}
|
||||
});
|
||||
Schema::create('variantes', function (Blueprint $table): void {
|
||||
$table->id();
|
||||
$table->foreignId('catalog_item_id');
|
||||
$table->foreignId('inventory_id');
|
||||
$table->decimal('precio', 10, 2);
|
||||
$table->unsignedBigInteger('event_date_id')->nullable();
|
||||
$table->unsignedBigInteger('replaced_by_variant_id')->nullable();
|
||||
$table->timestamp('sales_disabled_at')->nullable();
|
||||
$table->softDeletes();
|
||||
});
|
||||
Schema::create('event_dates', function (Blueprint $table): void {
|
||||
$table->id();
|
||||
$table->date('date');
|
||||
$table->time('time_start')->nullable();
|
||||
});
|
||||
Schema::create('attribute', function (Blueprint $table): void {
|
||||
$table->id();
|
||||
$table->string('codigo');
|
||||
});
|
||||
Schema::create('item_attributes', function (Blueprint $table): void {
|
||||
$table->id();
|
||||
$table->foreignId('attribute_id');
|
||||
$table->boolean('allow_multi_select')->default(false);
|
||||
});
|
||||
Schema::create('variant_values', function (Blueprint $table): void {
|
||||
$table->id();
|
||||
$table->foreignId('variant_id');
|
||||
$table->foreignId('item_attribute_id');
|
||||
$table->string('value');
|
||||
});
|
||||
Schema::create('variant_event_dates', function (Blueprint $table): void {
|
||||
$table->foreignId('variant_id');
|
||||
$table->foreignId('event_date_id');
|
||||
});
|
||||
Schema::create('tickets', function (Blueprint $table): void {
|
||||
$table->id();
|
||||
$table->foreignId('user_id');
|
||||
$table->foreignId('source_variant_id');
|
||||
$table->string('tenant_code')->nullable();
|
||||
$table->uuid('ticket')->nullable()->unique();
|
||||
$table->unsignedBigInteger('source_catalog_item_id')->nullable();
|
||||
$table->unsignedBigInteger('source_purchase_item_id')->nullable();
|
||||
$table->unsignedBigInteger('event_id')->nullable();
|
||||
$table->timestamp('used_at')->nullable();
|
||||
});
|
||||
(require database_path('migrations/2026_09_23_010000_create_desfile_entry_reservations_table.php'))->up();
|
||||
(require database_path('migrations/2026_09_24_000000_add_administrative_entry_reservation_stock.php'))->up();
|
||||
DB::table('tenants')->insert(['codigo' => 'desfile_pura_tendencia']);
|
||||
DB::table('users')->insert(['id' => 1, 'tenant_codigo' => 'desfile_pura_tendencia']);
|
||||
DB::table('catalog_items')->insert([
|
||||
'id' => 1, 'tenant_code' => 'desfile_pura_tendencia', 'slug' => 'entrada',
|
||||
'inventory_policy' => 'tracked', 'precio' => 100,
|
||||
]);
|
||||
foreach ([1, 2] as $id) {
|
||||
DB::table('inventories')->insert(['id' => $id, 'real_stock' => 1]);
|
||||
DB::table('variantes')->insert(['id' => $id, 'catalog_item_id' => 1, 'inventory_id' => $id, 'precio' => 250]);
|
||||
}
|
||||
foreach (['tipo' => 'NORMAL', 'sector' => 'A', 'fila' => '3', 'asiento' => '17'] as $code => $value) {
|
||||
$attributeId = DB::table('attribute')->insertGetId(['codigo' => $code]);
|
||||
$itemAttributeId = DB::table('item_attributes')->insertGetId(['attribute_id' => $attributeId]);
|
||||
foreach ([1, 2] as $variantId) {
|
||||
DB::table('variant_values')->insert([
|
||||
'variant_id' => $variantId, 'item_attribute_id' => $itemAttributeId, 'value' => $value,
|
||||
]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private function service(bool $failSecond = false): EntryReservationService
|
||||
{
|
||||
$generator = Mockery::mock(TicketGeneratorService::class);
|
||||
$generator->shouldReceive('generate')->andReturnUsing(function ($entry, $user, $quantity, $variantId) use ($failSecond) {
|
||||
if ($failSecond && $variantId === 2) {
|
||||
throw new \RuntimeException('Ticket generation failed');
|
||||
}
|
||||
$this->assertSame(1, $quantity);
|
||||
$id = DB::table('tickets')->insertGetId(['user_id' => $user->id, 'source_variant_id' => $variantId]);
|
||||
|
||||
return collect([Ticket::query()->findOrFail($id)]);
|
||||
});
|
||||
|
||||
return new EntryReservationService($generator);
|
||||
}
|
||||
|
||||
private function rows(): array
|
||||
{
|
||||
return [['variant_id' => 1, 'tipo_pago' => 'sin_cargo'], ['variant_id' => 2, 'tipo_pago' => 'otro_metodo']];
|
||||
}
|
||||
|
||||
public function test_reserves_stock_calculates_prices_and_replays_without_duplicates(): void
|
||||
{
|
||||
$service = $this->service();
|
||||
$key = (string) Str::uuid();
|
||||
$user = User::query()->findOrFail(1);
|
||||
$result = $service->reserve($user, $key, $this->rows());
|
||||
$this->assertSame(['0.00', '250.00'], $result->pluck('importe')->all());
|
||||
$replayed = $service->reserve($user, $key, $this->rows());
|
||||
$this->assertSame($result->pluck('id')->all(), $replayed->pluck('id')->all());
|
||||
$this->assertDatabaseCount('tickets', 2);
|
||||
$this->assertDatabaseCount('desfile_entry_reservations', 2);
|
||||
$this->assertDatabaseCount('desfile_reservation_batches', 1);
|
||||
foreach (Inventory::all() as $inventory) {
|
||||
$this->assertSame(1, $inventory->entry_reserved_stock);
|
||||
$this->assertSame(1, $inventory->real_stock);
|
||||
$this->assertSame(0, $inventory->reserved_stock);
|
||||
$this->assertSame(0, $inventory->sold_units);
|
||||
$this->assertSame(0, $inventory->availableStock());
|
||||
}
|
||||
$this->assertDatabaseHas('tickets', ['user_id' => 1, 'source_variant_id' => 1]);
|
||||
}
|
||||
|
||||
public function test_conflicting_cart_stock_rejects_the_entire_batch(): void
|
||||
{
|
||||
DB::table('inventories')->where('id', 2)->update(['reserved_stock' => 1]);
|
||||
try {
|
||||
$this->service()->reserve(User::findOrFail(1), (string) Str::uuid(), $this->rows());
|
||||
$this->fail('Expected unavailable variant');
|
||||
} catch (ValidationException $error) {
|
||||
$this->assertArrayHasKey('rows.1.variant_id', $error->errors());
|
||||
$this->assertStringContainsString('Tipo: NORMAL, Sector: A, Fila: 3, Asiento: 17', $error->errors()['rows.1.variant_id'][0]);
|
||||
}
|
||||
$this->assertDatabaseCount('tickets', 0);
|
||||
$this->assertDatabaseCount('desfile_entry_reservations', 0);
|
||||
$this->assertSame(0, (int) Inventory::sum('entry_reserved_stock'));
|
||||
}
|
||||
|
||||
public function test_ticket_failure_rolls_back_stock_tickets_and_idempotency_record(): void
|
||||
{
|
||||
try {
|
||||
$this->service(true)->reserve(User::findOrFail(1), (string) Str::uuid(), $this->rows());
|
||||
$this->fail('Expected generation failure');
|
||||
} catch (\RuntimeException $error) {
|
||||
$this->assertSame('Ticket generation failed', $error->getMessage());
|
||||
}
|
||||
$this->assertDatabaseCount('tickets', 0);
|
||||
$this->assertDatabaseCount('desfile_entry_reservations', 0);
|
||||
$this->assertDatabaseCount('desfile_reservation_batches', 0);
|
||||
$this->assertSame(0, (int) Inventory::sum('entry_reserved_stock'));
|
||||
}
|
||||
|
||||
public function test_new_attempt_cannot_reserve_an_already_reserved_variant(): void
|
||||
{
|
||||
$service = $this->service();
|
||||
$user = User::findOrFail(1);
|
||||
$service->reserve($user, (string) Str::uuid(), $this->rows());
|
||||
$this->expectException(ValidationException::class);
|
||||
$service->reserve($user, (string) Str::uuid(), $this->rows());
|
||||
}
|
||||
|
||||
public function test_a_reused_key_with_different_rows_is_rejected(): void
|
||||
{
|
||||
$service = $this->service();
|
||||
$key = (string) Str::uuid();
|
||||
$user = User::findOrFail(1);
|
||||
$service->reserve($user, $key, $this->rows());
|
||||
try {
|
||||
$service->reserve($user, $key, [['variant_id' => 1, 'tipo_pago' => 'otro_metodo']]);
|
||||
$this->fail('Expected conflict');
|
||||
} catch (HttpException $error) {
|
||||
$this->assertSame(409, $error->getStatusCode());
|
||||
}
|
||||
$this->assertDatabaseCount('tickets', 2);
|
||||
}
|
||||
|
||||
public function test_variants_outside_the_tenant_catalog_are_rejected(): void
|
||||
{
|
||||
DB::table('variantes')->where('id', 2)->update(['catalog_item_id' => 999]);
|
||||
$this->expectException(ValidationException::class);
|
||||
$this->service()->reserve(User::findOrFail(1), (string) Str::uuid(), $this->rows());
|
||||
}
|
||||
|
||||
public function test_shared_inventory_is_checked_for_the_whole_batch(): void
|
||||
{
|
||||
DB::table('variantes')->where('id', 2)->update(['inventory_id' => 1]);
|
||||
try {
|
||||
$this->service()->reserve(User::findOrFail(1), (string) Str::uuid(), $this->rows());
|
||||
$this->fail('Expected insufficient shared stock');
|
||||
} catch (ValidationException $error) {
|
||||
$this->assertSame(['rows.0.variant_id', 'rows.1.variant_id'], array_keys($error->errors()));
|
||||
foreach ($error->errors() as $messages) {
|
||||
$this->assertStringContainsString('Tipo: NORMAL, Sector: A, Fila: 3, Asiento: 17', $messages[0]);
|
||||
}
|
||||
}
|
||||
$this->assertDatabaseCount('tickets', 0);
|
||||
}
|
||||
|
||||
public function test_cart_cannot_reserve_administratively_reserved_stock(): void
|
||||
{
|
||||
$this->service()->reserve(User::findOrFail(1), (string) Str::uuid(), $this->rows());
|
||||
$this->expectException(\InvalidArgumentException::class);
|
||||
Inventory::findOrFail(1)->reserve(1, true);
|
||||
}
|
||||
|
||||
public function test_request_rejects_duplicate_variants_and_client_amounts(): void
|
||||
{
|
||||
$rules = (new StoreEntryReservationsRequest)->rules();
|
||||
$validator = Validator::make([
|
||||
'idempotency_key' => (string) Str::uuid(),
|
||||
'rows' => [
|
||||
['variant_id' => 1, 'tipo_pago' => 'sin_cargo', 'importe' => 0],
|
||||
['variant_id' => 1, 'tipo_pago' => 'invalid'],
|
||||
],
|
||||
], $rules);
|
||||
$this->assertTrue($validator->fails());
|
||||
$this->assertArrayHasKey('rows.0', $validator->errors()->toArray());
|
||||
$this->assertArrayHasKey('rows.1.variant_id', $validator->errors()->toArray());
|
||||
$this->assertArrayHasKey('rows.1.tipo_pago', $validator->errors()->toArray());
|
||||
}
|
||||
|
||||
public function test_real_ticket_generator_links_admin_variant_and_reservation(): void
|
||||
{
|
||||
$validity = Mockery::mock(TicketValidityResolver::class);
|
||||
$validity->shouldReceive('resolveVariant')->andReturn(
|
||||
ResolvedTicketValidity::unrestricted(),
|
||||
);
|
||||
$service = new EntryReservationService(new TicketGeneratorService($validity));
|
||||
$result = $service->reserve(User::findOrFail(1), (string) Str::uuid(), $this->rows());
|
||||
foreach ($result as $reservation) {
|
||||
$this->assertDatabaseHas('tickets', [
|
||||
'id' => $reservation->ticket_id, 'user_id' => 1,
|
||||
'source_variant_id' => $reservation->variant_id,
|
||||
'source_catalog_item_id' => 1, 'tenant_code' => 'desfile_pura_tendencia',
|
||||
'source_purchase_item_id' => null,
|
||||
]);
|
||||
$this->assertTrue(Str::isUuid($reservation->ticket->ticket));
|
||||
}
|
||||
}
|
||||
|
||||
public function test_request_rejects_a_user_from_another_tenant(): void
|
||||
{
|
||||
$request = new StoreEntryReservationsRequest;
|
||||
$request->setUserResolver(fn () => new User(['tenant_codigo' => 'other']));
|
||||
$this->assertFalse($request->authorize());
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user