Compare commits
22 Commits
dev
...
feature/re
| Author | SHA1 | Date | |
|---|---|---|---|
| 9c14153199 | |||
| 756f4dad0a | |||
| 205d77bc0b | |||
| 4f7ede1072 | |||
| 4bb4f526e4 | |||
| c0c19c9c01 | |||
| b4da6e3747 | |||
| 1880fc8147 | |||
| 96df431d60 | |||
| 106cf017dc | |||
| d5fdae9a24 | |||
| 4abb6c67fd | |||
| 6384c0046d | |||
| 2ddb046c26 | |||
| 5d00dc439e | |||
| 210c854fee | |||
| beb5d18b29 | |||
| de259f4286 | |||
| f19bca64d0 | |||
| 18f739b712 | |||
| 1564985259 | |||
| 471a941587 |
@@ -45,6 +45,7 @@ COMMANDS_LOG_LEVEL=info
|
|||||||
COMMANDS_LOG_DAYS=30
|
COMMANDS_LOG_DAYS=30
|
||||||
EMAILS_LOG_LEVEL=info
|
EMAILS_LOG_LEVEL=info
|
||||||
EMAILS_LOG_DAYS=30
|
EMAILS_LOG_DAYS=30
|
||||||
|
EMAIL_DELIVERY_LEASE_SECONDS=300
|
||||||
|
|
||||||
DB_CONNECTION=mysql
|
DB_CONNECTION=mysql
|
||||||
DB_HOST=127.0.0.1
|
DB_HOST=127.0.0.1
|
||||||
|
|||||||
@@ -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,
|
||||||
|
)
|
||||||
|
);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
12
app/Domains/Event/Enums/EventDateStatus.php
Normal file
12
app/Domains/Event/Enums/EventDateStatus.php
Normal 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';
|
||||||
|
}
|
||||||
22
app/Domains/Event/Events/EventDateRescheduled.php
Normal file
22
app/Domains/Event/Events/EventDateRescheduled.php
Normal file
@@ -0,0 +1,22 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Domains\Event\Events;
|
||||||
|
|
||||||
|
use Illuminate\Foundation\Events\Dispatchable;
|
||||||
|
|
||||||
|
class EventDateRescheduled
|
||||||
|
{
|
||||||
|
use Dispatchable;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param list<array{purchase_id: int, ticket_ids: list<int>}> $purchaseTickets
|
||||||
|
*/
|
||||||
|
public function __construct(
|
||||||
|
public readonly string $tenantCode,
|
||||||
|
public readonly int $sourceEventDateId,
|
||||||
|
public readonly int $destinationEventDateId,
|
||||||
|
public readonly string $previousDate,
|
||||||
|
public readonly string $newDate,
|
||||||
|
public readonly array $purchaseTickets,
|
||||||
|
) {}
|
||||||
|
}
|
||||||
20
app/Domains/Event/Events/EventDateSuspended.php
Normal file
20
app/Domains/Event/Events/EventDateSuspended.php
Normal file
@@ -0,0 +1,20 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Domains\Event\Events;
|
||||||
|
|
||||||
|
use Illuminate\Foundation\Events\Dispatchable;
|
||||||
|
|
||||||
|
class EventDateSuspended
|
||||||
|
{
|
||||||
|
use Dispatchable;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param list<array{purchase_id: int, ticket_ids: list<int>}> $purchaseTickets
|
||||||
|
*/
|
||||||
|
public function __construct(
|
||||||
|
public readonly string $tenantCode,
|
||||||
|
public readonly int $eventDateId,
|
||||||
|
public readonly string $date,
|
||||||
|
public readonly array $purchaseTickets,
|
||||||
|
) {}
|
||||||
|
}
|
||||||
@@ -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')
|
||||||
),
|
),
|
||||||
]);
|
]);
|
||||||
}
|
}
|
||||||
|
|||||||
21
app/Domains/Event/Requests/RescheduleEventDateRequest.php
Normal file
21
app/Domains/Event/Requests/RescheduleEventDateRequest.php
Normal 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'],
|
||||||
|
];
|
||||||
|
}
|
||||||
|
}
|
||||||
23
app/Domains/Event/Requests/StoreEventDateRequest.php
Normal file
23
app/Domains/Event/Requests/StoreEventDateRequest.php
Normal 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'],
|
||||||
|
];
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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.'
|
||||||
|
);
|
||||||
|
}
|
||||||
},
|
},
|
||||||
];
|
];
|
||||||
}
|
}
|
||||||
|
|||||||
28
app/Domains/Event/Resources/EventDateResource.php
Normal file
28
app/Domains/Event/Resources/EventDateResource.php
Normal 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(),
|
||||||
|
];
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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,
|
||||||
|
|||||||
@@ -0,0 +1,57 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Domains\Event\Services;
|
||||||
|
|
||||||
|
use App\Domains\Purchase\Models\Purchase;
|
||||||
|
use App\Domains\Tenant\Models\Tenant;
|
||||||
|
use App\Domains\Ticket\Models\Ticket;
|
||||||
|
use App\Domains\Ticket\Services\TicketValidityResolver;
|
||||||
|
use Illuminate\Database\Eloquent\Builder;
|
||||||
|
use Illuminate\Support\Collection;
|
||||||
|
|
||||||
|
class AffectedEventDatePurchaseResolver
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* Finds active tickets belonging to paid purchases before an event-date mutation.
|
||||||
|
*
|
||||||
|
* @param Collection<int, int>|list<int> $eventDateIds
|
||||||
|
* @return list<array{purchase_id: int, ticket_ids: list<int>}>
|
||||||
|
*/
|
||||||
|
public function resolve(Tenant $tenant, Collection|array $eventDateIds): array
|
||||||
|
{
|
||||||
|
$eventDateIds = collect($eventDateIds)->map(fn (mixed $id): int => (int) $id)->unique()->values();
|
||||||
|
|
||||||
|
if ($eventDateIds->isEmpty()) {
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @var Collection<int, Ticket> $tickets */
|
||||||
|
$tickets = Ticket::query()
|
||||||
|
->where('tenant_code', $tenant->codigo)
|
||||||
|
->whereHas('sourcePurchaseItem.purchase', fn (Builder $query) => $query
|
||||||
|
->where('status', Purchase::STATUS_PAID))
|
||||||
|
->whereHas('sourceVariant', function (Builder $query) use ($eventDateIds): void {
|
||||||
|
$query->whereIn('event_date_id', $eventDateIds)
|
||||||
|
->orWhereHas('eventDates', fn (Builder $eventDates) => $eventDates
|
||||||
|
->whereIn('event_dates.id', $eventDateIds));
|
||||||
|
})
|
||||||
|
->with([
|
||||||
|
...TicketValidityResolver::RELATIONS,
|
||||||
|
'sourcePurchaseItem.purchase',
|
||||||
|
])
|
||||||
|
->get()
|
||||||
|
->filter(fn (Ticket $ticket): bool => $ticket->is_active())
|
||||||
|
->values();
|
||||||
|
|
||||||
|
return $tickets
|
||||||
|
->groupBy(fn (Ticket $ticket): int => (int) $ticket->sourcePurchaseItem->purchase->getKey())
|
||||||
|
->map(function (Collection $purchaseTickets): array {
|
||||||
|
return [
|
||||||
|
'purchase_id' => (int) $purchaseTickets->first()->sourcePurchaseItem->purchase->getKey(),
|
||||||
|
'ticket_ids' => $purchaseTickets->modelKeys(),
|
||||||
|
];
|
||||||
|
})
|
||||||
|
->values()
|
||||||
|
->all();
|
||||||
|
}
|
||||||
|
}
|
||||||
37
app/Domains/Event/Services/EffectiveEventDateResolver.php
Normal file
37
app/Domains/Event/Services/EffectiveEventDateResolver.php
Normal 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;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -2,7 +2,13 @@
|
|||||||
|
|
||||||
namespace App\Domains\Event\Services;
|
namespace App\Domains\Event\Services;
|
||||||
|
|
||||||
|
use App\Domains\Catalog\Models\Variant;
|
||||||
|
use App\Domains\Event\Events\EventDateRescheduled;
|
||||||
|
use App\Domains\Event\Events\EventDateSuspended;
|
||||||
|
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\Collection;
|
||||||
use Illuminate\Support\Facades\DB;
|
use Illuminate\Support\Facades\DB;
|
||||||
use Illuminate\Validation\ValidationException;
|
use Illuminate\Validation\ValidationException;
|
||||||
|
|
||||||
@@ -14,6 +20,11 @@ class EventService
|
|||||||
'facebook_url' => 'facebook',
|
'facebook_url' => 'facebook',
|
||||||
];
|
];
|
||||||
|
|
||||||
|
public function __construct(
|
||||||
|
private readonly EffectiveEventDateResolver $effectiveEventDateResolver,
|
||||||
|
private readonly AffectedEventDatePurchaseResolver $affectedPurchaseResolver,
|
||||||
|
) {}
|
||||||
|
|
||||||
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 +38,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 +56,217 @@ 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.'],
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
|
$purchaseTickets = $this->affectedPurchaseResolver->resolve(
|
||||||
|
$tenant,
|
||||||
|
$this->affectedDateIds($tenant, $source),
|
||||||
|
);
|
||||||
|
$source->update(['rescheduled_to_event_date_id' => $destination->getKey()]);
|
||||||
|
|
||||||
|
EventDateRescheduled::dispatch(
|
||||||
|
$tenant->codigo,
|
||||||
|
$source->getKey(),
|
||||||
|
$destination->getKey(),
|
||||||
|
$source->date->format('d/m/Y'),
|
||||||
|
$destination->date->format('d/m/Y'),
|
||||||
|
$purchaseTickets,
|
||||||
|
);
|
||||||
|
|
||||||
|
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');
|
||||||
|
}
|
||||||
|
|
||||||
|
$purchaseTickets = $this->affectedPurchaseResolver->resolve(
|
||||||
|
$tenant,
|
||||||
|
$this->affectedDateIds($tenant, $date),
|
||||||
|
);
|
||||||
|
$date->update(['suspended_at' => now()]);
|
||||||
|
$this->disableTicketsWithoutUsableDates($tenant, $date);
|
||||||
|
|
||||||
|
EventDateSuspended::dispatch(
|
||||||
|
$tenant->codigo,
|
||||||
|
$date->getKey(),
|
||||||
|
$date->date->format('d/m/Y'),
|
||||||
|
$purchaseTickets,
|
||||||
|
);
|
||||||
|
|
||||||
|
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
|
/** @return Collection<int, int> */
|
||||||
->selectedByVariants()
|
private function affectedDateIds(Tenant $tenant, EventDate $eventDate): Collection
|
||||||
->whereHas('sourceTickets')
|
{
|
||||||
->exists()
|
$affectedDateIds = collect([$eventDate->getKey()]);
|
||||||
|| $eventDate->variants()->whereHas('sourceTickets')->exists())) {
|
$frontier = $affectedDateIds;
|
||||||
throw ValidationException::withMessages([
|
|
||||||
'dates' => ['No se puede eliminar una fecha utilizada por tickets generados.'],
|
while ($frontier->isNotEmpty()) {
|
||||||
]);
|
$predecessors = $tenant->eventDates()
|
||||||
|
->whereIn('rescheduled_to_event_date_id', $frontier)
|
||||||
|
->pluck('id')
|
||||||
|
->diff($affectedDateIds)
|
||||||
|
->values();
|
||||||
|
$affectedDateIds = $affectedDateIds->merge($predecessors)->unique()->values();
|
||||||
|
$frontier = $predecessors;
|
||||||
}
|
}
|
||||||
|
|
||||||
$datesToDelete->each->delete();
|
return $affectedDateIds;
|
||||||
$tenant->unsetRelation('eventDates');
|
}
|
||||||
|
|
||||||
|
private function disableTicketsWithoutUsableDates(Tenant $tenant, EventDate $suspendedDate): void
|
||||||
|
{
|
||||||
|
$affectedDateIds = $this->affectedDateIds($tenant, $suspendedDate);
|
||||||
|
|
||||||
|
$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 */
|
||||||
|
|||||||
@@ -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']);
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -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'],
|
|
||||||
],
|
|
||||||
],
|
],
|
||||||
];
|
];
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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'],
|
||||||
|
|||||||
@@ -0,0 +1,32 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Domains\Notification\Listeners;
|
||||||
|
|
||||||
|
use App\Domains\Event\Events\EventDateRescheduled;
|
||||||
|
use App\Domains\Notification\Services\NotificationMailService;
|
||||||
|
use Illuminate\Contracts\Queue\ShouldQueueAfterCommit;
|
||||||
|
use Illuminate\Queue\InteractsWithQueue;
|
||||||
|
|
||||||
|
class SendEventDateRescheduledEmails implements ShouldQueueAfterCommit
|
||||||
|
{
|
||||||
|
use InteractsWithQueue;
|
||||||
|
|
||||||
|
public string $queue = 'emails';
|
||||||
|
|
||||||
|
public int $tries = 3;
|
||||||
|
|
||||||
|
/** @var array<int, int> */
|
||||||
|
public array $backoff = [30, 120, 300];
|
||||||
|
|
||||||
|
public function handle(EventDateRescheduled $event): void
|
||||||
|
{
|
||||||
|
app(NotificationMailService::class)->sendEventDateRescheduled(
|
||||||
|
$event->tenantCode,
|
||||||
|
$event->sourceEventDateId,
|
||||||
|
$event->destinationEventDateId,
|
||||||
|
$event->previousDate,
|
||||||
|
$event->newDate,
|
||||||
|
$event->purchaseTickets,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,30 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Domains\Notification\Listeners;
|
||||||
|
|
||||||
|
use App\Domains\Event\Events\EventDateSuspended;
|
||||||
|
use App\Domains\Notification\Services\NotificationMailService;
|
||||||
|
use Illuminate\Contracts\Queue\ShouldQueueAfterCommit;
|
||||||
|
use Illuminate\Queue\InteractsWithQueue;
|
||||||
|
|
||||||
|
class SendEventDateSuspendedEmails implements ShouldQueueAfterCommit
|
||||||
|
{
|
||||||
|
use InteractsWithQueue;
|
||||||
|
|
||||||
|
public string $queue = 'emails';
|
||||||
|
|
||||||
|
public int $tries = 3;
|
||||||
|
|
||||||
|
/** @var array<int, int> */
|
||||||
|
public array $backoff = [30, 120, 300];
|
||||||
|
|
||||||
|
public function handle(EventDateSuspended $event): void
|
||||||
|
{
|
||||||
|
app(NotificationMailService::class)->sendEventDateSuspended(
|
||||||
|
$event->tenantCode,
|
||||||
|
$event->eventDateId,
|
||||||
|
$event->date,
|
||||||
|
$event->purchaseTickets,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
44
app/Domains/Notification/Models/EmailDelivery.php
Normal file
44
app/Domains/Notification/Models/EmailDelivery.php
Normal file
@@ -0,0 +1,44 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Domains\Notification\Models;
|
||||||
|
|
||||||
|
use Illuminate\Database\Eloquent\Attributes\Fillable;
|
||||||
|
use Illuminate\Database\Eloquent\Model;
|
||||||
|
|
||||||
|
#[Fillable([
|
||||||
|
'idempotency_key',
|
||||||
|
'email_type',
|
||||||
|
'tenant_code',
|
||||||
|
'status',
|
||||||
|
'attempts',
|
||||||
|
'context',
|
||||||
|
'recipient_fingerprint',
|
||||||
|
'claim_token',
|
||||||
|
'claimed_at',
|
||||||
|
'lease_expires_at',
|
||||||
|
'sent_at',
|
||||||
|
'failed_at',
|
||||||
|
'last_error',
|
||||||
|
])]
|
||||||
|
class EmailDelivery extends Model
|
||||||
|
{
|
||||||
|
public const STATUS_PENDING = 'pending';
|
||||||
|
|
||||||
|
public const STATUS_PROCESSING = 'processing';
|
||||||
|
|
||||||
|
public const STATUS_SENT = 'sent';
|
||||||
|
|
||||||
|
public const STATUS_FAILED = 'failed';
|
||||||
|
|
||||||
|
protected function casts(): array
|
||||||
|
{
|
||||||
|
return [
|
||||||
|
'attempts' => 'integer',
|
||||||
|
'context' => 'array',
|
||||||
|
'claimed_at' => 'datetime',
|
||||||
|
'lease_expires_at' => 'datetime',
|
||||||
|
'sent_at' => 'datetime',
|
||||||
|
'failed_at' => 'datetime',
|
||||||
|
];
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,112 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Domains\Notification\Services;
|
||||||
|
|
||||||
|
use App\Domains\Notification\Models\EmailDelivery;
|
||||||
|
use Closure;
|
||||||
|
use Illuminate\Database\Query\Expression;
|
||||||
|
use Illuminate\Support\Str;
|
||||||
|
use Throwable;
|
||||||
|
|
||||||
|
class IdempotentEmailDeliveryService
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* @param array<string, mixed> $context
|
||||||
|
* @param Closure(): void $send
|
||||||
|
*/
|
||||||
|
public function sendOnce(
|
||||||
|
string $key,
|
||||||
|
string $type,
|
||||||
|
?string $tenantCode,
|
||||||
|
array $context,
|
||||||
|
string $recipient,
|
||||||
|
Closure $send,
|
||||||
|
): bool {
|
||||||
|
$now = now();
|
||||||
|
|
||||||
|
EmailDelivery::query()->insertOrIgnore([
|
||||||
|
'idempotency_key' => $key,
|
||||||
|
'email_type' => $type,
|
||||||
|
'tenant_code' => $tenantCode,
|
||||||
|
'status' => EmailDelivery::STATUS_PENDING,
|
||||||
|
'attempts' => 0,
|
||||||
|
'context' => json_encode($context, JSON_THROW_ON_ERROR),
|
||||||
|
'recipient_fingerprint' => $this->recipientFingerprint($recipient),
|
||||||
|
'created_at' => $now,
|
||||||
|
'updated_at' => $now,
|
||||||
|
]);
|
||||||
|
|
||||||
|
$claimToken = (string) Str::uuid();
|
||||||
|
$leaseExpiresAt = $now->copy()->addSeconds(
|
||||||
|
max(1, (int) config('mail.delivery_lease_seconds', 300)),
|
||||||
|
);
|
||||||
|
|
||||||
|
$claimed = EmailDelivery::query()
|
||||||
|
->where('idempotency_key', $key)
|
||||||
|
->where(function ($query) use ($now): void {
|
||||||
|
$query->whereIn('status', [
|
||||||
|
EmailDelivery::STATUS_PENDING,
|
||||||
|
EmailDelivery::STATUS_FAILED,
|
||||||
|
])->orWhere(function ($query) use ($now): void {
|
||||||
|
$query->where('status', EmailDelivery::STATUS_PROCESSING)
|
||||||
|
->where('lease_expires_at', '<=', $now);
|
||||||
|
});
|
||||||
|
})
|
||||||
|
->update([
|
||||||
|
'status' => EmailDelivery::STATUS_PROCESSING,
|
||||||
|
'attempts' => new Expression('attempts + 1'),
|
||||||
|
'context' => json_encode($context, JSON_THROW_ON_ERROR),
|
||||||
|
'recipient_fingerprint' => $this->recipientFingerprint($recipient),
|
||||||
|
'claim_token' => $claimToken,
|
||||||
|
'claimed_at' => $now,
|
||||||
|
'lease_expires_at' => $leaseExpiresAt,
|
||||||
|
'failed_at' => null,
|
||||||
|
'last_error' => null,
|
||||||
|
'updated_at' => $now,
|
||||||
|
]) === 1;
|
||||||
|
|
||||||
|
if (! $claimed) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
$send();
|
||||||
|
|
||||||
|
EmailDelivery::query()
|
||||||
|
->where('idempotency_key', $key)
|
||||||
|
->where('claim_token', $claimToken)
|
||||||
|
->update([
|
||||||
|
'status' => EmailDelivery::STATUS_SENT,
|
||||||
|
'claim_token' => null,
|
||||||
|
'lease_expires_at' => null,
|
||||||
|
'sent_at' => now(),
|
||||||
|
'updated_at' => now(),
|
||||||
|
]);
|
||||||
|
} catch (Throwable $exception) {
|
||||||
|
EmailDelivery::query()
|
||||||
|
->where('idempotency_key', $key)
|
||||||
|
->where('claim_token', $claimToken)
|
||||||
|
->update([
|
||||||
|
'status' => EmailDelivery::STATUS_FAILED,
|
||||||
|
'claim_token' => null,
|
||||||
|
'lease_expires_at' => null,
|
||||||
|
'failed_at' => now(),
|
||||||
|
'last_error' => Str::limit($exception::class, 2000, ''),
|
||||||
|
'updated_at' => now(),
|
||||||
|
]);
|
||||||
|
|
||||||
|
throw $exception;
|
||||||
|
}
|
||||||
|
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
private function recipientFingerprint(string $recipient): string
|
||||||
|
{
|
||||||
|
return hash_hmac(
|
||||||
|
'sha256',
|
||||||
|
mb_strtolower(trim($recipient)),
|
||||||
|
(string) config('app.key'),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -11,6 +11,7 @@ use App\Domains\Tenant\Models\Tenant;
|
|||||||
use App\Domains\Ticket\Models\Ticket;
|
use App\Domains\Ticket\Models\Ticket;
|
||||||
use App\Domains\Ticket\Services\TicketPdfService;
|
use App\Domains\Ticket\Services\TicketPdfService;
|
||||||
use App\Domains\Ticket\Services\TicketPresentationResolver;
|
use App\Domains\Ticket\Services\TicketPresentationResolver;
|
||||||
|
use App\Domains\Ticket\Services\TicketValidityResolver;
|
||||||
use Closure;
|
use Closure;
|
||||||
use Illuminate\Support\Collection;
|
use Illuminate\Support\Collection;
|
||||||
use Illuminate\Support\Facades\Log;
|
use Illuminate\Support\Facades\Log;
|
||||||
@@ -21,32 +22,42 @@ class NotificationMailService
|
|||||||
public function __construct(
|
public function __construct(
|
||||||
private readonly MailService $mailService,
|
private readonly MailService $mailService,
|
||||||
private readonly TicketPdfService $ticketPdfService,
|
private readonly TicketPdfService $ticketPdfService,
|
||||||
|
private readonly IdempotentEmailDeliveryService $emailDeliveryService,
|
||||||
) {}
|
) {}
|
||||||
|
|
||||||
public function sendWelcome(int $userId, string $tenantCode): void
|
public function sendWelcome(int $userId, string $tenantCode): void
|
||||||
{
|
{
|
||||||
$this->sendLogged('welcome', [
|
$context = [
|
||||||
'user_id' => $userId,
|
'user_id' => $userId,
|
||||||
'tenant_code' => $tenantCode,
|
'tenant_code' => $tenantCode,
|
||||||
], function () use ($userId, $tenantCode): array {
|
];
|
||||||
$tenant = Tenant::query()->with('websiteType')->where('codigo', $tenantCode)->firstOrFail();
|
$tenant = Tenant::query()->with('websiteType')->where('codigo', $tenantCode)->firstOrFail();
|
||||||
$user = User::query()->findOrFail($userId);
|
$user = User::query()->findOrFail($userId);
|
||||||
$brand = $tenant->websiteType ?? $tenant;
|
|
||||||
$tenantUrl = 'https://'.$tenant->dominio.$tenant->base_path;
|
|
||||||
|
|
||||||
$this->mailService
|
$this->sendIdempotently(
|
||||||
->forTenant($tenantCode)
|
"welcome:{$tenantCode}:{$userId}",
|
||||||
->send(
|
'welcome',
|
||||||
$user->email,
|
$tenantCode,
|
||||||
"Bienvenido a {$brand->nombre}",
|
$context,
|
||||||
view('mail.notifications.welcome', compact('brand', 'user', 'tenantUrl'))->render(),
|
$user->email,
|
||||||
$brand,
|
function () use ($user, $tenant, $tenantCode): array {
|
||||||
);
|
$brand = $tenant->websiteType ?? $tenant;
|
||||||
|
$tenantUrl = 'https://'.$tenant->dominio.$tenant->base_path;
|
||||||
|
|
||||||
return [
|
$this->mailService
|
||||||
'brand_type' => $tenant->websiteType === null ? 'tenant' : 'website_type',
|
->forTenant($tenantCode)
|
||||||
];
|
->send(
|
||||||
});
|
$user->email,
|
||||||
|
"Bienvenido a {$brand->nombre}",
|
||||||
|
view('mail.notifications.welcome', compact('brand', 'user', 'tenantUrl'))->render(),
|
||||||
|
$brand,
|
||||||
|
);
|
||||||
|
|
||||||
|
return [
|
||||||
|
'brand_type' => $tenant->websiteType === null ? 'tenant' : 'website_type',
|
||||||
|
];
|
||||||
|
},
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
public function sendPasswordResetCode(
|
public function sendPasswordResetCode(
|
||||||
@@ -60,128 +71,356 @@ class NotificationMailService
|
|||||||
'channel' => $channel,
|
'channel' => $channel,
|
||||||
];
|
];
|
||||||
|
|
||||||
$this->sendLogged('password_reset', $context, function () use ($attemptId, $tenantCode, $channel, $context): ?array {
|
$tenant = Tenant::query()
|
||||||
$tenant = Tenant::query()
|
->with('websiteType')
|
||||||
->with('websiteType')
|
->where('codigo', $tenantCode)
|
||||||
->where('codigo', $tenantCode)
|
->firstOrFail();
|
||||||
->firstOrFail();
|
$attempt = ResetPasswordAttempt::query()
|
||||||
$attempt = ResetPasswordAttempt::query()
|
->with('user')
|
||||||
->with('user')
|
->findOrFail($attemptId);
|
||||||
->findOrFail($attemptId);
|
|
||||||
|
|
||||||
if ($attempt->status !== ResetPasswordAttempt::STATUS_PENDING) {
|
if ($attempt->status !== ResetPasswordAttempt::STATUS_PENDING) {
|
||||||
$this->logSkipped('password_reset', array_merge($context, [
|
$this->logSkipped('password_reset', array_merge($context, [
|
||||||
'reason' => 'attempt_not_pending',
|
'reason' => 'attempt_not_pending',
|
||||||
'attempt_status' => $attempt->status,
|
'attempt_status' => $attempt->status,
|
||||||
'user_id' => $attempt->user_id,
|
|
||||||
]));
|
|
||||||
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
$recoveryDomain = match ($channel) {
|
|
||||||
PasswordResetRequested::CHANNEL_ADMINAPP => $tenant->websiteType?->dominio,
|
|
||||||
PasswordResetRequested::CHANNEL_SCANNER => $tenant->websiteType?->scanner_domain,
|
|
||||||
default => $tenant->dominio,
|
|
||||||
};
|
|
||||||
$recoveryBasePath = $channel === PasswordResetRequested::CHANNEL_STOREFRONT
|
|
||||||
&& $tenant->base_path !== '/'
|
|
||||||
? $tenant->base_path
|
|
||||||
: '';
|
|
||||||
$recoveryQuery = ['email' => $attempt->user->email];
|
|
||||||
if (
|
|
||||||
$channel === PasswordResetRequested::CHANNEL_SCANNER
|
|
||||||
&& $attempt->reason === ResetPasswordAttempt::REASON_STAFF_CREATED
|
|
||||||
) {
|
|
||||||
$recoveryQuery['code'] = $attempt->codigo;
|
|
||||||
}
|
|
||||||
$recoveryUrl = $recoveryDomain === null
|
|
||||||
? null
|
|
||||||
: 'https://'.$recoveryDomain.$recoveryBasePath.'/recuperar-contrasena/codigo?'.http_build_query($recoveryQuery);
|
|
||||||
$brand = $tenant->websiteType ?? $tenant;
|
|
||||||
|
|
||||||
[$subject, $template] = match ($attempt->reason) {
|
|
||||||
ResetPasswordAttempt::REASON_STAFF_CREATED => [
|
|
||||||
'Tu cuenta de escáner está lista', 'scanner-created',
|
|
||||||
],
|
|
||||||
ResetPasswordAttempt::REASON_ADMINISTRATOR_CREATED => [
|
|
||||||
'Tu cuenta de administrador está lista', 'administrator-created',
|
|
||||||
],
|
|
||||||
ResetPasswordAttempt::REASON_ACCOUNT_LOCKED => [
|
|
||||||
'Desbloqueá tu cuenta', 'account-locked',
|
|
||||||
],
|
|
||||||
default => ['Código para recuperar tu contraseña', 'password-reset'],
|
|
||||||
};
|
|
||||||
|
|
||||||
$this->mailService
|
|
||||||
->forTenant($tenantCode)
|
|
||||||
->send(
|
|
||||||
$attempt->user->email,
|
|
||||||
"{$subject} - {$brand->nombre}",
|
|
||||||
view("mail.notifications.{$template}", [
|
|
||||||
'attempt' => $attempt,
|
|
||||||
'recoveryUrl' => $recoveryUrl,
|
|
||||||
'brand' => $brand,
|
|
||||||
])->render(),
|
|
||||||
$brand,
|
|
||||||
);
|
|
||||||
|
|
||||||
return [
|
|
||||||
'user_id' => $attempt->user_id,
|
'user_id' => $attempt->user_id,
|
||||||
'recovery_domain_available' => $recoveryDomain !== null,
|
]));
|
||||||
];
|
|
||||||
});
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
$this->sendIdempotently(
|
||||||
|
"password-reset:{$attemptId}",
|
||||||
|
'password_reset',
|
||||||
|
$tenantCode,
|
||||||
|
$context,
|
||||||
|
$attempt->user->email,
|
||||||
|
function () use ($attempt, $tenant, $tenantCode, $channel): array {
|
||||||
|
$recoveryDomain = match ($channel) {
|
||||||
|
PasswordResetRequested::CHANNEL_ADMINAPP => $tenant->websiteType?->dominio,
|
||||||
|
PasswordResetRequested::CHANNEL_SCANNER => $tenant->websiteType?->scanner_domain,
|
||||||
|
default => $tenant->dominio,
|
||||||
|
};
|
||||||
|
$recoveryBasePath = $channel === PasswordResetRequested::CHANNEL_STOREFRONT
|
||||||
|
&& $tenant->base_path !== '/'
|
||||||
|
? $tenant->base_path
|
||||||
|
: '';
|
||||||
|
$recoveryQuery = ['email' => $attempt->user->email];
|
||||||
|
if (
|
||||||
|
$channel === PasswordResetRequested::CHANNEL_SCANNER
|
||||||
|
&& $attempt->reason === ResetPasswordAttempt::REASON_STAFF_CREATED
|
||||||
|
) {
|
||||||
|
$recoveryQuery['code'] = $attempt->codigo;
|
||||||
|
}
|
||||||
|
$recoveryUrl = $recoveryDomain === null
|
||||||
|
? null
|
||||||
|
: 'https://'.$recoveryDomain.$recoveryBasePath.'/recuperar-contrasena/codigo?'.http_build_query($recoveryQuery);
|
||||||
|
$brand = $tenant->websiteType ?? $tenant;
|
||||||
|
|
||||||
|
[$subject, $template] = match ($attempt->reason) {
|
||||||
|
ResetPasswordAttempt::REASON_STAFF_CREATED => [
|
||||||
|
'Tu cuenta de escáner está lista', 'scanner-created',
|
||||||
|
],
|
||||||
|
ResetPasswordAttempt::REASON_ADMINISTRATOR_CREATED => [
|
||||||
|
'Tu cuenta de administrador está lista', 'administrator-created',
|
||||||
|
],
|
||||||
|
ResetPasswordAttempt::REASON_ACCOUNT_LOCKED => [
|
||||||
|
'Desbloqueá tu cuenta', 'account-locked',
|
||||||
|
],
|
||||||
|
default => ['Código para recuperar tu contraseña', 'password-reset'],
|
||||||
|
};
|
||||||
|
|
||||||
|
$this->mailService
|
||||||
|
->forTenant($tenantCode)
|
||||||
|
->send(
|
||||||
|
$attempt->user->email,
|
||||||
|
"{$subject} - {$brand->nombre}",
|
||||||
|
view("mail.notifications.{$template}", [
|
||||||
|
'attempt' => $attempt,
|
||||||
|
'recoveryUrl' => $recoveryUrl,
|
||||||
|
'brand' => $brand,
|
||||||
|
])->render(),
|
||||||
|
$brand,
|
||||||
|
);
|
||||||
|
|
||||||
|
return [
|
||||||
|
'user_id' => $attempt->user_id,
|
||||||
|
'recovery_domain_available' => $recoveryDomain !== null,
|
||||||
|
];
|
||||||
|
},
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
public function sendPurchaseConfirmed(int $purchaseId): void
|
public function sendPurchaseConfirmed(int $purchaseId): void
|
||||||
{
|
{
|
||||||
$context = ['purchase_id' => $purchaseId];
|
$context = ['purchase_id' => $purchaseId];
|
||||||
|
|
||||||
$this->sendLogged('purchase_confirmed', $context, function () use ($purchaseId, $context): ?array {
|
$purchase = Purchase::query()
|
||||||
$purchase = Purchase::query()
|
->with(['tenant', 'user', 'items'])
|
||||||
->with(['tenant', 'user', 'items'])
|
->find($purchaseId);
|
||||||
->find($purchaseId);
|
|
||||||
|
|
||||||
if ($purchase === null) {
|
if ($purchase === null) {
|
||||||
$this->logSkipped('purchase_confirmed', array_merge($context, [
|
$this->logSkipped('purchase_confirmed', array_merge($context, [
|
||||||
'reason' => 'purchase_not_found',
|
'reason' => 'purchase_not_found',
|
||||||
'missing_model' => Purchase::class,
|
'missing_model' => Purchase::class,
|
||||||
|
]));
|
||||||
|
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
$recipient = $this->recipientFor($purchase);
|
||||||
|
if ($recipient === '') {
|
||||||
|
$this->logSkipped('purchase_confirmed', array_merge($context, ['reason' => 'missing_recipient']));
|
||||||
|
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
$this->sendIdempotently(
|
||||||
|
"purchase-confirmed:{$purchaseId}",
|
||||||
|
'purchase_confirmed',
|
||||||
|
$purchase->tenant_codigo,
|
||||||
|
$context,
|
||||||
|
$recipient,
|
||||||
|
function () use ($purchase, $recipient): array {
|
||||||
|
/** @var Collection<int, Ticket> $tickets */
|
||||||
|
$tickets = $purchase->tickets()
|
||||||
|
->where('tenant_code', $purchase->tenant_codigo)
|
||||||
|
->with(TicketPresentationResolver::RELATIONS)
|
||||||
|
->get();
|
||||||
|
$attachments = $tickets->isEmpty()
|
||||||
|
? []
|
||||||
|
: [[
|
||||||
|
'data' => $this->ticketPdfService->contents($purchase->tenant, $tickets),
|
||||||
|
'name' => $this->ticketPdfService->filename($tickets),
|
||||||
|
'mime' => 'application/pdf',
|
||||||
|
]];
|
||||||
|
|
||||||
|
$this->mailService
|
||||||
|
->forTenant($purchase->tenant_codigo)
|
||||||
|
->send(
|
||||||
|
$recipient,
|
||||||
|
"Compra confirmada - Compra #{$purchase->getKey()}",
|
||||||
|
view('mail.notifications.purchase-confirmed', compact('purchase', 'tickets'))->render(),
|
||||||
|
attachments: $attachments,
|
||||||
|
);
|
||||||
|
|
||||||
|
return [
|
||||||
|
'tenant_code' => $purchase->tenant_codigo,
|
||||||
|
'user_id' => $purchase->user_id,
|
||||||
|
'purchase_status' => $purchase->status,
|
||||||
|
'purchase_item_count' => $purchase->items->count(),
|
||||||
|
'ticket_count' => $tickets->count(),
|
||||||
|
'ticket_ids' => $tickets->modelKeys(),
|
||||||
|
];
|
||||||
|
},
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param list<array{purchase_id: int, ticket_ids: list<int>}> $purchaseTickets
|
||||||
|
*/
|
||||||
|
public function sendEventDateRescheduled(
|
||||||
|
string $tenantCode,
|
||||||
|
int $sourceEventDateId,
|
||||||
|
int $destinationEventDateId,
|
||||||
|
string $previousDate,
|
||||||
|
string $newDate,
|
||||||
|
array $purchaseTickets,
|
||||||
|
): void {
|
||||||
|
foreach ($purchaseTickets as $purchaseTicketGroup) {
|
||||||
|
$purchaseId = $purchaseTicketGroup['purchase_id'];
|
||||||
|
$ticketIds = $purchaseTicketGroup['ticket_ids'];
|
||||||
|
$context = [
|
||||||
|
'tenant_code' => $tenantCode,
|
||||||
|
'event_date_id' => $sourceEventDateId,
|
||||||
|
'destination_event_date_id' => $destinationEventDateId,
|
||||||
|
'purchase_id' => $purchaseId,
|
||||||
|
'ticket_ids' => $ticketIds,
|
||||||
|
];
|
||||||
|
$purchase = $this->eventDateNotificationPurchase($tenantCode, $purchaseId);
|
||||||
|
|
||||||
|
if ($purchase === null || $purchase->status !== Purchase::STATUS_PAID) {
|
||||||
|
$this->logSkipped('event_date_rescheduled', array_merge($context, [
|
||||||
|
'reason' => 'purchase_not_paid_or_not_found',
|
||||||
]));
|
]));
|
||||||
|
|
||||||
return null;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
/** @var Collection<int, Ticket> $tickets */
|
/** @var Collection<int, Ticket> $tickets */
|
||||||
$tickets = $purchase->tickets()
|
$tickets = $purchase->tickets()
|
||||||
->where('tenant_code', $purchase->tenant_codigo)
|
->where('tenant_code', $tenantCode)
|
||||||
->with(TicketPresentationResolver::RELATIONS)
|
->whereKey($ticketIds)
|
||||||
->get();
|
->with([
|
||||||
$attachments = $tickets->isEmpty()
|
...TicketPresentationResolver::RELATIONS,
|
||||||
? []
|
...TicketValidityResolver::RELATIONS,
|
||||||
: [[
|
])
|
||||||
'data' => $this->ticketPdfService->contents($purchase->tenant, $tickets),
|
->get()
|
||||||
'name' => $this->ticketPdfService->filename($tickets),
|
->filter(fn (Ticket $ticket): bool => $ticket->is_active())
|
||||||
'mime' => 'application/pdf',
|
->values();
|
||||||
]];
|
|
||||||
|
|
||||||
$this->mailService
|
if ($tickets->isEmpty()) {
|
||||||
->forTenant($purchase->tenant_codigo)
|
$this->logSkipped('event_date_rescheduled', array_merge($context, [
|
||||||
->send(
|
'reason' => 'no_longer_active_tickets',
|
||||||
$this->recipientFor($purchase),
|
]));
|
||||||
"Compra confirmada - Compra #{$purchase->getKey()}",
|
|
||||||
view('mail.notifications.purchase-confirmed', compact('purchase', 'tickets'))->render(),
|
|
||||||
attachments: $attachments,
|
|
||||||
);
|
|
||||||
|
|
||||||
return [
|
continue;
|
||||||
'tenant_code' => $purchase->tenant_codigo,
|
}
|
||||||
'user_id' => $purchase->user_id,
|
|
||||||
'purchase_status' => $purchase->status,
|
$recipient = $this->recipientFor($purchase);
|
||||||
'purchase_item_count' => $purchase->items->count(),
|
if ($recipient === '') {
|
||||||
'ticket_count' => $tickets->count(),
|
$this->logSkipped('event_date_rescheduled', array_merge($context, [
|
||||||
'ticket_ids' => $tickets->modelKeys(),
|
'reason' => 'missing_recipient',
|
||||||
|
]));
|
||||||
|
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
$deliveryKey = "event-date-rescheduled:{$sourceEventDateId}:{$destinationEventDateId}:{$purchaseId}";
|
||||||
|
$this->sendIdempotently(
|
||||||
|
$deliveryKey,
|
||||||
|
'event_date_rescheduled',
|
||||||
|
$tenantCode,
|
||||||
|
$context,
|
||||||
|
$recipient,
|
||||||
|
function () use (
|
||||||
|
$tenantCode,
|
||||||
|
$purchase,
|
||||||
|
$recipient,
|
||||||
|
$previousDate,
|
||||||
|
$newDate,
|
||||||
|
$tickets,
|
||||||
|
): array {
|
||||||
|
$brand = $purchase->tenant->websiteType ?? $purchase->tenant;
|
||||||
|
|
||||||
|
$this->mailService
|
||||||
|
->forTenant($tenantCode)
|
||||||
|
->send(
|
||||||
|
$recipient,
|
||||||
|
"Tu evento fue reprogramado - Compra #{$purchase->getKey()}",
|
||||||
|
view('mail.notifications.event-date-rescheduled', compact(
|
||||||
|
'purchase', 'previousDate', 'newDate', 'tickets'
|
||||||
|
))->render(),
|
||||||
|
$brand,
|
||||||
|
);
|
||||||
|
|
||||||
|
return ['ticket_count' => $tickets->count()];
|
||||||
|
},
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param list<array{purchase_id: int, ticket_ids: list<int>}> $purchaseTickets
|
||||||
|
*/
|
||||||
|
public function sendEventDateSuspended(
|
||||||
|
string $tenantCode,
|
||||||
|
int $eventDateId,
|
||||||
|
string $date,
|
||||||
|
array $purchaseTickets,
|
||||||
|
): void {
|
||||||
|
foreach ($purchaseTickets as $purchaseTicketGroup) {
|
||||||
|
$purchaseId = $purchaseTicketGroup['purchase_id'];
|
||||||
|
$ticketIds = $purchaseTicketGroup['ticket_ids'];
|
||||||
|
$context = [
|
||||||
|
'tenant_code' => $tenantCode,
|
||||||
|
'event_date_id' => $eventDateId,
|
||||||
|
'purchase_id' => $purchaseId,
|
||||||
|
'ticket_ids' => $ticketIds,
|
||||||
];
|
];
|
||||||
});
|
$purchase = $this->eventDateNotificationPurchase($tenantCode, $purchaseId);
|
||||||
|
|
||||||
|
if ($purchase === null || $purchase->status !== Purchase::STATUS_PAID) {
|
||||||
|
$this->logSkipped('event_date_suspended', array_merge($context, [
|
||||||
|
'reason' => 'purchase_not_paid_or_not_found',
|
||||||
|
]));
|
||||||
|
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @var Collection<int, Ticket> $tickets */
|
||||||
|
$tickets = $purchase->tickets()
|
||||||
|
->where('tenant_code', $tenantCode)
|
||||||
|
->whereKey($ticketIds)
|
||||||
|
->with([
|
||||||
|
...TicketPresentationResolver::RELATIONS,
|
||||||
|
...TicketValidityResolver::RELATIONS,
|
||||||
|
])
|
||||||
|
->get()
|
||||||
|
->filter(fn (Ticket $ticket): bool => in_array($ticket->status, [
|
||||||
|
Ticket::STATUS_ACTIVE,
|
||||||
|
Ticket::STATUS_DISABLED,
|
||||||
|
], true))
|
||||||
|
->values();
|
||||||
|
|
||||||
|
if ($tickets->isEmpty()) {
|
||||||
|
$this->logSkipped('event_date_suspended', array_merge($context, [
|
||||||
|
'reason' => 'no_longer_relevant_tickets',
|
||||||
|
]));
|
||||||
|
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
$recipient = $this->recipientFor($purchase);
|
||||||
|
if ($recipient === '') {
|
||||||
|
$this->logSkipped('event_date_suspended', array_merge($context, [
|
||||||
|
'reason' => 'missing_recipient',
|
||||||
|
]));
|
||||||
|
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
$deliveryKey = "event-date-suspended:{$eventDateId}:{$purchaseId}";
|
||||||
|
$disabledTickets = $tickets
|
||||||
|
->filter(fn (Ticket $ticket): bool => $ticket->status === Ticket::STATUS_DISABLED)
|
||||||
|
->values();
|
||||||
|
$activeTickets = $tickets
|
||||||
|
->filter(fn (Ticket $ticket): bool => $ticket->status === Ticket::STATUS_ACTIVE)
|
||||||
|
->values();
|
||||||
|
|
||||||
|
$this->sendIdempotently(
|
||||||
|
$deliveryKey,
|
||||||
|
'event_date_suspended',
|
||||||
|
$tenantCode,
|
||||||
|
$context,
|
||||||
|
$recipient,
|
||||||
|
function () use (
|
||||||
|
$tenantCode,
|
||||||
|
$purchase,
|
||||||
|
$recipient,
|
||||||
|
$date,
|
||||||
|
$disabledTickets,
|
||||||
|
$activeTickets,
|
||||||
|
): array {
|
||||||
|
$brand = $purchase->tenant->websiteType ?? $purchase->tenant;
|
||||||
|
|
||||||
|
$this->mailService
|
||||||
|
->forTenant($tenantCode)
|
||||||
|
->send(
|
||||||
|
$recipient,
|
||||||
|
"Una fecha de tu evento fue suspendida - Compra #{$purchase->getKey()}",
|
||||||
|
view('mail.notifications.event-date-suspended', compact(
|
||||||
|
'purchase', 'date', 'disabledTickets', 'activeTickets'
|
||||||
|
))->render(),
|
||||||
|
$brand,
|
||||||
|
);
|
||||||
|
|
||||||
|
return [
|
||||||
|
'ticket_count' => $disabledTickets->count() + $activeTickets->count(),
|
||||||
|
'disabled_ticket_ids' => $disabledTickets->modelKeys(),
|
||||||
|
'active_ticket_ids' => $activeTickets->modelKeys(),
|
||||||
|
];
|
||||||
|
},
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private function eventDateNotificationPurchase(string $tenantCode, int $purchaseId): ?Purchase
|
||||||
|
{
|
||||||
|
return Purchase::query()
|
||||||
|
->where('tenant_codigo', $tenantCode)
|
||||||
|
->with(['tenant.websiteType', 'user'])
|
||||||
|
->find($purchaseId);
|
||||||
}
|
}
|
||||||
|
|
||||||
private function recipientFor(Purchase $purchase): string
|
private function recipientFor(Purchase $purchase): string
|
||||||
@@ -189,6 +428,34 @@ class NotificationMailService
|
|||||||
return (string) ($purchase->email ?: $purchase->user?->email);
|
return (string) ($purchase->email ?: $purchase->user?->email);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param array<string, mixed> $context
|
||||||
|
* @param Closure(): array<string, mixed> $send
|
||||||
|
*/
|
||||||
|
private function sendIdempotently(
|
||||||
|
string $key,
|
||||||
|
string $emailType,
|
||||||
|
?string $tenantCode,
|
||||||
|
array $context,
|
||||||
|
string $recipient,
|
||||||
|
Closure $send,
|
||||||
|
): void {
|
||||||
|
$sent = $this->emailDeliveryService->sendOnce(
|
||||||
|
$key,
|
||||||
|
$emailType,
|
||||||
|
$tenantCode,
|
||||||
|
$context,
|
||||||
|
$recipient,
|
||||||
|
function () use ($emailType, $context, $send): void {
|
||||||
|
$this->sendLogged($emailType, $context, $send);
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
if (! $sent) {
|
||||||
|
$this->logSkipped($emailType, array_merge($context, ['reason' => 'already_claimed']));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @param array<string, mixed> $context
|
* @param array<string, mixed> $context
|
||||||
* @param Closure(): (array<string, mixed>|null) $send
|
* @param Closure(): (array<string, mixed>|null) $send
|
||||||
|
|||||||
@@ -12,7 +12,19 @@ Orquesta notificaciones de negocio por correo a partir de eventos de otros domin
|
|||||||
|
|
||||||
## Componentes
|
## Componentes
|
||||||
|
|
||||||
Los listeners `SendWelcomeEmail`, `SendPasswordResetEmail` y `SendPurchaseConfirmedEmail` delegan en `NotificationMailService`. Este servicio carga el contexto necesario, renderiza las vistas y envía mediante `Integration/MailService`.
|
Los listeners delegan en `NotificationMailService`. Este servicio carga el contexto necesario, renderiza las vistas y envía mediante `Integration/MailService`.
|
||||||
|
|
||||||
|
`IdempotentEmailDeliveryService` coordina los envíos automáticos mediante la tabla
|
||||||
|
`email_deliveries`. Cada correo utiliza una clave de negocio única:
|
||||||
|
|
||||||
|
- bienvenida: `welcome:{tenant_code}:{user_id}`;
|
||||||
|
- recuperación: `password-reset:{attempt_id}`;
|
||||||
|
- compra confirmada: `purchase-confirmed:{purchase_id}`;
|
||||||
|
- reprogramación: `event-date-rescheduled:{source_event_date_id}:{destination_event_date_id}:{purchase_id}`;
|
||||||
|
- suspensión: `event-date-suspended:{event_date_id}:{purchase_id}`.
|
||||||
|
|
||||||
|
Los correos de prueba y de validación de una integración SMTP no usan esta capa,
|
||||||
|
porque su reenvío explícito es parte de su comportamiento esperado.
|
||||||
|
|
||||||
## API y dependencias
|
## API y dependencias
|
||||||
|
|
||||||
@@ -25,3 +37,12 @@ No expone rutas HTTP. Consume datos de `Auth`, `Tenant`, `Purchase` y `Ticket`,
|
|||||||
- Los correos de cuenta (bienvenida y recuperación de contraseña) usan la identidad visual del `WebsiteType` asociado al tenant, con fallback al tenant si no tiene uno configurado.
|
- Los correos de cuenta (bienvenida y recuperación de contraseña) usan la identidad visual del `WebsiteType` asociado al tenant, con fallback al tenant si no tiene uno configurado.
|
||||||
- El correo transaccional de compra confirmada usa la identidad visual del tenant y adjunta un único PDF cuando la compra generó tickets.
|
- El correo transaccional de compra confirmada usa la identidad visual del tenant y adjunta un único PDF cuando la compra generó tickets.
|
||||||
- Los handlers deben permanecer idempotentes o tolerantes a reintentos de cola.
|
- Los handlers deben permanecer idempotentes o tolerantes a reintentos de cola.
|
||||||
|
- Una entrega queda en estado `processing` mientras un worker posee su claim. Si
|
||||||
|
el worker se interrumpe, el claim vence según `EMAIL_DELIVERY_LEASE_SECONDS` y
|
||||||
|
otro intento puede recuperarlo.
|
||||||
|
- Los fallos quedan registrados como `failed` y pueden ser retomados por los
|
||||||
|
reintentos de la cola. Los envíos exitosos permanecen como `sent` y las llamadas
|
||||||
|
posteriores con la misma clave no vuelven a enviar el correo.
|
||||||
|
- SMTP no ofrece una confirmación transaccional junto con la base de datos. Una
|
||||||
|
interrupción ocurrida después de entregar el correo y antes de registrar
|
||||||
|
`sent` puede producir un duplicado excepcional al recuperar el claim.
|
||||||
|
|||||||
@@ -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',
|
||||||
];
|
];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -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' => [
|
||||||
|
|||||||
@@ -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, '.', '');
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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),
|
||||||
]);
|
]);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -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),
|
||||||
];
|
];
|
||||||
|
|||||||
@@ -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,
|
||||||
];
|
];
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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,
|
||||||
|
|||||||
@@ -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',
|
||||||
];
|
];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -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',
|
||||||
|
|||||||
@@ -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',
|
||||||
|
],
|
||||||
];
|
];
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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
|
||||||
|
|||||||
@@ -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();
|
||||||
|
|||||||
@@ -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);
|
||||||
|
|||||||
@@ -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'],
|
||||||
|
|||||||
22
app/Domains/Ticket/Requests/AdminAppTicketRefundRequest.php
Normal file
22
app/Domains/Ticket/Requests/AdminAppTicketRefundRequest.php
Normal 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'])],
|
||||||
|
];
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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,
|
||||||
];
|
];
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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'],
|
||||||
|
];
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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),
|
||||||
];
|
];
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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,
|
||||||
|
|||||||
@@ -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,
|
||||||
) {}
|
) {}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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));
|
||||||
|
|||||||
@@ -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();
|
||||||
|
|||||||
@@ -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');
|
||||||
|
|||||||
@@ -2,10 +2,14 @@
|
|||||||
|
|
||||||
namespace App\Providers;
|
namespace App\Providers;
|
||||||
|
|
||||||
|
use App\Domains\Event\Events\EventDateRescheduled;
|
||||||
|
use App\Domains\Event\Events\EventDateSuspended;
|
||||||
use App\Domains\Integration\Models\Integration;
|
use App\Domains\Integration\Models\Integration;
|
||||||
use App\Domains\Integration\Policies\IntegrationPolicy;
|
use App\Domains\Integration\Policies\IntegrationPolicy;
|
||||||
use App\Domains\Notification\Events\PasswordResetRequested;
|
use App\Domains\Notification\Events\PasswordResetRequested;
|
||||||
use App\Domains\Notification\Events\UserRegistered;
|
use App\Domains\Notification\Events\UserRegistered;
|
||||||
|
use App\Domains\Notification\Listeners\SendEventDateRescheduledEmails;
|
||||||
|
use App\Domains\Notification\Listeners\SendEventDateSuspendedEmails;
|
||||||
use App\Domains\Notification\Listeners\SendPasswordResetEmail;
|
use App\Domains\Notification\Listeners\SendPasswordResetEmail;
|
||||||
use App\Domains\Notification\Listeners\SendPurchaseConfirmedEmail;
|
use App\Domains\Notification\Listeners\SendPurchaseConfirmedEmail;
|
||||||
use App\Domains\Notification\Listeners\SendWelcomeEmail;
|
use App\Domains\Notification\Listeners\SendWelcomeEmail;
|
||||||
@@ -40,6 +44,8 @@ class AppServiceProvider extends ServiceProvider
|
|||||||
);
|
);
|
||||||
Event::listen(PurchasePaid::class, GenerateTicketsForPaidPurchase::class);
|
Event::listen(PurchasePaid::class, GenerateTicketsForPaidPurchase::class);
|
||||||
Event::listen(PurchasePaid::class, SendPurchaseConfirmedEmail::class);
|
Event::listen(PurchasePaid::class, SendPurchaseConfirmedEmail::class);
|
||||||
|
Event::listen(EventDateRescheduled::class, SendEventDateRescheduledEmails::class);
|
||||||
|
Event::listen(EventDateSuspended::class, SendEventDateSuspendedEmails::class);
|
||||||
Event::listen(UserRegistered::class, SendWelcomeEmail::class);
|
Event::listen(UserRegistered::class, SendWelcomeEmail::class);
|
||||||
Event::listen(PasswordResetRequested::class, SendPasswordResetEmail::class);
|
Event::listen(PasswordResetRequested::class, SendPasswordResetEmail::class);
|
||||||
|
|
||||||
|
|||||||
@@ -16,6 +16,8 @@ return [
|
|||||||
|
|
||||||
'default' => env('MAIL_MAILER', 'log'),
|
'default' => env('MAIL_MAILER', 'log'),
|
||||||
|
|
||||||
|
'delivery_lease_seconds' => (int) env('EMAIL_DELIVERY_LEASE_SECONDS', 300),
|
||||||
|
|
||||||
/*
|
/*
|
||||||
|--------------------------------------------------------------------------
|
|--------------------------------------------------------------------------
|
||||||
| Mailer Configurations
|
| Mailer Configurations
|
||||||
|
|||||||
@@ -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',
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
};
|
||||||
@@ -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',
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
};
|
||||||
@@ -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');
|
||||||
|
});
|
||||||
|
}
|
||||||
|
};
|
||||||
@@ -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');
|
||||||
|
});
|
||||||
|
}
|
||||||
|
};
|
||||||
@@ -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');
|
||||||
|
});
|
||||||
|
}
|
||||||
|
};
|
||||||
@@ -0,0 +1,34 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
use Illuminate\Database\Migrations\Migration;
|
||||||
|
use Illuminate\Database\Schema\Blueprint;
|
||||||
|
use Illuminate\Support\Facades\Schema;
|
||||||
|
|
||||||
|
return new class extends Migration
|
||||||
|
{
|
||||||
|
public function up(): void
|
||||||
|
{
|
||||||
|
Schema::create('email_deliveries', function (Blueprint $table): void {
|
||||||
|
$table->id();
|
||||||
|
$table->string('idempotency_key')->unique();
|
||||||
|
$table->string('email_type')->index();
|
||||||
|
$table->string('tenant_code')->nullable()->index();
|
||||||
|
$table->string('status')->index();
|
||||||
|
$table->unsignedInteger('attempts')->default(0);
|
||||||
|
$table->json('context')->nullable();
|
||||||
|
$table->string('recipient_fingerprint', 64)->nullable();
|
||||||
|
$table->uuid('claim_token')->nullable()->index();
|
||||||
|
$table->timestamp('claimed_at')->nullable();
|
||||||
|
$table->timestamp('lease_expires_at')->nullable()->index();
|
||||||
|
$table->timestamp('sent_at')->nullable();
|
||||||
|
$table->timestamp('failed_at')->nullable();
|
||||||
|
$table->text('last_error')->nullable();
|
||||||
|
$table->timestamps();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
public function down(): void
|
||||||
|
{
|
||||||
|
Schema::dropIfExists('email_deliveries');
|
||||||
|
}
|
||||||
|
};
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
<h1 style="margin: 0 0 20px;">Tu evento fue reprogramado</h1>
|
||||||
|
<p>Te informamos que la fecha de tu evento cambió.</p>
|
||||||
|
<p>
|
||||||
|
<strong>Fecha anterior:</strong> {{ $previousDate }}<br>
|
||||||
|
<strong>Nueva fecha:</strong> {{ $newDate }}
|
||||||
|
</p>
|
||||||
|
<p>Tus tickets continúan siendo válidos para la nueva fecha.</p>
|
||||||
|
<p><strong>Tickets afectados</strong></p>
|
||||||
|
<ul>
|
||||||
|
@foreach ($tickets as $ticket)
|
||||||
|
<li>{{ $ticket->name }} · #{{ $ticket->id }}</li>
|
||||||
|
@endforeach
|
||||||
|
</ul>
|
||||||
|
<p style="color: #64748b; font-size: 13px;">Compra #{{ $purchase->id }}</p>
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
<h1 style="margin: 0 0 20px;">Actualización sobre tu evento</h1>
|
||||||
|
<p>La fecha <strong>{{ $date }}</strong> fue suspendida.</p>
|
||||||
|
|
||||||
|
@if ($disabledTickets->isNotEmpty())
|
||||||
|
<p>Los siguientes tickets quedaron inhabilitados porque no tienen otra fecha disponible:</p>
|
||||||
|
<ul>
|
||||||
|
@foreach ($disabledTickets as $ticket)
|
||||||
|
<li>{{ $ticket->name }} · #{{ $ticket->id }}</li>
|
||||||
|
@endforeach
|
||||||
|
</ul>
|
||||||
|
<p>Para conocer las alternativas o condiciones de devolución, comunicate con la organización.</p>
|
||||||
|
@endif
|
||||||
|
|
||||||
|
@if ($activeTickets->isNotEmpty())
|
||||||
|
<p>Estos tickets conservan otras fechas disponibles:</p>
|
||||||
|
<ul>
|
||||||
|
@foreach ($activeTickets as $ticket)
|
||||||
|
<li>{{ $ticket->name }} · #{{ $ticket->id }}</li>
|
||||||
|
@endforeach
|
||||||
|
</ul>
|
||||||
|
@endif
|
||||||
|
|
||||||
|
<p style="color: #64748b; font-size: 13px;">Compra #{{ $purchase->id }}</p>
|
||||||
@@ -6,12 +6,20 @@ 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\Event\Events\EventDateRescheduled;
|
||||||
|
use App\Domains\Event\Events\EventDateSuspended;
|
||||||
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\Facades\Event;
|
||||||
|
use Illuminate\Support\Str;
|
||||||
use Laravel\Sanctum\Sanctum;
|
use Laravel\Sanctum\Sanctum;
|
||||||
use Tests\TestCase;
|
use Tests\TestCase;
|
||||||
|
|
||||||
@@ -34,9 +42,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 +54,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 +68,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 +82,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 +157,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 +172,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 +183,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 +192,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 +213,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 +231,152 @@ 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
|
||||||
|
{
|
||||||
|
Event::fake([EventDateRescheduled::class]);
|
||||||
|
$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);
|
||||||
|
|
||||||
|
Event::assertDispatched(EventDateRescheduled::class, function (EventDateRescheduled $event) use ($tenant, $original, $destination): bool {
|
||||||
|
return $event->tenantCode === $tenant->codigo
|
||||||
|
&& $event->sourceEventDateId === $original->id
|
||||||
|
&& $event->destinationEventDateId === $destination->id
|
||||||
|
&& $event->previousDate === '09/10/2027'
|
||||||
|
&& $event->newDate === '20/10/2027'
|
||||||
|
&& $event->purchaseTickets === [];
|
||||||
|
});
|
||||||
|
|
||||||
|
$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
|
||||||
|
{
|
||||||
|
Event::fake([EventDateSuspended::class]);
|
||||||
|
$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));
|
||||||
|
|
||||||
|
Event::assertDispatched(EventDateSuspended::class, function (EventDateSuspended $event) use ($tenant, $suspendedDate): bool {
|
||||||
|
return $event->tenantCode === $tenant->codigo
|
||||||
|
&& $event->eventDateId === $suspendedDate->id
|
||||||
|
&& $event->date === '09/10/2027'
|
||||||
|
&& $event->purchaseTickets === [];
|
||||||
|
});
|
||||||
|
|
||||||
|
$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 +384,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 +394,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 +454,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 +466,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");
|
||||||
|
|||||||
@@ -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'],
|
||||||
],
|
],
|
||||||
],
|
],
|
||||||
],
|
],
|
||||||
|
|||||||
@@ -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' => [
|
||||||
[
|
[
|
||||||
|
|||||||
@@ -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'])]
|
||||||
|
|||||||
@@ -0,0 +1,136 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace Tests\Feature\Notification;
|
||||||
|
|
||||||
|
use App\Domains\Notification\Models\EmailDelivery;
|
||||||
|
use App\Domains\Notification\Services\IdempotentEmailDeliveryService;
|
||||||
|
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||||
|
use RuntimeException;
|
||||||
|
use Tests\TestCase;
|
||||||
|
|
||||||
|
class IdempotentEmailDeliveryServiceTest extends TestCase
|
||||||
|
{
|
||||||
|
use RefreshDatabase;
|
||||||
|
|
||||||
|
public function test_it_sends_once_for_the_same_business_key(): void
|
||||||
|
{
|
||||||
|
$calls = 0;
|
||||||
|
$service = app(IdempotentEmailDeliveryService::class);
|
||||||
|
|
||||||
|
$first = $service->sendOnce(
|
||||||
|
'welcome:tenant:10',
|
||||||
|
'welcome',
|
||||||
|
'tenant',
|
||||||
|
['user_id' => 10],
|
||||||
|
'ada@example.com',
|
||||||
|
function () use (&$calls): void {
|
||||||
|
$calls++;
|
||||||
|
},
|
||||||
|
);
|
||||||
|
$second = $service->sendOnce(
|
||||||
|
'welcome:tenant:10',
|
||||||
|
'welcome',
|
||||||
|
'tenant',
|
||||||
|
['user_id' => 10],
|
||||||
|
'ada@example.com',
|
||||||
|
function () use (&$calls): void {
|
||||||
|
$calls++;
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
$this->assertTrue($first);
|
||||||
|
$this->assertFalse($second);
|
||||||
|
$this->assertSame(1, $calls);
|
||||||
|
$this->assertDatabaseHas('email_deliveries', [
|
||||||
|
'idempotency_key' => 'welcome:tenant:10',
|
||||||
|
'status' => EmailDelivery::STATUS_SENT,
|
||||||
|
'attempts' => 1,
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function test_it_records_a_failure_and_allows_a_retry(): void
|
||||||
|
{
|
||||||
|
$service = app(IdempotentEmailDeliveryService::class);
|
||||||
|
|
||||||
|
try {
|
||||||
|
$service->sendOnce(
|
||||||
|
'purchase-confirmed:20',
|
||||||
|
'purchase_confirmed',
|
||||||
|
'tenant',
|
||||||
|
['purchase_id' => 20],
|
||||||
|
'buyer@example.com',
|
||||||
|
fn () => throw new RuntimeException('Sensitive SMTP detail'),
|
||||||
|
);
|
||||||
|
$this->fail('The delivery exception was not rethrown.');
|
||||||
|
} catch (RuntimeException) {
|
||||||
|
$this->assertDatabaseHas('email_deliveries', [
|
||||||
|
'idempotency_key' => 'purchase-confirmed:20',
|
||||||
|
'status' => EmailDelivery::STATUS_FAILED,
|
||||||
|
'attempts' => 1,
|
||||||
|
'last_error' => RuntimeException::class,
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
|
$sent = $service->sendOnce(
|
||||||
|
'purchase-confirmed:20',
|
||||||
|
'purchase_confirmed',
|
||||||
|
'tenant',
|
||||||
|
['purchase_id' => 20],
|
||||||
|
'buyer@example.com',
|
||||||
|
static function (): void {},
|
||||||
|
);
|
||||||
|
|
||||||
|
$this->assertTrue($sent);
|
||||||
|
$this->assertDatabaseHas('email_deliveries', [
|
||||||
|
'idempotency_key' => 'purchase-confirmed:20',
|
||||||
|
'status' => EmailDelivery::STATUS_SENT,
|
||||||
|
'attempts' => 2,
|
||||||
|
'last_error' => null,
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function test_it_recovers_an_expired_claim_but_not_an_active_one(): void
|
||||||
|
{
|
||||||
|
config(['mail.delivery_lease_seconds' => 300]);
|
||||||
|
$service = app(IdempotentEmailDeliveryService::class);
|
||||||
|
$delivery = EmailDelivery::query()->create([
|
||||||
|
'idempotency_key' => 'password-reset:30',
|
||||||
|
'email_type' => 'password_reset',
|
||||||
|
'tenant_code' => 'tenant',
|
||||||
|
'status' => EmailDelivery::STATUS_PROCESSING,
|
||||||
|
'attempts' => 1,
|
||||||
|
'context' => ['attempt_id' => 30],
|
||||||
|
'recipient_fingerprint' => str_repeat('a', 64),
|
||||||
|
'claim_token' => fake()->uuid(),
|
||||||
|
'claimed_at' => now(),
|
||||||
|
'lease_expires_at' => now()->addMinute(),
|
||||||
|
]);
|
||||||
|
|
||||||
|
$activeClaim = $service->sendOnce(
|
||||||
|
$delivery->idempotency_key,
|
||||||
|
$delivery->email_type,
|
||||||
|
$delivery->tenant_code,
|
||||||
|
$delivery->context,
|
||||||
|
'ada@example.com',
|
||||||
|
static function (): void {},
|
||||||
|
);
|
||||||
|
$this->assertFalse($activeClaim);
|
||||||
|
|
||||||
|
$delivery->update(['lease_expires_at' => now()->subSecond()]);
|
||||||
|
$expiredClaim = $service->sendOnce(
|
||||||
|
$delivery->idempotency_key,
|
||||||
|
$delivery->email_type,
|
||||||
|
$delivery->tenant_code,
|
||||||
|
$delivery->context,
|
||||||
|
'ada@example.com',
|
||||||
|
static function (): void {},
|
||||||
|
);
|
||||||
|
|
||||||
|
$this->assertTrue($expiredClaim);
|
||||||
|
$this->assertDatabaseHas('email_deliveries', [
|
||||||
|
'idempotency_key' => 'password-reset:30',
|
||||||
|
'status' => EmailDelivery::STATUS_SENT,
|
||||||
|
'attempts' => 2,
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -14,6 +14,7 @@ use App\Domains\Purchase\Models\Purchase;
|
|||||||
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\Models\Ticket;
|
use App\Domains\Ticket\Models\Ticket;
|
||||||
|
use Barryvdh\DomPDF\ServiceProvider as DomPdfServiceProvider;
|
||||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||||
use Illuminate\Mail\Mailable;
|
use Illuminate\Mail\Mailable;
|
||||||
use Illuminate\Support\Facades\Mail;
|
use Illuminate\Support\Facades\Mail;
|
||||||
@@ -31,6 +32,7 @@ class NotificationMailServiceTest extends TestCase
|
|||||||
{
|
{
|
||||||
parent::setUp();
|
parent::setUp();
|
||||||
|
|
||||||
|
$this->app->register(DomPdfServiceProvider::class);
|
||||||
Mail::fake();
|
Mail::fake();
|
||||||
Integration::query()->create([
|
Integration::query()->create([
|
||||||
'integration_code' => 'email',
|
'integration_code' => 'email',
|
||||||
@@ -75,6 +77,9 @@ class NotificationMailServiceTest extends TestCase
|
|||||||
$this->useWebsiteTypeBranding();
|
$this->useWebsiteTypeBranding();
|
||||||
|
|
||||||
app(NotificationMailService::class)->sendWelcome($this->user->id, $this->tenant->codigo);
|
app(NotificationMailService::class)->sendWelcome($this->user->id, $this->tenant->codigo);
|
||||||
|
app(NotificationMailService::class)->sendWelcome($this->user->id, $this->tenant->codigo);
|
||||||
|
|
||||||
|
Mail::assertSent(Mailable::class, 1);
|
||||||
|
|
||||||
Mail::assertSent(Mailable::class, function (Mailable $mail): bool {
|
Mail::assertSent(Mailable::class, function (Mailable $mail): bool {
|
||||||
$mail->assertTo('ada@example.com');
|
$mail->assertTo('ada@example.com');
|
||||||
@@ -98,6 +103,12 @@ class NotificationMailServiceTest extends TestCase
|
|||||||
$attempt->id,
|
$attempt->id,
|
||||||
$this->tenant->codigo,
|
$this->tenant->codigo,
|
||||||
);
|
);
|
||||||
|
app(NotificationMailService::class)->sendPasswordResetCode(
|
||||||
|
$attempt->id,
|
||||||
|
$this->tenant->codigo,
|
||||||
|
);
|
||||||
|
|
||||||
|
Mail::assertSent(Mailable::class, 1);
|
||||||
|
|
||||||
Mail::assertSent(Mailable::class, function (Mailable $mail): bool {
|
Mail::assertSent(Mailable::class, function (Mailable $mail): bool {
|
||||||
$mail->assertTo('ada@example.com');
|
$mail->assertTo('ada@example.com');
|
||||||
@@ -113,6 +124,27 @@ class NotificationMailServiceTest extends TestCase
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public function test_password_reset_idempotency_is_scoped_to_each_attempt(): void
|
||||||
|
{
|
||||||
|
$firstAttempt = $this->user->resetPasswordAttempts()->create(['codigo' => '0123']);
|
||||||
|
$secondAttempt = $this->user->resetPasswordAttempts()->create(['codigo' => '4567']);
|
||||||
|
$service = app(NotificationMailService::class);
|
||||||
|
|
||||||
|
$service->sendPasswordResetCode($firstAttempt->id, $this->tenant->codigo);
|
||||||
|
$service->sendPasswordResetCode($firstAttempt->id, $this->tenant->codigo);
|
||||||
|
$service->sendPasswordResetCode($secondAttempt->id, $this->tenant->codigo);
|
||||||
|
|
||||||
|
Mail::assertSent(Mailable::class, 2);
|
||||||
|
$this->assertDatabaseHas('email_deliveries', [
|
||||||
|
'idempotency_key' => "password-reset:{$firstAttempt->id}",
|
||||||
|
'status' => 'sent',
|
||||||
|
]);
|
||||||
|
$this->assertDatabaseHas('email_deliveries', [
|
||||||
|
'idempotency_key' => "password-reset:{$secondAttempt->id}",
|
||||||
|
'status' => 'sent',
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
public function test_it_links_scanner_password_resets_to_the_scanner_domain(): void
|
public function test_it_links_scanner_password_resets_to_the_scanner_domain(): void
|
||||||
{
|
{
|
||||||
$websiteType = WebsiteType::query()->create([
|
$websiteType = WebsiteType::query()->create([
|
||||||
@@ -261,6 +293,9 @@ class NotificationMailServiceTest extends TestCase
|
|||||||
]);
|
]);
|
||||||
|
|
||||||
app(NotificationMailService::class)->sendPurchaseConfirmed($purchase->id);
|
app(NotificationMailService::class)->sendPurchaseConfirmed($purchase->id);
|
||||||
|
app(NotificationMailService::class)->sendPurchaseConfirmed($purchase->id);
|
||||||
|
|
||||||
|
Mail::assertSent(Mailable::class, 1);
|
||||||
|
|
||||||
Mail::assertSent(Mailable::class, function (Mailable $mail) use ($purchase): bool {
|
Mail::assertSent(Mailable::class, function (Mailable $mail) use ($purchase): bool {
|
||||||
return $mail->subject === "Compra confirmada - Compra #{$purchase->id}"
|
return $mail->subject === "Compra confirmada - Compra #{$purchase->id}"
|
||||||
@@ -270,6 +305,143 @@ class NotificationMailServiceTest extends TestCase
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public function test_it_sends_one_rescheduling_email_per_purchase_and_does_not_duplicate_it(): void
|
||||||
|
{
|
||||||
|
$purchase = Purchase::query()->create([
|
||||||
|
'tenant_codigo' => $this->tenant->codigo,
|
||||||
|
'user_id' => $this->user->id,
|
||||||
|
'status' => Purchase::STATUS_PAID,
|
||||||
|
'payment_method' => 'transfer',
|
||||||
|
'total' => 25,
|
||||||
|
'email' => 'checkout@example.com',
|
||||||
|
]);
|
||||||
|
$purchaseItem = $purchase->items()->create([
|
||||||
|
'source_catalog_item_id' => $this->catalogItem()->id,
|
||||||
|
'nombre' => 'Entrada',
|
||||||
|
'item_nombre' => 'Entrada general',
|
||||||
|
'variant_attributes' => [],
|
||||||
|
'cantidad' => 2,
|
||||||
|
'precio_unitario' => 25,
|
||||||
|
'total' => 25,
|
||||||
|
]);
|
||||||
|
$firstTicket = $this->ticketFor($purchaseItem->id);
|
||||||
|
$secondTicket = $this->ticketFor($purchaseItem->id);
|
||||||
|
$purchaseTickets = [[
|
||||||
|
'purchase_id' => $purchase->id,
|
||||||
|
'ticket_ids' => [$firstTicket->id, $secondTicket->id],
|
||||||
|
]];
|
||||||
|
|
||||||
|
app(NotificationMailService::class)->sendEventDateRescheduled(
|
||||||
|
$this->tenant->codigo,
|
||||||
|
10,
|
||||||
|
20,
|
||||||
|
'09/10/2027',
|
||||||
|
'20/10/2027',
|
||||||
|
$purchaseTickets,
|
||||||
|
);
|
||||||
|
app(NotificationMailService::class)->sendEventDateRescheduled(
|
||||||
|
$this->tenant->codigo,
|
||||||
|
10,
|
||||||
|
20,
|
||||||
|
'09/10/2027',
|
||||||
|
'20/10/2027',
|
||||||
|
$purchaseTickets,
|
||||||
|
);
|
||||||
|
|
||||||
|
Mail::assertSent(Mailable::class, 1);
|
||||||
|
Mail::assertSent(Mailable::class, function (Mailable $mail) use ($purchase, $firstTicket, $secondTicket): bool {
|
||||||
|
$mail->assertTo('checkout@example.com');
|
||||||
|
|
||||||
|
return $mail->subject === "Tu evento fue reprogramado - Compra #{$purchase->id}"
|
||||||
|
&& str_contains($mail->render(), '09/10/2027')
|
||||||
|
&& str_contains($mail->render(), '20/10/2027')
|
||||||
|
&& str_contains($mail->render(), '#'.$firstTicket->id)
|
||||||
|
&& str_contains($mail->render(), '#'.$secondTicket->id);
|
||||||
|
});
|
||||||
|
$this->assertDatabaseHas('email_deliveries', [
|
||||||
|
'idempotency_key' => "event-date-rescheduled:10:20:{$purchase->id}",
|
||||||
|
'email_type' => 'event_date_rescheduled',
|
||||||
|
'status' => 'sent',
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function test_suspension_email_uses_the_account_email_and_separates_disabled_tickets(): void
|
||||||
|
{
|
||||||
|
$purchase = Purchase::query()->create([
|
||||||
|
'tenant_codigo' => $this->tenant->codigo,
|
||||||
|
'user_id' => $this->user->id,
|
||||||
|
'status' => Purchase::STATUS_PAID,
|
||||||
|
'payment_method' => 'transfer',
|
||||||
|
'total' => 25,
|
||||||
|
'email' => null,
|
||||||
|
]);
|
||||||
|
$purchaseItem = $purchase->items()->create([
|
||||||
|
'source_catalog_item_id' => $this->catalogItem()->id,
|
||||||
|
'nombre' => 'Entrada',
|
||||||
|
'item_nombre' => 'Entrada general',
|
||||||
|
'variant_attributes' => [],
|
||||||
|
'cantidad' => 2,
|
||||||
|
'precio_unitario' => 25,
|
||||||
|
'total' => 25,
|
||||||
|
]);
|
||||||
|
$disabledTicket = $this->ticketFor($purchaseItem->id);
|
||||||
|
$disabledTicket->markAsDisabled();
|
||||||
|
$disabledTicket->save();
|
||||||
|
$activeTicket = $this->ticketFor($purchaseItem->id);
|
||||||
|
|
||||||
|
app(NotificationMailService::class)->sendEventDateSuspended(
|
||||||
|
$this->tenant->codigo,
|
||||||
|
10,
|
||||||
|
'09/10/2027',
|
||||||
|
[[
|
||||||
|
'purchase_id' => $purchase->id,
|
||||||
|
'ticket_ids' => [$disabledTicket->id, $activeTicket->id],
|
||||||
|
]],
|
||||||
|
);
|
||||||
|
app(NotificationMailService::class)->sendEventDateSuspended(
|
||||||
|
$this->tenant->codigo,
|
||||||
|
10,
|
||||||
|
'09/10/2027',
|
||||||
|
[[
|
||||||
|
'purchase_id' => $purchase->id,
|
||||||
|
'ticket_ids' => [$disabledTicket->id, $activeTicket->id],
|
||||||
|
]],
|
||||||
|
);
|
||||||
|
|
||||||
|
Mail::assertSent(Mailable::class, 1);
|
||||||
|
|
||||||
|
Mail::assertSent(Mailable::class, function (Mailable $mail) use ($disabledTicket, $activeTicket): bool {
|
||||||
|
$mail->assertTo('ada@example.com');
|
||||||
|
|
||||||
|
return str_contains($mail->render(), 'quedaron inhabilitados')
|
||||||
|
&& str_contains($mail->render(), 'conservan otras fechas disponibles')
|
||||||
|
&& str_contains($mail->render(), '#'.$disabledTicket->id)
|
||||||
|
&& str_contains($mail->render(), '#'.$activeTicket->id);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
private function ticketFor(int $purchaseItemId): Ticket
|
||||||
|
{
|
||||||
|
return Ticket::query()->create([
|
||||||
|
'tenant_code' => $this->tenant->codigo,
|
||||||
|
'ticket' => fake()->uuid(),
|
||||||
|
'source_purchase_item_id' => $purchaseItemId,
|
||||||
|
'user_id' => $this->user->id,
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
|
private function catalogItem(): CatalogItem
|
||||||
|
{
|
||||||
|
return CatalogItem::query()->create([
|
||||||
|
'tenant_code' => $this->tenant->codigo,
|
||||||
|
'slug' => fake()->unique()->slug(),
|
||||||
|
'nombre' => 'Entrada',
|
||||||
|
'descripcion' => 'Entrada general',
|
||||||
|
'precio' => 25,
|
||||||
|
'has_tickets' => true,
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
private function useWebsiteTypeBranding(): void
|
private function useWebsiteTypeBranding(): void
|
||||||
{
|
{
|
||||||
$websiteType = WebsiteType::query()->create([
|
$websiteType = WebsiteType::query()->create([
|
||||||
|
|||||||
@@ -2,6 +2,10 @@
|
|||||||
|
|
||||||
namespace Tests\Feature\Notification;
|
namespace Tests\Feature\Notification;
|
||||||
|
|
||||||
|
use App\Domains\Event\Events\EventDateRescheduled;
|
||||||
|
use App\Domains\Event\Events\EventDateSuspended;
|
||||||
|
use App\Domains\Notification\Listeners\SendEventDateRescheduledEmails;
|
||||||
|
use App\Domains\Notification\Listeners\SendEventDateSuspendedEmails;
|
||||||
use App\Domains\Notification\Listeners\SendPurchaseConfirmedEmail;
|
use App\Domains\Notification\Listeners\SendPurchaseConfirmedEmail;
|
||||||
use App\Domains\Notification\Services\NotificationMailService;
|
use App\Domains\Notification\Services\NotificationMailService;
|
||||||
use App\Domains\Purchase\Events\PurchasePaid;
|
use App\Domains\Purchase\Events\PurchasePaid;
|
||||||
@@ -27,4 +31,42 @@ class QueuedNotificationListenerTest extends TestCase
|
|||||||
|
|
||||||
$this->assertSame(123, $purchasePaid->purchaseId);
|
$this->assertSame(123, $purchasePaid->purchaseId);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public function test_rescheduled_date_email_listener_delegates_the_captured_purchase_tickets(): void
|
||||||
|
{
|
||||||
|
$mailService = Mockery::mock(NotificationMailService::class);
|
||||||
|
$mailService->shouldReceive('sendEventDateRescheduled')
|
||||||
|
->once()
|
||||||
|
->with('acme', 10, 20, '2027-10-09', '2027-10-20', [[
|
||||||
|
'purchase_id' => 123,
|
||||||
|
'ticket_ids' => [456, 789],
|
||||||
|
]]);
|
||||||
|
$this->app->instance(NotificationMailService::class, $mailService);
|
||||||
|
|
||||||
|
(new SendEventDateRescheduledEmails)->handle(new EventDateRescheduled(
|
||||||
|
'acme', 10, 20, '2027-10-09', '2027-10-20', [[
|
||||||
|
'purchase_id' => 123,
|
||||||
|
'ticket_ids' => [456, 789],
|
||||||
|
]]
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
|
public function test_suspended_date_email_listener_delegates_the_captured_purchase_tickets(): void
|
||||||
|
{
|
||||||
|
$mailService = Mockery::mock(NotificationMailService::class);
|
||||||
|
$mailService->shouldReceive('sendEventDateSuspended')
|
||||||
|
->once()
|
||||||
|
->with('acme', 10, '2027-10-09', [[
|
||||||
|
'purchase_id' => 123,
|
||||||
|
'ticket_ids' => [456],
|
||||||
|
]]);
|
||||||
|
$this->app->instance(NotificationMailService::class, $mailService);
|
||||||
|
|
||||||
|
(new SendEventDateSuspendedEmails)->handle(new EventDateSuspended(
|
||||||
|
'acme', 10, '2027-10-09', [[
|
||||||
|
'purchase_id' => 123,
|
||||||
|
'ticket_ids' => [456],
|
||||||
|
]]
|
||||||
|
));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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',
|
||||||
],
|
],
|
||||||
],
|
],
|
||||||
]);
|
]);
|
||||||
|
|||||||
159
tests/Feature/Tenant/TenantRefundConfigurationTest.php
Normal file
159
tests/Feature/Tenant/TenantRefundConfigurationTest.php
Normal 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);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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([
|
||||||
|
|||||||
@@ -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();
|
||||||
|
|||||||
@@ -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(),
|
||||||
|
|||||||
@@ -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
|
||||||
|
|||||||
@@ -3,6 +3,7 @@
|
|||||||
namespace Tests\Unit\Notification;
|
namespace Tests\Unit\Notification;
|
||||||
|
|
||||||
use App\Domains\Integration\Services\MailService;
|
use App\Domains\Integration\Services\MailService;
|
||||||
|
use App\Domains\Notification\Services\IdempotentEmailDeliveryService;
|
||||||
use App\Domains\Notification\Services\NotificationMailService;
|
use App\Domains\Notification\Services\NotificationMailService;
|
||||||
use App\Domains\Purchase\Models\Purchase;
|
use App\Domains\Purchase\Models\Purchase;
|
||||||
use App\Domains\Ticket\Services\TicketPdfService;
|
use App\Domains\Ticket\Services\TicketPdfService;
|
||||||
@@ -28,6 +29,7 @@ class NotificationMailServiceLoggingTest extends TestCase
|
|||||||
$this->service = new NotificationMailService(
|
$this->service = new NotificationMailService(
|
||||||
$this->mailService,
|
$this->mailService,
|
||||||
Mockery::mock(TicketPdfService::class),
|
Mockery::mock(TicketPdfService::class),
|
||||||
|
Mockery::mock(IdempotentEmailDeliveryService::class),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -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');
|
||||||
|
|||||||
Reference in New Issue
Block a user