Compare commits

...

32 Commits

Author SHA1 Message Date
4f7ede1072 feat(purchase,sale,ticket): expose refunded total summary in admin sales and tickets 2026-09-11 16:23:23 -03:00
4bb4f526e4 feat(event): support ticket refund configuration in event endpoints 2026-09-11 16:22:46 -03:00
c0c19c9c01 feat(tenant): add master toggle for ticket refunds 2026-09-11 16:22:27 -03:00
b4da6e3747 feat(event): omit rescheduled and suspended dates from tenant resource 2026-09-11 16:21:37 -03:00
1880fc8147 feat(event): suspend event dates instead of cancelling 2026-09-11 15:57:17 -03:00
96df431d60 feat(event): implement admin date creation, rescheduling, and cancellation endpoints 2026-09-11 12:28:51 -03:00
106cf017dc feat(ticket): resolve effective event dates and handle reschedule chains 2026-09-11 12:28:37 -03:00
d5fdae9a24 feat(event): add rescheduling and cancellation state to event dates 2026-09-11 12:28:29 -03:00
4abb6c67fd feat(ticket): add refund calculation functionality and corresponding tests 2026-09-11 10:43:03 -03:00
6384c0046d feat(ticket): validate ticket capability status and use transaction in cancel and refund 2026-09-11 09:25:32 -03:00
2ddb046c26 feat(ticket): add action capability helpers and expose them in admin resource 2026-09-11 09:25:19 -03:00
5d00dc439e feat(ticket): implement refund functionality and expose allow_refund flag 2026-09-10 17:05:57 -03:00
210c854fee feat(tenant): add allow_refund and allow_partial_refund methods 2026-09-10 17:04:34 -03:00
beb5d18b29 feat(ticket): add cancel ticket functionality and corresponding tests 2026-09-10 16:28:45 -03:00
de259f4286 feat(ticket): implement terminal status management and validation 2026-09-10 16:20:35 -03:00
f19bca64d0 feat(admin): expose ticket refund states 2026-09-10 16:10:17 -03:00
18f739b712 feat(ticket): add refundable terminal states 2026-09-10 16:10:08 -03:00
1564985259 feat(tenant): expose ticket refund configuration 2026-09-10 15:29:41 -03:00
471a941587 feat(tenant): persist ticket refund configuration 2026-09-10 15:29:35 -03:00
4c647968cb Merge branch 'fix/admin_title' into dev 2026-09-09 16:30:00 -03:00
55dcc2e37f feat(website): add site_title to AdminAppBootstrapResource and related tests 2026-09-09 16:29:37 -03:00
cac4fcf2b2 feat(scanner): update scan handling to return results for invalid QR data and other scan conditions 2026-09-09 12:49:27 -03:00
64e965aff7 feat(scanner): update scan attempt result labels for consistency 2026-09-09 08:47:10 -03:00
002f08a8fa feat(staff): expose scanner attempt history 2026-09-08 10:56:27 -03:00
531dbe52b9 feat(scanner): expose scan result labels 2026-09-08 10:24:28 -03:00
a885a2fc0e feat(scanner): expose assigned scan categories 2026-09-08 10:01:18 -03:00
0c49bae752 feat(scanner): add scan attempt detail endpoint 2026-09-08 08:51:19 -03:00
67bcb420e4 feat(scanner): return scan attempt result context 2026-09-08 08:51:10 -03:00
34058e6a81 feat(scanner): implement scan attempt endpoint and update routes and tests 2026-09-07 16:56:12 -03:00
8a65d358a4 feat(scanner): implement scan attempt tracking with new request and resource classes 2026-09-07 16:55:52 -03:00
193e10dc48 feat(scan): implement scan attempt tracking and validation logic 2026-09-07 16:39:14 -03:00
b607c1b673 feat(scanner): refactor ticket scanning endpoint to accept UUID in request body and add validation 2026-09-07 16:18:16 -03:00
78 changed files with 3242 additions and 300 deletions

View File

@@ -1249,7 +1249,7 @@
"name": "Ticket",
"item": [
{
"name": "List Ticket",
"name": "List Scan Attempt",
"request": {
"method": "GET",
"header": [
@@ -5998,9 +5998,9 @@
"type": "text"
}
],
"description": "Ruta Laravel: `GET /api/v1/scanner/tickets`\n\nControlador: `App\\Domains\\Ticket\\Controllers\\Scanner\\TicketController@index`\n\nRequiere autenticación Sanctum.",
"description": "Ruta Laravel: `GET /api/v1/scanner/attempts`\n\nControlador: `App\\Domains\\Ticket\\Controllers\\Scanner\\ScanAttemptController`\n\nRequiere autenticación Sanctum.",
"url": {
"raw": "{{base_url}}/api/v1/scanner/tickets?page=1&per_page=20",
"raw": "{{base_url}}/api/v1/scanner/attempts?page=1&per_page=20",
"host": [
"{{base_url}}"
],
@@ -6008,7 +6008,7 @@
"api",
"v1",
"scanner",
"tickets"
"attempts"
],
"query": [
{
@@ -6086,11 +6086,16 @@
"key": "Accept",
"value": "application/json",
"type": "text"
},
{
"key": "Content-Type",
"value": "application/json",
"type": "text"
}
],
"description": "Ruta Laravel: `POST /api/v1/scanner/tickets/{ticketUuid}/scan`\n\nControlador: `App\\Domains\\Ticket\\Controllers\\Scanner\\TicketController@scan`\n\nRequiere autenticación Sanctum.",
"description": "Ruta Laravel: `POST /api/v1/scanner/tickets/scan`\n\nControlador: `App\\Domains\\Ticket\\Controllers\\Scanner\\TicketController@scan`\n\nRequiere autenticación Sanctum.",
"url": {
"raw": "{{base_url}}/api/v1/scanner/tickets/{{ticket_uuid}}/scan",
"raw": "{{base_url}}/api/v1/scanner/tickets/scan",
"host": [
"{{base_url}}"
],
@@ -6099,10 +6104,18 @@
"v1",
"scanner",
"tickets",
"{{ticket_uuid}}",
"scan"
]
},
"body": {
"mode": "raw",
"raw": "{\n \"data\": \"{{ticket_uuid}}\"\n}",
"options": {
"raw": {
"language": "json"
}
}
},
"auth": {
"type": "bearer",
"bearer": [

View File

@@ -6,6 +6,7 @@ use App\Domains\Authorization\Enums\RoleCode;
use App\Domains\Authorization\Models\Role;
use App\Domains\Catalog\Models\Category;
use App\Domains\Tenant\Models\Tenant;
use App\Domains\Ticket\Models\ScanAttempt;
use Database\Factories\UserFactory;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Attributes\Hidden;
@@ -46,6 +47,12 @@ class User extends Authenticatable
return $this->hasMany(LoginAttempt::class);
}
/** @return HasMany<ScanAttempt, $this> */
public function scanAttempts(): HasMany
{
return $this->hasMany(ScanAttempt::class, 'scanner_user_id');
}
/**
* @return BelongsTo<Role, $this>
*/

View File

@@ -24,6 +24,11 @@ class UserResource extends JsonResource
'telefono' => $this->telefono,
'rol_codigo' => $this->rol_codigo,
'tenant_codigo' => $this->tenant_codigo,
'categories' => $this->whenLoaded('scanCategories', fn () => $this->scanCategories
->map(fn ($category) => [
'id' => $category->id,
'nombre' => $category->nombre,
])->values()),
];
}
}

View File

@@ -19,6 +19,16 @@ class ScannerContextService
$user->setRelation('tenant', $tenant);
if ($tenant->requiresScannerCategoryValidation()) {
$categories = $user->scanCategories()
->orderBy('nombre')
->get();
if ($categories->isNotEmpty()) {
$user->setRelation('scanCategories', $categories);
}
}
return $user;
}
}

View File

@@ -17,6 +17,7 @@ class AdminAppBootstrapResource extends JsonResource
return [
'website_type_code' => $websiteType->codigo,
'site_title' => $websiteType->site_title,
'primary_color' => $websiteType->primary_color,
'secondary_color' => $websiteType->secondary_color,
'danger_color' => $websiteType->danger_color,

View File

@@ -2,7 +2,11 @@
namespace App\Domains\Event\Controllers\AdminApp;
use App\Domains\Event\Models\EventDate;
use App\Domains\Event\Requests\RescheduleEventDateRequest;
use App\Domains\Event\Requests\StoreEventDateRequest;
use App\Domains\Event\Requests\UpdateEventRequest;
use App\Domains\Event\Resources\EventDateResource;
use App\Domains\Event\Resources\EventResource;
use App\Domains\Event\Services\EventService;
use App\Http\Controllers\Controller;
@@ -28,4 +32,37 @@ class EventController extends Controller
)
);
}
public function storeDate(StoreEventDateRequest $request): EventDateResource
{
return EventDateResource::make(
$this->eventService->createDateForTenant(
$request->user()->tenant()->firstOrFail(),
$request->validated(),
)
);
}
public function rescheduleDate(
RescheduleEventDateRequest $request,
EventDate $eventDate,
): EventDateResource {
return EventDateResource::make(
$this->eventService->rescheduleDateForTenant(
$request->user()->tenant()->firstOrFail(),
$eventDate,
$request->validated(),
)
);
}
public function suspendDate(Request $request, EventDate $eventDate): EventDateResource
{
return EventDateResource::make(
$this->eventService->suspendDateForTenant(
$request->user()->tenant()->firstOrFail(),
$eventDate,
)
);
}
}

View File

@@ -0,0 +1,12 @@
<?php
namespace App\Domains\Event\Enums;
enum EventDateStatus: string
{
case Rescheduled = 'rescheduled';
case Suspended = 'suspended';
case Scheduled = 'scheduled';
case InProgress = 'in_progress';
case Completed = 'completed';
}

View File

@@ -3,6 +3,7 @@
namespace App\Domains\Event\Models;
use App\Domains\Catalog\Models\Variant;
use App\Domains\Event\Enums\EventDateStatus;
use App\Domains\Event\Services\EventDateTextFormatter;
use App\Domains\Tenant\Models\Tenant;
use App\Domains\Ticket\Enums\ValidityTimeType;
@@ -21,6 +22,8 @@ use Illuminate\Support\Carbon;
'date',
'time_start',
'time_end',
'rescheduled_to_event_date_id',
'suspended_at',
])]
class EventDate extends Model
{
@@ -28,6 +31,8 @@ class EventDate extends Model
public $timestamps = false;
protected $appends = ['status'];
protected static function booted(): void
{
static::creating(fn (self $eventDate) => $eventDate->syncValidityTime());
@@ -52,6 +57,8 @@ class EventDate extends Model
return [
'date' => 'date:Y-m-d',
'validity_time_id' => 'integer',
'rescheduled_to_event_date_id' => 'integer',
'suspended_at' => 'datetime',
];
}
@@ -67,6 +74,18 @@ class EventDate extends Model
return $this->belongsTo(ValidityTime::class);
}
/** @return BelongsTo<EventDate, $this> */
public function rescheduledTo(): BelongsTo
{
return $this->belongsTo(self::class, 'rescheduled_to_event_date_id');
}
/** @return HasMany<EventDate, $this> */
public function rescheduledFrom(): HasMany
{
return $this->hasMany(self::class, 'rescheduled_to_event_date_id');
}
/** @return HasMany<Variant, $this> */
public function variants(): HasMany
{
@@ -94,6 +113,27 @@ class EventDate extends Model
return Carbon::parse($this->date->format('Y-m-d').' '.$this->time_end);
}
public function getStatusAttribute(): EventDateStatus
{
if ($this->rescheduled_to_event_date_id !== null) {
return EventDateStatus::Rescheduled;
}
if ($this->suspended_at !== null) {
return EventDateStatus::Suspended;
}
if (now()->lt($this->startsAt())) {
return EventDateStatus::Scheduled;
}
if (now()->lt($this->endsAt())) {
return EventDateStatus::InProgress;
}
return EventDateStatus::Completed;
}
private function syncTenantDateText(): void
{
$tenant = $this->tenant()->first();
@@ -104,7 +144,10 @@ class EventDate extends Model
$tenant->update([
'event_date_text' => app(EventDateTextFormatter::class)->format(
$tenant->eventDates()->pluck('date')
$tenant->eventDates()
->whereNull('rescheduled_to_event_date_id')
->whereNull('suspended_at')
->pluck('date')
),
]);
}

View File

@@ -0,0 +1,21 @@
<?php
namespace App\Domains\Event\Requests;
use Illuminate\Foundation\Http\FormRequest;
class RescheduleEventDateRequest extends FormRequest
{
public function authorize(): bool
{
return true;
}
/** @return array<string, mixed> */
public function rules(): array
{
return [
'date' => ['required', 'date_format:Y-m-d'],
];
}
}

View File

@@ -0,0 +1,23 @@
<?php
namespace App\Domains\Event\Requests;
use Illuminate\Foundation\Http\FormRequest;
class StoreEventDateRequest extends FormRequest
{
public function authorize(): bool
{
return true;
}
/** @return array<string, mixed> */
public function rules(): array
{
return [
'date' => ['required', 'date_format:Y-m-d'],
'start_time' => ['required', 'date_format:H:i'],
'end_time' => ['required', 'date_format:H:i'],
];
}
}

View File

@@ -19,11 +19,6 @@ class UpdateEventRequest extends FormRequest
return [
'title' => ['required', 'string', 'max:255'],
'location' => ['required', 'string', 'max:255'],
'dates' => ['required', 'array', 'min:1'],
'dates.*' => ['required', 'array:date,start_time,end_time'],
'dates.*.date' => ['required', 'date_format:Y-m-d', 'distinct'],
'dates.*.start_time' => ['required', 'date_format:H:i'],
'dates.*.end_time' => ['required', 'date_format:H:i'],
'social_media' => ['sometimes', 'array'],
'social_media.*' => ['required', 'array:code,url,orden'],
'social_media.*.code' => [
@@ -38,6 +33,16 @@ class UpdateEventRequest extends FormRequest
'contact.whatsapp_url' => ['nullable', 'url', 'max:2048'],
'contact.instagram_url' => ['nullable', 'url', 'max:2048'],
'contact.facebook_url' => ['nullable', 'url', 'max:2048'],
'allow_ticket_refund' => ['sometimes', 'boolean'],
'allow_ticket_total_refund' => ['sometimes', 'boolean'],
'allow_ticket_partial_refund' => ['sometimes', 'boolean'],
'ticket_partial_refund_percentage' => [
'sometimes',
'numeric',
'decimal:0,2',
'min:0',
'max:99.99',
],
];
}
@@ -54,6 +59,41 @@ class UpdateEventRequest extends FormRequest
'The social media field is required.'
);
}
if (! array_key_exists('allow_ticket_refund', $input)) {
return;
}
foreach ([
'allow_ticket_total_refund',
'allow_ticket_partial_refund',
'ticket_partial_refund_percentage',
] as $field) {
if (! array_key_exists($field, $input)) {
$validator->errors()->add($field, 'El campo es obligatorio.');
}
}
$totalEnabled = $this->boolean('allow_ticket_total_refund');
$partialEnabled = $this->boolean('allow_ticket_partial_refund');
$refundEnabled = $this->boolean('allow_ticket_refund');
if ($refundEnabled && ! $totalEnabled && ! $partialEnabled) {
$validator->errors()->add(
'allow_ticket_refund',
'Seleccioná al menos un tipo de reembolso.'
);
}
if ($refundEnabled
&& $partialEnabled
&& (float) ($input['ticket_partial_refund_percentage'] ?? 0) <= 0) {
$validator->errors()->add(
'ticket_partial_refund_percentage',
'Ingresá un porcentaje mayor que cero para el reembolso parcial.'
);
}
},
];
}

View File

@@ -0,0 +1,28 @@
<?php
namespace App\Domains\Event\Resources;
use App\Domains\Event\Models\EventDate;
use App\Domains\Ticket\Resources\ValidityTimeResource;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;
/** @mixin EventDate */
class EventDateResource extends JsonResource
{
/** @return array<string, mixed> */
public function toArray(Request $request): array
{
return [
'id' => $this->id,
'validity_time_id' => $this->validity_time_id,
'validity_time' => ValidityTimeResource::make($this->whenLoaded('validityTime')),
'date' => $this->date->format('Y-m-d'),
'start_time' => substr($this->time_start, 0, 5),
'end_time' => substr($this->time_end, 0, 5),
'status' => $this->status->value,
'rescheduled_to_event_date_id' => $this->rescheduled_to_event_date_id,
'suspended_at' => $this->suspended_at?->toISOString(),
];
}
}

View File

