Compare commits

...

19 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
53 changed files with 2293 additions and 138 deletions

View File

@@ -2,7 +2,11 @@
namespace App\Domains\Event\Controllers\AdminApp; 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\Requests\UpdateEventRequest;
use App\Domains\Event\Resources\EventDateResource;
use App\Domains\Event\Resources\EventResource; use App\Domains\Event\Resources\EventResource;
use App\Domains\Event\Services\EventService; use App\Domains\Event\Services\EventService;
use App\Http\Controllers\Controller; 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; namespace App\Domains\Event\Models;
use App\Domains\Catalog\Models\Variant; use App\Domains\Catalog\Models\Variant;
use App\Domains\Event\Enums\EventDateStatus;
use App\Domains\Event\Services\EventDateTextFormatter; use App\Domains\Event\Services\EventDateTextFormatter;
use App\Domains\Tenant\Models\Tenant; use App\Domains\Tenant\Models\Tenant;
use App\Domains\Ticket\Enums\ValidityTimeType; use App\Domains\Ticket\Enums\ValidityTimeType;
@@ -21,6 +22,8 @@ use Illuminate\Support\Carbon;
'date', 'date',
'time_start', 'time_start',
'time_end', 'time_end',
'rescheduled_to_event_date_id',
'suspended_at',
])] ])]
class EventDate extends Model class EventDate extends Model
{ {
@@ -28,6 +31,8 @@ class EventDate extends Model
public $timestamps = false; public $timestamps = false;
protected $appends = ['status'];
protected static function booted(): void protected static function booted(): void
{ {
static::creating(fn (self $eventDate) => $eventDate->syncValidityTime()); static::creating(fn (self $eventDate) => $eventDate->syncValidityTime());
@@ -52,6 +57,8 @@ class EventDate extends Model
return [ return [
'date' => 'date:Y-m-d', 'date' => 'date:Y-m-d',
'validity_time_id' => 'integer', '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 $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> */ /** @return HasMany<Variant, $this> */
public function variants(): HasMany public function variants(): HasMany
{ {
@@ -94,6 +113,27 @@ class EventDate extends Model
return Carbon::parse($this->date->format('Y-m-d').' '.$this->time_end); 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 private function syncTenantDateText(): void
{ {
$tenant = $this->tenant()->first(); $tenant = $this->tenant()->first();
@@ -104,7 +144,10 @@ class EventDate extends Model
$tenant->update([ $tenant->update([
'event_date_text' => app(EventDateTextFormatter::class)->format( '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 [ return [
'title' => ['required', 'string', 'max:255'], 'title' => ['required', 'string', 'max:255'],
'location' => ['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' => ['sometimes', 'array'],
'social_media.*' => ['required', 'array:code,url,orden'], 'social_media.*' => ['required', 'array:code,url,orden'],
'social_media.*.code' => [ 'social_media.*.code' => [
@@ -38,6 +33,16 @@ class UpdateEventRequest extends FormRequest
'contact.whatsapp_url' => ['nullable', 'url', 'max:2048'], 'contact.whatsapp_url' => ['nullable', 'url', 'max:2048'],
'contact.instagram_url' => ['nullable', 'url', 'max:2048'], 'contact.instagram_url' => ['nullable', 'url', 'max:2048'],
'contact.facebook_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.' '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; namespace App\Domains\Event\Resources;
use App\Domains\Tenant\Models\Tenant; use App\Domains\Tenant\Models\Tenant;
use App\Domains\Ticket\Resources\ValidityTimeResource;
use Illuminate\Http\Request; use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource; use Illuminate\Http\Resources\Json\JsonResource;
@@ -19,14 +18,11 @@ class EventResource extends JsonResource
'id' => $this->id, 'id' => $this->id,
'title' => $this->event_title, 'title' => $this->event_title,
'location' => $this->event_location, 'location' => $this->event_location,
'dates' => $this->eventDates->map(fn ($eventDate): array => [ 'allow_ticket_refund' => $this->allow_ticket_refund,
'id' => $eventDate->id, 'allow_ticket_total_refund' => $this->allow_ticket_total_refund,
'validity_time_id' => $eventDate->validity_time_id, 'allow_ticket_partial_refund' => $this->allow_ticket_partial_refund,
'validity_time' => ValidityTimeResource::make($eventDate->validityTime), 'ticket_partial_refund_percentage' => $this->ticket_partial_refund_percentage,
'date' => $eventDate->date->format('Y-m-d'), 'dates' => EventDateResource::collection($this->eventDates),
'start_time' => substr($eventDate->time_start, 0, 5),
'end_time' => substr($eventDate->time_end, 0, 5),
])->values(),
'social_media' => $this->socialMedia->map(fn ($item): array => [ 'social_media' => $this->socialMedia->map(fn ($item): array => [
'code' => $item->code, 'code' => $item->code,
'url' => $item->pivot->url, '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; 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\Tenant\Models\Tenant;
use App\Domains\Ticket\Models\Ticket;
use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\DB;
use Illuminate\Validation\ValidationException; use Illuminate\Validation\ValidationException;
@@ -14,6 +17,10 @@ class EventService
'facebook_url' => 'facebook', 'facebook_url' => 'facebook',
]; ];
public function __construct(
private readonly EffectiveEventDateResolver $effectiveEventDateResolver,
) {}
public function forTenant(Tenant $tenant): Tenant public function forTenant(Tenant $tenant): Tenant
{ {
return $tenant->load(['eventDates.validityTime', 'socialMedia']); return $tenant->load(['eventDates.validityTime', 'socialMedia']);
@@ -27,9 +34,14 @@ class EventService
$tenant->update([ $tenant->update([
'event_title' => $data['title'], 'event_title' => $data['title'],
'event_location' => $data['location'], '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)) { if (array_key_exists('social_media', $data)) {
$this->syncSocialMedia($tenant, $data['social_media']); $this->syncSocialMedia($tenant, $data['social_media']);
} else { } else {
@@ -40,41 +52,185 @@ class EventService
}); });
} }
/** @param array<int, array{date: string, start_time: string, end_time: string}> $dates */ /** @param array{date: string, start_time: string, end_time: string} $data */
private function syncDates(Tenant $tenant, array $dates): void 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) { if ($tenant->eventDates()->where($attributes)->exists()) {
$attributes = [ throw ValidationException::withMessages([
'date' => $date['date'], 'date' => ['La fecha y el horario ya existen.'],
'time_start' => $date['start_time'], ]);
'time_end' => $date['end_time'], }
];
$existingDate = $existingDates->get($index); return $tenant->eventDates()->create($attributes)->load('validityTime');
});
}
if ($existingDate) { /** @param array{date: string} $data */
$existingDate->update($attributes); public function rescheduleDateForTenant(Tenant $tenant, EventDate $eventDate, array $data): EventDate
} else { {
$tenant->eventDates()->create($attributes); 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 private function disableTicketsWithoutUsableDates(Tenant $tenant, EventDate $suspendedDate): void
->selectedByVariants() {
->whereHas('sourceTickets') $affectedDateIds = collect([$suspendedDate->getKey()]);
->exists() $frontier = $affectedDateIds;
|| $eventDate->variants()->whereHas('sourceTickets')->exists())) {
throw ValidationException::withMessages([ while ($frontier->isNotEmpty()) {
'dates' => ['No se puede eliminar una fecha utilizada por tickets generados.'], $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(); $variants = Variant::withTrashed()
$tenant->unsetRelation('eventDates'); ->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 */ /** @param array<string, string|null> $contact */

View File

@@ -8,4 +8,7 @@ Route::prefix('v1/adminapp/tenant')
->group(function (): void { ->group(function (): void {
Route::get('event', [EventController::class, 'show']); Route::get('event', [EventController::class, 'show']);
Route::put('event', [EventController::class, 'update']); 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, 'required' => false,
'default' => null, 'default' => null,
'placeholder' => 'Estado', 'placeholder' => 'Estado',
'options' => [ 'options' => Ticket::statusOptions(),
['value' => Ticket::STATUS_ACTIVE, 'label' => 'Activo'],
['value' => Ticket::STATUS_USED, 'label' => 'Usado'],
['value' => Ticket::STATUS_EXPIRED, 'label' => 'Vencido'],
],
], ],
]; ];
} }

View File

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

View File

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

View File

@@ -25,6 +25,7 @@ class PurchaseItemResource extends JsonResource
'quantity' => (int) $this->cantidad, 'quantity' => (int) $this->cantidad,
'unit_price' => $this->formatMoney($this->precio_unitario), 'unit_price' => $this->formatMoney($this->precio_unitario),
'line_total' => $this->formatMoney($this->total), 'line_total' => $this->formatMoney($this->total),
'refunded_amount' => $this->formatMoney($this->refunded_amount),
'source_catalog_item_id' => $this->source_catalog_item_id, 'source_catalog_item_id' => $this->source_catalog_item_id,
'source_variant_id' => $this->source_variant_id, 'source_variant_id' => $this->source_variant_id,
'item_details' => [ '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()) $this->saleService->sales($tenant, $request->validated())
)->additional([ )->additional([
'confirmed_sales_total' => $this->saleService->confirmedSalesTotal($tenant), '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, 'quantity' => (int) $item->cantidad,
'unit_price' => $this->formatMoney($item->precio_unitario), 'unit_price' => $this->formatMoney($item->precio_unitario),
'total' => $this->formatMoney($item->total), 'total' => $this->formatMoney($item->total),
'refunded_amount' => $this->formatMoney($item->refunded_amount),
])->values(), ])->values(),
'total' => $this->formatMoney($this->total), 'total' => $this->formatMoney($this->total),
]; ];

View File

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

View File

@@ -52,6 +52,10 @@ use Illuminate\Support\Facades\Schema;
'checkout_editing_policy', 'checkout_editing_policy',
'display_cart_item_images', 'display_cart_item_images',
'scanner_category_validation_enabled', 'scanner_category_validation_enabled',
'allow_ticket_refund',
'allow_ticket_total_refund',
'allow_ticket_partial_refund',
'ticket_partial_refund_percentage',
'event_title', 'event_title',
'event_location', 'event_location',
'event_date_text', 'event_date_text',
@@ -72,6 +76,10 @@ class Tenant extends Model
'checkout_editing_policy' => CartEditingPolicy::Disabled->value, 'checkout_editing_policy' => CartEditingPolicy::Disabled->value,
'display_cart_item_images' => true, 'display_cart_item_images' => true,
'scanner_category_validation_enabled' => 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 public function getRouteKeyName(): string
@@ -106,6 +114,35 @@ class Tenant extends Model
return $this->scanner_category_validation_enabled; 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. * Get the attributes that should be cast.
* *
@@ -124,6 +161,10 @@ class Tenant extends Model
'checkout_editing_policy' => CartEditingPolicy::class, 'checkout_editing_policy' => CartEditingPolicy::class,
'display_cart_item_images' => 'boolean', 'display_cart_item_images' => 'boolean',
'scanner_category_validation_enabled' => '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',
]; ];
} }

View File

@@ -117,6 +117,16 @@ class StoreTenantRequest extends FormRequest
], ],
'display_cart_item_images' => ['sometimes', 'boolean'], 'display_cart_item_images' => ['sometimes', 'boolean'],
'scanner_category_validation_enabled' => ['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' => [ 'website_type_code' => [
'required_with:extras', 'required_with:extras',
'sometimes', 'sometimes',

View File

@@ -138,6 +138,16 @@ class UpdateTenantRequest extends FormRequest
], ],
'display_cart_item_images' => ['sometimes', 'boolean'], 'display_cart_item_images' => ['sometimes', 'boolean'],
'scanner_category_validation_enabled' => ['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\Attachment;
use App\Domains\Attachable\Models\AttachmentCrop; use App\Domains\Attachable\Models\AttachmentCrop;
use App\Domains\Catalog\Models\Category; use App\Domains\Catalog\Models\Category;
use App\Domains\Event\Models\EventDate;
use App\Domains\Menu\Models\Menu; use App\Domains\Menu\Models\Menu;
use App\Domains\Tenant\Models\Tenant; use App\Domains\Tenant\Models\Tenant;
use Illuminate\Http\Request; use Illuminate\Http\Request;
@@ -50,12 +51,16 @@ class TenantResource extends JsonResource
: [ : [
'title' => $this->event_title, 'title' => $this->event_title,
'location' => $this->event_location, 'location' => $this->event_location,
'dates' => $this->eventDates->map(fn ($eventDate): array => [ 'dates' => $this->eventDates
'id' => $eventDate->id, ->filter(fn (EventDate $eventDate): bool => $eventDate->rescheduled_to_event_date_id === null
'date' => $eventDate->date->format('Y-m-d'), && $eventDate->suspended_at === null
'time_start' => $eventDate->time_start, )
'time_end' => $eventDate->time_end, ->map(fn (EventDate $eventDate): array => [
])->values(), 'id' => $eventDate->id,
'date' => $eventDate->date->format('Y-m-d'),
'time_start' => $eventDate->time_start,
'time_end' => $eventDate->time_end,
])->values(),
]), ]),
'extras' => $this->whenLoaded( 'extras' => $this->whenLoaded(
'websiteExtras', 'websiteExtras',
@@ -82,6 +87,10 @@ class TenantResource extends JsonResource
'checkout_editing_policy' => CartEditingPolicyResource::make($this->checkout_editing_policy), 'checkout_editing_policy' => CartEditingPolicyResource::make($this->checkout_editing_policy),
'display_cart_item_images' => $this->display_cart_item_images, 'display_cart_item_images' => $this->display_cart_item_images,
'scanner_category_validation_enabled' => $this->scanner_category_validation_enabled, '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( 'social_media' => $this->whenLoaded(
'socialMedia', 'socialMedia',
fn () => $this->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\AdminAppTicketExportRequest;
use App\Domains\Ticket\Requests\AdminAppTicketIndexRequest; 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\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\AdminAppTicketExcelService;
use App\Domains\Ticket\Services\AdminAppTicketPdfService; use App\Domains\Ticket\Services\AdminAppTicketPdfService;
use App\Domains\Ticket\Services\AdminAppTicketService; use App\Domains\Ticket\Services\AdminAppTicketService;
use App\Http\Controllers\Controller; use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Http\Response; use Illuminate\Http\Response;
use Symfony\Component\HttpFoundation\StreamedResponse; 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 public function downloadPdf(AdminAppTicketExportRequest $request): Response
{ {
$tenant = $request->user()->tenant()->firstOrFail(); $tenant = $request->user()->tenant()->firstOrFail();

View File

@@ -5,6 +5,7 @@ namespace App\Domains\Ticket\Models;
use App\Domains\Auth\Models\User; use App\Domains\Auth\Models\User;
use App\Domains\Catalog\Models\CatalogItem; use App\Domains\Catalog\Models\CatalogItem;
use App\Domains\Catalog\Models\Variant; use App\Domains\Catalog\Models\Variant;
use App\Domains\Logging\Models\Concerns\LogsValueChanges;
use App\Domains\Purchase\Models\PurchaseItem; use App\Domains\Purchase\Models\PurchaseItem;
use App\Domains\Tenant\Models\Tenant; use App\Domains\Tenant\Models\Tenant;
use App\Domains\Ticket\Services\ResolvedTicketValidity; use App\Domains\Ticket\Services\ResolvedTicketValidity;
@@ -18,6 +19,7 @@ use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo; use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany; use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Support\Collection; use Illuminate\Support\Collection;
use Illuminate\Validation\ValidationException;
#[Fillable([ #[Fillable([
'tenant_code', 'tenant_code',
@@ -26,12 +28,15 @@ use Illuminate\Support\Collection;
'source_catalog_item_id', 'source_catalog_item_id',
'source_variant_id', 'source_variant_id',
'used_at', 'used_at',
'disabled_at',
'cancelled_at',
'refunded_at',
'scanner_user_id', 'scanner_user_id',
'user_id', 'user_id',
])] ])]
class Ticket extends Model class Ticket extends Model
{ {
use HasFactory; use HasFactory, LogsValueChanges;
private ?ResolvedTicketValidity $resolvedValidity = null; private ?ResolvedTicketValidity $resolvedValidity = null;
@@ -41,8 +46,22 @@ class Ticket extends Model
public const STATUS_USED = 'used'; public const STATUS_USED = 'used';
public const STATUS_DISABLED = 'disabled';
public const STATUS_CANCELLED = 'cancelled';
public const STATUS_REFUNDED = 'refunded';
public $timestamps = false; public $timestamps = false;
/** @var list<string> */
protected array $loggedAttributes = [
'used_at',
'disabled_at',
'cancelled_at',
'refunded_at',
];
protected $appends = [ protected $appends = [
'name', 'name',
'description', 'description',
@@ -59,17 +78,123 @@ class Ticket extends Model
'source_variant_id' => 'integer', 'source_variant_id' => 'integer',
'source_purchase_item_id' => 'integer', 'source_purchase_item_id' => 'integer',
'used_at' => 'datetime', 'used_at' => 'datetime',
'disabled_at' => 'datetime',
'cancelled_at' => 'datetime',
'refunded_at' => 'datetime',
'scanner_user_id' => 'integer', 'scanner_user_id' => 'integer',
'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> */ /** @return BelongsTo<Tenant, $this> */
public function tenant(): BelongsTo public function tenant(): BelongsTo
{ {
return $this->belongsTo(Tenant::class, 'tenant_code', 'codigo'); 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> */ /** @return BelongsTo<User, $this> */
public function user(): BelongsTo public function user(): BelongsTo
{ {
@@ -108,7 +233,7 @@ class Ticket extends Model
public function isValid(): bool public function isValid(): bool
{ {
if ($this->used_at !== null) { if ($this->hasTerminalStatus() || $this->used_at !== null) {
return false; return false;
} }
@@ -122,7 +247,9 @@ class Ticket extends Model
public function getIsExpiredAttribute(): bool 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 public function getIsUsedAttribute(): bool
@@ -132,6 +259,18 @@ class Ticket extends Model
public function getStatusAttribute(): string 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) { if ($this->is_used) {
return self::STATUS_USED; return self::STATUS_USED;
} }
@@ -143,6 +282,102 @@ class Ticket extends Model
return self::STATUS_ACTIVE; 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 public function getNameAttribute(): string
{ {
return app(TicketPresentationResolver::class)->name($this); return app(TicketPresentationResolver::class)->name($this);

View File

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

@@ -15,20 +15,24 @@ class AdminAppTicketCollection extends ResourceCollection
private readonly int $totalTickets; private readonly int $totalTickets;
private readonly string $refundedTotal;
public function __construct(AdminAppTicketResult $result) public function __construct(AdminAppTicketResult $result)
{ {
parent::__construct($result->tickets); parent::__construct($result->tickets);
$this->scannedTickets = $result->scannedTickets; $this->scannedTickets = $result->scannedTickets;
$this->totalTickets = $result->totalTickets; $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 public function with(Request $request): array
{ {
return [ return [
'scanned_tickets' => $this->scannedTickets, 'scanned_tickets' => $this->scannedTickets,
'total_tickets' => $this->totalTickets, '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 [ return [
...parent::toArray($request), ...parent::toArray($request),
...$details, ...$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), 'values' => $rowService->values($this->resource, $details),
]; ];
} }

View File

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

View File

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

View File

@@ -31,10 +31,12 @@ class AdminAppTicketRowService
?? $ticket->sourceCatalogItem?->nombre ?? $ticket->sourceCatalogItem?->nombre
?? $ticket->name, ?? $ticket->name,
'amount' => $purchaseItem?->precio_unitario, 'amount' => $purchaseItem?->precio_unitario,
'refunded_amount' => $purchaseItem?->refunded_amount,
'client' => $purchaseItem?->purchase?->nombre_apellido ?? $ticket->user?->nombre_apellido, 'client' => $purchaseItem?->purchase?->nombre_apellido ?? $ticket->user?->nombre_apellido,
'status' => $ticket->status, 'status' => $ticket->status,
'scanned_by' => $ticket->scannerUser?->nombre_apellido, 'scanned_by' => $ticket->scannerUser?->nombre_apellido,
'variant_properties' => $this->variantProperties($ticket), 'variant_properties' => $this->variantProperties($ticket),
'allow_refund' => $ticket->allow_refund(),
]; ];
} }
@@ -95,11 +97,7 @@ class AdminAppTicketRowService
return match ($type) { return match ($type) {
'order_number' => '#'.$value, 'order_number' => '#'.$value,
'currency' => '$'.number_format((float) $value, 2, ',', '.'), 'currency' => '$'.number_format((float) $value, 2, ',', '.'),
'status' => match ((string) $value) { 'status' => Ticket::statusLabel((string) $value),
Ticket::STATUS_USED => 'Usado',
Ticket::STATUS_EXPIRED => 'Vencido',
default => 'Activo',
},
default => (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\Auth\Models\User;
use App\Domains\Purchase\Models\PurchaseItem; use App\Domains\Purchase\Models\PurchaseItem;
use App\Domains\Purchase\Services\PurchaseRefundSummaryService;
use App\Domains\Tenant\Models\Tenant; use App\Domains\Tenant\Models\Tenant;
use App\Domains\Ticket\Models\Ticket; use App\Domains\Ticket\Models\Ticket;
use Illuminate\Database\Eloquent\Builder; use Illuminate\Database\Eloquent\Builder;
use Illuminate\Pagination\LengthAwarePaginator; use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Support\Collection; use Illuminate\Support\Collection;
use Illuminate\Support\Facades\DB;
use Illuminate\Validation\ValidationException;
class AdminAppTicketService class AdminAppTicketService
{ {
private const RELATIONS = [ private const RELATIONS = [
...TicketValidityResolver::RELATIONS, ...TicketValidityResolver::RELATIONS,
...TicketPresentationResolver::RELATIONS, ...TicketPresentationResolver::RELATIONS,
'tenant',
'user', 'user',
'scannerUser', 'scannerUser',
'sourceCatalogItem.category', 'sourceCatalogItem.category',
@@ -24,6 +28,7 @@ class AdminAppTicketService
public function __construct( public function __construct(
private readonly AdminAppTicketColumnService $columnService, private readonly AdminAppTicketColumnService $columnService,
private readonly AdminAppTicketRowService $rowService, private readonly AdminAppTicketRowService $rowService,
private readonly PurchaseRefundSummaryService $refundSummaryService,
) {} ) {}
/** /**
@@ -42,20 +47,30 @@ class AdminAppTicketService
->get(); ->get();
$matchingTickets = $this->sortTickets($matchingTickets, $tenant, $filters); $matchingTickets = $this->sortTickets($matchingTickets, $tenant, $filters);
$tickets = $this->paginate($matchingTickets, $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 { } else {
$tickets = (clone $query) $tickets = (clone $query)
->with(self::RELATIONS) ->with(self::RELATIONS)
->when(! $databaseSorted, fn (Builder $query): Builder => $query->orderByDesc('id')) ->when(! $databaseSorted, fn (Builder $query): Builder => $query->orderByDesc('id'))
->paginateFromRequest() ->paginateFromRequest()
->withQueryString(); ->withQueryString();
$scannedTickets = $countQuery->whereNotNull('used_at')->count();
$counts = $this->calculateTicketCounts($countQuery);
$scannedTickets = $counts['scanned'];
$totalTickets = $counts['total'];
} }
return new AdminAppTicketResult( return new AdminAppTicketResult(
tickets: $tickets, tickets: $tickets,
scannedTickets: $scannedTickets, 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); 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 * @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> * @return Builder<Ticket>
@@ -255,13 +418,41 @@ class AdminAppTicketService
} }
if ($status === Ticket::STATUS_USED) { 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; return;
} }
$matchingIds = (clone $query) $matchingIds = (clone $query)
->whereNull('used_at') ->whereNull('used_at')
->whereNull('disabled_at')
->whereNull('cancelled_at')
->whereNull('refunded_at')
->with(TicketValidityResolver::RELATIONS) ->with(TicketValidityResolver::RELATIONS)
->get() ->get()
->filter(fn (Ticket $ticket): bool => $ticket->status === $status) ->filter(fn (Ticket $ticket): bool => $ticket->status === $status)
@@ -270,6 +461,35 @@ class AdminAppTicketService
$query->whereIn('tickets.id', $matchingIds); $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 private function normalizedCategory(string $category): string
{ {
return mb_strtolower(trim($category)); return mb_strtolower(trim($category));

View File

@@ -4,6 +4,8 @@ namespace App\Domains\Ticket\Services;
use App\Domains\Catalog\Models\Variant; use App\Domains\Catalog\Models\Variant;
use App\Domains\Catalog\Models\VariantDefinition; 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\Ticket;
use App\Domains\Ticket\Models\ValidityTime; use App\Domains\Ticket\Models\ValidityTime;
use Illuminate\Support\Collection; use Illuminate\Support\Collection;
@@ -17,6 +19,14 @@ use Illuminate\Support\Collection;
*/ */
class TicketValidityResolver 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. */ /** Relaciones necesarias para resolver tickets sin consultas N+1. */
public const RELATIONS = [ public const RELATIONS = [
'sourceVariant.eventDates.validityTime', 'sourceVariant.eventDates.validityTime',
@@ -56,7 +66,18 @@ class TicketValidityResolver
]); ]);
$dimensions = collect(); $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)) { if ($eventDates->contains(fn ($eventDate): bool => $eventDate->validityTime === null)) {
return ResolvedTicketValidity::unresolvable(); return ResolvedTicketValidity::unresolvable();

View File

@@ -9,6 +9,18 @@ Route::prefix('v1/adminapp/tenant')
Route::get('tickets', [TicketController::class, 'index']) Route::get('tickets', [TicketController::class, 'index'])
->middleware('tenant.menu:adminapp.tickets') ->middleware('tenant.menu:adminapp.tickets')
->name('adminapp.tickets.index'); ->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']) Route::get('tickets/pdf', [TicketController::class, 'downloadPdf'])
->middleware('tenant.menu:adminapp.tickets') ->middleware('tenant.menu:adminapp.tickets')
->name('adminapp.tickets.pdf'); ->name('adminapp.tickets.pdf');

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

@@ -6,12 +6,17 @@ use App\Domains\Attachable\Enums\AttachmentType;
use App\Domains\Attachable\Models\Attachment; use App\Domains\Attachable\Models\Attachment;
use App\Domains\Auth\Models\User; use App\Domains\Auth\Models\User;
use App\Domains\Authorization\Enums\RoleCode; 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\Tenant;
use App\Domains\Tenant\Models\WebsiteType; use App\Domains\Tenant\Models\WebsiteType;
use App\Domains\Ticket\Enums\ValidityTimeType; use App\Domains\Ticket\Enums\ValidityTimeType;
use App\Domains\Ticket\Models\Ticket;
use Database\Seeders\AuthorizationSeeder; use Database\Seeders\AuthorizationSeeder;
use Database\Seeders\SocialMediaSeeder; use Database\Seeders\SocialMediaSeeder;
use Illuminate\Foundation\Testing\RefreshDatabase; use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Str;
use Laravel\Sanctum\Sanctum; use Laravel\Sanctum\Sanctum;
use Tests\TestCase; use Tests\TestCase;
@@ -34,9 +39,10 @@ class AdminAppEventControllerTest extends TestCase
{ {
$this->getJson('/api/v1/adminapp/tenant/event')->assertUnauthorized(); $this->getJson('/api/v1/adminapp/tenant/event')->assertUnauthorized();
$this->putJson('/api/v1/adminapp/tenant/event', $this->eventPayload())->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'); $tenant = $this->createTenant('acme');
Sanctum::actingAs($this->createAdminAppUser($tenant)); Sanctum::actingAs($this->createAdminAppUser($tenant));
@@ -45,10 +51,11 @@ class AdminAppEventControllerTest extends TestCase
->assertOk() ->assertOk()
->assertJsonPath('data.title', 'Festival Acme') ->assertJsonPath('data.title', 'Festival Acme')
->assertJsonPath('data.location', 'Predio Ferial, Rosario') ->assertJsonPath('data.location', 'Predio Ferial, Rosario')
->assertJsonPath('data.dates.0.date', '2026-10-09') ->assertJsonPath('data.allow_ticket_refund', true)
->assertJsonPath('data.dates.0.validity_time.type', 'fixed_window') ->assertJsonPath('data.allow_ticket_total_refund', true)
->assertJsonPath('data.dates.0.start_time', '09:00') ->assertJsonPath('data.allow_ticket_partial_refund', true)
->assertJsonPath('data.dates.0.end_time', '18:30') ->assertJsonPath('data.ticket_partial_refund_percentage', '25.50')
->assertJsonCount(0, 'data.dates')
->assertJsonPath('data.contact.whatsapp_url', 'https://wa.me/5493415550101') ->assertJsonPath('data.contact.whatsapp_url', 'https://wa.me/5493415550101')
->assertJsonPath('data.contact.instagram_url', 'https://instagram.com/acme') ->assertJsonPath('data.contact.instagram_url', 'https://instagram.com/acme')
->assertJsonPath('data.contact.facebook_url', null); ->assertJsonPath('data.contact.facebook_url', null);
@@ -58,25 +65,13 @@ class AdminAppEventControllerTest extends TestCase
'id' => $tenant->id, 'id' => $tenant->id,
'event_title' => 'Festival Acme', 'event_title' => 'Festival Acme',
'event_location' => 'Predio Ferial, Rosario', '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', [ $this->assertDatabaseCount('event_dates', 0);
'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->assertDatabaseHas('tenant_social_media', [ $this->assertDatabaseHas('tenant_social_media', [
'tenant_code' => $tenant->codigo, 'tenant_code' => $tenant->codigo,
'social_media_code' => 'whatsapp', '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 public function test_an_adminapp_user_can_read_only_its_tenant_active_event(): void
{ {
$tenant = $this->createTenant('acme'); $tenant = $this->createTenant('acme');
@@ -109,7 +154,7 @@ class AdminAppEventControllerTest extends TestCase
->assertJsonCount(0, 'data.dates'); ->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'); $tenant = $this->createTenant('acme');
$eventTenant = $this->createActiveEvent($tenant, 'Old Event'); $eventTenant = $this->createActiveEvent($tenant, 'Old Event');
@@ -124,7 +169,6 @@ class AdminAppEventControllerTest extends TestCase
'time_end' => '12:00', 'time_end' => '12:00',
]); ]);
$firstValidityTimeId = $firstDate->validity_time_id; $firstValidityTimeId = $firstDate->validity_time_id;
$removedValidityTimeId = $removedDate->validity_time_id;
$tenant->socialMedia()->attach('facebook', [ $tenant->socialMedia()->attach('facebook', [
'url' => 'https://facebook.com/old', 'url' => 'https://facebook.com/old',
'orden' => 2, 'orden' => 2,
@@ -136,12 +180,6 @@ class AdminAppEventControllerTest extends TestCase
Sanctum::actingAs($this->createAdminAppUser($tenant)); Sanctum::actingAs($this->createAdminAppUser($tenant));
$payload = $this->eventPayload(); $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) $this->putJson('/api/v1/adminapp/tenant/event', $payload)
->assertOk() ->assertOk()
->assertJsonPath('data.id', $tenant->id) ->assertJsonPath('data.id', $tenant->id)
@@ -151,17 +189,16 @@ class AdminAppEventControllerTest extends TestCase
$this->assertDatabaseHas('event_dates', [ $this->assertDatabaseHas('event_dates', [
'id' => $firstDate->id, 'id' => $firstDate->id,
'validity_time_id' => $firstValidityTimeId, 'validity_time_id' => $firstValidityTimeId,
'date' => '2026-11-15', 'date' => '2026-10-01',
]); ]);
$this->assertDatabaseHas('validity_times', [ $this->assertDatabaseHas('validity_times', [
'id' => $firstValidityTimeId, 'id' => $firstValidityTimeId,
'type' => ValidityTimeType::FixedWindow->value, 'type' => ValidityTimeType::FixedWindow->value,
'fixed_starts_at' => '2026-11-15 10:00:00', 'fixed_starts_at' => '2026-10-01 08:00:00',
'fixed_expires_at' => '2026-11-15 20:00:00', 'fixed_expires_at' => '2026-10-01 12:00:00',
]); ]);
$this->assertDatabaseMissing('event_dates', ['id' => $removedDate->id]); $this->assertDatabaseHas('event_dates', ['id' => $removedDate->id]);
$this->assertDatabaseMissing('validity_times', ['id' => $removedValidityTimeId]); $this->assertSame('1 y 2 de Octubre 2026', $tenant->fresh()->event_date_text);
$this->assertSame('15 de Noviembre 2026', $tenant->fresh()->event_date_text);
$this->assertDatabaseMissing('tenant_social_media', [ $this->assertDatabaseMissing('tenant_social_media', [
'tenant_code' => $tenant->codigo, 'tenant_code' => $tenant->codigo,
'social_media_code' => 'facebook', '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'); $tenant = $this->createTenant('acme');
Sanctum::actingAs($this->createAdminAppUser($tenant)); Sanctum::actingAs($this->createAdminAppUser($tenant));
$payload = $this->eventPayload(); foreach ([9, 10, 11, 12] as $day) {
$payload['dates'] = collect([9, 10, 11, 12]) $this->postJson('/api/v1/adminapp/tenant/event-dates', [
->map(fn (int $day): array => [
'date' => sprintf('2026-10-%02d', $day), 'date' => sprintf('2026-10-%02d', $day),
'start_time' => '09:00', 'start_time' => '09:00',
'end_time' => '18:30', 'end_time' => '18:30',
]) ])->assertCreated()->assertJsonPath('data.status', 'scheduled');
->all(); }
$this->putJson('/api/v1/adminapp/tenant/event', $payload)->assertOk();
$this->assertSame( $this->assertSame(
'9, 10, 11 y 12 de Octubre 2026', '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'); $tenant = $this->createTenant('acme');
Sanctum::actingAs($this->createAdminAppUser($tenant)); Sanctum::actingAs($this->createAdminAppUser($tenant));
@@ -202,10 +363,6 @@ class AdminAppEventControllerTest extends TestCase
$this->putJson('/api/v1/adminapp/tenant/event', [ $this->putJson('/api/v1/adminapp/tenant/event', [
'title' => '', 'title' => '',
'location' => '', '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' => [ 'contact' => [
'whatsapp_url' => 'not-a-url', 'whatsapp_url' => 'not-a-url',
'instagram_url' => null, 'instagram_url' => null,
@@ -216,12 +373,15 @@ class AdminAppEventControllerTest extends TestCase
->assertJsonValidationErrors([ ->assertJsonValidationErrors([
'title', 'title',
'location', 'location',
'dates.0.date',
'dates.0.start_time',
'dates.1.date',
'contact.whatsapp_url', '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); $this->assertNull($tenant->fresh()->event_title);
} }
@@ -273,11 +433,10 @@ class AdminAppEventControllerTest extends TestCase
return [ return [
'title' => 'Festival Acme', 'title' => 'Festival Acme',
'location' => 'Predio Ferial, Rosario', 'location' => 'Predio Ferial, Rosario',
'dates' => [[ 'allow_ticket_refund' => true,
'date' => '2026-10-09', 'allow_ticket_total_refund' => true,
'start_time' => '09:00', 'allow_ticket_partial_refund' => true,
'end_time' => '18:30', 'ticket_partial_refund_percentage' => 25.50,
]],
'contact' => [ 'contact' => [
'whatsapp_url' => 'https://wa.me/5493415550101', 'whatsapp_url' => 'https://wa.me/5493415550101',
'instagram_url' => 'https://instagram.com/acme', '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 private function createTenant(string $code): Tenant
{ {
$headerLogo = $this->createAttachment("{$code}-header"); $headerLogo = $this->createAttachment("{$code}-header");

View File

@@ -78,6 +78,9 @@ class AdminAppTicketFilterFormControllerTest extends TestCase
['value' => 'active', 'label' => 'Activo'], ['value' => 'active', 'label' => 'Activo'],
['value' => 'used', 'label' => 'Usado'], ['value' => 'used', 'label' => 'Usado'],
['value' => 'expired', 'label' => 'Vencido'], ['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' => 'active', 'label' => 'Activo'],
['value' => 'used', 'label' => 'Usado'], ['value' => 'used', 'label' => 'Usado'],
['value' => 'expired', 'label' => 'Vencido'], ['value' => 'expired', 'label' => 'Vencido'],
['value' => 'disabled', 'label' => 'Inhabilitado'],
['value' => 'cancelled', 'label' => 'Cancelado'],
['value' => 'refunded', 'label' => 'Reembolsado'],
], ],
'categories' => [ '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\Concerns\LogsValueChanges;
use App\Domains\Logging\Models\ValueChange; use App\Domains\Logging\Models\ValueChange;
use App\Domains\Purchase\Models\Purchase; use App\Domains\Purchase\Models\Purchase;
use App\Domains\Ticket\Models\Ticket;
use Illuminate\Database\Eloquent\Attributes\Fillable; use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Schema; use Illuminate\Support\Facades\Schema;
use Illuminate\Validation\ValidationException;
use Tests\TestCase; use Tests\TestCase;
class LogsValueChangesTest extends TestCase class LogsValueChangesTest extends TestCase
@@ -52,6 +54,16 @@ class LogsValueChangesTest extends TestCase
$table->timestamps(); $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 = require database_path('migrations/2026_08_03_000200_create_value_changes_table.php');
$migration->up(); $migration->up();
$tenantMigration = require database_path('migrations/2026_08_04_000000_add_tenant_code_to_value_changes_table.php'); $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, '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'])] #[Fillable(['name', 'price', 'description'])]

View File

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

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.tenant_code', $tenant->codigo)
->assertJsonPath('data.0.values.id', $ticket->id) ->assertJsonPath('data.0.values.id', $ticket->id)
->assertJsonPath('data.0.values.status', Ticket::STATUS_ACTIVE) ->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') ->assertJsonMissingPath('data.0.values.ticket')
->assertJsonPath('data.0.values.date', '-') ->assertJsonPath('data.0.values.date', '-')
->assertJsonPath('data.0.values.size', '-') ->assertJsonPath('data.0.values.size', '-')
@@ -79,6 +84,283 @@ class AdminAppTicketControllerTest extends TestCase
->assertJsonPath('meta.total', 1); ->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 public function test_it_searches_by_id_and_does_not_search_by_uuid(): void
{ {
$tenant = $this->createTenant('fiesta_futbol_infantil'); $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)->update(['used_at' => now()]);
$this->createTicket($tenant, $admin); $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()]); $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') $this->getJson('/api/v1/adminapp/tenant/tickets?q=does-not-match')
->assertOk() ->assertOk()
->assertJsonCount(0, 'data') ->assertJsonCount(0, 'data')
->assertJsonPath('scanned_tickets', 0) ->assertJsonPath('scanned_tickets', 0)
->assertJsonPath('total_tickets', 0); ->assertJsonPath('total_tickets', 0)
->assertJsonPath('refunded_total', '250.00');
$this->getJson('/api/v1/adminapp/tenant/tickets') $this->getJson('/api/v1/adminapp/tenant/tickets')
->assertOk() ->assertOk()
->assertJsonCount(5, 'data')
->assertJsonPath('scanned_tickets', 1) ->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 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.order_number', $purchase->id)
->assertJsonPath('data.0.product', 'Remera') ->assertJsonPath('data.0.product', 'Remera')
->assertJsonPath('data.0.amount', '8000.00') ->assertJsonPath('data.0.amount', '8000.00')
->assertJsonPath('data.0.refunded_amount', '0.00')
->assertJsonPath('data.0.status', Ticket::STATUS_USED) ->assertJsonPath('data.0.status', Ticket::STATUS_USED)
->assertJsonPath('data.0.scanned_by', $admin->nombre_apellido) ->assertJsonPath('data.0.scanned_by', $admin->nombre_apellido)
->assertJsonPath('data.0.variant_properties.0.code', 'size') ->assertJsonPath('data.0.variant_properties.0.code', 'size')
@@ -498,6 +824,28 @@ class AdminAppTicketControllerTest extends TestCase
->assertJsonPath('data.0.id', $active->id); ->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 public function test_it_downloads_filtered_ticket_reports(): void
{ {
$tenant = $this->createTenant('fiesta_futbol_infantil'); $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 private function grantTicketsMenu(Tenant $tenant): void
{ {
$menu = Menu::query()->create([ $menu = Menu::query()->create([

View File

@@ -272,6 +272,11 @@ class ScannerTicketControllerTest extends TestCase
->assertJsonPath('data.ticket.scanner_user_id', $this->scanner->id) ->assertJsonPath('data.ticket.scanner_user_id', $this->scanner->id)
->assertJsonPath('data.ticket.is_valid', false) ->assertJsonPath('data.ticket.is_valid', false)
->assertJsonPath('data.ticket.is_used', true) ->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.ticket.client', $this->ticketOwner->nombre_apellido)
->assertJsonPath('data.client.id', $this->ticketOwner->id) ->assertJsonPath('data.client.id', $this->ticketOwner->id)
->assertJsonPath('data.client.nombre_apellido', $this->ticketOwner->nombre_apellido); ->assertJsonPath('data.client.nombre_apellido', $this->ticketOwner->nombre_apellido);
@@ -280,6 +285,14 @@ class ScannerTicketControllerTest extends TestCase
'id' => $ticket->id, 'id' => $ticket->id,
'scanner_user_id' => $this->scanner->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); $this->assertNotNull($ticket->fresh()->used_at);
$scanAttempt = ScanAttempt::query()->sole(); $scanAttempt = ScanAttempt::query()->sole();

View File

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

View File

@@ -3,9 +3,11 @@
namespace Tests\Unit\Event; namespace Tests\Unit\Event;
use App\Domains\Catalog\Models\Variant; use App\Domains\Catalog\Models\Variant;
use App\Domains\Event\Enums\EventDateStatus;
use App\Domains\Event\Models\EventDate; use App\Domains\Event\Models\EventDate;
use App\Domains\Tenant\Models\Tenant; use App\Domains\Tenant\Models\Tenant;
use App\Domains\Ticket\Models\ValidityTime; use App\Domains\Ticket\Models\ValidityTime;
use Illuminate\Support\Carbon;
use Tests\TestCase; use Tests\TestCase;
class EventModelsTest extends TestCase class EventModelsTest extends TestCase
@@ -30,6 +32,37 @@ class EventModelsTest extends TestCase
$this->assertInstanceOf(ValidityTime::class, $eventDate->validityTime()->getRelated()); $this->assertInstanceOf(ValidityTime::class, $eventDate->validityTime()->getRelated());
$this->assertInstanceOf(EventDate::class, (new ValidityTime)->eventDate()->getRelated()); $this->assertInstanceOf(EventDate::class, (new ValidityTime)->eventDate()->getRelated());
$this->assertInstanceOf(Variant::class, $eventDate->variants()->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 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\ResolvedValidityGroup;
use App\Domains\Ticket\Services\TicketValidityResolver; use App\Domains\Ticket\Services\TicketValidityResolver;
use Illuminate\Support\Carbon; use Illuminate\Support\Carbon;
use Illuminate\Validation\ValidationException;
use Tests\TestCase; use Tests\TestCase;
class TicketTest extends TestCase class TicketTest extends TestCase
@@ -31,6 +32,9 @@ class TicketTest extends TestCase
'source_catalog_item_id' => '20', 'source_catalog_item_id' => '20',
'source_variant_id' => '30', 'source_variant_id' => '30',
'used_at' => null, 'used_at' => null,
'disabled_at' => '2026-09-10 10:00:00',
'cancelled_at' => null,
'refunded_at' => null,
'scanner_user_id' => '15', 'scanner_user_id' => '15',
'user_id' => '10', 'user_id' => '10',
]); ]);
@@ -40,6 +44,9 @@ class TicketTest extends TestCase
$this->assertSame(20, $ticket->source_catalog_item_id); $this->assertSame(20, $ticket->source_catalog_item_id);
$this->assertSame(30, $ticket->source_variant_id); $this->assertSame(30, $ticket->source_variant_id);
$this->assertNull($ticket->used_at); $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(15, $ticket->scanner_user_id);
$this->assertSame(10, $ticket->user_id); $this->assertSame(10, $ticket->user_id);
$this->assertInstanceOf(Tenant::class, $ticket->tenant()->getRelated()); $this->assertInstanceOf(Tenant::class, $ticket->tenant()->getRelated());
@@ -57,6 +64,25 @@ class TicketTest extends TestCase
$this->assertSame(Ticket::STATUS_ACTIVE, $ticket->status); $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 public function test_fixed_window_controls_ticket_validity(): void
{ {
Carbon::setTestNow('2026-07-21 10:00:00'); Carbon::setTestNow('2026-07-21 10:00:00');
@@ -154,6 +180,78 @@ class TicketTest extends TestCase
$this->assertSame(Ticket::STATUS_USED, $ticket->status); $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 public function test_all_validity_times_in_the_same_group_must_be_active(): void
{ {
Carbon::setTestNow('2026-08-20 13:00:00'); Carbon::setTestNow('2026-08-20 13:00:00');