Compare commits

...

10 Commits

35 changed files with 1248 additions and 123 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 = [
'date' => $date['date'],
'time_start' => $date['start_time'],
'time_end' => $date['end_time'],
];
$existingDate = $existingDates->get($index);
if ($existingDate) {
$existingDate->update($attributes);
} else {
$tenant->eventDates()->create($attributes);
}
}
$datesToDelete = $existingDates->slice(count($dates));
if ($datesToDelete->contains(fn ($eventDate): bool => $eventDate
->selectedByVariants()
->whereHas('sourceTickets')
->exists()
|| $eventDate->variants()->whereHas('sourceTickets')->exists())) {
throw ValidationException::withMessages([ throw ValidationException::withMessages([
'dates' => ['No se puede eliminar una fecha utilizada por tickets generados.'], 'date' => ['La fecha y el horario ya existen.'],
]); ]);
} }
$datesToDelete->each->delete(); return $tenant->eventDates()->create($attributes)->load('validityTime');
$tenant->unsetRelation('eventDates'); });
}
/** @param array{date: string} $data */
public function rescheduleDateForTenant(Tenant $tenant, EventDate $eventDate, array $data): EventDate
{
return DB::transaction(function () use ($tenant, $eventDate, $data): EventDate {
$source = $this->lockedDateForTenant($tenant, $eventDate);
if ($source->suspended_at !== null) {
throw ValidationException::withMessages([
'event_date' => ['No se puede reprogramar una fecha suspendida.'],
]);
}
if ($source->rescheduled_to_event_date_id !== null) {
throw ValidationException::withMessages([
'event_date' => ['La fecha ya fue reprogramada.'],
]);
}
$destination = $tenant->eventDates()
->whereDate('date', $data['date'])
->lockForUpdate()
->first();
if ($destination === null) {
$destination = $tenant->eventDates()->create([
'date' => $data['date'],
'time_start' => $source->time_start,
'time_end' => $source->time_end,
]);
}
if ($destination->is($source) || $this->chainContains($destination, $source)) {
throw ValidationException::withMessages([
'date' => ['La reprogramación generaría una referencia circular.'],
]);
}
if ($this->effectiveEventDateResolver->resolve($destination) === null) {
throw ValidationException::withMessages([
'date' => ['La fecha de destino no es utilizable.'],
]);
}
$source->update(['rescheduled_to_event_date_id' => $destination->getKey()]);
return $source->fresh(['validityTime', 'rescheduledTo.validityTime']);
});
}
public function suspendDateForTenant(Tenant $tenant, EventDate $eventDate): EventDate
{
return DB::transaction(function () use ($tenant, $eventDate): EventDate {
$date = $this->lockedDateForTenant($tenant, $eventDate);
if ($date->rescheduled_to_event_date_id !== null) {
throw ValidationException::withMessages([
'event_date' => ['No se puede suspender una fecha que ya fue reprogramada.'],
]);
}
if ($date->suspended_at !== null) {
return $date->load('validityTime');
}
$date->update(['suspended_at' => now()]);
$this->disableTicketsWithoutUsableDates($tenant, $date);
return $date->fresh('validityTime');
});
}
private function lockedDateForTenant(Tenant $tenant, EventDate $eventDate): EventDate
{
return $tenant->eventDates()
->whereKey($eventDate->getKey())
->lockForUpdate()
->firstOrFail();
}
private function chainContains(EventDate $start, EventDate $expected): bool
{
$current = $start;
$visited = [];
while ($current->rescheduled_to_event_date_id !== null) {
if ($current->is($expected)) {
return true;
}
if (isset($visited[$current->getKey()])) {
return true;
}
$visited[$current->getKey()] = true;
$current = $current->rescheduledTo()->lockForUpdate()->first();
if ($current === null) {
return false;
}
}
return $current->is($expected);
}
private function disableTicketsWithoutUsableDates(Tenant $tenant, EventDate $suspendedDate): void
{
$affectedDateIds = collect([$suspendedDate->getKey()]);
$frontier = $affectedDateIds;
while ($frontier->isNotEmpty()) {
$predecessors = $tenant->eventDates()
->whereIn('rescheduled_to_event_date_id', $frontier)
->pluck('id')
->diff($affectedDateIds)
->values();
$affectedDateIds = $affectedDateIds->merge($predecessors)->unique()->values();
$frontier = $predecessors;
}
$variants = Variant::withTrashed()
->where(function ($query) use ($affectedDateIds): void {
$query->whereIn('event_date_id', $affectedDateIds)
->orWhereHas('eventDates', fn ($eventDates) => $eventDates
->whereIn('event_dates.id', $affectedDateIds));
})
->with(['eventDates', 'eventDate'])
->get();
foreach ($variants as $variant) {
$hasUsableDate = $variant->selectedEventDates()->contains(
fn (EventDate $candidate): bool => $this->effectiveEventDateResolver->resolve($candidate) !== null
);
if ($hasUsableDate) {
continue;
}
Ticket::query()
->where('tenant_code', $tenant->codigo)
->where('source_variant_id', $variant->getKey())
->whereNull('disabled_at')
->whereNull('cancelled_at')
->whereNull('refunded_at')
->lockForUpdate()
->get()
->each(function (Ticket $ticket): void {
$ticket->markAsDisabled();
$ticket->save();
});
}
}
/**
* @param array{date: string, start_time: string, end_time: string} $data
* @return array{date: string, time_start: string, time_end: string}
*/
private function dateAttributes(array $data): array
{
return [
'date' => $data['date'],
'time_start' => $data['start_time'].':00',
'time_end' => $data['end_time'].':00',
];
} }
/** @param array<string, string|null> $contact */ /** @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

@@ -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

@@ -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,7 @@ 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_total_refund',
'allow_ticket_partial_refund', 'allow_ticket_partial_refund',
'ticket_partial_refund_percentage', 'ticket_partial_refund_percentage',
@@ -75,6 +76,7 @@ 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_total_refund' => false,
'allow_ticket_partial_refund' => false, 'allow_ticket_partial_refund' => false,
'ticket_partial_refund_percentage' => 0, 'ticket_partial_refund_percentage' => 0,
@@ -114,12 +116,14 @@ class Tenant extends Model
public function allow_refund(): bool public function allow_refund(): bool
{ {
return (bool) $this->allow_ticket_total_refund || $this->allow_partial_refund(); return (bool) $this->allow_ticket_refund
&& ((bool) $this->allow_ticket_total_refund || $this->allow_partial_refund());
} }
public function allow_partial_refund(): bool public function allow_partial_refund(): bool
{ {
return (bool) $this->allow_ticket_partial_refund return (bool) $this->allow_ticket_refund
&& (bool) $this->allow_ticket_partial_refund
&& $this->ticket_partial_refund_percentage !== null && $this->ticket_partial_refund_percentage !== null
&& (float) $this->ticket_partial_refund_percentage > 0; && (float) $this->ticket_partial_refund_percentage > 0;
} }
@@ -157,6 +161,7 @@ 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_total_refund' => 'boolean',
'allow_ticket_partial_refund' => 'boolean', 'allow_ticket_partial_refund' => 'boolean',
'ticket_partial_refund_percentage' => 'decimal:2', 'ticket_partial_refund_percentage' => 'decimal:2',

View File

@@ -117,6 +117,7 @@ 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_total_refund' => ['sometimes', 'boolean'],
'allow_ticket_partial_refund' => ['sometimes', 'boolean'], 'allow_ticket_partial_refund' => ['sometimes', 'boolean'],
'ticket_partial_refund_percentage' => [ 'ticket_partial_refund_percentage' => [

View File

@@ -138,6 +138,7 @@ 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_total_refund' => ['sometimes', 'boolean'],
'allow_ticket_partial_refund' => ['sometimes', 'boolean'], 'allow_ticket_partial_refund' => ['sometimes', 'boolean'],
'ticket_partial_refund_percentage' => [ 'ticket_partial_refund_percentage' => [

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,7 +51,11 @@ 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
->filter(fn (EventDate $eventDate): bool => $eventDate->rescheduled_to_event_date_id === null
&& $eventDate->suspended_at === null
)
->map(fn (EventDate $eventDate): array => [
'id' => $eventDate->id, 'id' => $eventDate->id,
'date' => $eventDate->date->format('Y-m-d'), 'date' => $eventDate->date->format('Y-m-d'),
'time_start' => $eventDate->time_start, 'time_start' => $eventDate->time_start,
@@ -82,6 +87,7 @@ 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_total_refund' => $this->allow_ticket_total_refund,
'allow_ticket_partial_refund' => $this->allow_ticket_partial_refund, 'allow_ticket_partial_refund' => $this->allow_ticket_partial_refund,
'ticket_partial_refund_percentage' => $this->ticket_partial_refund_percentage, 'ticket_partial_refund_percentage' => $this->ticket_partial_refund_percentage,

View File

@@ -6,6 +6,7 @@ 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\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\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;
@@ -39,6 +40,15 @@ class TicketController extends Controller
return new AdminAppTicketResource($this->ticketService->cancel($tenant, $ticket)); 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 public function refund(AdminAppTicketRefundRequest $request, int $ticket): AdminAppTicketResource
{ {
$tenant = $request->user()->tenant()->firstOrFail(); $tenant = $request->user()->tenant()->firstOrFail();

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

@@ -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

@@ -4,6 +4,7 @@ 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;
@@ -27,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,
) {} ) {}
/** /**
@@ -45,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),
); );
} }
@@ -80,14 +92,74 @@ class AdminAppTicketService
public function cancel(Tenant $tenant, int $ticketId): Ticket public function cancel(Tenant $tenant, int $ticketId): Ticket
{ {
return DB::transaction(function () use ($tenant, $ticketId): Ticket {
$ticket = Ticket::query() $ticket = Ticket::query()
->where('tenant_code', $tenant->codigo) ->where('tenant_code', $tenant->codigo)
->lockForUpdate()
->findOrFail($ticketId); ->findOrFail($ticketId);
if (! $ticket->can_cancel()) {
throw ValidationException::withMessages([
'status' => 'El ticket debe estar activo para poder cancelarlo.',
]);
}
$ticket->markAsCancelled(); $ticket->markAsCancelled();
$ticket->save(); $ticket->save();
return $ticket->refresh()->load(self::RELATIONS); 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 public function refund(Tenant $tenant, int $ticketId, string $refundType): Ticket
@@ -100,6 +172,18 @@ class AdminAppTicketService
->lockForUpdate() ->lockForUpdate()
->findOrFail($ticketId); ->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() $purchaseItem = PurchaseItem::query()
->lockForUpdate() ->lockForUpdate()
->find($ticket->source_purchase_item_id); ->find($ticket->source_purchase_item_id);
@@ -133,8 +217,8 @@ class AdminAppTicketService
private function ensureRefundIsAllowed(Tenant $tenant, string $refundType): void private function ensureRefundIsAllowed(Tenant $tenant, string $refundType): void
{ {
$isAllowed = match ($refundType) { $isAllowed = match ($refundType) {
'partial' => $tenant->allow_partial_refund(), 'partial' => $tenant->allow_refund() && $tenant->allow_partial_refund(),
'total' => (bool) $tenant->allow_ticket_total_refund, 'total' => $tenant->allow_refund() && (bool) $tenant->allow_ticket_total_refund,
}; };
if (! $isAllowed) { if (! $isAllowed) {
@@ -377,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

@@ -13,6 +13,10 @@ Route::prefix('v1/adminapp/tenant')
->whereNumber('ticket') ->whereNumber('ticket')
->middleware('tenant.menu:adminapp.tickets') ->middleware('tenant.menu:adminapp.tickets')
->name('adminapp.tickets.cancel'); ->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']) Route::post('tickets/{ticket}/refund', [TicketController::class, 'refund'])
->whereNumber('ticket') ->whereNumber('ticket')
->middleware('tenant.menu:adminapp.tickets') ->middleware('tenant.menu:adminapp.tickets')

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

@@ -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();

View File

@@ -18,12 +18,14 @@ class TenantRefundConfigurationTest extends TestCase
{ {
$tenant = $this->createTenant('refund-defaults'); $tenant = $this->createTenant('refund-defaults');
$this->assertFalse($tenant->allow_ticket_refund);
$this->assertFalse($tenant->allow_ticket_total_refund); $this->assertFalse($tenant->allow_ticket_total_refund);
$this->assertFalse($tenant->allow_ticket_partial_refund); $this->assertFalse($tenant->allow_ticket_partial_refund);
$this->assertSame('0.00', $tenant->ticket_partial_refund_percentage); $this->assertSame('0.00', $tenant->ticket_partial_refund_percentage);
$this->getJson("/api/tenants/{$tenant->codigo}") $this->getJson("/api/tenants/{$tenant->codigo}")
->assertOk() ->assertOk()
->assertJsonPath('data.allow_ticket_refund', false)
->assertJsonPath('data.allow_ticket_total_refund', false) ->assertJsonPath('data.allow_ticket_total_refund', false)
->assertJsonPath('data.allow_ticket_partial_refund', false) ->assertJsonPath('data.allow_ticket_partial_refund', false)
->assertJsonPath('data.ticket_partial_refund_percentage', '0.00'); ->assertJsonPath('data.ticket_partial_refund_percentage', '0.00');
@@ -34,17 +36,20 @@ class TenantRefundConfigurationTest extends TestCase
$tenant = $this->createTenant('refund-update'); $tenant = $this->createTenant('refund-update');
$this->putJson("/api/tenants/{$tenant->codigo}", [ $this->putJson("/api/tenants/{$tenant->codigo}", [
'allow_ticket_refund' => true,
'allow_ticket_total_refund' => true, 'allow_ticket_total_refund' => true,
'allow_ticket_partial_refund' => true, 'allow_ticket_partial_refund' => true,
'ticket_partial_refund_percentage' => 25.50, 'ticket_partial_refund_percentage' => 25.50,
]) ])
->assertOk() ->assertOk()
->assertJsonPath('data.allow_ticket_refund', true)
->assertJsonPath('data.allow_ticket_total_refund', true) ->assertJsonPath('data.allow_ticket_total_refund', true)
->assertJsonPath('data.allow_ticket_partial_refund', true) ->assertJsonPath('data.allow_ticket_partial_refund', true)
->assertJsonPath('data.ticket_partial_refund_percentage', '25.50'); ->assertJsonPath('data.ticket_partial_refund_percentage', '25.50');
$this->assertDatabaseHas('tenants', [ $this->assertDatabaseHas('tenants', [
'id' => $tenant->id, 'id' => $tenant->id,
'allow_ticket_refund' => true,
'allow_ticket_total_refund' => true, 'allow_ticket_total_refund' => true,
'allow_ticket_partial_refund' => true, 'allow_ticket_partial_refund' => true,
'ticket_partial_refund_percentage' => 25.50, 'ticket_partial_refund_percentage' => 25.50,
@@ -64,6 +69,7 @@ class TenantRefundConfigurationTest extends TestCase
public function test_tenant_allow_refund_logic(): void public function test_tenant_allow_refund_logic(): void
{ {
$tenant = new Tenant([ $tenant = new Tenant([
'allow_ticket_refund' => false,
'allow_ticket_total_refund' => false, 'allow_ticket_total_refund' => false,
'allow_ticket_partial_refund' => false, 'allow_ticket_partial_refund' => false,
'ticket_partial_refund_percentage' => 0, 'ticket_partial_refund_percentage' => 0,
@@ -83,6 +89,10 @@ class TenantRefundConfigurationTest extends TestCase
// Partial refund enabled and percentage is set // Partial refund enabled and percentage is set
$tenant->ticket_partial_refund_percentage = 25.50; $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->allow_refund());
$this->assertTrue($tenant->allowRefund()); $this->assertTrue($tenant->allowRefund());
$this->assertTrue($tenant->allow_refund); $this->assertTrue($tenant->allow_refund);
@@ -101,6 +111,13 @@ class TenantRefundConfigurationTest extends TestCase
$tenant->ticket_partial_refund_percentage = 50.00; $tenant->ticket_partial_refund_percentage = 50.00;
$this->assertTrue($tenant->allow_refund()); $this->assertTrue($tenant->allow_refund());
$this->assertTrue($tenant->allow_partial_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 private function createTenant(string $code): Tenant

View File

@@ -100,7 +100,10 @@ class AdminAppTicketControllerTest extends TestCase
->assertJsonPath('data.0.can_refund', false); ->assertJsonPath('data.0.can_refund', false);
// Total refund allowed // Total refund allowed
$tenant->update(['allow_ticket_total_refund' => true]); $tenant->update([
'allow_ticket_refund' => true,
'allow_ticket_total_refund' => true,
]);
$this->getJson('/api/v1/adminapp/tenant/tickets') $this->getJson('/api/v1/adminapp/tenant/tickets')
->assertOk() ->assertOk()
->assertJsonPath('data.0.allow_refund', true) ->assertJsonPath('data.0.allow_refund', true)
@@ -108,6 +111,7 @@ class AdminAppTicketControllerTest extends TestCase
// Partial refund allowed with percentage set // Partial refund allowed with percentage set
$tenant->update([ $tenant->update([
'allow_ticket_refund' => true,
'allow_ticket_total_refund' => false, 'allow_ticket_total_refund' => false,
'allow_ticket_partial_refund' => true, 'allow_ticket_partial_refund' => true,
'ticket_partial_refund_percentage' => 20.00, 'ticket_partial_refund_percentage' => 20.00,
@@ -117,6 +121,17 @@ class AdminAppTicketControllerTest extends TestCase
->assertJsonPath('data.0.allow_refund', true) ->assertJsonPath('data.0.allow_refund', true)
->assertJsonPath('data.0.can_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 // Partial refund enabled but percentage is 0
$tenant->update([ $tenant->update([
'ticket_partial_refund_percentage' => 0, 'ticket_partial_refund_percentage' => 0,
@@ -162,7 +177,10 @@ class AdminAppTicketControllerTest extends TestCase
public function test_it_totally_refunds_a_ticket_when_the_tenant_allows_it(): void public function test_it_totally_refunds_a_ticket_when_the_tenant_allows_it(): void
{ {
$tenant = $this->createTenant('ticket-total-refund'); $tenant = $this->createTenant('ticket-total-refund');
$tenant->update(['allow_ticket_total_refund' => true]); $tenant->update([
'allow_ticket_refund' => true,
'allow_ticket_total_refund' => true,
]);
$admin = $this->createAdminAppUser($tenant); $admin = $this->createAdminAppUser($tenant);
$this->grantTicketsMenu($tenant); $this->grantTicketsMenu($tenant);
Sanctum::actingAs($admin); Sanctum::actingAs($admin);
@@ -184,6 +202,7 @@ class AdminAppTicketControllerTest extends TestCase
{ {
$tenant = $this->createTenant('ticket-partial-refund'); $tenant = $this->createTenant('ticket-partial-refund');
$tenant->update([ $tenant->update([
'allow_ticket_refund' => true,
'allow_ticket_partial_refund' => true, 'allow_ticket_partial_refund' => true,
'ticket_partial_refund_percentage' => 25.50, 'ticket_partial_refund_percentage' => 25.50,
]); ]);
@@ -235,6 +254,113 @@ class AdminAppTicketControllerTest extends TestCase
->assertJsonValidationErrors('refund_type'); ->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');
@@ -410,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

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

@@ -67,6 +67,7 @@ class TicketTest extends TestCase
public function test_it_exposes_admin_action_capabilities(): void public function test_it_exposes_admin_action_capabilities(): void
{ {
$tenant = new Tenant([ $tenant = new Tenant([
'allow_ticket_refund' => true,
'allow_ticket_total_refund' => true, 'allow_ticket_total_refund' => true,
]); ]);
$active = (new Ticket)->setRelation('tenant', $tenant); $active = (new Ticket)->setRelation('tenant', $tenant);