@@ -3,7 +3,6 @@
namespace App\Domains\Event\Resources;
use App\Domains\Tenant\Models\Tenant;
use App\Domains\Ticket\Resources\ValidityTimeResource;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;
@@ -19,14 +18,11 @@ class EventResource extends JsonResource
'id' => $this->id,
'title' => $this->event_title,
'location' => $this->event_location,
'dates' => $this->eventDates->map(fn ($eventDate): array => [
'id' => $eventDate->id,
'validity_time_id' => $eventDate->validity_time_id,
'validity_time' => ValidityTimeResource::make($eventDate->validityTime),
'date' => $eventDate->date->format('Y-m-d'),
'start_time' => substr($eventDate->time_start, 0, 5),
'end_time' => substr($eventDate->time_end, 0, 5),
])->values(),
'allow_ticket_refund' => $this->allow_ticket_refund,
'allow_ticket_total_refund' => $this->allow_ticket_total_refund,
'allow_ticket_partial_refund' => $this->allow_ticket_partial_refund,
'ticket_partial_refund_percentage' => $this->ticket_partial_refund_percentage,
'dates' => EventDateResource::collection($this->eventDates),
'social_media' => $this->socialMedia->map(fn ($item): array => [
'code' => $item->code,
'url' => $item->pivot->url,

View File

@@ -0,0 +1,37 @@
<?php
namespace App\Domains\Event\Services;
use App\Domains\Event\Models\EventDate;
class EffectiveEventDateResolver
{
public function resolve(EventDate $eventDate): ?EventDate
{
$current = $eventDate;
$visited = [];
while (true) {
$identity = $current->getKey() === null
? 'object:'.spl_object_id($current)
: 'key:'.$current->getKey();
if (isset($visited[$identity])) {
return null;
}
$visited[$identity] = true;
if ($current->rescheduled_to_event_date_id === null) {
return $current->suspended_at === null ? $current : null;
}
$current->loadMissing('rescheduledTo');
$current = $current->rescheduledTo;
if ($current === null) {
return null;
}
}
}
}

View File

@@ -2,7 +2,10 @@
namespace App\Domains\Event\Services;
use App\Domains\Catalog\Models\Variant;
use App\Domains\Event\Models\EventDate;
use App\Domains\Tenant\Models\Tenant;
use App\Domains\Ticket\Models\Ticket;
use Illuminate\Support\Facades\DB;
use Illuminate\Validation\ValidationException;
@@ -14,6 +17,10 @@ class EventService
'facebook_url' => 'facebook',
];
public function __construct(
private readonly EffectiveEventDateResolver $effectiveEventDateResolver,
) {}
public function forTenant(Tenant $tenant): Tenant
{
return $tenant->load(['eventDates.validityTime', 'socialMedia']);
@@ -27,9 +34,14 @@ class EventService
$tenant->update([
'event_title' => $data['title'],
'event_location' => $data['location'],
...array_intersect_key($data, array_flip([
'allow_ticket_refund',
'allow_ticket_total_refund',
'allow_ticket_partial_refund',
'ticket_partial_refund_percentage',
])),
]);
$this->syncDates($tenant, $data['dates']);
if (array_key_exists('social_media', $data)) {
$this->syncSocialMedia($tenant, $data['social_media']);
} else {
@@ -40,41 +52,185 @@ class EventService
});
}
/** @param array<int, array{date: string, start_time: string, end_time: string}> $dates */
private function syncDates(Tenant $tenant, array $dates): void
/** @param array{date: string, start_time: string, end_time: string} $data */
public function createDateForTenant(Tenant $tenant, array $data): EventDate
{
$existingDates = $tenant->eventDates()->get()->values();
return DB::transaction(function () use ($tenant, $data): EventDate {
$attributes = $this->dateAttributes($data);
foreach (array_values($dates) as $index => $date) {
$attributes = [
'date' => $date['date'],
'time_start' => $date['start_time'],
'time_end' => $date['end_time'],
];
if ($tenant->eventDates()->where($attributes)->exists()) {
throw ValidationException::withMessages([
'date' => ['La fecha y el horario ya existen.'],
]);
}
$existingDate = $existingDates->get($index);
return $tenant->eventDates()->create($attributes)->load('validityTime');
});
}
if ($existingDate) {
$existingDate->update($attributes);
} else {
$tenant->eventDates()->create($attributes);
/** @param array{date: string} $data */
public function rescheduleDateForTenant(Tenant $tenant, EventDate $eventDate, array $data): EventDate
{
return DB::transaction(function () use ($tenant, $eventDate, $data): EventDate {
$source = $this->lockedDateForTenant($tenant, $eventDate);
if ($source->suspended_at !== null) {
throw ValidationException::withMessages([
'event_date' => ['No se puede reprogramar una fecha suspendida.'],
]);
}
if ($source->rescheduled_to_event_date_id !== null) {
throw ValidationException::withMessages([
'event_date' => ['La fecha ya fue reprogramada.'],
]);
}
$destination = $tenant->eventDates()
->whereDate('date', $data['date'])
->lockForUpdate()
->first();
if ($destination === null) {
$destination = $tenant->eventDates()->create([
'date' => $data['date'],
'time_start' => $source->time_start,
'time_end' => $source->time_end,
]);
}
if ($destination->is($source) || $this->chainContains($destination, $source)) {
throw ValidationException::withMessages([
'date' => ['La reprogramación generaría una referencia circular.'],
]);
}
if ($this->effectiveEventDateResolver->resolve($destination) === null) {
throw ValidationException::withMessages([
'date' => ['La fecha de destino no es utilizable.'],
]);
}
$source->update(['rescheduled_to_event_date_id' => $destination->getKey()]);
return $source->fresh(['validityTime', 'rescheduledTo.validityTime']);
});
}
public function suspendDateForTenant(Tenant $tenant, EventDate $eventDate): EventDate
{
return DB::transaction(function () use ($tenant, $eventDate): EventDate {
$date = $this->lockedDateForTenant($tenant, $eventDate);
if ($date->rescheduled_to_event_date_id !== null) {
throw ValidationException::withMessages([
'event_date' => ['No se puede suspender una fecha que ya fue reprogramada.'],
]);
}
if ($date->suspended_at !== null) {
return $date->load('validityTime');
}
$date->update(['suspended_at' => now()]);
$this->disableTicketsWithoutUsableDates($tenant, $date);
return $date->fresh('validityTime');
});
}
private function lockedDateForTenant(Tenant $tenant, EventDate $eventDate): EventDate
{
return $tenant->eventDates()
->whereKey($eventDate->getKey())
->lockForUpdate()
->firstOrFail();
}
private function chainContains(EventDate $start, EventDate $expected): bool
{
$current = $start;
$visited = [];
while ($current->rescheduled_to_event_date_id !== null) {
if ($current->is($expected)) {
return true;
}
if (isset($visited[$current->getKey()])) {
return true;
}
$visited[$current->getKey()] = true;
$current = $current->rescheduledTo()->lockForUpdate()->first();
if ($current === null) {
return false;
}
}
$datesToDelete = $existingDates->slice(count($dates));
return $current->is($expected);
}
if ($datesToDelete->contains(fn ($eventDate): bool => $eventDate
->selectedByVariants()
->whereHas('sourceTickets')
->exists()
|| $eventDate->variants()->whereHas('sourceTickets')->exists())) {
throw ValidationException::withMessages([
'dates' => ['No se puede eliminar una fecha utilizada por tickets generados.'],
]);
private function disableTicketsWithoutUsableDates(Tenant $tenant, EventDate $suspendedDate): void
{
$affectedDateIds = collect([$suspendedDate->getKey()]);
$frontier = $affectedDateIds;
while ($frontier->isNotEmpty()) {
$predecessors = $tenant->eventDates()
->whereIn('rescheduled_to_event_date_id', $frontier)
->pluck('id')
->diff($affectedDateIds)
->values();
$affectedDateIds = $affectedDateIds->merge($predecessors)->unique()->values();
$frontier = $predecessors;
}
$datesToDelete->each->delete();
$tenant->unsetRelation('eventDates');
$variants = Variant::withTrashed()
->where(function ($query) use ($affectedDateIds): void {
$query->whereIn('event_date_id', $affectedDateIds)
->orWhereHas('eventDates', fn ($eventDates) => $eventDates
->whereIn('event_dates.id', $affectedDateIds));
})
->with(['eventDates', 'eventDate'])
->get();
foreach ($variants as $variant) {
$hasUsableDate = $variant->selectedEventDates()->contains(
fn (EventDate $candidate): bool => $this->effectiveEventDateResolver->resolve($candidate) !== null
);
if ($hasUsableDate) {
continue;
}
Ticket::query()
->where('tenant_code', $tenant->codigo)
->where('source_variant_id', $variant->getKey())
->whereNull('disabled_at')
->whereNull('cancelled_at')
->whereNull('refunded_at')
->lockForUpdate()
->get()
->each(function (Ticket $ticket): void {
$ticket->markAsDisabled();
$ticket->save();
});
}
}
/**
* @param array{date: string, start_time: string, end_time: string} $data
* @return array{date: string, time_start: string, time_end: string}
*/
private function dateAttributes(array $data): array
{
return [
'date' => $data['date'],
'time_start' => $data['start_time'].':00',
'time_end' => $data['end_time'].':00',
];
}
/** @param array<string, string|null> $contact */

View File

@@ -8,4 +8,7 @@ Route::prefix('v1/adminapp/tenant')
->group(function (): void {
Route::get('event', [EventController::class, 'show']);
Route::put('event', [EventController::class, 'update']);
Route::post('event-dates', [EventController::class, 'storeDate']);
Route::post('event-dates/{eventDate}/reschedule', [EventController::class, 'rescheduleDate']);
Route::post('event-dates/{eventDate}/suspend', [EventController::class, 'suspendDate']);
});

View File

@@ -124,11 +124,7 @@ class TicketFilterFormService
'required' => false,
'default' => null,
'placeholder' => 'Estado',
'options' => [
['value' => Ticket::STATUS_ACTIVE, 'label' => 'Activo'],
['value' => Ticket::STATUS_USED, 'label' => 'Usado'],
['value' => Ticket::STATUS_EXPIRED, 'label' => 'Vencido'],
],
'options' => Ticket::statusOptions(),
],
];
}

View File

@@ -236,11 +236,7 @@ class TicketFormService
?: $left['label'] <=> $right['label']);
return [
'statuses' => [
['value' => Ticket::STATUS_ACTIVE, 'label' => 'Activo'],
['value' => Ticket::STATUS_USED, 'label' => 'Usado'],
['value' => Ticket::STATUS_EXPIRED, 'label' => 'Vencido'],
],
'statuses' => Ticket::statusOptions(),
'categories' => array_values(array_map(
fn (array $category): array => [
'value' => $category['value'],

View File

@@ -27,6 +27,7 @@ use Illuminate\Database\Eloquent\Relations\HasMany;
'discount_total',
'tax_total',
'total',
'refunded_amount',
])]
class PurchaseItem extends Model
{
@@ -47,6 +48,7 @@ class PurchaseItem extends Model
'discount_total' => 'decimal:2',
'tax_total' => 'decimal:2',
'total' => 'decimal:2',
'refunded_amount' => 'decimal:2',
];
}

View File

@@ -25,6 +25,7 @@ class PurchaseItemResource extends JsonResource
'quantity' => (int) $this->cantidad,
'unit_price' => $this->formatMoney($this->precio_unitario),
'line_total' => $this->formatMoney($this->total),
'refunded_amount' => $this->formatMoney($this->refunded_amount),
'source_catalog_item_id' => $this->source_catalog_item_id,
'source_variant_id' => $this->source_variant_id,
'item_details' => [

View File

@@ -0,0 +1,22 @@
<?php
namespace App\Domains\Purchase\Services;
use App\Domains\Purchase\Models\PurchaseItem;
use App\Domains\Tenant\Models\Tenant;
use Illuminate\Database\Eloquent\Builder;
class PurchaseRefundSummaryService
{
public function totalForTenant(Tenant $tenant): string
{
$total = PurchaseItem::query()
->whereHas(
'purchase',
fn (Builder $query): Builder => $query->where('tenant_codigo', $tenant->codigo)
)
->sum('refunded_amount');
return number_format((float) $total, 2, '.', '');
}
}

View File

@@ -35,6 +35,7 @@ class SaleController extends Controller
$this->saleService->sales($tenant, $request->validated())
)->additional([
'confirmed_sales_total' => $this->saleService->confirmedSalesTotal($tenant),
'refunded_total' => $this->saleService->refundedTotal($tenant),
]);
}

View File

@@ -22,6 +22,7 @@ class SaleDetailResource extends JsonResource
'quantity' => (int) $item->cantidad,
'unit_price' => $this->formatMoney($item->precio_unitario),
'total' => $this->formatMoney($item->total),
'refunded_amount' => $this->formatMoney($item->refunded_amount),
])->values(),
'total' => $this->formatMoney($this->total),
];

View File

@@ -17,6 +17,7 @@ class SaleTicketResource extends JsonResource
'id' => $this->id,
'expires_at' => $this->getEffectiveExpiresAt(),
'status' => $this->status,
'status_label' => $this->status_label,
];
}
}

View File

@@ -5,6 +5,7 @@ namespace App\Domains\Sale\Services;
use App\Domains\Logging\Models\ValueChange;
use App\Domains\Purchase\Models\Purchase;
use App\Domains\Purchase\Services\CheckoutService;
use App\Domains\Purchase\Services\PurchaseRefundSummaryService;
use App\Domains\Tenant\Models\Tenant;
use App\Domains\Ticket\Models\Ticket;
use App\Domains\Ticket\Services\TicketPresentationResolver;
@@ -17,6 +18,7 @@ class AdminAppSaleService
{
public function __construct(
protected CheckoutService $checkoutService,
protected PurchaseRefundSummaryService $refundSummaryService,
) {}
public function confirmedSalesTotal(Tenant $tenant): string
@@ -29,6 +31,11 @@ class AdminAppSaleService
return number_format((float) $total, 2, '.', '');
}
public function refundedTotal(Tenant $tenant): string
{
return $this->refundSummaryService->totalForTenant($tenant);
}
/**
* @param array{
* q?: string|null,

View File

@@ -6,6 +6,9 @@ use App\Domains\Staff\Requests\StoreStaffRequest;
use App\Domains\Staff\Requests\UpdateStaffRequest;
use App\Domains\Staff\Resources\StaffResource;
use App\Domains\Staff\Services\StaffService;
use App\Domains\Ticket\Requests\ScanAttemptIndexRequest;
use App\Domains\Ticket\Resources\Scanner\ScanAttemptResource;
use App\Domains\Ticket\Services\ScannerTicketService;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\AnonymousResourceCollection;
@@ -13,7 +16,10 @@ use Symfony\Component\HttpFoundation\Response;
class AdminAppStaffController extends Controller
{
public function __construct(private readonly StaffService $staffService) {}
public function __construct(
private readonly StaffService $staffService,
private readonly ScannerTicketService $scannerTicketService,
) {}
public function index(Request $request): AnonymousResourceCollection
{
@@ -46,4 +52,18 @@ class AdminAppStaffController extends Controller
return response()->noContent();
}
public function scanAttempts(
ScanAttemptIndexRequest $request,
int $staff,
): AnonymousResourceCollection {
$scanner = $this->staffService->find(
$request->user()->tenant()->firstOrFail(),
$staff,
);
return ScanAttemptResource::collection(
$this->scannerTicketService->attemptsByStaff($scanner, $request->validated())
);
}
}

View File

@@ -6,5 +6,6 @@ use Illuminate\Support\Facades\Route;
Route::prefix('v1/adminapp/tenant')
->middleware(['auth:sanctum', 'adminapp.tenant'])
->group(function (): void {
Route::get('staff/{staff}/scan-attempts', [AdminAppStaffController::class, 'scanAttempts']);
Route::apiResource('staff', AdminAppStaffController::class)->except('show');
});

View File

@@ -12,6 +12,7 @@ use App\Domains\Event\Models\EventDate;
use App\Domains\Menu\Models\Menu;
use App\Domains\Menu\Models\TenantMenu;
use App\Domains\Tenant\Enums\CartEditingPolicy;
use App\Domains\Ticket\Models\ScanAttempt;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
@@ -51,6 +52,10 @@ use Illuminate\Support\Facades\Schema;
'checkout_editing_policy',
'display_cart_item_images',
'scanner_category_validation_enabled',
'allow_ticket_refund',
'allow_ticket_total_refund',
'allow_ticket_partial_refund',
'ticket_partial_refund_percentage',
'event_title',
'event_location',
'event_date_text',
@@ -71,6 +76,10 @@ class Tenant extends Model
'checkout_editing_policy' => CartEditingPolicy::Disabled->value,
'display_cart_item_images' => true,
'scanner_category_validation_enabled' => true,
'allow_ticket_refund' => false,
'allow_ticket_total_refund' => false,
'allow_ticket_partial_refund' => false,
'ticket_partial_refund_percentage' => 0,
];
public function getRouteKeyName(): string
@@ -105,6 +114,35 @@ class Tenant extends Model
return $this->scanner_category_validation_enabled;
}
public function allow_refund(): bool
{
return (bool) $this->allow_ticket_refund
&& ((bool) $this->allow_ticket_total_refund || $this->allow_partial_refund());
}
public function allow_partial_refund(): bool
{
return (bool) $this->allow_ticket_refund
&& (bool) $this->allow_ticket_partial_refund
&& $this->ticket_partial_refund_percentage !== null
&& (float) $this->ticket_partial_refund_percentage > 0;
}
public function allowRefund(): bool
{
return $this->allow_refund();
}
public function allowPartialRefund(): bool
{
return $this->allow_partial_refund();
}
public function getAllowRefundAttribute(): bool
{
return $this->allow_refund();
}
/**
* Get the attributes that should be cast.
*
@@ -123,6 +161,10 @@ class Tenant extends Model
'checkout_editing_policy' => CartEditingPolicy::class,
'display_cart_item_images' => 'boolean',
'scanner_category_validation_enabled' => 'boolean',
'allow_ticket_refund' => 'boolean',
'allow_ticket_total_refund' => 'boolean',
'allow_ticket_partial_refund' => 'boolean',
'ticket_partial_refund_percentage' => 'decimal:2',
];
}
@@ -195,6 +237,12 @@ class Tenant extends Model
return $this->hasMany(Category::class, 'tenant_code', 'codigo');
}
/** @return HasMany<ScanAttempt, $this> */
public function scanAttempts(): HasMany
{
return $this->hasMany(ScanAttempt::class, 'tenant_code', 'codigo');
}
/**
* @return BelongsToMany<SocialMedia, $this>
*/

View File

@@ -117,6 +117,16 @@ class StoreTenantRequest extends FormRequest
],
'display_cart_item_images' => ['sometimes', 'boolean'],
'scanner_category_validation_enabled' => ['sometimes', 'boolean'],
'allow_ticket_refund' => ['sometimes', 'boolean'],
'allow_ticket_total_refund' => ['sometimes', 'boolean'],
'allow_ticket_partial_refund' => ['sometimes', 'boolean'],
'ticket_partial_refund_percentage' => [
'sometimes',
'numeric',
'decimal:0,2',
'min:0',
'max:99.99',
],
'website_type_code' => [
'required_with:extras',
'sometimes',

View File

@@ -138,6 +138,16 @@ class UpdateTenantRequest extends FormRequest
],
'display_cart_item_images' => ['sometimes', 'boolean'],
'scanner_category_validation_enabled' => ['sometimes', 'boolean'],
'allow_ticket_refund' => ['sometimes', 'boolean'],
'allow_ticket_total_refund' => ['sometimes', 'boolean'],
'allow_ticket_partial_refund' => ['sometimes', 'boolean'],
'ticket_partial_refund_percentage' => [
'sometimes',
'numeric',
'decimal:0,2',
'min:0',
'max:99.99',
],
];
}
}

View File

@@ -5,6 +5,7 @@ namespace App\Domains\Tenant\Resources;
use App\Domains\Attachable\Models\Attachment;
use App\Domains\Attachable\Models\AttachmentCrop;
use App\Domains\Catalog\Models\Category;
use App\Domains\Event\Models\EventDate;
use App\Domains\Menu\Models\Menu;
use App\Domains\Tenant\Models\Tenant;
use Illuminate\Http\Request;
@@ -50,12 +51,16 @@ class TenantResource extends JsonResource
: [
'title' => $this->event_title,
'location' => $this->event_location,
'dates' => $this->eventDates->map(fn ($eventDate): array => [
'id' => $eventDate->id,
'date' => $eventDate->date->format('Y-m-d'),
'time_start' => $eventDate->time_start,
'time_end' => $eventDate->time_end,
])->values(),
'dates' => $this->eventDates
->filter(fn (EventDate $eventDate): bool => $eventDate->rescheduled_to_event_date_id === null
&& $eventDate->suspended_at === null
)
->map(fn (EventDate $eventDate): array => [
'id' => $eventDate->id,
'date' => $eventDate->date->format('Y-m-d'),
'time_start' => $eventDate->time_start,
'time_end' => $eventDate->time_end,
])->values(),
]),
'extras' => $this->whenLoaded(
'websiteExtras',
@@ -82,6 +87,10 @@ class TenantResource extends JsonResource
'checkout_editing_policy' => CartEditingPolicyResource::make($this->checkout_editing_policy),
'display_cart_item_images' => $this->display_cart_item_images,
'scanner_category_validation_enabled' => $this->scanner_category_validation_enabled,
'allow_ticket_refund' => $this->allow_ticket_refund,
'allow_ticket_total_refund' => $this->allow_ticket_total_refund,
'allow_ticket_partial_refund' => $this->allow_ticket_partial_refund,
'ticket_partial_refund_percentage' => $this->ticket_partial_refund_percentage,
'social_media' => $this->whenLoaded(
'socialMedia',
fn () => $this->socialMedia

View File

@@ -4,11 +4,15 @@ namespace App\Domains\Ticket\Controllers\AdminApp;
use App\Domains\Ticket\Requests\AdminAppTicketExportRequest;
use App\Domains\Ticket\Requests\AdminAppTicketIndexRequest;
use App\Domains\Ticket\Requests\AdminAppTicketRefundRequest;
use App\Domains\Ticket\Resources\AdminApp\AdminAppTicketCollection;
use App\Domains\Ticket\Resources\AdminApp\AdminAppTicketRefundCalculationResource;
use App\Domains\Ticket\Resources\AdminApp\AdminAppTicketResource;
use App\Domains\Ticket\Services\AdminAppTicketExcelService;
use App\Domains\Ticket\Services\AdminAppTicketPdfService;
use App\Domains\Ticket\Services\AdminAppTicketService;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Symfony\Component\HttpFoundation\StreamedResponse;
@@ -29,6 +33,31 @@ class TicketController extends Controller
);
}
public function cancel(Request $request, int $ticket): AdminAppTicketResource
{
$tenant = $request->user()->tenant()->firstOrFail();
return new AdminAppTicketResource($this->ticketService->cancel($tenant, $ticket));
}
public function calculateRefund(Request $request, int $ticket): AdminAppTicketRefundCalculationResource
{
$tenant = $request->user()->tenant()->firstOrFail();
return new AdminAppTicketRefundCalculationResource(
$this->ticketService->calculateRefund($tenant, $ticket)
);
}
public function refund(AdminAppTicketRefundRequest $request, int $ticket): AdminAppTicketResource
{
$tenant = $request->user()->tenant()->firstOrFail();
return new AdminAppTicketResource(
$this->ticketService->refund($tenant, $ticket, $request->validated('refund_type'))
);
}
public function downloadPdf(AdminAppTicketExportRequest $request): Response
{
$tenant = $request->user()->tenant()->firstOrFail();

View File

@@ -0,0 +1,37 @@
<?php
namespace App\Domains\Ticket\Controllers\Scanner;
use App\Domains\Auth\Models\User;
use App\Domains\Ticket\Requests\ScanAttemptIndexRequest;
use App\Domains\Ticket\Resources\Scanner\ScanAttemptResource;
use App\Domains\Ticket\Resources\Scanner\ScannerScanResultResource;
use App\Domains\Ticket\Services\ScannerTicketService;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\AnonymousResourceCollection;
class ScanAttemptController extends Controller
{
public function __construct(private readonly ScannerTicketService $ticketService) {}
public function __invoke(ScanAttemptIndexRequest $request): AnonymousResourceCollection
{
/** @var User $scanner */
$scanner = $request->user();
return ScanAttemptResource::collection(
$this->ticketService->attemptsBy($scanner, $request->validated())
);
}
public function show(Request $request, int $scanAttempt): ScannerScanResultResource
{
/** @var User $scanner */
$scanner = $request->user();
return ScannerScanResultResource::make(
$this->ticketService->scanAttemptDetail($scanner, $scanAttempt)
);
}
}

View File

@@ -3,28 +3,18 @@
namespace App\Domains\Ticket\Controllers\Scanner;
use App\Domains\Auth\Models\User;
use App\Domains\Ticket\Requests\ScannerTicketIndexRequest;
use App\Domains\Ticket\Resources\Scanner\ScannedTicketResource;
use App\Domains\Ticket\Resources\Scanner\ScannerScanResultResource;
use App\Domains\Ticket\Resources\TicketResource;
use App\Domains\Ticket\Services\ScannerTicketService;
use App\Http\Controllers\Controller;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\AnonymousResourceCollection;
use Symfony\Component\HttpFoundation\Response;
class TicketController extends Controller
{
public function __construct(private readonly ScannerTicketService $ticketService) {}
public function index(ScannerTicketIndexRequest $request): AnonymousResourceCollection
{
/** @var User $scanner */
$scanner = $request->user();
return ScannedTicketResource::collection(
$this->ticketService->scannedBy($scanner, $request->validated())
);
}
public function show(Request $request, string $ticketUuid): TicketResource
{
/** @var User $scanner */
@@ -35,13 +25,13 @@ class TicketController extends Controller
);
}
public function scan(Request $request, string $ticketUuid): TicketResource
public function scan(Request $request): JsonResponse
{
/** @var User $scanner */
$scanner = $request->user();
return TicketResource::make(
$this->ticketService->scan($scanner, $ticketUuid)
);
return ScannerScanResultResource::make(
$this->ticketService->scan($scanner, $request->input('data'))
)->response()->setStatusCode(Response::HTTP_OK);
}
}

View File

@@ -0,0 +1,16 @@
<?php
namespace App\Domains\Ticket\Enums;
enum ScanAttemptResult: string
{
case Processing = 'processing';
case Accepted = 'accepted';
case InvalidQr = 'invalid_qr';
case TicketNotFound = 'ticket_not_found';
case CategoryForbidden = 'category_forbidden';
case AlreadyScanned = 'already_scanned';
case Expired = 'expired';
case NotValid = 'not_valid';
case UnexpectedError = 'unexpected_error';
}

View File

@@ -0,0 +1,52 @@
<?php
namespace App\Domains\Ticket\Models;
use App\Domains\Auth\Models\User;
use App\Domains\Tenant\Models\Tenant;
use App\Domains\Ticket\Enums\ScanAttemptResult;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
#[Fillable([
'tenant_code',
'scanner_user_id',
'ticket_id',
'data',
'result',
'resolved_at',
])]
class ScanAttempt extends Model
{
public const UPDATED_AT = null;
/** @return BelongsTo<User, $this> */
public function scanner(): BelongsTo
{
return $this->belongsTo(User::class, 'scanner_user_id')->withTrashed();
}
/** @return BelongsTo<Ticket, $this> */
public function ticket(): BelongsTo
{
return $this->belongsTo(Ticket::class);
}
/** @return BelongsTo<Tenant, $this> */
public function tenant(): BelongsTo
{
return $this->belongsTo(Tenant::class, 'tenant_code', 'codigo');
}
protected function casts(): array
{
return [
'scanner_user_id' => 'integer',
'ticket_id' => 'integer',
'result' => ScanAttemptResult::class,
'created_at' => 'datetime',
'resolved_at' => 'datetime',
];
}
}

View File

@@ -5,6 +5,7 @@ namespace App\Domains\Ticket\Models;
use App\Domains\Auth\Models\User;
use App\Domains\Catalog\Models\CatalogItem;
use App\Domains\Catalog\Models\Variant;
use App\Domains\Logging\Models\Concerns\LogsValueChanges;
use App\Domains\Purchase\Models\PurchaseItem;
use App\Domains\Tenant\Models\Tenant;
use App\Domains\Ticket\Services\ResolvedTicketValidity;
@@ -16,7 +17,9 @@ use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Support\Collection;
use Illuminate\Validation\ValidationException;
#[Fillable([
'tenant_code',
@@ -25,12 +28,15 @@ use Illuminate\Support\Collection;
'source_catalog_item_id',
'source_variant_id',
'used_at',
'disabled_at',
'cancelled_at',
'refunded_at',
'scanner_user_id',
'user_id',
])]
class Ticket extends Model
{
use HasFactory;
use HasFactory, LogsValueChanges;
private ?ResolvedTicketValidity $resolvedValidity = null;
@@ -40,8 +46,22 @@ class Ticket extends Model
public const STATUS_USED = 'used';
public const STATUS_DISABLED = 'disabled';
public const STATUS_CANCELLED = 'cancelled';
public const STATUS_REFUNDED = 'refunded';
public $timestamps = false;
/** @var list<string> */
protected array $loggedAttributes = [
'used_at',
'disabled_at',
'cancelled_at',
'refunded_at',
];
protected $appends = [
'name',
'description',
@@ -58,17 +78,123 @@ class Ticket extends Model
'source_variant_id' => 'integer',
'source_purchase_item_id' => 'integer',
'used_at' => 'datetime',
'disabled_at' => 'datetime',
'cancelled_at' => 'datetime',
'refunded_at' => 'datetime',
'scanner_user_id' => 'integer',
'user_id' => 'integer',
];
}
/** @return list<string> */
public static function statuses(): array
{
return array_keys(self::statusLabels());
}
/** @return array<string, string> */
public static function statusLabels(): array
{
return [
self::STATUS_ACTIVE => 'Activo',
self::STATUS_USED => 'Usado',
self::STATUS_EXPIRED => 'Vencido',
self::STATUS_DISABLED => 'Inhabilitado',
self::STATUS_CANCELLED => 'Cancelado',
self::STATUS_REFUNDED => 'Reembolsado',
];
}
/** @return list<array{value: string, label: string}> */
public static function statusOptions(): array
{
return collect(self::statusLabels())
->map(fn (string $label, string $status): array => [
'value' => $status,
'label' => $label,
])
->values()
->all();
}
public static function statusLabel(string $status): string
{
return self::statusLabels()[$status] ?? $status;
}
protected static function booted(): void
{
static::saving(function (self $ticket): void {
$ticket->ensureTerminalStatusTransitionIsAllowed();
});
}
/** @return BelongsTo<Tenant, $this> */
public function tenant(): BelongsTo
{
return $this->belongsTo(Tenant::class, 'tenant_code', 'codigo');
}
public function allow_refund(): bool
{
return $this->tenant?->allow_refund() ?? false;
}
public function allowRefund(): bool
{
return $this->allow_refund();
}
public function getAllowRefundAttribute(): bool
{
return $this->allow_refund();
}
public function is_active(): bool
{
return $this->status === self::STATUS_ACTIVE;
}
public function isActive(): bool
{
return $this->is_active();
}
public function getIsActiveAttribute(): bool
{
return $this->is_active();
}
public function can_cancel(): bool
{
return $this->is_active();
}
public function canCancel(): bool
{
return $this->can_cancel();
}
public function getCanCancelAttribute(): bool
{
return $this->can_cancel();
}
public function can_refund(): bool
{
return $this->is_active() && $this->allow_refund();
}
public function canRefund(): bool
{
return $this->can_refund();
}
public function getCanRefundAttribute(): bool
{
return $this->can_refund();
}
/** @return BelongsTo<User, $this> */
public function user(): BelongsTo
{
@@ -81,6 +207,12 @@ class Ticket extends Model
return $this->belongsTo(User::class, 'scanner_user_id')->withTrashed();
}
/** @return HasMany<ScanAttempt, $this> */
public function scanAttempts(): HasMany
{
return $this->hasMany(ScanAttempt::class);
}
/** @return BelongsTo<PurchaseItem, $this> */
public function sourcePurchaseItem(): BelongsTo
{
@@ -101,7 +233,7 @@ class Ticket extends Model
public function isValid(): bool
{
if ($this->used_at !== null) {
if ($this->hasTerminalStatus() || $this->used_at !== null) {
return false;
}
@@ -115,7 +247,9 @@ class Ticket extends Model
public function getIsExpiredAttribute(): bool
{
return $this->used_at === null && $this->resolvedValidity()->isExpired();
return ! $this->hasTerminalStatus()
&& $this->used_at === null
&& $this->resolvedValidity()->isExpired();
}
public function getIsUsedAttribute(): bool
@@ -125,6 +259,18 @@ class Ticket extends Model
public function getStatusAttribute(): string
{
if ($this->refunded_at !== null) {
return self::STATUS_REFUNDED;
}
if ($this->cancelled_at !== null) {
return self::STATUS_CANCELLED;
}
if ($this->disabled_at !== null) {
return self::STATUS_DISABLED;
}
if ($this->is_used) {
return self::STATUS_USED;
}
@@ -136,6 +282,102 @@ class Ticket extends Model
return self::STATUS_ACTIVE;
}
public function getStatusLabelAttribute(): string
{
return self::statusLabel($this->status);
}
public function markAsDisabled(): void
{
$this->markAsTerminalStatus(self::STATUS_DISABLED);
}
public function markAsCancelled(): void
{
$this->markAsTerminalStatus(self::STATUS_CANCELLED);
}
public function markAsRefunded(): void
{
$this->markAsTerminalStatus(self::STATUS_REFUNDED);
}
protected function valueChangeTenantCode(): string
{
return $this->tenant_code;
}
private function hasTerminalStatus(): bool
{
return $this->terminalStatus() !== null;
}
private function markAsTerminalStatus(string $status): void
{
$currentStatus = $this->terminalStatus();
if ($currentStatus === $status) {
return;
}
if ($currentStatus !== null) {
$this->throwTerminalStatusTransitionException();
}
$this->ensureTerminalStatusTransitionIsAllowed($status);
$this->{self::terminalStatusTimestampColumn($status)} = now();
}
private function ensureTerminalStatusTransitionIsAllowed(?string $targetStatus = null): void
{
$currentStatus = $this->terminalStatusFromAttributes($this->getRawOriginal());
$nextStatus = $targetStatus ?? $this->terminalStatus();
if ($currentStatus === null || $nextStatus === null || $currentStatus === $nextStatus) {
return;
}
$this->throwTerminalStatusTransitionException();
}
private function throwTerminalStatusTransitionException(): never
{
throw ValidationException::withMessages([
'status' => 'No se puede cambiar un ticket con estado terminal a otro estado terminal.',
]);
}
private function terminalStatus(): ?string
{
return $this->terminalStatusFromAttributes($this->getAttributes());
}
/** @param array<string, mixed> $attributes */
private function terminalStatusFromAttributes(array $attributes): ?string
{
foreach ([
self::STATUS_REFUNDED,
self::STATUS_CANCELLED,
self::STATUS_DISABLED,
] as $status) {
if (($attributes[self::terminalStatusTimestampColumn($status)] ?? null) !== null) {
return $status;
}
}
return null;
}
private static function terminalStatusTimestampColumn(string $status): string
{
return match ($status) {
self::STATUS_DISABLED => 'disabled_at',
self::STATUS_CANCELLED => 'cancelled_at',
self::STATUS_REFUNDED => 'refunded_at',
};
}
public function getNameAttribute(): string
{
return app(TicketPresentationResolver::class)->name($this);

View File

@@ -32,11 +32,7 @@ class AdminAppTicketIndexRequest extends FormRequest
'status' => [
'sometimes',
'nullable',
Rule::in([
Ticket::STATUS_ACTIVE,
Ticket::STATUS_USED,
Ticket::STATUS_EXPIRED,
]),
Rule::in(Ticket::statuses()),
],
'page' => ['sometimes', 'integer', 'min:1'],
'per_page' => ['sometimes', 'integer', 'min:1', 'max:100'],

View File

@@ -0,0 +1,22 @@
<?php
namespace App\Domains\Ticket\Requests;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;
class AdminAppTicketRefundRequest extends FormRequest
{
public function authorize(): bool
{
return true;
}
/** @return array<string, list<string|object>> */
public function rules(): array
{
return [
'refund_type' => ['required', 'string', Rule::in(['partial', 'total'])],
];
}
}

View File

@@ -4,7 +4,7 @@ namespace App\Domains\Ticket\Requests;
use Illuminate\Foundation\Http\FormRequest;
class ScannerTicketIndexRequest extends FormRequest
class ScanAttemptIndexRequest extends FormRequest
{
public function authorize(): bool
{

View File

@@ -15,20 +15,24 @@ class AdminAppTicketCollection extends ResourceCollection
private readonly int $totalTickets;
private readonly string $refundedTotal;
public function __construct(AdminAppTicketResult $result)
{
parent::__construct($result->tickets);
$this->scannedTickets = $result->scannedTickets;
$this->totalTickets = $result->totalTickets;
$this->refundedTotal = $result->refundedTotal;
}
/** @return array{scanned_tickets: int, total_tickets: int} */
/** @return array{scanned_tickets: int, total_tickets: int, refunded_total: string} */
public function with(Request $request): array
{
return [
'scanned_tickets' => $this->scannedTickets,
'total_tickets' => $this->totalTickets,
'refunded_total' => $this->refundedTotal,
];
}
}

View File

@@ -0,0 +1,26 @@
<?php
namespace App\Domains\Ticket\Resources\AdminApp;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;
/**
* @property-read array{
* total: string|null,
* partial: string|null,
* } $resource
*/
class AdminAppTicketRefundCalculationResource extends JsonResource
{
/**
* @return array{total: string|null, partial: string|null}
*/
public function toArray(Request $request): array
{
return [
'total' => $this->resource['total'],
'partial' => $this->resource['partial'],
];
}
}

View File

@@ -19,6 +19,10 @@ class AdminAppTicketResource extends TicketResource
return [
...parent::toArray($request),
...$details,
'allow_refund' => $this->resource->allow_refund(),
'is_active' => $this->resource->is_active(),
'can_cancel' => $this->resource->can_cancel(),
'can_refund' => $this->resource->can_refund(),
'values' => $rowService->values($this->resource, $details),
];
}

View File

@@ -0,0 +1,46 @@
<?php
namespace App\Domains\Ticket\Resources\Scanner;
use App\Domains\Ticket\Enums\ScanAttemptResult;
use App\Domains\Ticket\Models\ScanAttempt;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;
/** @mixin ScanAttempt */
class ScanAttemptResource extends JsonResource
{
/** @return array<string, mixed> */
public function toArray(Request $request): array
{
return [
'id' => $this->id,
'data' => $this->data,
'ticket_id' => $this->ticket_id,
'ticket' => $this->ticket?->ticket,
'category' => $this->ticket?->sourceCatalogItem?->category?->nombre,
'attempted_at' => $this->created_at,
'resolved_at' => $this->resolved_at,
'result' => $this->result->value,
'result_label' => match ($this->result) {
ScanAttemptResult::Accepted => 'Verificado',
ScanAttemptResult::AlreadyScanned => 'Usado',
ScanAttemptResult::Expired => 'Vencido',
default => 'Error',
},
'result_detail_label' => match ($this->result) {
ScanAttemptResult::Processing => 'Error',
ScanAttemptResult::Accepted => 'Verificado',
ScanAttemptResult::InvalidQr => 'QR no pertenece al evento',
ScanAttemptResult::TicketNotFound => 'Error',
ScanAttemptResult::CategoryForbidden => 'Error',
ScanAttemptResult::AlreadyScanned => 'Usado',
ScanAttemptResult::Expired => 'Vencido',
ScanAttemptResult::NotValid => 'No válido',
ScanAttemptResult::UnexpectedError => 'Error',
},
'can_view_ticket' => $this->ticket !== null
&& $this->result !== ScanAttemptResult::CategoryForbidden,
];
}
}

View File

@@ -1,24 +0,0 @@
<?php
namespace App\Domains\Ticket\Resources\Scanner;
use App\Domains\Ticket\Models\Ticket;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;
/** @mixin Ticket */
class ScannedTicketResource extends JsonResource
{
/** @return array<string, mixed> */
public function toArray(Request $request): array
{
return [
'product' => $this->name,
'id' => $this->id,
'ticket' => $this->ticket,
'used_at' => $this->used_at,
'expires_at' => $this->getEffectiveExpiresAt(),
'status' => $this->status,
];
}
}

View File

@@ -0,0 +1,28 @@
<?php
namespace App\Domains\Ticket\Resources\Scanner;
use App\Domains\Ticket\Models\ScanAttempt;
use App\Domains\Ticket\Resources\TicketResource;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;
/** @mixin ScanAttempt */
class ScannerScanResultResource extends JsonResource
{
/** @return array<string, mixed> */
public function toArray(Request $request): array
{
$ticket = $this->ticket;
$client = $ticket?->user;
return [
'scan_attempt' => ScanAttemptResource::make($this->resource),
'ticket' => $ticket === null ? null : TicketResource::make($ticket),
'client' => $client === null ? null : [
'id' => $client->id,
'nombre_apellido' => $client->nombre_apellido,
],
];
}
}

View File

@@ -16,6 +16,8 @@ class TicketResource extends JsonResource
'id' => $this->id,
'tenant_code' => $this->tenant_code,
'ticket' => $this->ticket,
'status' => $this->status,
'status_label' => $this->status_label,
'name' => $this->name,
'description' => $this->description,
'client' => $this->user?->nombre_apellido,

View File

@@ -12,5 +12,6 @@ final readonly class AdminAppTicketResult
public LengthAwarePaginator $tickets,
public int $scannedTickets,
public int $totalTickets,
public string $refundedTotal,
) {}
}

View File

@@ -31,10 +31,12 @@ class AdminAppTicketRowService
?? $ticket->sourceCatalogItem?->nombre
?? $ticket->name,
'amount' => $purchaseItem?->precio_unitario,
'refunded_amount' => $purchaseItem?->refunded_amount,
'client' => $purchaseItem?->purchase?->nombre_apellido ?? $ticket->user?->nombre_apellido,
'status' => $ticket->status,
'scanned_by' => $ticket->scannerUser?->nombre_apellido,
'variant_properties' => $this->variantProperties($ticket),
'allow_refund' => $ticket->allow_refund(),
];
}
@@ -95,11 +97,7 @@ class AdminAppTicketRowService
return match ($type) {
'order_number' => '#'.$value,
'currency' => '$'.number_format((float) $value, 2, ',', '.'),
'status' => match ((string) $value) {
Ticket::STATUS_USED => 'Usado',
Ticket::STATUS_EXPIRED => 'Vencido',
default => 'Activo',
},
'status' => Ticket::statusLabel((string) $value),
default => (string) $value,
};
}

View File

@@ -4,17 +4,21 @@ namespace App\Domains\Ticket\Services;
use App\Domains\Auth\Models\User;
use App\Domains\Purchase\Models\PurchaseItem;
use App\Domains\Purchase\Services\PurchaseRefundSummaryService;
use App\Domains\Tenant\Models\Tenant;
use App\Domains\Ticket\Models\Ticket;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\DB;
use Illuminate\Validation\ValidationException;
class AdminAppTicketService
{
private const RELATIONS = [
...TicketValidityResolver::RELATIONS,
...TicketPresentationResolver::RELATIONS,
'tenant',
'user',
'scannerUser',
'sourceCatalogItem.category',
@@ -24,6 +28,7 @@ class AdminAppTicketService
public function __construct(
private readonly AdminAppTicketColumnService $columnService,
private readonly AdminAppTicketRowService $rowService,
private readonly PurchaseRefundSummaryService $refundSummaryService,
) {}
/**
@@ -42,20 +47,30 @@ class AdminAppTicketService
->get();
$matchingTickets = $this->sortTickets($matchingTickets, $tenant, $filters);
$tickets = $this->paginate($matchingTickets, $filters);
$scannedTickets = $matchingTickets->whereNotNull('used_at')->count();
$scannedTickets = $matchingTickets
->filter(fn (Ticket $ticket): bool => $ticket->status === Ticket::STATUS_USED)
->count();
$activeTickets = $matchingTickets
->filter(fn (Ticket $ticket): bool => $ticket->is_active())
->count();
$totalTickets = $activeTickets + $scannedTickets;
} else {
$tickets = (clone $query)
->with(self::RELATIONS)
->when(! $databaseSorted, fn (Builder $query): Builder => $query->orderByDesc('id'))
->paginateFromRequest()
->withQueryString();
$scannedTickets = $countQuery->whereNotNull('used_at')->count();
$counts = $this->calculateTicketCounts($countQuery);
$scannedTickets = $counts['scanned'];
$totalTickets = $counts['total'];
}
return new AdminAppTicketResult(
tickets: $tickets,
scannedTickets: $scannedTickets,
totalTickets: $tickets->total(),
totalTickets: $totalTickets,
refundedTotal: $this->refundSummaryService->totalForTenant($tenant),
);
}
@@ -75,6 +90,154 @@ class AdminAppTicketService
return $databaseSorted ? $tickets : $this->sortTickets($tickets, $tenant, $filters);
}
public function cancel(Tenant $tenant, int $ticketId): Ticket
{
return DB::transaction(function () use ($tenant, $ticketId): Ticket {
$ticket = Ticket::query()
->where('tenant_code', $tenant->codigo)
->lockForUpdate()
->findOrFail($ticketId);
if (! $ticket->can_cancel()) {
throw ValidationException::withMessages([
'status' => 'El ticket debe estar activo para poder cancelarlo.',
]);
}
$ticket->markAsCancelled();
$ticket->save();
return $ticket->refresh()->load(self::RELATIONS);
});
}
/**
* @return array{
* total: string|null,
* partial: string|null,
* }
*/
public function calculateRefund(Tenant $tenant, int $ticketId): array
{
$ticket = Ticket::query()
->where('tenant_code', $tenant->codigo)
->findOrFail($ticketId);
if (! $ticket->can_refund()) {
throw ValidationException::withMessages([
'refund' => 'El reembolso no está disponible para este ticket.',
]);
}
$purchaseItem = PurchaseItem::query()
->find($ticket->source_purchase_item_id);
if ($purchaseItem === null) {
throw ValidationException::withMessages([
'ticket' => 'El ticket no tiene un ítem de compra asociado para reembolsar.',
]);
}
$unitPrice = (float) $purchaseItem->precio_unitario;
$itemTotal = (float) $purchaseItem->total;
$itemRefundedAmount = (float) ($purchaseItem->refunded_amount ?? 0);
$remainingItemAmount = max(0.0, round($itemTotal - $itemRefundedAmount, 2));
$total = null;
if ($tenant->allow_refund() && $tenant->allow_ticket_total_refund && $unitPrice <= $remainingItemAmount) {
$total = number_format($unitPrice, 2, '.', '');
}
$partial = null;
if ($tenant->allow_refund() && $tenant->allow_partial_refund()) {
$partialAmount = $this->refundAmount($purchaseItem, $tenant, 'partial');
if ($partialAmount <= $remainingItemAmount) {
$partial = number_format($partialAmount, 2, '.', '');
}
}
return [
'total' => $total,
'partial' => $partial,
];
}
public function refund(Tenant $tenant, int $ticketId, string $refundType): Ticket
{
$this->ensureRefundIsAllowed($tenant, $refundType);
return DB::transaction(function () use ($tenant, $ticketId, $refundType): Ticket {
$ticket = Ticket::query()
->where('tenant_code', $tenant->codigo)
->lockForUpdate()
->findOrFail($ticketId);
if (! $ticket->can_refund()) {
if ($ticket->status !== Ticket::STATUS_ACTIVE) {
throw ValidationException::withMessages([
'status' => 'El ticket debe estar activo para poder reembolsarlo.',
]);
}
throw ValidationException::withMessages([
'refund' => 'El reembolso no está disponible para este ticket.',
]);
}
$purchaseItem = PurchaseItem::query()
->lockForUpdate()
->find($ticket->source_purchase_item_id);
if ($purchaseItem === null) {
throw ValidationException::withMessages([
'ticket' => 'El ticket no tiene un ítem de compra asociado para reembolsar.',
]);
}
$refundAmount = $this->refundAmount($purchaseItem, $tenant, $refundType);
$refundedAmount = round((float) $purchaseItem->refunded_amount + $refundAmount, 2);
if ($refundedAmount > (float) $purchaseItem->total) {
throw ValidationException::withMessages([
'refund_type' => 'El importe reembolsado no puede superar el total del ítem de compra.',
]);
}
$ticket->markAsRefunded();
$ticket->save();
$purchaseItem->update([
'refunded_amount' => number_format($refundedAmount, 2, '.', ''),
]);
return $ticket->refresh()->load(self::RELATIONS);
});
}
private function ensureRefundIsAllowed(Tenant $tenant, string $refundType): void
{
$isAllowed = match ($refundType) {
'partial' => $tenant->allow_refund() && $tenant->allow_partial_refund(),
'total' => $tenant->allow_refund() && (bool) $tenant->allow_ticket_total_refund,
};
if (! $isAllowed) {
throw ValidationException::withMessages([
'refund_type' => 'El tipo de reembolso solicitado no está habilitado para este tenant.',
]);
}
}
private function refundAmount(PurchaseItem $purchaseItem, Tenant $tenant, string $refundType): float
{
$ticketAmount = (float) $purchaseItem->precio_unitario;
return match ($refundType) {
'partial' => round($ticketAmount * (float) $tenant->ticket_partial_refund_percentage / 100, 2),
'total' => $ticketAmount,
};
}
/**
* @param array{q?: string|null, category?: string|null, product?: string|null, type?: string|null, date?: string|null, size?: string|null, status?: string|null, page?: int, per_page?: int} $filters
* @return Builder<Ticket>
@@ -255,13 +418,41 @@ class AdminAppTicketService
}
if ($status === Ticket::STATUS_USED) {
$query->whereNotNull('used_at');
$query
->whereNotNull('used_at')
->whereNull('disabled_at')
->whereNull('cancelled_at')
->whereNull('refunded_at');
return;
}
$timestampColumn = match ($status) {
Ticket::STATUS_DISABLED => 'disabled_at',
Ticket::STATUS_CANCELLED => 'cancelled_at',
Ticket::STATUS_REFUNDED => 'refunded_at',
default => null,
};
if ($timestampColumn !== null) {
$query->whereNotNull($timestampColumn);
if ($status === Ticket::STATUS_DISABLED) {
$query->whereNull('cancelled_at')->whereNull('refunded_at');
}
if ($status === Ticket::STATUS_CANCELLED) {
$query->whereNull('refunded_at');
}
return;
}
$matchingIds = (clone $query)
->whereNull('used_at')
->whereNull('disabled_at')
->whereNull('cancelled_at')
->whereNull('refunded_at')
->with(TicketValidityResolver::RELATIONS)
->get()
->filter(fn (Ticket $ticket): bool => $ticket->status === $status)
@@ -270,6 +461,35 @@ class AdminAppTicketService
$query->whereIn('tickets.id', $matchingIds);
}
/**
* @param Builder<Ticket> $countQuery
* @return array{scanned: int, total: int}
*/
private function calculateTicketCounts(Builder $countQuery): array
{
$scannedTickets = (clone $countQuery)
->whereNotNull('used_at')
->whereNull('disabled_at')
->whereNull('cancelled_at')
->whereNull('refunded_at')
->count();
$activeTickets = (clone $countQuery)
->whereNull('used_at')
->whereNull('disabled_at')
->whereNull('cancelled_at')
->whereNull('refunded_at')
->with(TicketValidityResolver::RELATIONS)
->get()
->filter(fn (Ticket $ticket): bool => $ticket->is_active())
->count();
return [
'scanned' => $scannedTickets,
'total' => $activeTickets + $scannedTickets,
];
}
private function normalizedCategory(string $category): string
{
return mb_strtolower(trim($category));

View File

@@ -3,46 +3,116 @@
namespace App\Domains\Ticket\Services;
use App\Domains\Auth\Models\User;
use App\Domains\Ticket\Enums\ScanAttemptResult;
use App\Domains\Ticket\Models\ScanAttempt;
use App\Domains\Ticket\Models\Ticket;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Support\Facades\DB;
use Illuminate\Validation\ValidationException;
use Illuminate\Support\Str;
use Throwable;
class ScannerTicketService
{
/**
* @param array{q?: string|null, page?: int, per_page?: int} $filters
* @return LengthAwarePaginator<Ticket>
* @return LengthAwarePaginator<ScanAttempt>
*/
public function scannedBy(User $scanner, array $filters = []): LengthAwarePaginator
public function attemptsBy(User $scanner, array $filters = []): LengthAwarePaginator
{
$search = trim((string) ($filters['q'] ?? ''));
return $this->baseQuery()
return ScanAttempt::query()
->with('ticket.sourceCatalogItem.category')
->where('tenant_code', $scanner->tenant_codigo)
->where('scanner_user_id', $scanner->getKey())
->when($search !== '', function (Builder $query) use ($search): void {
$usedAtDate = $this->parseSearchDate($search);
$attemptedAtDate = $this->parseSearchDate($search);
$query->where(function (Builder $searchQuery) use ($search, $usedAtDate): void {
$searchQuery->where('ticket', 'like', "%{$search}%");
$query->where(function (Builder $searchQuery) use ($search, $attemptedAtDate): void {
$searchQuery->where('data', 'like', "%{$search}%");
if (ctype_digit($search)) {
$searchQuery->orWhere('id', (int) $search);
}
if ($usedAtDate !== null) {
$searchQuery->orWhereDate('used_at', $usedAtDate);
if ($attemptedAtDate !== null) {
$searchQuery->orWhereDate('created_at', $attemptedAtDate);
}
});
})
->orderByDesc('used_at')
->orderByDesc('created_at')
->orderByDesc('id')
->paginateFromRequest()
->withQueryString();
}
/**
* @param array{q?: string|null, page?: int, per_page?: int} $filters
* @return LengthAwarePaginator<ScanAttempt>
*/
public function attemptsByStaff(User $scanner, array $filters = []): LengthAwarePaginator
{
$search = trim((string) ($filters['q'] ?? ''));
return ScanAttempt::query()
->with('ticket.sourceCatalogItem.category')
->where('tenant_code', $scanner->tenant_codigo)
->where('scanner_user_id', $scanner->getKey())
->when($search !== '', function (Builder $query) use ($search): void {
$attemptedAtDate = $this->parseSearchDate($search);
$attemptedAtDayMonth = $this->parseSearchDayMonth($search);
$query->where(function (Builder $searchQuery) use (
$search,
$attemptedAtDate,
$attemptedAtDayMonth,
): void {
$searchQuery
->whereHas(
'ticket.sourceCatalogItem.category',
fn (Builder $categoryQuery): Builder => $categoryQuery
->where('nombre', 'like', "%{$search}%")
)
->orWhere('created_at', 'like', "%{$search}%");
if (ctype_digit($search)) {
$searchQuery->orWhere('ticket_id', (int) $search);
}
if ($attemptedAtDate !== null) {
$searchQuery->orWhereDate('created_at', $attemptedAtDate);
}
if ($attemptedAtDayMonth !== null) {
$searchQuery->orWhere(function (Builder $dateQuery) use ($attemptedAtDayMonth): void {
$dateQuery
->whereDay('created_at', $attemptedAtDayMonth['day'])
->whereMonth('created_at', $attemptedAtDayMonth['month']);
});
}
});
})
->orderByDesc('created_at')
->orderByDesc('id')
->paginateFromRequest()
->withQueryString();
}
public function scanAttemptDetail(User $scanner, int $scanAttemptId): ScanAttempt
{
$scanAttempt = ScanAttempt::query()
->with('ticket')
->where('tenant_code', $scanner->tenant_codigo)
->where('scanner_user_id', $scanner->getKey())
->findOrFail($scanAttemptId);
$scanAttempt->ticket?->loadMissing($this->relations());
return $scanAttempt;
}
private function parseSearchDate(string $search): ?string
{
if (preg_match('/^(\d{4})-(\d{2})-(\d{2})$/', $search, $matches) === 1) {
@@ -67,6 +137,19 @@ class ScannerTicketService
return null;
}
/** @return array{day: int, month: int}|null */
private function parseSearchDayMonth(string $search): ?array
{
if (preg_match('/^(\d{1,2})\/(\d{1,2})$/', $search, $matches) !== 1) {
return null;
}
$day = (int) $matches[1];
$month = (int) $matches[2];
return checkdate($month, $day, 2000) ? compact('day', 'month') : null;
}
public function detail(User $scanner, string $ticketUuid): Ticket
{
$query = $this->baseQuery()
@@ -90,42 +173,117 @@ class ScannerTicketService
return $query->firstOrFail();
}
public function scan(User $scanner, string $ticketUuid): Ticket
public function scan(User $scanner, mixed $scannedData): ScanAttempt
{
return DB::transaction(function () use ($scanner, $ticketUuid): Ticket {
$ticket = $this->baseQuery()
->where('tenant_code', $scanner->tenant_codigo)
->where('ticket', $ticketUuid)
->lockForUpdate()
->firstOrFail();
$scanAttempt = ScanAttempt::query()->create([
'tenant_code' => $scanner->tenant_codigo,
'scanner_user_id' => $scanner->getKey(),
'data' => $this->serializeScannedData($scannedData),
'result' => ScanAttemptResult::Processing,
]);
if (! $this->scannerCanScan($scanner, $ticket)) {
throw ValidationException::withMessages([
'ticket' => __('api.ticket.scanner_category_forbidden'),
]);
}
if (! is_string($scannedData) || ! Str::isUuid($scannedData)) {
$this->resolveScanAttempt($scanAttempt, ScanAttemptResult::InvalidQr);
if ($ticket->is_used) {
throw ValidationException::withMessages([
'ticket' => __('api.ticket.already_scanned'),
]);
}
return $scanAttempt->refresh();
}
if (! $ticket->is_valid) {
throw ValidationException::withMessages([
'ticket' => $ticket->is_expired
? __('api.ticket.expired_for_scan')
: __('api.ticket.not_valid_for_scan'),
]);
}
$ticketId = null;
$ticket->forceFill([
'used_at' => now(),
'scanner_user_id' => $scanner->getKey(),
])->save();
try {
return DB::transaction(function () use (
$scanner,
$scannedData,
$scanAttempt,
&$ticketId,
): ScanAttempt {
$ticket = $this->baseQuery()
->where('tenant_code', $scanner->tenant_codigo)
->where('ticket', $scannedData)
->lockForUpdate()
->firstOrFail();
$ticketId = (int) $ticket->getKey();
return $ticket->refresh()->load($this->relations());
});
if (! $this->scannerCanScan($scanner, $ticket)) {
$this->resolveScanAttempt(
$scanAttempt,
ScanAttemptResult::CategoryForbidden,
$ticketId,
);
return $scanAttempt->refresh()->setRelation('ticket', $ticket);
}
if ($ticket->is_used) {
$this->resolveScanAttempt(
$scanAttempt,
ScanAttemptResult::AlreadyScanned,
$ticketId,
);
return $scanAttempt->refresh()->setRelation('ticket', $ticket);
}
if (! $ticket->is_valid) {
$result = $ticket->is_expired
? ScanAttemptResult::Expired
: ScanAttemptResult::NotValid;
$this->resolveScanAttempt($scanAttempt, $result, $ticketId);
return $scanAttempt->refresh()->setRelation('ticket', $ticket);
}
$ticket->forceFill([
'used_at' => now(),
'scanner_user_id' => $scanner->getKey(),
])->save();
$this->resolveScanAttempt(
$scanAttempt,
ScanAttemptResult::Accepted,
$ticketId,
);
$ticket = $ticket->refresh()->load($this->relations());
return $scanAttempt->refresh()->setRelation('ticket', $ticket);
});
} catch (ModelNotFoundException) {
$this->resolveScanAttempt($scanAttempt, ScanAttemptResult::TicketNotFound);
return $scanAttempt->refresh();
} catch (Throwable $exception) {
report($exception);
$this->resolveScanAttempt($scanAttempt, ScanAttemptResult::UnexpectedError, $ticketId);
return $scanAttempt->refresh();
}
}
private function resolveScanAttempt(
ScanAttempt $scanAttempt,
ScanAttemptResult $result,
?int $ticketId = null,
): void {
$scanAttempt->forceFill([
'ticket_id' => $ticketId,
'result' => $result,
'resolved_at' => now(),
])->save();
}
private function serializeScannedData(mixed $scannedData): ?string
{
if ($scannedData === null || is_string($scannedData)) {
return $scannedData;
}
$encoded = json_encode(
$scannedData,
JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_INVALID_UTF8_SUBSTITUTE,
);
return $encoded === false ? get_debug_type($scannedData) : $encoded;
}
/** @return Builder<Ticket> */

View File

@@ -4,6 +4,8 @@ namespace App\Domains\Ticket\Services;
use App\Domains\Catalog\Models\Variant;
use App\Domains\Catalog\Models\VariantDefinition;
use App\Domains\Event\Models\EventDate;
use App\Domains\Event\Services\EffectiveEventDateResolver;
use App\Domains\Ticket\Models\Ticket;
use App\Domains\Ticket\Models\ValidityTime;
use Illuminate\Support\Collection;
@@ -17,6 +19,14 @@ use Illuminate\Support\Collection;
*/
class TicketValidityResolver
{
private readonly EffectiveEventDateResolver $effectiveEventDateResolver;
public function __construct(?EffectiveEventDateResolver $effectiveEventDateResolver = null)
{
$this->effectiveEventDateResolver = $effectiveEventDateResolver
?? new EffectiveEventDateResolver;
}
/** Relaciones necesarias para resolver tickets sin consultas N+1. */
public const RELATIONS = [
'sourceVariant.eventDates.validityTime',
@@ -56,7 +66,18 @@ class TicketValidityResolver
]);
$dimensions = collect();
$eventDates = $variant->selectedEventDates();
$selectedEventDates = $variant->selectedEventDates();
$eventDates = $selectedEventDates
->map(fn (EventDate $eventDate): ?EventDate => $this->effectiveEventDateResolver->resolve($eventDate))
->filter()
->unique(fn (EventDate $eventDate): int => $eventDate->getKey() ?? spl_object_id($eventDate))
->values();
if ($selectedEventDates->isNotEmpty() && $eventDates->isEmpty()) {
return ResolvedTicketValidity::unresolvable();
}
$eventDates->each->loadMissing('validityTime');
if ($eventDates->contains(fn ($eventDate): bool => $eventDate->validityTime === null)) {
return ResolvedTicketValidity::unresolvable();

View File

@@ -9,6 +9,18 @@ Route::prefix('v1/adminapp/tenant')
Route::get('tickets', [TicketController::class, 'index'])
->middleware('tenant.menu:adminapp.tickets')
->name('adminapp.tickets.index');
Route::post('tickets/{ticket}/cancel', [TicketController::class, 'cancel'])
->whereNumber('ticket')
->middleware('tenant.menu:adminapp.tickets')
->name('adminapp.tickets.cancel');
Route::get('tickets/{ticket}/refund', [TicketController::class, 'calculateRefund'])
->whereNumber('ticket')
->middleware('tenant.menu:adminapp.tickets')
->name('adminapp.tickets.calculate-refund');
Route::post('tickets/{ticket}/refund', [TicketController::class, 'refund'])
->whereNumber('ticket')
->middleware('tenant.menu:adminapp.tickets')
->name('adminapp.tickets.refund');
Route::get('tickets/pdf', [TicketController::class, 'downloadPdf'])
->middleware('tenant.menu:adminapp.tickets')
->name('adminapp.tickets.pdf');

View File

@@ -1,14 +1,18 @@
<?php
use App\Domains\Ticket\Controllers\Scanner\ScanAttemptController;
use App\Domains\Ticket\Controllers\Scanner\TicketController;
use Illuminate\Support\Facades\Route;
Route::prefix('v1/scanner/tickets')
->middleware(['auth:sanctum', 'scanner.tenant'])
Route::middleware(['auth:sanctum', 'scanner.tenant'])
->group(function (): void {
Route::get('/', [TicketController::class, 'index']);
Route::get('{ticketUuid}', [TicketController::class, 'show'])
->whereUuid('ticketUuid');
Route::post('{ticketUuid}/scan', [TicketController::class, 'scan'])
->whereUuid('ticketUuid');
Route::get('v1/scanner/attempts', ScanAttemptController::class);
Route::get('v1/scanner/attempts/{scanAttempt}', [ScanAttemptController::class, 'show'])
->whereNumber('scanAttempt');
Route::prefix('v1/scanner/tickets')->group(function (): void {
Route::post('scan', [TicketController::class, 'scan']);
Route::get('{ticketUuid}', [TicketController::class, 'show'])
->whereUuid('ticketUuid');
});
});

View File

@@ -0,0 +1,46 @@
<?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('scan_attempts', function (Blueprint $table): void {
$table->id();
$table->string('tenant_code');
$table->foreignId('scanner_user_id')
->nullable()
->constrained('users')
->cascadeOnUpdate()
->nullOnDelete();
$table->foreignId('ticket_id')
->nullable()
->constrained('tickets')
->cascadeOnUpdate()
->nullOnDelete();
$table->text('data')->nullable();
$table->string('result', 32);
$table->timestamp('resolved_at')->nullable();
$table->timestamp('created_at')->useCurrent();
$table->foreign('tenant_code')
->references('codigo')
->on('tenants')
->cascadeOnUpdate()
->restrictOnDelete();
$table->index(['scanner_user_id', 'created_at']);
$table->index(['tenant_code', 'created_at']);
$table->index(['ticket_id', 'created_at']);
$table->index(['tenant_code', 'result', 'created_at']);
});
}
public function down(): void
{
Schema::dropIfExists('scan_attempts');
}
};

View File

@@ -0,0 +1,28 @@
<?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('tenants', function (Blueprint $table): void {
$table->boolean('allow_ticket_total_refund')->default(false);
$table->boolean('allow_ticket_partial_refund')->default(false);
$table->decimal('ticket_partial_refund_percentage', 4, 2)->default(0);
});
}
public function down(): void
{
Schema::table('tenants', function (Blueprint $table): void {
$table->dropColumn([
'allow_ticket_total_refund',
'allow_ticket_partial_refund',
'ticket_partial_refund_percentage',
]);
});
}
};

View File

@@ -0,0 +1,36 @@
<?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->dateTime('disabled_at')->nullable()->after('used_at');
$table->dateTime('cancelled_at')->nullable()->after('disabled_at');
$table->dateTime('refunded_at')->nullable()->after('cancelled_at');
});
Schema::table('compra_items', function (Blueprint $table): void {
$table->decimal('refunded_amount', 10, 2)->default(0)->after('total');
});
}
public function down(): void
{
Schema::table('compra_items', function (Blueprint $table): void {
$table->dropColumn('refunded_amount');
});
Schema::table('tickets', function (Blueprint $table): void {
$table->dropColumn([
'disabled_at',
'cancelled_at',
'refunded_at',
]);
});
}
};

View File

@@ -0,0 +1,30 @@
<?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('event_dates', function (Blueprint $table): void {
$table->foreignId('rescheduled_to_event_date_id')
->nullable()
->after('validity_time_id')
->constrained('event_dates')
->restrictOnDelete();
$table->dateTime('cancelled_at')
->nullable()
->after('rescheduled_to_event_date_id');
});
}
public function down(): void
{
Schema::table('event_dates', function (Blueprint $table): void {
$table->dropConstrainedForeignId('rescheduled_to_event_date_id');
$table->dropColumn('cancelled_at');
});
}
};

View File

@@ -0,0 +1,34 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
Schema::table('tenants', function (Blueprint $table): void {
$table->boolean('allow_ticket_refund')
->default(false)
->after('scanner_category_validation_enabled');
});
DB::table('tenants')
->where('allow_ticket_total_refund', true)
->orWhere(function ($query): void {
$query
->where('allow_ticket_partial_refund', true)
->where('ticket_partial_refund_percentage', '>', 0);
})
->update(['allow_ticket_refund' => true]);
}
public function down(): void
{
Schema::table('tenants', function (Blueprint $table): void {
$table->dropColumn('allow_ticket_refund');
});
}
};

View File

@@ -0,0 +1,22 @@
<?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('event_dates', function (Blueprint $table): void {
$table->renameColumn('cancelled_at', 'suspended_at');
});
}
public function down(): void
{
Schema::table('event_dates', function (Blueprint $table): void {
$table->renameColumn('suspended_at', 'cancelled_at');
});
}
};

View File

@@ -113,6 +113,7 @@ function bodyFor(string $method, string $uri): ?array
'POST api/v1/scanner/password/reset-attempts' => ['email' => '{{scanner_email}}'],
'POST api/v1/scanner/password/reset-attempts/validate' => ['email' => '{{scanner_email}}', 'codigo' => '{{reset_code}}'],
'POST api/v1/scanner/password/reset' => ['email' => '{{scanner_email}}', 'codigo' => '{{reset_code}}', 'password' => '{{scanner_password}}', 'password_confirmation' => '{{scanner_password}}'],
'POST api/v1/scanner/tickets/scan' => ['data' => '{{ticket_uuid}}'],
];
if (isset($exact[$key])) {
@@ -201,7 +202,7 @@ function queryFor(string $uri): array
['key' => 'page', 'value' => '1'],
['key' => 'per_page', 'value' => '20'],
],
'api/v1/scanner/tickets' => [['key' => 'q', 'value' => '', 'disabled' => true], ['key' => 'page', 'value' => '1'], ['key' => 'per_page', 'value' => '20']],
'api/v1/scanner/attempts' => [['key' => 'q', 'value' => '', 'disabled' => true], ['key' => 'page', 'value' => '1'], ['key' => 'per_page', 'value' => '20']],
'api/storage-test/s3/temporary-url' => [['key' => 'path', 'value' => '{{s3_path}}'], ['key' => 'expires_in_minutes', 'value' => '60']],
default => [],
};

View File

@@ -8,6 +8,7 @@ use App\Domains\Authorization\Enums\PermissionCode;
use App\Domains\Authorization\Enums\RoleCode;
use App\Domains\Authorization\Models\Permission;
use App\Domains\Authorization\Models\Role;
use App\Domains\Catalog\Models\Category;
use App\Domains\Menu\Models\Menu;
use App\Domains\Tenant\Models\Tenant;
use Illuminate\Foundation\Testing\RefreshDatabase;
@@ -85,6 +86,65 @@ class ScannerMeControllerTest extends TestCase
$this->getJson('/api/v1/scanner/me')->assertForbidden();
}
public function test_it_returns_assigned_scan_categories_when_validation_is_enabled(): void
{
$this->createScannerRole();
$tenant = $this->createTenant();
$scanner = User::factory()->create([
'rol_codigo' => RoleCode::Scanner->value,
'tenant_codigo' => $tenant->codigo,
]);
$meals = Category::query()->create(['tenant_code' => $tenant->codigo, 'nombre' => 'Comidas']);
$entries = Category::query()->create(['tenant_code' => $tenant->codigo, 'nombre' => 'Entradas']);
$scanner->scanCategories()->attach([$meals->id, $entries->id]);
Sanctum::actingAs($scanner);
$this->getJson('/api/v1/scanner/me')
->assertOk()
->assertJsonPath('data.user.categories.0.id', $meals->id)
->assertJsonPath('data.user.categories.0.nombre', 'Comidas')
->assertJsonPath('data.user.categories.1.id', $entries->id)
->assertJsonPath('data.user.categories.1.nombre', 'Entradas');
}
public function test_it_omits_scan_categories_when_validation_is_disabled_or_none_are_assigned(): void
{
$this->createScannerRole();
$tenant = $this->createTenant();
$scanner = User::factory()->create([
'rol_codigo' => RoleCode::Scanner->value,
'tenant_codigo' => $tenant->codigo,
]);
Sanctum::actingAs($scanner);
$this->getJson('/api/v1/scanner/me')
->assertOk()
->assertJsonMissingPath('data.user.categories');
$category = Category::query()->create(['tenant_code' => $tenant->codigo, 'nombre' => 'Entradas']);
$scanner->scanCategories()->attach($category);
$tenant->update(['scanner_category_validation_enabled' => false]);
$this->getJson('/api/v1/scanner/me')
->assertOk()
->assertJsonMissingPath('data.user.categories');
}
private function createScannerRole(): Role
{
$role = Role::query()->create([
'codigo' => RoleCode::Scanner->value,
'nombre' => 'Scanner',
]);
$permission = Permission::query()->create([
'codigo' => PermissionCode::ScanTickets->value,
'nombre' => 'Escanear tickets',
]);
$role->permissions()->attach($permission->codigo);
return $role;
}
private function createTenant(): Tenant
{
$logo = Attachment::query()->create([

View File

@@ -6,12 +6,17 @@ use App\Domains\Attachable\Enums\AttachmentType;
use App\Domains\Attachable\Models\Attachment;
use App\Domains\Auth\Models\User;
use App\Domains\Authorization\Enums\RoleCode;
use App\Domains\Catalog\Models\CatalogItem;
use App\Domains\Catalog\Models\Inventory;
use App\Domains\Catalog\Models\Variant;
use App\Domains\Tenant\Models\Tenant;
use App\Domains\Tenant\Models\WebsiteType;
use App\Domains\Ticket\Enums\ValidityTimeType;
use App\Domains\Ticket\Models\Ticket;
use Database\Seeders\AuthorizationSeeder;
use Database\Seeders\SocialMediaSeeder;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Str;
use Laravel\Sanctum\Sanctum;
use Tests\TestCase;
@@ -34,9 +39,10 @@ class AdminAppEventControllerTest extends TestCase
{
$this->getJson('/api/v1/adminapp/tenant/event')->assertUnauthorized();
$this->putJson('/api/v1/adminapp/tenant/event', $this->eventPayload())->assertUnauthorized();
$this->postJson('/api/v1/adminapp/tenant/event-dates', $this->datePayload())->assertUnauthorized();
}
public function test_an_adminapp_user_can_create_the_active_event_and_contact_information(): void
public function test_an_adminapp_user_can_update_event_and_contact_information_without_synchronizing_dates(): void
{
$tenant = $this->createTenant('acme');
Sanctum::actingAs($this->createAdminAppUser($tenant));
@@ -45,10 +51,11 @@ class AdminAppEventControllerTest extends TestCase
->assertOk()
->assertJsonPath('data.title', 'Festival Acme')
->assertJsonPath('data.location', 'Predio Ferial, Rosario')
->assertJsonPath('data.dates.0.date', '2026-10-09')
->assertJsonPath('data.dates.0.validity_time.type', 'fixed_window')
->assertJsonPath('data.dates.0.start_time', '09:00')
->assertJsonPath('data.dates.0.end_time', '18:30')
->assertJsonPath('data.allow_ticket_refund', true)
->assertJsonPath('data.allow_ticket_total_refund', true)
->assertJsonPath('data.allow_ticket_partial_refund', true)
->assertJsonPath('data.ticket_partial_refund_percentage', '25.50')
->assertJsonCount(0, 'data.dates')
->assertJsonPath('data.contact.whatsapp_url', 'https://wa.me/5493415550101')
->assertJsonPath('data.contact.instagram_url', 'https://instagram.com/acme')
->assertJsonPath('data.contact.facebook_url', null);
@@ -58,25 +65,13 @@ class AdminAppEventControllerTest extends TestCase
'id' => $tenant->id,
'event_title' => 'Festival Acme',
'event_location' => 'Predio Ferial, Rosario',
'event_date_text' => '9 de Octubre 2026',
'event_date_text' => null,
'allow_ticket_refund' => true,
'allow_ticket_total_refund' => true,
'allow_ticket_partial_refund' => true,
'ticket_partial_refund_percentage' => 25.50,
]);
$this->assertDatabaseHas('event_dates', [
'tenant_code' => $tenant->codigo,
'date' => '2026-10-09',
'time_start' => '09:00:00',
'time_end' => '18:30:00',
]);
$eventDate = $tenant->eventDates()->with('validityTime')->sole();
$this->assertSame($eventDate->validity_time_id, $response->json('data.dates.0.validity_time_id'));
$this->assertSame(ValidityTimeType::FixedWindow, $eventDate->validityTime->type);
$this->assertSame(
'2026-10-09 09:00:00',
$eventDate->validityTime->fixed_starts_at->format('Y-m-d H:i:s'),
);
$this->assertSame(
'2026-10-09 18:30:00',
$eventDate->validityTime->fixed_expires_at->format('Y-m-d H:i:s'),
);
$this->assertDatabaseCount('event_dates', 0);
$this->assertDatabaseHas('tenant_social_media', [
'tenant_code' => $tenant->codigo,
'social_media_code' => 'whatsapp',
@@ -84,6 +79,56 @@ class AdminAppEventControllerTest extends TestCase
]);
}
public function test_disabling_refunds_preserves_the_configured_types_and_percentage(): void
{
$tenant = $this->createTenant('acme');
$tenant->update([
'allow_ticket_refund' => true,
'allow_ticket_total_refund' => true,
'allow_ticket_partial_refund' => true,
'ticket_partial_refund_percentage' => 35.50,
]);
Sanctum::actingAs($this->createAdminAppUser($tenant));
$payload = $this->eventPayload();
$payload['allow_ticket_refund'] = false;
$payload['ticket_partial_refund_percentage'] = 35.50;
$this->putJson('/api/v1/adminapp/tenant/event', $payload)
->assertOk()
->assertJsonPath('data.allow_ticket_refund', false)
->assertJsonPath('data.allow_ticket_total_refund', true)
->assertJsonPath('data.allow_ticket_partial_refund', true)
->assertJsonPath('data.ticket_partial_refund_percentage', '35.50');
$tenant->refresh();
$this->assertFalse($tenant->allow_refund());
$this->assertTrue($tenant->allow_ticket_total_refund);
$this->assertTrue($tenant->allow_ticket_partial_refund);
$this->assertSame('35.50', $tenant->ticket_partial_refund_percentage);
}
public function test_enabled_refunds_require_a_type_and_a_valid_partial_percentage(): void
{
$tenant = $this->createTenant('acme');
Sanctum::actingAs($this->createAdminAppUser($tenant));
$payload = $this->eventPayload();
$payload['allow_ticket_total_refund'] = false;
$payload['allow_ticket_partial_refund'] = false;
$this->putJson('/api/v1/adminapp/tenant/event', $payload)
->assertUnprocessable()
->assertJsonValidationErrors('allow_ticket_refund');
$payload['allow_ticket_partial_refund'] = true;
$payload['ticket_partial_refund_percentage'] = 0;
$this->putJson('/api/v1/adminapp/tenant/event', $payload)
->assertUnprocessable()
->assertJsonValidationErrors('ticket_partial_refund_percentage');
}
public function test_an_adminapp_user_can_read_only_its_tenant_active_event(): void
{
$tenant = $this->createTenant('acme');
@@ -109,7 +154,7 @@ class AdminAppEventControllerTest extends TestCase
->assertJsonCount(0, 'data.dates');
}
public function test_updating_reuses_the_active_event_and_synchronizes_dates_and_contact(): void
public function test_updating_event_does_not_change_or_delete_existing_dates(): void
{
$tenant = $this->createTenant('acme');
$eventTenant = $this->createActiveEvent($tenant, 'Old Event');
@@ -124,7 +169,6 @@ class AdminAppEventControllerTest extends TestCase
'time_end' => '12:00',
]);
$firstValidityTimeId = $firstDate->validity_time_id;
$removedValidityTimeId = $removedDate->validity_time_id;
$tenant->socialMedia()->attach('facebook', [
'url' => 'https://facebook.com/old',
'orden' => 2,
@@ -136,12 +180,6 @@ class AdminAppEventControllerTest extends TestCase
Sanctum::actingAs($this->createAdminAppUser($tenant));
$payload = $this->eventPayload();
$payload['dates'] = [[
'date' => '2026-11-15',
'start_time' => '10:00',
'end_time' => '20:00',
]];
$this->putJson('/api/v1/adminapp/tenant/event', $payload)
->assertOk()
->assertJsonPath('data.id', $tenant->id)
@@ -151,17 +189,16 @@ class AdminAppEventControllerTest extends TestCase
$this->assertDatabaseHas('event_dates', [
'id' => $firstDate->id,
'validity_time_id' => $firstValidityTimeId,
'date' => '2026-11-15',
'date' => '2026-10-01',
]);
$this->assertDatabaseHas('validity_times', [
'id' => $firstValidityTimeId,
'type' => ValidityTimeType::FixedWindow->value,
'fixed_starts_at' => '2026-11-15 10:00:00',
'fixed_expires_at' => '2026-11-15 20:00:00',
'fixed_starts_at' => '2026-10-01 08:00:00',
'fixed_expires_at' => '2026-10-01 12:00:00',
]);
$this->assertDatabaseMissing('event_dates', ['id' => $removedDate->id]);
$this->assertDatabaseMissing('validity_times', ['id' => $removedValidityTimeId]);
$this->assertSame('15 de Noviembre 2026', $tenant->fresh()->event_date_text);
$this->assertDatabaseHas('event_dates', ['id' => $removedDate->id]);
$this->assertSame('1 y 2 de Octubre 2026', $tenant->fresh()->event_date_text);
$this->assertDatabaseMissing('tenant_social_media', [
'tenant_code' => $tenant->codigo,
'social_media_code' => 'facebook',
@@ -173,20 +210,17 @@ class AdminAppEventControllerTest extends TestCase
]);
}
public function test_updating_event_dates_recalculates_the_tenant_date_text(): void
public function test_dates_are_created_independently_and_recalculate_the_tenant_date_text(): void
{
$tenant = $this->createTenant('acme');
Sanctum::actingAs($this->createAdminAppUser($tenant));
$payload = $this->eventPayload();
$payload['dates'] = collect([9, 10, 11, 12])
->map(fn (int $day): array => [
foreach ([9, 10, 11, 12] as $day) {
$this->postJson('/api/v1/adminapp/tenant/event-dates', [
'date' => sprintf('2026-10-%02d', $day),
'start_time' => '09:00',
'end_time' => '18:30',
])
->all();
$this->putJson('/api/v1/adminapp/tenant/event', $payload)->assertOk();
])->assertCreated()->assertJsonPath('data.status', 'scheduled');
}
$this->assertSame(
'9, 10, 11 y 12 de Octubre 2026',
@@ -194,7 +228,134 @@ class AdminAppEventControllerTest extends TestCase
);
}
public function test_update_validates_event_dates_and_contact_urls(): void
public function test_rescheduling_reuses_an_existing_date_and_tickets_resolve_its_validity(): void
{
$tenant = $this->createActiveEvent($this->createTenant('acme'), 'Festival Acme');
$admin = $this->createAdminAppUser($tenant);
$original = $tenant->eventDates()->create([
'date' => '2027-10-09',
'time_start' => '09:00',
'time_end' => '18:30',
]);
$destination = $tenant->eventDates()->create([
'date' => '2027-10-20',
'time_start' => '11:00',
'time_end' => '20:00',
]);
$variant = $this->createVariant($tenant, $original->id);
$ticket = $this->createTicket($tenant, $admin, $variant);
Sanctum::actingAs($admin);
$this->postJson("/api/v1/adminapp/tenant/event-dates/{$original->id}/reschedule", [
'date' => '2027-10-20',
])
->assertOk()
->assertJsonPath('data.status', 'rescheduled')
->assertJsonPath('data.rescheduled_to_event_date_id', $destination->id);
$this->assertDatabaseCount('event_dates', 2);
$this->assertSame('20 de Octubre 2027', $tenant->fresh()->event_date_text);
$this->getJson('/api/tenants/bootstrap?dominio=acme.test&path=%2F')
->assertOk()
->assertJsonCount(1, 'data.event.dates')
->assertJsonPath('data.event.dates.0.id', $destination->id)
->assertJsonPath('data.event_date_text', '20 de Octubre 2027');
$this->assertSame(
'2027-10-20 11:00:00',
$ticket->resolvedValidity()->effectiveStartsAt()?->format('Y-m-d H:i:s'),
);
$this->assertDatabaseHas('validity_times', [
'id' => $original->validity_time_id,
'fixed_starts_at' => '2027-10-09 09:00:00',
]);
$this->postJson("/api/v1/adminapp/tenant/event-dates/{$destination->id}/reschedule", [
'date' => '2027-10-25',
])->assertOk()->assertJsonPath('data.status', 'rescheduled');
$this->assertDatabaseCount('event_dates', 3);
$this->assertSame('25 de Octubre 2027', $tenant->fresh()->event_date_text);
$this->getJson('/api/tenants/bootstrap?dominio=acme.test&path=%2F')
->assertOk()
->assertJsonCount(1, 'data.event.dates')
->assertJsonPath('data.event.dates.0.date', '2027-10-25')
->assertJsonPath('data.event_date_text', '25 de Octubre 2027');
$this->assertSame(
'2027-10-25 11:00:00',
$ticket->fresh()->resolvedValidity()->effectiveStartsAt()?->format('Y-m-d H:i:s'),
);
}
public function test_suspending_disables_only_tickets_without_another_usable_date(): void
{
$tenant = $this->createActiveEvent($this->createTenant('acme'), 'Festival Acme');
$admin = $this->createAdminAppUser($tenant);
$suspendedDate = $tenant->eventDates()->create([
'date' => '2027-10-09',
'time_start' => '09:00',
'time_end' => '18:30',
]);
$otherDate = $tenant->eventDates()->create([
'date' => '2027-10-10',
'time_start' => '09:00',
'time_end' => '18:30',
]);
$singleDateVariant = $this->createVariant($tenant, $suspendedDate->id);
$multipleDateVariant = $this->createVariant($tenant);
$multipleDateVariant->eventDates()->sync([$suspendedDate->id, $otherDate->id]);
$singleDateTicket = $this->createTicket($tenant, $admin, $singleDateVariant);
$multipleDateTicket = $this->createTicket($tenant, $admin, $multipleDateVariant);
Sanctum::actingAs($admin);
$this->postJson("/api/v1/adminapp/tenant/event-dates/{$suspendedDate->id}/suspend")
->assertOk()
->assertJsonPath('data.status', 'suspended')
->assertJsonPath('data.suspended_at', fn ($value) => is_string($value));
$this->assertNotNull($singleDateTicket->fresh()->disabled_at);
$this->assertNull($multipleDateTicket->fresh()->disabled_at);
$this->assertSame('10 de Octubre 2027', $tenant->fresh()->event_date_text);
$this->getJson('/api/tenants/bootstrap?dominio=acme.test&path=%2F')
->assertOk()
->assertJsonCount(1, 'data.event.dates')
->assertJsonPath('data.event.dates.0.id', $otherDate->id)
->assertJsonPath('data.event_date_text', '10 de Octubre 2027');
$this->assertSame(
'2027-10-10 09:00:00',
$multipleDateTicket->fresh()->resolvedValidity()->effectiveStartsAt()?->format('Y-m-d H:i:s'),
);
}
public function test_suspending_a_reschedule_destination_disables_tickets_from_predecessor_dates(): void
{
$tenant = $this->createTenant('acme');
$admin = $this->createAdminAppUser($tenant);
$original = $tenant->eventDates()->create([
'date' => '2027-10-09',
'time_start' => '09:00',
'time_end' => '18:30',
]);
$destination = $tenant->eventDates()->create([
'date' => '2027-10-20',
'time_start' => '09:00',
'time_end' => '18:30',
]);
$original->update(['rescheduled_to_event_date_id' => $destination->id]);
$ticket = $this->createTicket(
$tenant,
$admin,
$this->createVariant($tenant, $original->id),
);
Sanctum::actingAs($admin);
$this->postJson("/api/v1/adminapp/tenant/event-dates/{$destination->id}/suspend")
->assertOk();
$this->assertNotNull($ticket->fresh()->disabled_at);
$this->assertFalse($ticket->fresh()->resolvedValidity()->isResolvable);
}
public function test_update_and_date_creation_validate_their_own_payloads(): void
{
$tenant = $this->createTenant('acme');
Sanctum::actingAs($this->createAdminAppUser($tenant));
@@ -202,10 +363,6 @@ class AdminAppEventControllerTest extends TestCase
$this->putJson('/api/v1/adminapp/tenant/event', [
'title' => '',
'location' => '',
'dates' => [
['date' => '09/10/2026', 'start_time' => '9am', 'end_time' => '18:00'],
['date' => '09/10/2026', 'start_time' => '09:00', 'end_time' => '18:00'],
],
'contact' => [
'whatsapp_url' => 'not-a-url',
'instagram_url' => null,
@@ -216,12 +373,15 @@ class AdminAppEventControllerTest extends TestCase
->assertJsonValidationErrors([
'title',
'location',
'dates.0.date',
'dates.0.start_time',
'dates.1.date',
'contact.whatsapp_url',
]);
$this->postJson('/api/v1/adminapp/tenant/event-dates', [
'date' => '09/10/2026',
'start_time' => '9am',
'end_time' => '18:00',
])->assertUnprocessable()->assertJsonValidationErrors(['date', 'start_time']);
$this->assertNull($tenant->fresh()->event_title);
}
@@ -273,11 +433,10 @@ class AdminAppEventControllerTest extends TestCase
return [
'title' => 'Festival Acme',
'location' => 'Predio Ferial, Rosario',
'dates' => [[
'date' => '2026-10-09',
'start_time' => '09:00',
'end_time' => '18:30',
]],
'allow_ticket_refund' => true,
'allow_ticket_total_refund' => true,
'allow_ticket_partial_refund' => true,
'ticket_partial_refund_percentage' => 25.50,
'contact' => [
'whatsapp_url' => 'https://wa.me/5493415550101',
'instagram_url' => 'https://instagram.com/acme',
@@ -286,6 +445,43 @@ class AdminAppEventControllerTest extends TestCase
];
}
/** @return array{date: string, start_time: string, end_time: string} */
private function datePayload(): array
{
return [
'date' => '2026-10-09',
'start_time' => '09:00',
'end_time' => '18:30',
];
}
private function createVariant(Tenant $tenant, ?int $eventDateId = null): Variant
{
$item = CatalogItem::query()->create([
'tenant_code' => $tenant->codigo,
'slug' => 'item-'.Str::uuid(),
'nombre' => 'Entrada',
'precio' => '1000.00',
]);
return Variant::query()->create([
'catalog_item_id' => $item->id,
'inventory_id' => Inventory::query()->create()->id,
'event_date_id' => $eventDateId,
]);
}
private function createTicket(Tenant $tenant, User $user, Variant $variant): Ticket
{
return Ticket::query()->create([
'tenant_code' => $tenant->codigo,
'ticket' => (string) Str::uuid(),
'user_id' => $user->id,
'source_catalog_item_id' => $variant->catalog_item_id,
'source_variant_id' => $variant->id,
]);
}
private function createTenant(string $code): Tenant
{
$headerLogo = $this->createAttachment("{$code}-header");

View File

@@ -78,6 +78,9 @@ class AdminAppTicketFilterFormControllerTest extends TestCase
['value' => 'active', 'label' => 'Activo'],
['value' => 'used', 'label' => 'Usado'],
['value' => 'expired', 'label' => 'Vencido'],
['value' => 'disabled', 'label' => 'Inhabilitado'],
['value' => 'cancelled', 'label' => 'Cancelado'],
['value' => 'refunded', 'label' => 'Reembolsado'],
],
],
],

View File

@@ -63,6 +63,9 @@ class AdminAppTicketFormControllerTest extends TestCase
['value' => 'active', 'label' => 'Activo'],
['value' => 'used', 'label' => 'Usado'],
['value' => 'expired', 'label' => 'Vencido'],
['value' => 'disabled', 'label' => 'Inhabilitado'],
['value' => 'cancelled', 'label' => 'Cancelado'],
['value' => 'refunded', 'label' => 'Reembolsado'],
],
'categories' => [
[

View File

@@ -6,11 +6,13 @@ use App\Domains\Logging\Enums\ValueChangeActorType;
use App\Domains\Logging\Models\Concerns\LogsValueChanges;
use App\Domains\Logging\Models\ValueChange;
use App\Domains\Purchase\Models\Purchase;
use App\Domains\Ticket\Models\Ticket;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Schema;
use Illuminate\Validation\ValidationException;
use Tests\TestCase;
class LogsValueChangesTest extends TestCase
@@ -52,6 +54,16 @@ class LogsValueChangesTest extends TestCase
$table->timestamps();
});
Schema::create('tickets', function (Blueprint $table): void {
$table->id();
$table->string('tenant_code');
$table->uuid('ticket');
$table->dateTime('used_at')->nullable();
$table->dateTime('disabled_at')->nullable();
$table->dateTime('cancelled_at')->nullable();
$table->dateTime('refunded_at')->nullable();
});
$migration = require database_path('migrations/2026_08_03_000200_create_value_changes_table.php');
$migration->up();
$tenantMigration = require database_path('migrations/2026_08_04_000000_add_tenant_code_to_value_changes_table.php');
@@ -144,6 +156,39 @@ class LogsValueChangesTest extends TestCase
'user_id' => null,
]);
}
public function test_ticket_logs_its_status_changes(): void
{
$ticket = Ticket::query()->create([
'tenant_code' => 'test',
'ticket' => '794606d5-5f69-458d-9de7-03494757d626',
]);
$ticket->update(['disabled_at' => now()]);
$this->assertDatabaseHas('value_changes', [
'tenant_code' => 'test',
'trackable_type' => $ticket->getMorphClass(),
'trackable_id' => $ticket->id,
'attribute' => 'disabled_at',
'old_value' => null,
'actor_type' => ValueChangeActorType::System->value,
'user_id' => null,
]);
}
public function test_ticket_cannot_transition_between_terminal_statuses(): void
{
$ticket = Ticket::query()->create([
'tenant_code' => 'test',
'ticket' => '794606d5-5f69-458d-9de7-03494757d626',
]);
$ticket->update(['disabled_at' => now()]);
$this->expectException(ValidationException::class);
$ticket->update(['cancelled_at' => now()]);
}
}
#[Fillable(['name', 'price', 'description'])]

View File

@@ -163,6 +163,7 @@ class AdminAppSaleControllerTest extends TestCase
'cantidad' => 3,
'precio_unitario' => '10000.00',
'total' => '30000.00',
'refunded_amount' => '1250.00',
]);
$pendingCart = Cart::query()->create([
@@ -203,6 +204,7 @@ class AdminAppSaleControllerTest extends TestCase
'cantidad' => 2,
'precio_unitario' => '10000.00',
'total' => '20000.00',
'refunded_amount' => '2500.00',
]);
$supersededPurchase = Purchase::query()->create([
@@ -237,7 +239,8 @@ class AdminAppSaleControllerTest extends TestCase
->assertJsonPath('data.2.status_label', 'Confirmado')
->assertJsonPath('data.3.id', $supersededPurchase->id)
->assertJsonPath('data.3.admin_status', Purchase::ADMIN_STATUS_CANCELLED)
->assertJsonPath('data.3.status_label', 'Anulado');
->assertJsonPath('data.3.status_label', 'Anulado')
->assertJsonPath('refunded_total', '3750.00');
$this->getJson('/api/v1/adminapp/tenant/sales?status='.Purchase::STATUS_SUPERSEDED)
->assertUnprocessable();
@@ -507,12 +510,14 @@ class AdminAppSaleControllerTest extends TestCase
'id' => $firstTicket->id,
'expires_at' => null,
'status' => Ticket::STATUS_ACTIVE,
'status_label' => 'Activo',
],
[
'product' => 'Abono general',
'id' => $usedTicket->id,
'expires_at' => null,
'status' => Ticket::STATUS_USED,
'status_label' => 'Usado',
],
],
]);

View File

@@ -7,10 +7,13 @@ use App\Domains\Attachable\Models\Attachment;
use App\Domains\Auth\Models\ResetPasswordAttempt;
use App\Domains\Auth\Models\User;
use App\Domains\Authorization\Enums\RoleCode;
use App\Domains\Catalog\Models\CatalogItem;
use App\Domains\Catalog\Models\Category;
use App\Domains\Notification\Events\PasswordResetRequested;
use App\Domains\Tenant\Models\Tenant;
use App\Domains\Tenant\Models\WebsiteType;
use App\Domains\Ticket\Enums\ScanAttemptResult;
use App\Domains\Ticket\Models\ScanAttempt;
use App\Domains\Ticket\Models\Ticket;
use Database\Seeders\AuthorizationSeeder;
use Illuminate\Foundation\Testing\RefreshDatabase;
@@ -264,6 +267,159 @@ class StaffControllerTest extends TestCase
$this->getJson('/api/v1/adminapp/tenant/staff')->assertForbidden();
}
public function test_adminapp_can_search_staff_scan_attempts_by_ticket_id_category_and_date(): void
{
$scanner = User::factory()->create([
'rol_codigo' => RoleCode::Scanner->value,
'tenant_codigo' => $this->tenant->codigo,
]);
$otherScanner = User::factory()->create([
'rol_codigo' => RoleCode::Scanner->value,
'tenant_codigo' => $this->tenant->codigo,
]);
$category = $this->createCategory('Alojamiento');
$catalogItem = CatalogItem::query()->create([
'tenant_code' => $this->tenant->codigo,
'category_id' => $category->id,
'slug' => 'alojamiento-test',
'nombre' => 'Hotel',
'precio' => 100,
]);
$ticket = Ticket::query()->create([
'tenant_code' => $this->tenant->codigo,
'ticket' => (string) Str::uuid(),
'source_catalog_item_id' => $catalogItem->id,
'user_id' => $this->admin->id,
]);
$matching = $this->createScanAttempt($scanner, 'matching-qr', [
'ticket_id' => $ticket->id,
'created_at' => '2026-08-11 14:30:00',
]);
$this->createScanAttempt($scanner, 'another-qr', [
'created_at' => '2026-08-22 22:22:22',
]);
$this->createScanAttempt($otherScanner, 'matching-qr', [
'ticket_id' => $ticket->id,
'created_at' => '2026-08-11 14:30:00',
]);
Sanctum::actingAs($this->admin);
$this->getJson(
"/api/v1/adminapp/tenant/staff/{$scanner->id}/scan-attempts?q={$ticket->id}"
)->assertOk()
->assertJsonFragment([
'id' => $matching->id,
'ticket_id' => $ticket->id,
]);
$assertSingleMatchingAttempt = function (string $search) use ($scanner, $matching, $ticket): void {
$this->getJson(
"/api/v1/adminapp/tenant/staff/{$scanner->id}/scan-attempts?q=".urlencode($search).'&per_page=1'
)
->assertOk()
->assertJsonCount(1, 'data')
->assertJsonPath('data.0.id', $matching->id)
->assertJsonPath('data.0.ticket_id', $ticket->id)
->assertJsonPath('data.0.category', 'Alojamiento')
->assertJsonPath('data.0.result_label', 'Verificado')
->assertJsonPath('meta.current_page', 1)
->assertJsonPath('meta.per_page', 1)
->assertJsonPath('meta.total', 1);
};
$assertSingleMatchingAttempt('alojamiento');
$assertSingleMatchingAttempt('11/08/26');
}
public function test_adminapp_cannot_list_scan_attempts_for_non_scanner_staff(): void
{
$customer = User::factory()->create([
'rol_codigo' => RoleCode::User->value,
'tenant_codigo' => $this->tenant->codigo,
]);
Sanctum::actingAs($this->admin);
$this->getJson("/api/v1/adminapp/tenant/staff/{$customer->id}/scan-attempts")
->assertNotFound();
}
public function test_adminapp_can_search_staff_scan_attempts_by_day_and_month_across_years(): void
{
$scanner = User::factory()->create([
'rol_codigo' => RoleCode::Scanner->value,
'tenant_codigo' => $this->tenant->codigo,
]);
$firstMatch = $this->createScanAttempt($scanner, 'first-match', [
'created_at' => '2024-09-07 10:00:00',
]);
$secondMatch = $this->createScanAttempt($scanner, 'second-match', [
'created_at' => '2026-09-07 10:00:00',
]);
$this->createScanAttempt($scanner, 'different-day', [
'created_at' => '2026-09-08 10:00:00',
]);
Sanctum::actingAs($this->admin);
$this->getJson("/api/v1/adminapp/tenant/staff/{$scanner->id}/scan-attempts?q=07%2F09")
->assertOk()
->assertJsonCount(2, 'data')
->assertJsonPath('data.0.id', $secondMatch->id)
->assertJsonPath('data.1.id', $firstMatch->id)
->assertJsonPath('meta.total', 2);
}
public function test_adminapp_datetime_search_matches_text_in_any_datetime_component(): void
{
$scanner = User::factory()->create([
'rol_codigo' => RoleCode::Scanner->value,
'tenant_codigo' => $this->tenant->codigo,
]);
$matches = [
$this->createScanAttempt($scanner, 'year-match', [
'created_at' => '2007-11-12 10:00:08',
]),
$this->createScanAttempt($scanner, 'month-match', [
'created_at' => '2026-07-12 10:00:08',
]),
$this->createScanAttempt($scanner, 'day-match', [
'created_at' => '2026-11-07 10:00:08',
]),
$this->createScanAttempt($scanner, 'seconds-match', [
'created_at' => '2026-11-12 10:00:07',
]),
];
$this->createScanAttempt($scanner, 'no-match', [
'created_at' => '2026-11-12 10:00:08',
]);
Sanctum::actingAs($this->admin);
$response = $this->getJson(
"/api/v1/adminapp/tenant/staff/{$scanner->id}/scan-attempts?q=07"
)->assertOk()
->assertJsonCount(4, 'data')
->assertJsonPath('meta.total', 4);
foreach ($matches as $match) {
$response->assertJsonFragment(['id' => $match->id]);
}
}
/** @param array<string, mixed> $attributes */
private function createScanAttempt(User $scanner, string $data, array $attributes = []): ScanAttempt
{
$attempt = new ScanAttempt;
$attempt->forceFill(array_merge([
'tenant_code' => $this->tenant->codigo,
'scanner_user_id' => $scanner->id,
'data' => $data,
'result' => ScanAttemptResult::Accepted,
'resolved_at' => now(),
], $attributes));
$attempt->save();
return $attempt;
}
private function createAttachment(string $filename): Attachment
{
return Attachment::query()->create([

View File

@@ -20,6 +20,7 @@ class BootstrapAdminAppControllerTest extends TestCase
'codigo' => 'shopit',
'nombre' => 'ShopIt',
'dominio' => 'admin.shopit.test',
'site_title' => 'ShopIt Website Type',
'primary_color' => '#112233',
'secondary_color' => '#445566',
'danger_color' => '#aa0000',
@@ -38,6 +39,7 @@ class BootstrapAdminAppControllerTest extends TestCase
$this->getJson('/api/v1/adminapp/bootstrap/ADMIN.SHOPIT.TEST')
->assertOk()
->assertJsonPath('data.website_type_code', 'shopit')
->assertJsonPath('data.site_title', 'ShopIt Website Type')
->assertJsonPath('data.primary_color', '#112233')
->assertJsonPath('data.warning_color', '#ffaa00')
->assertJsonPath('data.login_header_footer_color', '#313131')

View File

@@ -21,6 +21,7 @@ class BootstrapScannerControllerTest extends TestCase
'nombre' => 'ShopIt',
'dominio' => 'admin.shopit.test',
'scanner_domain' => 'scanner.shopit.test',
'site_title' => 'ShopIt Website Type',
'primary_color' => '#112233',
'secondary_color' => '#445566',
'danger_color' => '#aa0000',
@@ -39,6 +40,7 @@ class BootstrapScannerControllerTest extends TestCase
$this->getJson('/api/v1/scanner/bootstrap/SCANNER.SHOPIT.TEST')
->assertOk()
->assertJsonPath('data.website_type_code', 'shopit')
->assertJsonPath('data.site_title', 'ShopIt Website Type')
->assertJsonPath('data.primary_color', '#112233')
->assertJsonPath('data.site_logo', $siteLogo->getTemporaryUrl(1440))
->assertJsonPath('data.footer_logo', null)

View File

@@ -0,0 +1,159 @@
<?php
namespace Tests\Feature\Tenant;
use App\Domains\Attachable\Enums\AttachmentType;
use App\Domains\Attachable\Models\Attachment;
use App\Domains\Tenant\Models\Tenant;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
use Tests\TestCase;
class TenantRefundConfigurationTest extends TestCase
{
use RefreshDatabase;
public function test_refund_configuration_has_database_defaults_and_is_exposed_by_the_api(): void
{
$tenant = $this->createTenant('refund-defaults');
$this->assertFalse($tenant->allow_ticket_refund);
$this->assertFalse($tenant->allow_ticket_total_refund);
$this->assertFalse($tenant->allow_ticket_partial_refund);
$this->assertSame('0.00', $tenant->ticket_partial_refund_percentage);
$this->getJson("/api/tenants/{$tenant->codigo}")
->assertOk()
->assertJsonPath('data.allow_ticket_refund', false)
->assertJsonPath('data.allow_ticket_total_refund', false)
->assertJsonPath('data.allow_ticket_partial_refund', false)
->assertJsonPath('data.ticket_partial_refund_percentage', '0.00');
}
public function test_refund_configuration_can_be_updated_and_validates_its_precision(): void
{
$tenant = $this->createTenant('refund-update');
$this->putJson("/api/tenants/{$tenant->codigo}", [
'allow_ticket_refund' => true,
'allow_ticket_total_refund' => true,
'allow_ticket_partial_refund' => true,
'ticket_partial_refund_percentage' => 25.50,
])
->assertOk()
->assertJsonPath('data.allow_ticket_refund', true)
->assertJsonPath('data.allow_ticket_total_refund', true)
->assertJsonPath('data.allow_ticket_partial_refund', true)
->assertJsonPath('data.ticket_partial_refund_percentage', '25.50');
$this->assertDatabaseHas('tenants', [
'id' => $tenant->id,
'allow_ticket_refund' => true,
'allow_ticket_total_refund' => true,
'allow_ticket_partial_refund' => true,
'ticket_partial_refund_percentage' => 25.50,
]);
$this->putJson("/api/tenants/{$tenant->codigo}", [
'ticket_partial_refund_percentage' => 100,
])->assertUnprocessable()
->assertJsonValidationErrors('ticket_partial_refund_percentage');
$this->putJson("/api/tenants/{$tenant->codigo}", [
'ticket_partial_refund_percentage' => 12.345,
])->assertUnprocessable()
->assertJsonValidationErrors('ticket_partial_refund_percentage');
}
public function test_tenant_allow_refund_logic(): void
{
$tenant = new Tenant([
'allow_ticket_refund' => false,
'allow_ticket_total_refund' => false,
'allow_ticket_partial_refund' => false,
'ticket_partial_refund_percentage' => 0,
]);
$this->assertFalse($tenant->allow_refund());
$this->assertFalse($tenant->allowRefund());
$this->assertFalse($tenant->allow_refund);
$this->assertFalse($tenant->allow_partial_refund());
$this->assertFalse($tenant->allowPartialRefund());
// Partial refund enabled but percentage is 0 / unset
$tenant->allow_ticket_partial_refund = true;
$tenant->ticket_partial_refund_percentage = 0;
$this->assertFalse($tenant->allow_refund());
$this->assertFalse($tenant->allow_partial_refund());
// Partial refund enabled and percentage is set
$tenant->ticket_partial_refund_percentage = 25.50;
$this->assertFalse($tenant->allow_refund());
$this->assertFalse($tenant->allow_partial_refund());
$tenant->allow_ticket_refund = true;
$this->assertTrue($tenant->allow_refund());
$this->assertTrue($tenant->allowRefund());
$this->assertTrue($tenant->allow_refund);
$this->assertTrue($tenant->allow_partial_refund());
$this->assertTrue($tenant->allowPartialRefund());
// Total refund enabled, partial refund disabled
$tenant->allow_ticket_partial_refund = false;
$tenant->allow_ticket_total_refund = true;
$tenant->ticket_partial_refund_percentage = 0;
$this->assertTrue($tenant->allow_refund());
$this->assertFalse($tenant->allow_partial_refund());
// Total refund enabled and partial refund enabled with percentage
$tenant->allow_ticket_partial_refund = true;
$tenant->ticket_partial_refund_percentage = 50.00;
$this->assertTrue($tenant->allow_refund());
$this->assertTrue($tenant->allow_partial_refund());
$tenant->allow_ticket_refund = false;
$this->assertFalse($tenant->allow_refund());
$this->assertFalse($tenant->allow_partial_refund());
$this->assertTrue($tenant->allow_ticket_total_refund);
$this->assertTrue($tenant->allow_ticket_partial_refund);
$this->assertSame('50.00', $tenant->ticket_partial_refund_percentage);
}
private function createTenant(string $code): Tenant
{
$attachmentIds = collect(['header', 'footer'])->map(function (string $name): int {
$key = (string) Str::uuid();
return Attachment::query()->create([
'key' => $key,
'path' => "tenants/{$key}.png",
'filename' => "{$name}.png",
'type' => AttachmentType::Image,
'mime_type' => 'image/png',
])->id;
});
$clientId = DB::table('clients')->insertGetId([
'code' => $code,
'name' => Str::headline($code),
]);
$tenantId = DB::table('tenants')->insertGetId([
'client_id' => $clientId,
'codigo' => $code,
'nombre' => Str::headline($code),
'dominio' => "{$code}.test",
'primary_color' => '#000000',
'secondary_color' => '#000000',
'danger_color' => '#000000',
'success_color' => '#000000',
'header_bg_color' => '#ffffff',
'footer_bg_color' => '#ffffff',
'header_logo_id' => $attachmentIds[0],
'footer_logo_id' => $attachmentIds[1],
]);
return Tenant::query()->findOrFail($tenantId);
}
}

View File

@@ -72,6 +72,11 @@ class AdminAppTicketControllerTest extends TestCase
->assertJsonPath('data.0.tenant_code', $tenant->codigo)
->assertJsonPath('data.0.values.id', $ticket->id)
->assertJsonPath('data.0.values.status', Ticket::STATUS_ACTIVE)
->assertJsonPath('data.0.status_label', 'Activo')
->assertJsonPath('data.0.allow_refund', false)
->assertJsonPath('data.0.is_active', true)
->assertJsonPath('data.0.can_cancel', true)
->assertJsonPath('data.0.can_refund', false)
->assertJsonMissingPath('data.0.values.ticket')
->assertJsonPath('data.0.values.date', '-')
->assertJsonPath('data.0.values.size', '-')
@@ -79,6 +84,283 @@ class AdminAppTicketControllerTest extends TestCase
->assertJsonPath('meta.total', 1);
}
public function test_it_exposes_allow_refund_flag_in_tickets_list(): void
{
$tenant = $this->createTenant('ticket-allow-refund');
$admin = $this->createAdminAppUser($tenant);
$this->grantTicketsMenu($tenant);
Sanctum::actingAs($admin);
$this->createTicket($tenant, $admin);
// Default: neither total nor partial refund allowed
$this->getJson('/api/v1/adminapp/tenant/tickets')
->assertOk()
->assertJsonPath('data.0.allow_refund', false)
->assertJsonPath('data.0.can_refund', false);
// Total refund allowed
$tenant->update([
'allow_ticket_refund' => true,
'allow_ticket_total_refund' => true,
]);
$this->getJson('/api/v1/adminapp/tenant/tickets')
->assertOk()
->assertJsonPath('data.0.allow_refund', true)
->assertJsonPath('data.0.can_refund', true);
// Partial refund allowed with percentage set
$tenant->update([
'allow_ticket_refund' => true,
'allow_ticket_total_refund' => false,
'allow_ticket_partial_refund' => true,
'ticket_partial_refund_percentage' => 20.00,
]);
$this->getJson('/api/v1/adminapp/tenant/tickets')
->assertOk()
->assertJsonPath('data.0.allow_refund', true)
->assertJsonPath('data.0.can_refund', true);
// Master toggle disabled while preserving the partial refund preference
$tenant->update(['allow_ticket_refund' => false]);
$this->getJson('/api/v1/adminapp/tenant/tickets')
->assertOk()
->assertJsonPath('data.0.allow_refund', false)
->assertJsonPath('data.0.can_refund', false);
$this->assertTrue($tenant->fresh()->allow_ticket_partial_refund);
$this->assertSame('20.00', $tenant->fresh()->ticket_partial_refund_percentage);
$tenant->update(['allow_ticket_refund' => true]);
// Partial refund enabled but percentage is 0
$tenant->update([
'ticket_partial_refund_percentage' => 0,
]);
$this->getJson('/api/v1/adminapp/tenant/tickets')
->assertOk()
->assertJsonPath('data.0.allow_refund', false)
->assertJsonPath('data.0.can_refund', false);
}
public function test_it_cancels_a_ticket_from_the_authenticated_tenant(): void
{
$tenant = $this->createTenant('ticket-cancellation');
$admin = $this->createAdminAppUser($tenant);
$this->grantTicketsMenu($tenant);
Sanctum::actingAs($admin);
$ticket = $this->createTicket($tenant, $admin);
$this->postJson("/api/v1/adminapp/tenant/tickets/{$ticket->id}/cancel")
->assertOk()
->assertJsonPath('data.id', $ticket->id)
->assertJsonPath('data.status', Ticket::STATUS_CANCELLED)
->assertJsonPath('data.status_label', 'Cancelado');
$this->assertNotNull($ticket->fresh()->cancelled_at);
}
public function test_it_does_not_cancel_a_ticket_with_another_terminal_status(): void
{
$tenant = $this->createTenant('ticket-cancellation');
$admin = $this->createAdminAppUser($tenant);
$this->grantTicketsMenu($tenant);
Sanctum::actingAs($admin);
$ticket = $this->createTicket($tenant, $admin, ['disabled_at' => now()]);
$this->postJson("/api/v1/adminapp/tenant/tickets/{$ticket->id}/cancel")
->assertUnprocessable()
->assertJsonValidationErrors('status');
$this->assertNull($ticket->fresh()->cancelled_at);
}
public function test_it_totally_refunds_a_ticket_when_the_tenant_allows_it(): void
{
$tenant = $this->createTenant('ticket-total-refund');
$tenant->update([
'allow_ticket_refund' => true,
'allow_ticket_total_refund' => true,
]);
$admin = $this->createAdminAppUser($tenant);
$this->grantTicketsMenu($tenant);
Sanctum::actingAs($admin);
[$ticket, $purchaseItem] = $this->createRefundableTicket($tenant, $admin, '100.00');
$this->postJson("/api/v1/adminapp/tenant/tickets/{$ticket->id}/refund", [
'refund_type' => 'total',
])
->assertOk()
->assertJsonPath('data.id', $ticket->id)
->assertJsonPath('data.status', Ticket::STATUS_REFUNDED)
->assertJsonPath('data.refunded_amount', '100.00');
$this->assertNotNull($ticket->fresh()->refunded_at);
$this->assertSame('100.00', $purchaseItem->fresh()->refunded_amount);
}
public function test_it_partially_refunds_a_ticket_using_the_tenant_percentage(): void
{
$tenant = $this->createTenant('ticket-partial-refund');
$tenant->update([
'allow_ticket_refund' => true,
'allow_ticket_partial_refund' => true,
'ticket_partial_refund_percentage' => 25.50,
]);
$admin = $this->createAdminAppUser($tenant);
$this->grantTicketsMenu($tenant);
Sanctum::actingAs($admin);
[$ticket, $purchaseItem] = $this->createRefundableTicket($tenant, $admin, '100.00');
$this->postJson("/api/v1/adminapp/tenant/tickets/{$ticket->id}/refund", [
'refund_type' => 'partial',
])
->assertOk()
->assertJsonPath('data.status', Ticket::STATUS_REFUNDED)
->assertJsonPath('data.refunded_amount', '25.50');
$this->assertSame('25.50', $purchaseItem->fresh()->refunded_amount);
}
public function test_it_does_not_refund_a_ticket_when_the_requested_refund_type_is_disabled(): void
{
$tenant = $this->createTenant('ticket-refund-disabled');
$admin = $this->createAdminAppUser($tenant);
$this->grantTicketsMenu($tenant);
Sanctum::actingAs($admin);
[$ticket, $purchaseItem] = $this->createRefundableTicket($tenant, $admin, '100.00');
$this->postJson("/api/v1/adminapp/tenant/tickets/{$ticket->id}/refund", [
'refund_type' => 'total',
])
->assertUnprocessable()
->assertJsonValidationErrors('refund_type');
$this->assertNull($ticket->fresh()->refunded_at);
$this->assertSame('0.00', $purchaseItem->fresh()->refunded_amount);
}
public function test_it_validates_the_refund_type(): void
{
$tenant = $this->createTenant('ticket-refund-validation');
$admin = $this->createAdminAppUser($tenant);
$this->grantTicketsMenu($tenant);
Sanctum::actingAs($admin);
[$ticket] = $this->createRefundableTicket($tenant, $admin, '100.00');
$this->postJson("/api/v1/adminapp/tenant/tickets/{$ticket->id}/refund", [
'refund_type' => 'invalid',
])
->assertUnprocessable()
->assertJsonValidationErrors('refund_type');
}
public function test_it_calculates_total_and_partial_refund_for_a_ticket(): void
{
$tenant = $this->createTenant('ticket-calc-both');
$tenant->update([
'allow_ticket_refund' => true,
'allow_ticket_total_refund' => true,
'allow_ticket_partial_refund' => true,
'ticket_partial_refund_percentage' => 30.00,
]);
$admin = $this->createAdminAppUser($tenant);
$this->grantTicketsMenu($tenant);
Sanctum::actingAs($admin);
[$ticket, $purchaseItem] = $this->createRefundableTicket($tenant, $admin, '100.00');
$this->getJson("/api/v1/adminapp/tenant/tickets/{$ticket->id}/refund")
->assertOk()
->assertJsonPath('data.total', '100.00')
->assertJsonPath('data.partial', '30.00');
}
public function test_it_calculates_only_total_when_partial_is_disabled(): void
{
$tenant = $this->createTenant('ticket-calc-total');
$tenant->update([
'allow_ticket_refund' => true,
'allow_ticket_total_refund' => true,
'allow_ticket_partial_refund' => false,
]);
$admin = $this->createAdminAppUser($tenant);
$this->grantTicketsMenu($tenant);
Sanctum::actingAs($admin);
[$ticket] = $this->createRefundableTicket($tenant, $admin, '150.00');
$this->getJson("/api/v1/adminapp/tenant/tickets/{$ticket->id}/refund")
->assertOk()
->assertJsonPath('data.total', '150.00')
->assertJsonPath('data.partial', null);
}
public function test_it_returns_null_when_remaining_item_balance_is_insufficient(): void
{
$tenant = $this->createTenant('ticket-calc-insufficient');
$tenant->update([
'allow_ticket_refund' => true,
'allow_ticket_total_refund' => true,
'allow_ticket_partial_refund' => true,
'ticket_partial_refund_percentage' => 50.00,
]);
$admin = $this->createAdminAppUser($tenant);
$this->grantTicketsMenu($tenant);
Sanctum::actingAs($admin);
[$ticket, $purchaseItem] = $this->createRefundableTicket($tenant, $admin, '100.00');
// Simulate 70 already refunded out of 100 on the item (remaining is 30)
$purchaseItem->update(['refunded_amount' => '70.00']);
$this->getJson("/api/v1/adminapp/tenant/tickets/{$ticket->id}/refund")
->assertOk()
// Total is 100, which exceeds remaining 30 -> total is null
->assertJsonPath('data.total', null)
// Partial is 50, which exceeds remaining 30 -> partial is null
->assertJsonPath('data.partial', null);
}
public function test_it_fails_calculating_refund_if_ticket_is_not_active(): void
{
$tenant = $this->createTenant('ticket-calc-inactive');
$tenant->update([
'allow_ticket_refund' => true,
'allow_ticket_total_refund' => true,
]);
$admin = $this->createAdminAppUser($tenant);
$this->grantTicketsMenu($tenant);
Sanctum::actingAs($admin);
[$ticket] = $this->createRefundableTicket($tenant, $admin, '100.00');
$ticket->update(['cancelled_at' => now()]);
$this->getJson("/api/v1/adminapp/tenant/tickets/{$ticket->id}/refund")
->assertUnprocessable()
->assertJsonValidationErrors('refund');
}
public function test_it_cannot_calculate_refund_for_another_tenants_ticket(): void
{
$tenantA = $this->createTenant('ticket-calc-a');
$tenantB = $this->createTenant('ticket-calc-b');
$tenantA->update([
'allow_ticket_refund' => true,
'allow_ticket_total_refund' => true,
]);
$tenantB->update([
'allow_ticket_refund' => true,
'allow_ticket_total_refund' => true,
]);
$adminA = $this->createAdminAppUser($tenantA);
$adminB = $this->createAdminAppUser($tenantB);
$this->grantTicketsMenu($tenantA);
[$ticketB] = $this->createRefundableTicket($tenantB, $adminB, '100.00');
Sanctum::actingAs($adminA);
$this->getJson("/api/v1/adminapp/tenant/tickets/{$ticketB->id}/refund")
->assertNotFound();
}
public function test_it_searches_by_id_and_does_not_search_by_uuid(): void
{
$tenant = $this->createTenant('fiesta_futbol_infantil');
@@ -254,18 +536,61 @@ class AdminAppTicketControllerTest extends TestCase
$this->createTicket($tenant, $admin)->update(['used_at' => now()]);
$this->createTicket($tenant, $admin);
$this->createTicket($tenant, $admin)->update(['cancelled_at' => now()]);
$this->createTicket($tenant, $admin)->update(['refunded_at' => now()]);
$this->createTicket($tenant, $admin)->update(['disabled_at' => now()]);
$this->createTicket($otherTenant, $otherUser)->update(['used_at' => now()]);
$catalogItem = CatalogItem::query()->create([
'tenant_code' => $tenant->codigo,
'slug' => 'refund-summary-item',
'nombre' => 'Entrada',
'precio' => '1000.00',
]);
$purchase = Purchase::query()->create([
'tenant_codigo' => $tenant->codigo,
'status' => Purchase::STATUS_PAID,
'total' => '1000.00',
]);
PurchaseItem::query()->create([
'compra_id' => $purchase->id,
'source_catalog_item_id' => $catalogItem->id,
'nombre' => 'Entrada',
'item_nombre' => 'Entrada',
'cantidad' => 1,
'precio_unitario' => '1000.00',
'total' => '1000.00',
'refunded_amount' => '250.00',
]);
$otherPurchase = Purchase::query()->create([
'tenant_codigo' => $otherTenant->codigo,
'status' => Purchase::STATUS_PAID,
'total' => '2000.00',
]);
PurchaseItem::query()->create([
'compra_id' => $otherPurchase->id,
'source_catalog_item_id' => $catalogItem->id,
'nombre' => 'Otra entrada',
'item_nombre' => 'Otra entrada',
'cantidad' => 1,
'precio_unitario' => '2000.00',
'total' => '2000.00',
'refunded_amount' => '2000.00',
]);
$this->getJson('/api/v1/adminapp/tenant/tickets?q=does-not-match')
->assertOk()
->assertJsonCount(0, 'data')
->assertJsonPath('scanned_tickets', 0)
->assertJsonPath('total_tickets', 0);
->assertJsonPath('total_tickets', 0)
->assertJsonPath('refunded_total', '250.00');
$this->getJson('/api/v1/adminapp/tenant/tickets')
->assertOk()
->assertJsonCount(5, 'data')
->assertJsonPath('scanned_tickets', 1)
->assertJsonPath('total_tickets', 2);
->assertJsonPath('total_tickets', 2)
->assertJsonPath('refunded_total', '250.00');
}
public function test_it_returns_structured_variant_properties(): void
@@ -335,6 +660,7 @@ class AdminAppTicketControllerTest extends TestCase
->assertJsonPath('data.0.order_number', $purchase->id)
->assertJsonPath('data.0.product', 'Remera')
->assertJsonPath('data.0.amount', '8000.00')
->assertJsonPath('data.0.refunded_amount', '0.00')
->assertJsonPath('data.0.status', Ticket::STATUS_USED)
->assertJsonPath('data.0.scanned_by', $admin->nombre_apellido)
->assertJsonPath('data.0.variant_properties.0.code', 'size')
@@ -498,6 +824,28 @@ class AdminAppTicketControllerTest extends TestCase
->assertJsonPath('data.0.id', $active->id);
}
public function test_it_filters_persisted_ticket_statuses(): void
{
$tenant = $this->createTenant('ticket-statuses');
$admin = $this->createAdminAppUser($tenant);
$this->grantTicketsMenu($tenant);
Sanctum::actingAs($admin);
foreach ([
Ticket::STATUS_DISABLED => 'disabled_at',
Ticket::STATUS_CANCELLED => 'cancelled_at',
Ticket::STATUS_REFUNDED => 'refunded_at',
] as $status => $timestamp) {
$ticket = $this->createTicket($tenant, $admin, [$timestamp => now()]);
$this->getJson('/api/v1/adminapp/tenant/tickets?status='.$status)
->assertOk()
->assertJsonCount(1, 'data')
->assertJsonPath('data.0.id', $ticket->id)
->assertJsonPath('data.0.status', $status);
}
}
public function test_it_downloads_filtered_ticket_reports(): void
{
$tenant = $this->createTenant('fiesta_futbol_infantil');
@@ -603,6 +951,43 @@ class AdminAppTicketControllerTest extends TestCase
]);
}
/** @return array{Ticket, PurchaseItem} */
private function createRefundableTicket(Tenant $tenant, User $admin, string $amount): array
{
$catalogItem = CatalogItem::query()->create([
'tenant_code' => $tenant->codigo,
'slug' => 'ticket-reembolsable-'.Str::uuid(),
'nombre' => 'Ticket reembolsable',
'precio' => $amount,
]);
$purchase = Purchase::query()->create([
'tenant_codigo' => $tenant->codigo,
'user_id' => $admin->id,
'status' => Purchase::STATUS_PAID,
'nombre_apellido' => $admin->nombre_apellido,
'total' => $amount,
]);
$purchaseItem = PurchaseItem::query()->create([
'compra_id' => $purchase->id,
'source_catalog_item_id' => $catalogItem->id,
'nombre' => 'Ticket reembolsable',
'descripcion' => '',
'slug' => 'ticket-reembolsable',
'item_nombre' => 'Ticket reembolsable',
'cantidad' => 1,
'precio_unitario' => $amount,
'total' => $amount,
]);
return [
$this->createTicket($tenant, $admin, [
'source_purchase_item_id' => $purchaseItem->id,
'source_catalog_item_id' => $catalogItem->id,
]),
$purchaseItem,
];
}
private function grantTicketsMenu(Tenant $tenant): void
{
$menu = Menu::query()->create([

View File

@@ -68,7 +68,7 @@ class PrepareLoadTestTicketsCommandTest extends TestCase
$first = $rows[0];
$this->withToken($first['scanner_token'])
->postJson("/api/v1/scanner/tickets/{$first['ticket_uuid']}/scan")
->postJson('/api/v1/scanner/tickets/scan', ['data' => $first['ticket_uuid']])
->assertOk()
->assertJsonPath('data.ticket', $first['ticket_uuid']);

View File

@@ -10,6 +10,8 @@ use App\Domains\Catalog\Models\CatalogItem;
use App\Domains\Catalog\Models\Category;
use App\Domains\Tenant\Models\Tenant;
use App\Domains\Tenant\Models\WebsiteType;
use App\Domains\Ticket\Enums\ScanAttemptResult;
use App\Domains\Ticket\Models\ScanAttempt;
use App\Domains\Ticket\Models\Ticket;
use Database\Seeders\AuthorizationSeeder;
use Illuminate\Foundation\Testing\RefreshDatabase;
@@ -50,108 +52,163 @@ class ScannerTicketControllerTest extends TestCase
public function test_scanner_routes_require_authentication_and_scan_permission(): void
{
$this->getJson('/api/v1/scanner/tickets')->assertUnauthorized();
$this->getJson('/api/v1/scanner/attempts')->assertUnauthorized();
Sanctum::actingAs(User::factory()->create([
'rol_codigo' => RoleCode::User->value,
'tenant_codigo' => $this->tenant->codigo,
]));
$this->getJson('/api/v1/scanner/tickets')->assertForbidden();
$this->getJson('/api/v1/scanner/attempts')->assertForbidden();
}
public function test_scanner_can_list_only_its_scanned_tickets_using_adminapp_format(): void
public function test_scanner_can_list_only_its_scan_attempts(): void
{
$older = $this->createTicket('11111111-1111-4111-8111-111111111111', [
'used_at' => now()->subMinutes(2),
'scanner_user_id' => $this->scanner->id,
$olderTicket = $this->createTicket('11111111-1111-4111-8111-111111111111');
$newerTicket = $this->createTicket('22222222-2222-4222-8222-222222222222');
$older = $this->createScanAttempt($olderTicket->ticket, [
'ticket_id' => $olderTicket->id,
'created_at' => now()->subMinutes(2),
]);
$newer = $this->createTicket('22222222-2222-4222-8222-222222222222', [
'used_at' => now()->subMinute(),
'scanner_user_id' => $this->scanner->id,
$newer = $this->createScanAttempt($newerTicket->ticket, [
'ticket_id' => $newerTicket->id,
'created_at' => now()->subMinute(),
]);
$otherScanner = User::factory()->create([
'rol_codigo' => RoleCode::Scanner->value,
'tenant_codigo' => $this->tenant->codigo,
]);
$this->createTicket('33333333-3333-4333-8333-333333333333', [
'used_at' => now(),
'scanner_user_id' => $otherScanner->id,
]);
$this->createScanAttempt('not-this-scanner', [], $otherScanner);
Sanctum::actingAs($this->scanner);
$this->getJson('/api/v1/scanner/tickets')
$this->getJson('/api/v1/scanner/attempts')
->assertOk()
->assertJsonCount(2, 'data')
->assertJsonPath('data.0.id', $newer->id)
->assertJsonPath('data.0.ticket', $newer->ticket)
->assertJsonPath('data.0.status', Ticket::STATUS_USED)
->assertJsonPath('data.0.data', $newer->data)
->assertJsonPath('data.0.ticket_id', $newerTicket->id)
->assertJsonPath('data.0.ticket', $newerTicket->ticket)
->assertJsonPath('data.0.resolved_at', $newer->resolved_at->toJSON())
->assertJsonPath('data.0.result', ScanAttemptResult::Accepted->value)
->assertJsonPath('data.0.result_label', 'Verificado')
->assertJsonPath('data.0.result_detail_label', 'Verificado')
->assertJsonPath('data.0.can_view_ticket', true)
->assertJsonPath('data.1.id', $older->id)
->assertJsonPath('meta.current_page', 1)
->assertJsonPath('meta.total', 2);
}
public function test_scanner_ticket_history_supports_id_search_and_pagination(): void
public function test_scanner_attempt_history_supports_data_search_and_pagination(): void
{
$matching = $this->createTicket('aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa', [
'used_at' => now(),
'scanner_user_id' => $this->scanner->id,
]);
$this->createTicket('bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb', [
'used_at' => now()->subMinute(),
'scanner_user_id' => $this->scanner->id,
]);
$matching = $this->createScanAttempt('aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa');
$this->createScanAttempt('bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb');
Sanctum::actingAs($this->scanner);
$this->getJson('/api/v1/scanner/tickets?q=aaaaaaaa&per_page=1')
$this->getJson('/api/v1/scanner/attempts?q=aaaaaaaa&per_page=1')
->assertOk()
->assertJsonCount(1, 'data')
->assertJsonPath('data.0.ticket', $matching->ticket)
->assertJsonPath('data.0.data', $matching->data)
->assertJsonPath('meta.current_page', 1)
->assertJsonPath('meta.per_page', 1)
->assertJsonPath('meta.total', 1);
}
public function test_scanner_ticket_history_can_be_searched_by_database_id(): void
public function test_scanner_attempt_history_can_be_searched_by_database_id(): void
{
$matching = $this->createTicket('cccccccc-cccc-4ccc-8ccc-cccccccccccc', [
'used_at' => now(),
'scanner_user_id' => $this->scanner->id,
]);
$this->createTicket('dddddddd-dddd-4ddd-8ddd-dddddddddddd', [
'used_at' => now()->subMinute(),
'scanner_user_id' => $this->scanner->id,
]);
$matching = $this->createScanAttempt('cccccccc-cccc-4ccc-8ccc-cccccccccccc');
$this->createScanAttempt('dddddddd-dddd-4ddd-8ddd-dddddddddddd');
Sanctum::actingAs($this->scanner);
$this->getJson("/api/v1/scanner/tickets?q={$matching->id}")
$this->getJson("/api/v1/scanner/attempts?q={$matching->id}")
->assertOk()
->assertJsonCount(1, 'data')
->assertJsonPath('data.0.id', $matching->id);
}
public function test_scanner_ticket_history_can_be_searched_by_used_date(): void
public function test_scanner_attempt_history_can_be_searched_by_attempt_date(): void
{
$matching = $this->createTicket('eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee', [
'used_at' => '2026-08-11 14:30:00',
'scanner_user_id' => $this->scanner->id,
$matching = $this->createScanAttempt('eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee', [
'created_at' => '2026-08-11 14:30:00',
]);
$this->createTicket('ffffffff-ffff-4fff-8fff-ffffffffffff', [
'used_at' => '2026-08-10 14:30:00',
'scanner_user_id' => $this->scanner->id,
$this->createScanAttempt('ffffffff-ffff-4fff-8fff-ffffffffffff', [
'created_at' => '2026-08-10 14:30:00',
]);
Sanctum::actingAs($this->scanner);
$this->getJson('/api/v1/scanner/tickets?q=11%2F08%2F26')
$this->getJson('/api/v1/scanner/attempts?q=11%2F08%2F26')
->assertOk()
->assertJsonCount(1, 'data')
->assertJsonPath('data.0.id', $matching->id);
}
public function test_scanner_can_read_its_scan_attempt_detail(): void
{
$ticket = $this->createTicket('abababab-abab-4bab-8bab-abababababab');
$scanAttempt = $this->createScanAttempt($ticket->ticket, [
'ticket_id' => $ticket->id,
]);
Sanctum::actingAs($this->scanner);
$this->getJson("/api/v1/scanner/attempts/{$scanAttempt->id}")
->assertOk()
->assertJsonPath('data.scan_attempt.id', $scanAttempt->id)
->assertJsonPath('data.scan_attempt.ticket_id', $ticket->id)
->assertJsonPath('data.scan_attempt.result', ScanAttemptResult::Accepted->value)
->assertJsonPath('data.scan_attempt.result_label', 'Verificado')
->assertJsonPath('data.scan_attempt.result_detail_label', 'Verificado')
->assertJsonPath('data.ticket.id', $ticket->id)
->assertJsonPath('data.ticket.ticket', $ticket->ticket)
->assertJsonPath('data.ticket.client', $this->ticketOwner->nombre_apellido)
->assertJsonPath('data.client.id', $this->ticketOwner->id)
->assertJsonPath('data.client.nombre_apellido', $this->ticketOwner->nombre_apellido);
}
public function test_scanner_cannot_read_another_scanners_attempt_detail(): void
{
$otherScanner = User::factory()->create([
'rol_codigo' => RoleCode::Scanner->value,
'tenant_codigo' => $this->tenant->codigo,
]);
$scanAttempt = $this->createScanAttempt('not-this-scanner', [], $otherScanner);
Sanctum::actingAs($this->scanner);
$this->getJson("/api/v1/scanner/attempts/{$scanAttempt->id}")
->assertNotFound();
}
public function test_scan_attempt_detail_returns_null_ticket_and_client_when_unassociated(): void
{
$scanAttempt = $this->createScanAttempt('not-a-ticket', [
'result' => ScanAttemptResult::TicketNotFound,
]);
Sanctum::actingAs($this->scanner);
$this->getJson("/api/v1/scanner/attempts/{$scanAttempt->id}")
->assertOk()
->assertJsonPath('data.scan_attempt.id', $scanAttempt->id)
->assertJsonPath('data.scan_attempt.result_label', 'Error')
->assertJsonPath('data.scan_attempt.result_detail_label', 'Error')
->assertJsonPath('data.ticket', null)
->assertJsonPath('data.client', null);
}
public function test_scan_attempt_detail_returns_specific_invalid_qr_label(): void
{
$scanAttempt = $this->createScanAttempt('not-a-valid-qr', [
'result' => ScanAttemptResult::InvalidQr,
]);
Sanctum::actingAs($this->scanner);
$this->getJson("/api/v1/scanner/attempts/{$scanAttempt->id}")
->assertOk()
->assertJsonPath('data.scan_attempt.result_label', 'Error')
->assertJsonPath('data.scan_attempt.result_detail_label', 'QR no pertenece al evento');
}
public function test_scanner_can_read_an_authorized_ticket_detail_by_uuid(): void
{
$ticket = $this->createTicket('44444444-4444-4444-8444-444444444444');
@@ -203,25 +260,80 @@ class ScannerTicketControllerTest extends TestCase
$ticket = $this->createTicket('77777777-7777-4777-8777-777777777777');
Sanctum::actingAs($this->scanner);
$this->postJson("/api/v1/scanner/tickets/{$ticket->ticket}/scan")
$this->postJson('/api/v1/scanner/tickets/scan', ['data' => $ticket->ticket])
->assertOk()
->assertJsonPath('data.ticket', $ticket->ticket)
->assertJsonPath('data.scanner_user_id', $this->scanner->id)
->assertJsonPath('data.is_valid', false)
->assertJsonPath('data.is_used', true);
->assertJsonPath('data.scan_attempt.data', $ticket->ticket)
->assertJsonPath('data.scan_attempt.ticket_id', $ticket->id)
->assertJsonPath('data.scan_attempt.ticket', $ticket->ticket)
->assertJsonPath('data.scan_attempt.result', ScanAttemptResult::Accepted->value)
->assertJsonPath('data.scan_attempt.result_label', 'Verificado')
->assertJsonPath('data.scan_attempt.result_detail_label', 'Verificado')
->assertJsonPath('data.ticket.ticket', $ticket->ticket)
->assertJsonPath('data.ticket.scanner_user_id', $this->scanner->id)
->assertJsonPath('data.ticket.is_valid', false)
->assertJsonPath('data.ticket.is_used', true)
->assertJsonPath('data.ticket.status', Ticket::STATUS_USED)
->assertJsonPath('data.ticket.status_label', 'Usado')
->assertJsonMissingPath('data.ticket.disabled_at')
->assertJsonMissingPath('data.ticket.cancelled_at')
->assertJsonMissingPath('data.ticket.refunded_at')
->assertJsonPath('data.ticket.client', $this->ticketOwner->nombre_apellido)
->assertJsonPath('data.client.id', $this->ticketOwner->id)
->assertJsonPath('data.client.nombre_apellido', $this->ticketOwner->nombre_apellido);
$this->assertDatabaseHas('tickets', [
'id' => $ticket->id,
'scanner_user_id' => $this->scanner->id,
]);
$this->assertDatabaseHas('value_changes', [
'tenant_code' => $this->tenant->codigo,
'trackable_type' => $ticket->getMorphClass(),
'trackable_id' => $ticket->id,
'attribute' => 'used_at',
'old_value' => null,
'user_id' => $this->scanner->id,
]);
$this->assertNotNull($ticket->fresh()->used_at);
$scanAttempt = ScanAttempt::query()->sole();
$this->assertSame($ticket->ticket, $scanAttempt->data);
$this->assertSame(ScanAttemptResult::Accepted, $scanAttempt->result);
$this->assertTrue($scanAttempt->scanner->is($this->scanner));
$this->assertTrue($scanAttempt->ticket->is($ticket));
$this->assertTrue($scanAttempt->tenant->is($this->tenant));
$this->assertNotNull($scanAttempt->resolved_at);
}
public function test_scan_returns_an_attempt_for_invalid_qr_data(): void
{
Sanctum::actingAs($this->scanner);
$this->postJson('/api/v1/scanner/tickets/scan')
->assertOk()
->assertJsonPath('data.scan_attempt.id', fn (mixed $id): bool => is_int($id))
->assertJsonPath('data.scan_attempt.result', ScanAttemptResult::InvalidQr->value);
$this->postJson('/api/v1/scanner/tickets/scan', ['data' => 'not-a-uuid'])
->assertOk()
->assertJsonPath('data.scan_attempt.id', fn (mixed $id): bool => is_int($id))
->assertJsonPath('data.scan_attempt.result', ScanAttemptResult::InvalidQr->value);
$scanAttempts = ScanAttempt::query()->orderBy('id')->get();
$this->assertCount(2, $scanAttempts);
$this->assertNull($scanAttempts[0]->data);
$this->assertSame('not-a-uuid', $scanAttempts[1]->data);
$this->assertTrue($scanAttempts->every(
fn (ScanAttempt $scanAttempt): bool => $scanAttempt->result === ScanAttemptResult::InvalidQr
&& $scanAttempt->scanner_user_id === $this->scanner->id
&& $scanAttempt->resolved_at !== null
));
}
public function test_ticket_cannot_be_scanned_twice(): void
{
$ticket = $this->createTicket('88888888-8888-4888-8888-888888888888');
Sanctum::actingAs($this->scanner);
$this->postJson("/api/v1/scanner/tickets/{$ticket->ticket}/scan")->assertOk();
$this->postJson('/api/v1/scanner/tickets/scan', ['data' => $ticket->ticket])->assertOk();
$otherScanner = User::factory()->create([
'rol_codigo' => RoleCode::Scanner->value,
@@ -230,10 +342,16 @@ class ScannerTicketControllerTest extends TestCase
$otherScanner->scanCategories()->attach($this->category);
Sanctum::actingAs($otherScanner);
$this->postJson("/api/v1/scanner/tickets/{$ticket->ticket}/scan")
->assertUnprocessable()
->assertJsonValidationErrors('ticket');
$this->postJson('/api/v1/scanner/tickets/scan', ['data' => $ticket->ticket])
->assertOk()
->assertJsonPath('data.scan_attempt.id', fn (mixed $id): bool => is_int($id))
->assertJsonPath('data.scan_attempt.result', ScanAttemptResult::AlreadyScanned->value);
$this->assertSame($this->scanner->id, $ticket->fresh()->scanner_user_id);
$this->assertDatabaseHas('scan_attempts', [
'scanner_user_id' => $otherScanner->id,
'ticket_id' => $ticket->id,
'result' => ScanAttemptResult::AlreadyScanned->value,
]);
}
public function test_scanner_cannot_scan_a_ticket_from_an_unassigned_category(): void
@@ -249,10 +367,16 @@ class ScannerTicketControllerTest extends TestCase
);
Sanctum::actingAs($this->scanner);
$this->postJson("/api/v1/scanner/tickets/{$ticket->ticket}/scan")
->assertUnprocessable()
->assertJsonValidationErrors('ticket');
$this->postJson('/api/v1/scanner/tickets/scan', ['data' => $ticket->ticket])
->assertOk()
->assertJsonPath('data.scan_attempt.id', fn (mixed $id): bool => is_int($id))
->assertJsonPath('data.scan_attempt.result', ScanAttemptResult::CategoryForbidden->value);
$this->assertNull($ticket->fresh()->used_at);
$this->assertDatabaseHas('scan_attempts', [
'scanner_user_id' => $this->scanner->id,
'ticket_id' => $ticket->id,
'result' => ScanAttemptResult::CategoryForbidden->value,
]);
}
public function test_scanner_can_read_and_scan_any_category_when_tenant_disables_validation(): void
@@ -274,9 +398,9 @@ class ScannerTicketControllerTest extends TestCase
->assertOk()
->assertJsonPath('data.id', $ticket->id);
$this->postJson("/api/v1/scanner/tickets/{$ticket->ticket}/scan")
$this->postJson('/api/v1/scanner/tickets/scan', ['data' => $ticket->ticket])
->assertOk()
->assertJsonPath('data.scanner_user_id', $this->scanner->id);
->assertJsonPath('data.ticket.scanner_user_id', $this->scanner->id);
}
public function test_disabled_category_validation_does_not_allow_scanning_another_tenant(): void
@@ -297,8 +421,17 @@ class ScannerTicketControllerTest extends TestCase
$this->getJson("/api/v1/scanner/tickets/{$foreignTicket->ticket}")
->assertNotFound();
$this->postJson("/api/v1/scanner/tickets/{$foreignTicket->ticket}/scan")
->assertNotFound();
$this->postJson('/api/v1/scanner/tickets/scan', ['data' => $foreignTicket->ticket])
->assertOk()
->assertJsonPath('data.scan_attempt.id', fn (mixed $id): bool => is_int($id))
->assertJsonPath('data.scan_attempt.result', ScanAttemptResult::TicketNotFound->value);
$this->assertDatabaseHas('scan_attempts', [
'tenant_code' => $this->tenant->codigo,
'scanner_user_id' => $this->scanner->id,
'ticket_id' => null,
'data' => $foreignTicket->ticket,
'result' => ScanAttemptResult::TicketNotFound->value,
]);
}
public function test_adminapp_cannot_access_scanner_routes_even_with_scan_permission(): void
@@ -311,10 +444,30 @@ class ScannerTicketControllerTest extends TestCase
$ticket = $this->createTicket((string) Str::uuid());
Sanctum::actingAs($admin);
$this->getJson('/api/v1/scanner/tickets')->assertForbidden();
$this->getJson('/api/v1/scanner/attempts')->assertForbidden();
$this->getJson("/api/v1/scanner/tickets/{$ticket->ticket}")->assertForbidden();
$this->postJson("/api/v1/scanner/tickets/{$ticket->ticket}/scan")->assertForbidden();
$this->postJson('/api/v1/scanner/tickets/scan', ['data' => $ticket->ticket])->assertForbidden();
$this->assertNull($ticket->fresh()->used_at);
$this->assertDatabaseCount('scan_attempts', 0);
}
/** @param array<string, mixed> $attributes */
private function createScanAttempt(
?string $data,
array $attributes = [],
?User $scanner = null,
): ScanAttempt {
$scanAttempt = new ScanAttempt;
$scanAttempt->forceFill(array_merge([
'tenant_code' => $this->tenant->codigo,
'scanner_user_id' => ($scanner ?? $this->scanner)->id,
'data' => $data,
'result' => ScanAttemptResult::Accepted,
'resolved_at' => now(),
], $attributes));
$scanAttempt->save();
return $scanAttempt;
}
/** @param array<string, mixed> $attributes */

View File

@@ -471,7 +471,9 @@ class TicketGeneratorServiceTest extends TestCase
$this->assertCount(2, $ticket->resolvedValidityGroups());
$this->assertTrue($ticket->resolvedValidityGroups()->every(
fn ($group): bool => $group->validityTimes->count() === 2
&& $group->validityTimes->contains($lunch)
&& $group->validityTimes->contains(
fn (ValidityTime $validityTime): bool => $validityTime->is($lunch)
)
));
$this->assertEqualsCanonicalizing(
$dates->pluck('validity_time_id')->all(),

View File

@@ -14,6 +14,7 @@ class AdminAppBootstrapResourceTest extends TestCase
'codigo' => 'shopit',
'nombre' => 'ShopIt',
'dominio' => 'admin.shopit.test',
'site_title' => 'ShopIt Website Type',
]);
$websiteType->setRelation('siteLogo', null);
$websiteType->setRelation('footerLogo', null);
@@ -23,6 +24,7 @@ class AdminAppBootstrapResourceTest extends TestCase
])->resolve(request());
$this->assertSame('shopit', $data['website_type_code']);
$this->assertSame('ShopIt Website Type', $data['site_title']);
$this->assertNull($data['favicon']);
$this->assertArrayNotHasKey('forms', $data);
}

View File

@@ -3,9 +3,11 @@
namespace Tests\Unit\Event;
use App\Domains\Catalog\Models\Variant;
use App\Domains\Event\Enums\EventDateStatus;
use App\Domains\Event\Models\EventDate;
use App\Domains\Tenant\Models\Tenant;
use App\Domains\Ticket\Models\ValidityTime;
use Illuminate\Support\Carbon;
use Tests\TestCase;
class EventModelsTest extends TestCase
@@ -30,6 +32,37 @@ class EventModelsTest extends TestCase
$this->assertInstanceOf(ValidityTime::class, $eventDate->validityTime()->getRelated());
$this->assertInstanceOf(EventDate::class, (new ValidityTime)->eventDate()->getRelated());
$this->assertInstanceOf(Variant::class, $eventDate->variants()->getRelated());
$this->assertInstanceOf(EventDate::class, $eventDate->rescheduledTo()->getRelated());
$this->assertInstanceOf(EventDate::class, $eventDate->rescheduledFrom()->getRelated());
}
public function test_event_date_status_is_computed_in_business_priority_order(): void
{
Carbon::setTestNow('2026-10-09 10:00:00');
try {
$eventDate = new EventDate([
'date' => '2026-10-09',
'time_start' => '09:00:00',
'time_end' => '18:30:00',
]);
$this->assertSame(EventDateStatus::InProgress, $eventDate->status);
$eventDate->date = '2026-10-10';
$this->assertSame(EventDateStatus::Scheduled, $eventDate->status);
$eventDate->date = '2026-10-08';
$this->assertSame(EventDateStatus::Completed, $eventDate->status);
$eventDate->suspended_at = now();
$this->assertSame(EventDateStatus::Suspended, $eventDate->status);
$eventDate->rescheduled_to_event_date_id = 123;
$this->assertSame(EventDateStatus::Rescheduled, $eventDate->status);
} finally {
Carbon::setTestNow();
}
}
public function test_tenant_has_many_event_dates(): void

View File

@@ -13,6 +13,7 @@ use App\Domains\Ticket\Services\ResolvedTicketValidity;
use App\Domains\Ticket\Services\ResolvedValidityGroup;
use App\Domains\Ticket\Services\TicketValidityResolver;
use Illuminate\Support\Carbon;
use Illuminate\Validation\ValidationException;
use Tests\TestCase;
class TicketTest extends TestCase
@@ -31,6 +32,9 @@ class TicketTest extends TestCase
'source_catalog_item_id' => '20',
'source_variant_id' => '30',
'used_at' => null,
'disabled_at' => '2026-09-10 10:00:00',
'cancelled_at' => null,
'refunded_at' => null,
'scanner_user_id' => '15',
'user_id' => '10',
]);
@@ -40,6 +44,9 @@ class TicketTest extends TestCase
$this->assertSame(20, $ticket->source_catalog_item_id);
$this->assertSame(30, $ticket->source_variant_id);
$this->assertNull($ticket->used_at);
$this->assertSame('2026-09-10 10:00:00', $ticket->disabled_at->format('Y-m-d H:i:s'));
$this->assertNull($ticket->cancelled_at);
$this->assertNull($ticket->refunded_at);
$this->assertSame(15, $ticket->scanner_user_id);
$this->assertSame(10, $ticket->user_id);
$this->assertInstanceOf(Tenant::class, $ticket->tenant()->getRelated());
@@ -57,6 +64,25 @@ class TicketTest extends TestCase
$this->assertSame(Ticket::STATUS_ACTIVE, $ticket->status);
}
public function test_it_exposes_admin_action_capabilities(): void
{
$tenant = new Tenant([
'allow_ticket_refund' => true,
'allow_ticket_total_refund' => true,
]);
$active = (new Ticket)->setRelation('tenant', $tenant);
$this->assertTrue($active->is_active());
$this->assertTrue($active->can_cancel());
$this->assertTrue($active->can_refund());
$active->used_at = now();
$this->assertFalse($active->is_active());
$this->assertFalse($active->can_cancel());
$this->assertFalse($active->can_refund());
}
public function test_fixed_window_controls_ticket_validity(): void
{
Carbon::setTestNow('2026-07-21 10:00:00');
@@ -154,6 +180,78 @@ class TicketTest extends TestCase
$this->assertSame(Ticket::STATUS_USED, $ticket->status);
}
public function test_persisted_terminal_statuses_make_the_ticket_invalid(): void
{
foreach ([
'disabled_at' => Ticket::STATUS_DISABLED,
'cancelled_at' => Ticket::STATUS_CANCELLED,
'refunded_at' => Ticket::STATUS_REFUNDED,
] as $timestamp => $status) {
$ticket = new Ticket([$timestamp => now()]);
$this->assertSame($status, $ticket->status);
$this->assertFalse($ticket->is_valid);
$this->assertFalse($ticket->is_expired);
}
}
public function test_it_exposes_every_supported_status(): void
{
$this->assertSame([
Ticket::STATUS_ACTIVE,
Ticket::STATUS_USED,
Ticket::STATUS_EXPIRED,
Ticket::STATUS_DISABLED,
Ticket::STATUS_CANCELLED,
Ticket::STATUS_REFUNDED,
], Ticket::statuses());
$this->assertSame('Inhabilitado', Ticket::statusLabel(Ticket::STATUS_DISABLED));
$this->assertSame('Cancelado', Ticket::statusLabel(Ticket::STATUS_CANCELLED));
$this->assertSame('Reembolsado', Ticket::statusLabel(Ticket::STATUS_REFUNDED));
}
public function test_refunded_has_priority_when_multiple_state_timestamps_exist(): void
{
$ticket = new Ticket([
'disabled_at' => now()->subHours(2),
'cancelled_at' => now()->subHour(),
'refunded_at' => now(),
]);
$this->assertSame(Ticket::STATUS_REFUNDED, $ticket->status);
}
public function test_it_marks_tickets_with_terminal_statuses(): void
{
Carbon::setTestNow('2026-09-10 12:00:00');
$disabled = new Ticket;
$disabled->markAsDisabled();
$cancelled = new Ticket;
$cancelled->markAsCancelled();
$refunded = new Ticket;
$refunded->markAsRefunded();
$this->assertSame(Ticket::STATUS_DISABLED, $disabled->status);
$this->assertSame('2026-09-10 12:00:00', $disabled->disabled_at->format('Y-m-d H:i:s'));
$this->assertSame(Ticket::STATUS_CANCELLED, $cancelled->status);
$this->assertSame('2026-09-10 12:00:00', $cancelled->cancelled_at->format('Y-m-d H:i:s'));
$this->assertSame(Ticket::STATUS_REFUNDED, $refunded->status);
$this->assertSame('2026-09-10 12:00:00', $refunded->refunded_at->format('Y-m-d H:i:s'));
}
public function test_it_does_not_allow_a_transition_between_terminal_statuses(): void
{
$ticket = new Ticket;
$ticket->markAsDisabled();
$this->expectException(ValidationException::class);
$ticket->markAsRefunded();
}
public function test_all_validity_times_in_the_same_group_must_be_active(): void
{
Carbon::setTestNow('2026-08-20 13:00:00');