refactor(backend): reorganize domains into Core, Commerce, Ticketing and Shared
This commit is contained in:
@@ -0,0 +1,87 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Ticket\Controllers\AdminApp;
|
||||
|
||||
use App\Domains\Ticket\Requests\AdminAppTicketExportRequest;
|
||||
use App\Domains\Ticket\Requests\AdminAppTicketIndexRequest;
|
||||
use App\Domains\Ticket\Requests\AdminAppTicketRefundRequest;
|
||||
use App\Domains\Ticket\Resources\AdminApp\AdminAppTicketCollection;
|
||||
use App\Domains\Ticket\Resources\AdminApp\AdminAppTicketRefundCalculationResource;
|
||||
use App\Domains\Ticket\Resources\AdminApp\AdminAppTicketResource;
|
||||
use App\Domains\Ticket\Services\AdminAppTicketExcelService;
|
||||
use App\Domains\Ticket\Services\AdminAppTicketPdfService;
|
||||
use App\Domains\Ticket\Services\AdminAppTicketService;
|
||||
use App\Http\Controllers\Controller;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Http\Response;
|
||||
use Symfony\Component\HttpFoundation\StreamedResponse;
|
||||
|
||||
class TicketController extends Controller
|
||||
{
|
||||
public function __construct(
|
||||
private readonly AdminAppTicketService $ticketService,
|
||||
private readonly AdminAppTicketPdfService $ticketPdfService,
|
||||
private readonly AdminAppTicketExcelService $ticketExcelService,
|
||||
) {}
|
||||
|
||||
public function index(AdminAppTicketIndexRequest $request): AdminAppTicketCollection
|
||||
{
|
||||
$tenant = $request->user()->tenant()->firstOrFail();
|
||||
|
||||
return new AdminAppTicketCollection(
|
||||
$this->ticketService->search($tenant, $request->validated())
|
||||
);
|
||||
}
|
||||
|
||||
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'),
|
||||
$request->user(),
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
public function downloadPdf(AdminAppTicketExportRequest $request): Response
|
||||
{
|
||||
$tenant = $request->user()->tenant()->firstOrFail();
|
||||
|
||||
return $this->ticketPdfService->download(
|
||||
$tenant,
|
||||
$this->ticketService->ticketsForExport($tenant, $request->validated()),
|
||||
$request->validated('timezone'),
|
||||
);
|
||||
}
|
||||
|
||||
public function downloadExcel(AdminAppTicketExportRequest $request): StreamedResponse
|
||||
{
|
||||
$tenant = $request->user()->tenant()->firstOrFail();
|
||||
|
||||
return $this->ticketExcelService->download(
|
||||
$tenant,
|
||||
$this->ticketService->ticketsForExport($tenant, $request->validated()),
|
||||
$request->validated('timezone'),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Ticket\Controllers\Scanner;
|
||||
|
||||
use App\Domains\Auth\Models\User;
|
||||
use App\Domains\Ticket\Requests\ScanAttemptIndexRequest;
|
||||
use App\Domains\Ticket\Resources\Scanner\ScanAttemptResource;
|
||||
use App\Domains\Ticket\Resources\Scanner\ScannerScanResultResource;
|
||||
use App\Domains\Ticket\Services\ScannerTicketService;
|
||||
use App\Http\Controllers\Controller;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Http\Resources\Json\AnonymousResourceCollection;
|
||||
|
||||
class ScanAttemptController extends Controller
|
||||
{
|
||||
public function __construct(private readonly ScannerTicketService $ticketService) {}
|
||||
|
||||
public function __invoke(ScanAttemptIndexRequest $request): AnonymousResourceCollection
|
||||
{
|
||||
/** @var User $scanner */
|
||||
$scanner = $request->user();
|
||||
|
||||
return ScanAttemptResource::collection(
|
||||
$this->ticketService->attemptsBy($scanner, $request->validated())
|
||||
);
|
||||
}
|
||||
|
||||
public function show(Request $request, int $scanAttempt): ScannerScanResultResource
|
||||
{
|
||||
/** @var User $scanner */
|
||||
$scanner = $request->user();
|
||||
|
||||
return ScannerScanResultResource::make(
|
||||
$this->ticketService->scanAttemptDetail($scanner, $scanAttempt)
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Ticket\Controllers\Scanner;
|
||||
|
||||
use App\Domains\Auth\Models\User;
|
||||
use App\Domains\Ticket\Resources\Scanner\ScannerScanResultResource;
|
||||
use App\Domains\Ticket\Resources\TicketResource;
|
||||
use App\Domains\Ticket\Services\ScannerTicketService;
|
||||
use App\Http\Controllers\Controller;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Symfony\Component\HttpFoundation\Response;
|
||||
|
||||
class TicketController extends Controller
|
||||
{
|
||||
public function __construct(private readonly ScannerTicketService $ticketService) {}
|
||||
|
||||
public function show(Request $request, string $ticketUuid): TicketResource
|
||||
{
|
||||
/** @var User $scanner */
|
||||
$scanner = $request->user();
|
||||
|
||||
return TicketResource::make(
|
||||
$this->ticketService->detail($scanner, $ticketUuid)
|
||||
);
|
||||
}
|
||||
|
||||
public function scan(Request $request): JsonResponse
|
||||
{
|
||||
/** @var User $scanner */
|
||||
$scanner = $request->user();
|
||||
|
||||
return ScannerScanResultResource::make(
|
||||
$this->ticketService->scan($scanner, $request->input('data'))
|
||||
)->response()->setStatusCode(Response::HTTP_OK);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Ticket\Controllers;
|
||||
|
||||
use App\Domains\Tenant\Models\Tenant;
|
||||
use App\Domains\Ticket\Exceptions\TicketNotAvailableException;
|
||||
use App\Domains\Ticket\Models\Ticket;
|
||||
use App\Domains\Ticket\Requests\DownloadTicketsPdfRequest;
|
||||
use App\Domains\Ticket\Resources\TicketResource;
|
||||
use App\Domains\Ticket\Services\TicketPdfService;
|
||||
use App\Domains\Ticket\Services\TicketPresentationResolver;
|
||||
use App\Domains\Ticket\Services\TicketValidityResolver;
|
||||
use App\Http\Controllers\Controller;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Http\Response;
|
||||
|
||||
class TicketController extends Controller
|
||||
{
|
||||
public function __construct(private readonly TicketPdfService $ticketPdfService) {}
|
||||
|
||||
public function index(Request $request, Tenant $tenant): JsonResponse
|
||||
{
|
||||
$tickets = Ticket::query()
|
||||
->where('tenant_code', $tenant->codigo)
|
||||
->where('user_id', $request->user()->getKey())
|
||||
->with([...TicketValidityResolver::RELATIONS, ...TicketPresentationResolver::RELATIONS])
|
||||
->orderByDesc('id')
|
||||
->get();
|
||||
|
||||
return TicketResource::collection($tickets)->response();
|
||||
}
|
||||
|
||||
public function downloadPdf(DownloadTicketsPdfRequest $request, Tenant $tenant): Response
|
||||
{
|
||||
$ticketIds = $request->validated('ticket_ids');
|
||||
$tickets = Ticket::query()
|
||||
->where('tenant_code', $tenant->codigo)
|
||||
->where('user_id', $request->user()->getKey())
|
||||
->whereIn('id', $ticketIds)
|
||||
->with([...TicketValidityResolver::RELATIONS, ...TicketPresentationResolver::RELATIONS])
|
||||
->orderByDesc('id')
|
||||
->get();
|
||||
|
||||
if ($tickets->count() !== count($ticketIds)) {
|
||||
throw new TicketNotAvailableException(__('api.ticket.not_available'));
|
||||
}
|
||||
|
||||
return $this->ticketPdfService->download($tenant, $tickets);
|
||||
}
|
||||
}
|
||||
16
app/Domains/Ticketing/Ticket/Enums/ScanAttemptResult.php
Normal file
16
app/Domains/Ticketing/Ticket/Enums/ScanAttemptResult.php
Normal file
@@ -0,0 +1,16 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Ticket\Enums;
|
||||
|
||||
enum ScanAttemptResult: string
|
||||
{
|
||||
case Processing = 'processing';
|
||||
case Accepted = 'accepted';
|
||||
case InvalidQr = 'invalid_qr';
|
||||
case TicketNotFound = 'ticket_not_found';
|
||||
case CategoryForbidden = 'category_forbidden';
|
||||
case AlreadyScanned = 'already_scanned';
|
||||
case Expired = 'expired';
|
||||
case NotValid = 'not_valid';
|
||||
case UnexpectedError = 'unexpected_error';
|
||||
}
|
||||
15
app/Domains/Ticketing/Ticket/Enums/ValidityTimeType.php
Normal file
15
app/Domains/Ticketing/Ticket/Enums/ValidityTimeType.php
Normal file
@@ -0,0 +1,15 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Ticket\Enums;
|
||||
|
||||
enum ValidityTimeType: string
|
||||
{
|
||||
case TimeWindow = 'time_window';
|
||||
case FixedWindow = 'fixed_window';
|
||||
|
||||
/** @return list<string> */
|
||||
public static function values(): array
|
||||
{
|
||||
return array_column(self::cases(), 'value');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Ticket\Exceptions;
|
||||
|
||||
use App\Domains\Catalog\Models\CatalogItem;
|
||||
use App\Domains\Catalog\Models\Variant;
|
||||
use App\Domains\Purchase\Models\Purchase;
|
||||
use App\Domains\Purchase\Models\PurchaseItem;
|
||||
use RuntimeException;
|
||||
|
||||
class TicketGenerationException extends RuntimeException
|
||||
{
|
||||
public static function invalidQuantity(): self
|
||||
{
|
||||
return new self(__('api.ticket.positive_quantity'));
|
||||
}
|
||||
|
||||
public static function emptyBundle(CatalogItem $bundle): self
|
||||
{
|
||||
return new self(__('api.ticket.empty_bundle', ['bundle' => $bundle->id]));
|
||||
}
|
||||
|
||||
public static function ticketsDisabled(CatalogItem $catalogItem): self
|
||||
{
|
||||
return new self(__('api.ticket.disabled', ['product' => $catalogItem->id]));
|
||||
}
|
||||
|
||||
public static function invalidValidityConfiguration(CatalogItem $catalogItem, Variant $variant): self
|
||||
{
|
||||
return new self("Variant {$variant->id} from catalog item {$catalogItem->id} has an invalid validity configuration.");
|
||||
}
|
||||
|
||||
public static function variantNotFound(
|
||||
CatalogItem $catalogItem,
|
||||
int $variantId,
|
||||
): self {
|
||||
return new self(
|
||||
__('api.ticket.invalid_variant', [
|
||||
'variant' => $variantId,
|
||||
'product' => $catalogItem->id,
|
||||
]),
|
||||
);
|
||||
}
|
||||
|
||||
public static function purchaseWithoutUser(Purchase $purchase): self
|
||||
{
|
||||
return new self(__('api.ticket.purchase_without_user', ['purchase' => $purchase->id]));
|
||||
}
|
||||
|
||||
public static function catalogItemNotFound(PurchaseItem $purchaseItem): self
|
||||
{
|
||||
return new self(__('api.ticket.product_not_found', ['purchase_item' => $purchaseItem->id]));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Ticket\Exceptions;
|
||||
|
||||
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
|
||||
|
||||
class TicketNotAvailableException extends NotFoundHttpException {}
|
||||
@@ -0,0 +1,63 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Ticket\Listeners;
|
||||
|
||||
use App\Domains\Catalog\Models\CatalogItem;
|
||||
use App\Domains\Purchase\Events\PurchasePaid;
|
||||
use App\Domains\Purchase\Models\Purchase;
|
||||
use App\Domains\Ticket\Exceptions\TicketGenerationException;
|
||||
use App\Domains\Ticket\Services\TicketGeneratorService;
|
||||
|
||||
class GenerateTicketsForPaidPurchase
|
||||
{
|
||||
public function __construct(
|
||||
private readonly TicketGeneratorService $ticketGenerator,
|
||||
) {}
|
||||
|
||||
public function handle(PurchasePaid $event): void
|
||||
{
|
||||
$purchase = Purchase::query()
|
||||
->with(['user', 'items'])
|
||||
->findOrFail($event->purchaseId);
|
||||
$user = $purchase->user;
|
||||
foreach ($purchase->items as $purchaseItem) {
|
||||
$catalogItem = CatalogItem::query()
|
||||
->where('tenant_code', $purchase->tenant_codigo)
|
||||
->find($purchaseItem->source_catalog_item_id);
|
||||
|
||||
if ($catalogItem === null) {
|
||||
throw TicketGenerationException::catalogItemNotFound($purchaseItem);
|
||||
}
|
||||
|
||||
if (! $this->requiresTickets($catalogItem)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if ($user === null) {
|
||||
throw TicketGenerationException::purchaseWithoutUser($purchase);
|
||||
}
|
||||
|
||||
$this->ticketGenerator->generate(
|
||||
$catalogItem,
|
||||
$user,
|
||||
$purchaseItem->cantidad,
|
||||
$purchaseItem->source_variant_id,
|
||||
$purchaseItem->getKey(),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
private function requiresTickets(CatalogItem $catalogItem): bool
|
||||
{
|
||||
if (! $catalogItem->isBundle()) {
|
||||
return $catalogItem->has_tickets;
|
||||
}
|
||||
|
||||
return $catalogItem->bundleComponents()
|
||||
->whereHas(
|
||||
'catalogItem',
|
||||
fn ($query) => $query->where('has_tickets', true),
|
||||
)
|
||||
->exists();
|
||||
}
|
||||
}
|
||||
52
app/Domains/Ticketing/Ticket/Models/ScanAttempt.php
Normal file
52
app/Domains/Ticketing/Ticket/Models/ScanAttempt.php
Normal file
@@ -0,0 +1,52 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Ticket\Models;
|
||||
|
||||
use App\Domains\Auth\Models\User;
|
||||
use App\Domains\Tenant\Models\Tenant;
|
||||
use App\Domains\Ticket\Enums\ScanAttemptResult;
|
||||
use Illuminate\Database\Eloquent\Attributes\Fillable;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
|
||||
#[Fillable([
|
||||
'tenant_code',
|
||||
'scanner_user_id',
|
||||
'ticket_id',
|
||||
'data',
|
||||
'result',
|
||||
'resolved_at',
|
||||
])]
|
||||
class ScanAttempt extends Model
|
||||
{
|
||||
public const UPDATED_AT = null;
|
||||
|
||||
/** @return BelongsTo<User, $this> */
|
||||
public function scanner(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(User::class, 'scanner_user_id')->withTrashed();
|
||||
}
|
||||
|
||||
/** @return BelongsTo<Ticket, $this> */
|
||||
public function ticket(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(Ticket::class);
|
||||
}
|
||||
|
||||
/** @return BelongsTo<Tenant, $this> */
|
||||
public function tenant(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(Tenant::class, 'tenant_code', 'codigo');
|
||||
}
|
||||
|
||||
protected function casts(): array
|
||||
{
|
||||
return [
|
||||
'scanner_user_id' => 'integer',
|
||||
'ticket_id' => 'integer',
|
||||
'result' => ScanAttemptResult::class,
|
||||
'created_at' => 'datetime',
|
||||
'resolved_at' => 'datetime',
|
||||
];
|
||||
}
|
||||
}
|
||||
426
app/Domains/Ticketing/Ticket/Models/Ticket.php
Normal file
426
app/Domains/Ticketing/Ticket/Models/Ticket.php
Normal file
@@ -0,0 +1,426 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Ticket\Models;
|
||||
|
||||
use App\Domains\Auth\Models\User;
|
||||
use App\Domains\Catalog\Models\CatalogItem;
|
||||
use App\Domains\Catalog\Models\Variant;
|
||||
use App\Domains\Logging\Models\Concerns\LogsValueChanges;
|
||||
use App\Domains\Purchase\Models\PurchaseItem;
|
||||
use App\Domains\Tenant\Models\Tenant;
|
||||
use App\Domains\Ticket\Services\ResolvedTicketValidity;
|
||||
use App\Domains\Ticket\Services\ResolvedValidityGroup;
|
||||
use App\Domains\Ticket\Services\TicketPresentationResolver;
|
||||
use App\Domains\Ticket\Services\TicketValidityResolver;
|
||||
use Carbon\CarbonInterface;
|
||||
use Illuminate\Database\Eloquent\Attributes\Fillable;
|
||||
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
use Illuminate\Database\Eloquent\Relations\HasMany;
|
||||
use Illuminate\Database\Eloquent\Relations\HasOne;
|
||||
use Illuminate\Support\Collection;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
|
||||
#[Fillable([
|
||||
'tenant_code',
|
||||
'ticket',
|
||||
'source_purchase_item_id',
|
||||
'source_catalog_item_id',
|
||||
'source_variant_id',
|
||||
'used_at',
|
||||
'disabled_at',
|
||||
'cancelled_at',
|
||||
'refunded_at',
|
||||
'scanner_user_id',
|
||||
'user_id',
|
||||
])]
|
||||
class Ticket extends Model
|
||||
{
|
||||
use HasFactory, LogsValueChanges;
|
||||
|
||||
private ?ResolvedTicketValidity $resolvedValidity = null;
|
||||
|
||||
public const STATUS_ACTIVE = 'active';
|
||||
|
||||
public const STATUS_EXPIRED = 'expired';
|
||||
|
||||
public const STATUS_USED = 'used';
|
||||
|
||||
public const STATUS_DISABLED = 'disabled';
|
||||
|
||||
public const STATUS_CANCELLED = 'cancelled';
|
||||
|
||||
public const STATUS_REFUNDED = 'refunded';
|
||||
|
||||
public $timestamps = false;
|
||||
|
||||
/** @var list<string> */
|
||||
protected array $loggedAttributes = [
|
||||
'used_at',
|
||||
'disabled_at',
|
||||
'cancelled_at',
|
||||
'refunded_at',
|
||||
];
|
||||
|
||||
protected $appends = [
|
||||
'name',
|
||||
'description',
|
||||
'is_valid',
|
||||
'is_expired',
|
||||
'is_used',
|
||||
'status',
|
||||
];
|
||||
|
||||
protected function casts(): array
|
||||
{
|
||||
return [
|
||||
'source_catalog_item_id' => 'integer',
|
||||
'source_variant_id' => 'integer',
|
||||
'source_purchase_item_id' => 'integer',
|
||||
'used_at' => 'datetime',
|
||||
'disabled_at' => 'datetime',
|
||||
'cancelled_at' => 'datetime',
|
||||
'refunded_at' => 'datetime',
|
||||
'scanner_user_id' => 'integer',
|
||||
'user_id' => 'integer',
|
||||
];
|
||||
}
|
||||
|
||||
/** @return list<string> */
|
||||
public static function statuses(): array
|
||||
{
|
||||
return array_keys(self::statusLabels());
|
||||
}
|
||||
|
||||
/** @return array<string, string> */
|
||||
public static function statusLabels(): array
|
||||
{
|
||||
return [
|
||||
self::STATUS_ACTIVE => 'Activo',
|
||||
self::STATUS_USED => 'Usado',
|
||||
self::STATUS_EXPIRED => 'Vencido',
|
||||
self::STATUS_DISABLED => 'Inhabilitado',
|
||||
self::STATUS_CANCELLED => 'Cancelado',
|
||||
self::STATUS_REFUNDED => 'Reembolsado',
|
||||
];
|
||||
}
|
||||
|
||||
/** @return list<array{value: string, label: string}> */
|
||||
public static function statusOptions(): array
|
||||
{
|
||||
return collect(self::statusLabels())
|
||||
->map(fn (string $label, string $status): array => [
|
||||
'value' => $status,
|
||||
'label' => $label,
|
||||
])
|
||||
->values()
|
||||
->all();
|
||||
}
|
||||
|
||||
public static function statusLabel(string $status): string
|
||||
{
|
||||
return self::statusLabels()[$status] ?? $status;
|
||||
}
|
||||
|
||||
protected static function booted(): void
|
||||
{
|
||||
static::saving(function (self $ticket): void {
|
||||
$ticket->ensureTerminalStatusTransitionIsAllowed();
|
||||
});
|
||||
}
|
||||
|
||||
/** @return BelongsTo<Tenant, $this> */
|
||||
public function tenant(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(Tenant::class, 'tenant_code', 'codigo');
|
||||
}
|
||||
|
||||
public function allow_refund(): bool
|
||||
{
|
||||
return $this->tenant?->allow_refund() ?? false;
|
||||
}
|
||||
|
||||
public function allowRefund(): bool
|
||||
{
|
||||
return $this->allow_refund();
|
||||
}
|
||||
|
||||
public function getAllowRefundAttribute(): bool
|
||||
{
|
||||
return $this->allow_refund();
|
||||
}
|
||||
|
||||
public function is_active(): bool
|
||||
{
|
||||
return $this->status === self::STATUS_ACTIVE;
|
||||
}
|
||||
|
||||
public function isActive(): bool
|
||||
{
|
||||
return $this->is_active();
|
||||
}
|
||||
|
||||
public function getIsActiveAttribute(): bool
|
||||
{
|
||||
return $this->is_active();
|
||||
}
|
||||
|
||||
public function can_cancel(): bool
|
||||
{
|
||||
return $this->is_active();
|
||||
}
|
||||
|
||||
public function canCancel(): bool
|
||||
{
|
||||
return $this->can_cancel();
|
||||
}
|
||||
|
||||
public function getCanCancelAttribute(): bool
|
||||
{
|
||||
return $this->can_cancel();
|
||||
}
|
||||
|
||||
public function can_refund(): bool
|
||||
{
|
||||
return $this->is_active() && $this->allow_refund();
|
||||
}
|
||||
|
||||
public function canRefund(): bool
|
||||
{
|
||||
return $this->can_refund();
|
||||
}
|
||||
|
||||
public function getCanRefundAttribute(): bool
|
||||
{
|
||||
return $this->can_refund();
|
||||
}
|
||||
|
||||
/** @return BelongsTo<User, $this> */
|
||||
public function user(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(User::class);
|
||||
}
|
||||
|
||||
/** @return BelongsTo<User, $this> */
|
||||
public function scannerUser(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(User::class, 'scanner_user_id')->withTrashed();
|
||||
}
|
||||
|
||||
/** @return HasMany<ScanAttempt, $this> */
|
||||
public function scanAttempts(): HasMany
|
||||
{
|
||||
return $this->hasMany(ScanAttempt::class);
|
||||
}
|
||||
|
||||
/** @return BelongsTo<PurchaseItem, $this> */
|
||||
public function sourcePurchaseItem(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(PurchaseItem::class, 'source_purchase_item_id');
|
||||
}
|
||||
|
||||
/** @return HasOne<TicketRefund, $this> */
|
||||
public function refund(): HasOne
|
||||
{
|
||||
return $this->hasOne(TicketRefund::class);
|
||||
}
|
||||
|
||||
/** @return BelongsTo<CatalogItem, $this> */
|
||||
public function sourceCatalogItem(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(CatalogItem::class, 'source_catalog_item_id')->withTrashed();
|
||||
}
|
||||
|
||||
/** @return BelongsTo<Variant, $this> */
|
||||
public function sourceVariant(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(Variant::class, 'source_variant_id')->withTrashed();
|
||||
}
|
||||
|
||||
public function isValid(): bool
|
||||
{
|
||||
if ($this->hasTerminalStatus() || $this->used_at !== null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return $this->resolvedValidity()->isValid();
|
||||
}
|
||||
|
||||
public function getIsValidAttribute(): bool
|
||||
{
|
||||
return $this->isValid();
|
||||
}
|
||||
|
||||
public function getIsExpiredAttribute(): bool
|
||||
{
|
||||
return ! $this->hasTerminalStatus()
|
||||
&& $this->used_at === null
|
||||
&& $this->resolvedValidity()->isExpired();
|
||||
}
|
||||
|
||||
public function getIsUsedAttribute(): bool
|
||||
{
|
||||
return $this->used_at !== null;
|
||||
}
|
||||
|
||||
public function getStatusAttribute(): string
|
||||
{
|
||||
if ($this->refunded_at !== null) {
|
||||
return self::STATUS_REFUNDED;
|
||||
}
|
||||
|
||||
if ($this->cancelled_at !== null) {
|
||||
return self::STATUS_CANCELLED;
|
||||
}
|
||||
|
||||
if ($this->disabled_at !== null) {
|
||||
return self::STATUS_DISABLED;
|
||||
}
|
||||
|
||||
if ($this->is_used) {
|
||||
return self::STATUS_USED;
|
||||
}
|
||||
|
||||
if ($this->is_expired) {
|
||||
return self::STATUS_EXPIRED;
|
||||
}
|
||||
|
||||
return self::STATUS_ACTIVE;
|
||||
}
|
||||
|
||||
public function getStatusLabelAttribute(): string
|
||||
{
|
||||
if ($this->status === self::STATUS_REFUNDED && $this->relationLoaded('refund')) {
|
||||
$refund = $this->getRelation('refund');
|
||||
|
||||
if ($refund instanceof TicketRefund) {
|
||||
return $refund->typeLabel();
|
||||
}
|
||||
}
|
||||
|
||||
return self::statusLabel($this->status);
|
||||
}
|
||||
|
||||
public function markAsDisabled(): void
|
||||
{
|
||||
$this->markAsTerminalStatus(self::STATUS_DISABLED);
|
||||
}
|
||||
|
||||
public function markAsCancelled(): void
|
||||
{
|
||||
$this->markAsTerminalStatus(self::STATUS_CANCELLED);
|
||||
}
|
||||
|
||||
public function markAsRefunded(): void
|
||||
{
|
||||
$this->markAsTerminalStatus(self::STATUS_REFUNDED);
|
||||
}
|
||||
|
||||
protected function valueChangeTenantCode(): string
|
||||
{
|
||||
return $this->tenant_code;
|
||||
}
|
||||
|
||||
private function hasTerminalStatus(): bool
|
||||
{
|
||||
return $this->terminalStatus() !== null;
|
||||
}
|
||||
|
||||
private function markAsTerminalStatus(string $status): void
|
||||
{
|
||||
$currentStatus = $this->terminalStatus();
|
||||
|
||||
if ($currentStatus === $status) {
|
||||
return;
|
||||
}
|
||||
|
||||
if ($currentStatus !== null) {
|
||||
$this->throwTerminalStatusTransitionException();
|
||||
}
|
||||
|
||||
$this->ensureTerminalStatusTransitionIsAllowed($status);
|
||||
|
||||
$this->{self::terminalStatusTimestampColumn($status)} = now();
|
||||
}
|
||||
|
||||
private function ensureTerminalStatusTransitionIsAllowed(?string $targetStatus = null): void
|
||||
{
|
||||
$currentStatus = $this->terminalStatusFromAttributes($this->getRawOriginal());
|
||||
$nextStatus = $targetStatus ?? $this->terminalStatus();
|
||||
|
||||
if ($currentStatus === null || $nextStatus === null || $currentStatus === $nextStatus) {
|
||||
return;
|
||||
}
|
||||
|
||||
$this->throwTerminalStatusTransitionException();
|
||||
}
|
||||
|
||||
private function throwTerminalStatusTransitionException(): never
|
||||
{
|
||||
throw ValidationException::withMessages([
|
||||
'status' => 'No se puede cambiar un ticket con estado terminal a otro estado terminal.',
|
||||
]);
|
||||
}
|
||||
|
||||
private function terminalStatus(): ?string
|
||||
{
|
||||
return $this->terminalStatusFromAttributes($this->getAttributes());
|
||||
}
|
||||
|
||||
/** @param array<string, mixed> $attributes */
|
||||
private function terminalStatusFromAttributes(array $attributes): ?string
|
||||
{
|
||||
foreach ([
|
||||
self::STATUS_REFUNDED,
|
||||
self::STATUS_CANCELLED,
|
||||
self::STATUS_DISABLED,
|
||||
] as $status) {
|
||||
if (($attributes[self::terminalStatusTimestampColumn($status)] ?? null) !== null) {
|
||||
return $status;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
private static function terminalStatusTimestampColumn(string $status): string
|
||||
{
|
||||
return match ($status) {
|
||||
self::STATUS_DISABLED => 'disabled_at',
|
||||
self::STATUS_CANCELLED => 'cancelled_at',
|
||||
self::STATUS_REFUNDED => 'refunded_at',
|
||||
};
|
||||
}
|
||||
|
||||
public function getNameAttribute(): string
|
||||
{
|
||||
return app(TicketPresentationResolver::class)->name($this);
|
||||
}
|
||||
|
||||
public function getDescriptionAttribute(): string
|
||||
{
|
||||
return app(TicketPresentationResolver::class)->description($this);
|
||||
}
|
||||
|
||||
public function getEffectiveStartsAt(): ?CarbonInterface
|
||||
{
|
||||
return $this->resolvedValidity()->effectiveStartsAt();
|
||||
}
|
||||
|
||||
public function getEffectiveExpiresAt(): ?CarbonInterface
|
||||
{
|
||||
return $this->resolvedValidity()->effectiveExpiresAt();
|
||||
}
|
||||
|
||||
/** @return Collection<int, ResolvedValidityGroup> */
|
||||
public function resolvedValidityGroups(): Collection
|
||||
{
|
||||
return $this->resolvedValidity()->groups;
|
||||
}
|
||||
|
||||
public function resolvedValidity(): ResolvedTicketValidity
|
||||
{
|
||||
return $this->resolvedValidity ??= app(TicketValidityResolver::class)->resolveTicket($this);
|
||||
}
|
||||
}
|
||||
66
app/Domains/Ticketing/Ticket/Models/TicketRefund.php
Normal file
66
app/Domains/Ticketing/Ticket/Models/TicketRefund.php
Normal file
@@ -0,0 +1,66 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Ticket\Models;
|
||||
|
||||
use App\Domains\Auth\Models\User;
|
||||
use App\Domains\Purchase\Models\PurchaseItem;
|
||||
use Illuminate\Database\Eloquent\Attributes\Fillable;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
|
||||
#[Fillable([
|
||||
'ticket_id',
|
||||
'purchase_item_id',
|
||||
'created_by_user_id',
|
||||
'type',
|
||||
'amount',
|
||||
])]
|
||||
class TicketRefund extends Model
|
||||
{
|
||||
public const TYPE_PARTIAL = 'partial';
|
||||
|
||||
public const TYPE_TOTAL = 'total';
|
||||
|
||||
protected function casts(): array
|
||||
{
|
||||
return [
|
||||
'ticket_id' => 'integer',
|
||||
'purchase_item_id' => 'integer',
|
||||
'created_by_user_id' => 'integer',
|
||||
'amount' => 'decimal:2',
|
||||
];
|
||||
}
|
||||
|
||||
/** @return list<string> */
|
||||
public static function types(): array
|
||||
{
|
||||
return [self::TYPE_PARTIAL, self::TYPE_TOTAL];
|
||||
}
|
||||
|
||||
public function typeLabel(): string
|
||||
{
|
||||
return match ($this->type) {
|
||||
self::TYPE_PARTIAL => 'Reembolso parcial',
|
||||
self::TYPE_TOTAL => 'Reembolso total',
|
||||
default => 'Reembolsado',
|
||||
};
|
||||
}
|
||||
|
||||
/** @return BelongsTo<Ticket, $this> */
|
||||
public function ticket(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(Ticket::class);
|
||||
}
|
||||
|
||||
/** @return BelongsTo<PurchaseItem, $this> */
|
||||
public function purchaseItem(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(PurchaseItem::class);
|
||||
}
|
||||
|
||||
/** @return BelongsTo<User, $this> */
|
||||
public function createdBy(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(User::class, 'created_by_user_id')->withTrashed();
|
||||
}
|
||||
}
|
||||
93
app/Domains/Ticketing/Ticket/Models/ValidityTime.php
Normal file
93
app/Domains/Ticketing/Ticket/Models/ValidityTime.php
Normal file
@@ -0,0 +1,93 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Ticket\Models;
|
||||
|
||||
use App\Domains\Catalog\Models\AttributeOption;
|
||||
use App\Domains\Event\Models\EventDate;
|
||||
use App\Domains\Ticket\Enums\ValidityTimeType;
|
||||
use Carbon\CarbonImmutable;
|
||||
use Carbon\CarbonInterface;
|
||||
use Illuminate\Database\Eloquent\Attributes\Fillable;
|
||||
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\HasMany;
|
||||
use Illuminate\Database\Eloquent\Relations\HasOne;
|
||||
|
||||
#[Fillable([
|
||||
'type',
|
||||
'start_time',
|
||||
'end_time',
|
||||
'fixed_starts_at',
|
||||
'fixed_expires_at',
|
||||
])]
|
||||
class ValidityTime extends Model
|
||||
{
|
||||
use HasFactory;
|
||||
|
||||
protected function casts(): array
|
||||
{
|
||||
return [
|
||||
'type' => ValidityTimeType::class,
|
||||
'fixed_starts_at' => 'datetime',
|
||||
'fixed_expires_at' => 'datetime',
|
||||
];
|
||||
}
|
||||
|
||||
/** @return HasMany<AttributeOption, $this> */
|
||||
public function attributeOptions(): HasMany
|
||||
{
|
||||
return $this->hasMany(AttributeOption::class);
|
||||
}
|
||||
|
||||
/** @return HasOne<EventDate, $this> */
|
||||
public function eventDate(): HasOne
|
||||
{
|
||||
return $this->hasOne(EventDate::class);
|
||||
}
|
||||
|
||||
public function startsAt(
|
||||
?CarbonInterface $at = null,
|
||||
): ?CarbonInterface {
|
||||
if ($this->type === ValidityTimeType::FixedWindow) {
|
||||
return $this->fixed_starts_at;
|
||||
}
|
||||
|
||||
return $this->atCurrentDate($this->start_time, $at);
|
||||
}
|
||||
|
||||
public function expiresAt(
|
||||
?CarbonInterface $at = null,
|
||||
): ?CarbonInterface {
|
||||
if ($this->type === ValidityTimeType::FixedWindow) {
|
||||
return $this->fixed_expires_at;
|
||||
}
|
||||
|
||||
return $this->atCurrentDate($this->end_time, $at);
|
||||
}
|
||||
|
||||
public function isValid(
|
||||
?CarbonInterface $at = null,
|
||||
): bool {
|
||||
$at ??= now();
|
||||
$startsAt = $this->startsAt($at);
|
||||
$expiresAt = $this->expiresAt($at);
|
||||
|
||||
return ($startsAt === null || $startsAt->lessThanOrEqualTo($at))
|
||||
&& ($expiresAt === null || $expiresAt->greaterThan($at));
|
||||
}
|
||||
|
||||
private function atCurrentDate(
|
||||
?string $time,
|
||||
?CarbonInterface $at,
|
||||
): ?CarbonInterface {
|
||||
if ($time === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$at ??= now();
|
||||
$localDate = CarbonImmutable::instance($at)
|
||||
->format('Y-m-d');
|
||||
|
||||
return CarbonImmutable::parse($localDate.' '.$time);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Ticket\Requests;
|
||||
|
||||
use App\Domains\Shared\Rules\ValidTimezone;
|
||||
|
||||
class AdminAppTicketExportRequest extends AdminAppTicketIndexRequest
|
||||
{
|
||||
/** @return array<string, mixed> */
|
||||
public function rules(): array
|
||||
{
|
||||
return [
|
||||
...parent::rules(),
|
||||
'timezone' => ['required', 'string', new ValidTimezone],
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Ticket\Requests;
|
||||
|
||||
use App\Domains\Ticket\Models\Ticket;
|
||||
use App\Domains\Ticket\Services\AdminAppTicketColumnService;
|
||||
use Illuminate\Foundation\Http\FormRequest;
|
||||
use Illuminate\Validation\Rule;
|
||||
|
||||
class AdminAppTicketIndexRequest extends FormRequest
|
||||
{
|
||||
public function authorize(): bool
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
/** @return array<string, list<string>> */
|
||||
public function rules(): array
|
||||
{
|
||||
$tenant = $this->user()?->tenant()->first();
|
||||
$sortableKeys = $tenant === null
|
||||
? []
|
||||
: app(AdminAppTicketColumnService::class)->sortableKeys($tenant);
|
||||
|
||||
return [
|
||||
'q' => ['sometimes', 'nullable', 'string', 'max:255'],
|
||||
'category' => ['sometimes', 'nullable', 'string', 'max:255'],
|
||||
'product' => ['sometimes', 'nullable', 'string', 'max:255'],
|
||||
'type' => ['sometimes', 'nullable', 'string', 'max:255'],
|
||||
'date' => ['sometimes', 'nullable', 'date_format:Y-m-d'],
|
||||
'size' => ['sometimes', 'nullable', 'string', 'max:255'],
|
||||
'status' => [
|
||||
'sometimes',
|
||||
'nullable',
|
||||
Rule::in(Ticket::statuses()),
|
||||
],
|
||||
'page' => ['sometimes', 'integer', 'min:1'],
|
||||
'per_page' => ['sometimes', 'integer', 'min:1', 'max:100'],
|
||||
'sort_by' => ['sometimes', 'nullable', 'string', Rule::in($sortableKeys)],
|
||||
'sort_direction' => ['sometimes', 'nullable', 'string', Rule::in(['asc', 'desc'])],
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Ticket\Requests;
|
||||
|
||||
use App\Domains\Ticket\Models\TicketRefund;
|
||||
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(TicketRefund::types())],
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Ticket\Requests;
|
||||
|
||||
use Illuminate\Foundation\Http\FormRequest;
|
||||
|
||||
class DownloadTicketsPdfRequest extends FormRequest
|
||||
{
|
||||
public function authorize(): bool
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
/** @return array<string, array<int, string>> */
|
||||
public function rules(): array
|
||||
{
|
||||
return [
|
||||
'ticket_ids' => ['required', 'array', 'min:1', 'max:25'],
|
||||
'ticket_ids.*' => ['required', 'integer', 'distinct'],
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Ticket\Requests;
|
||||
|
||||
use Illuminate\Foundation\Http\FormRequest;
|
||||
|
||||
class ScanAttemptIndexRequest extends FormRequest
|
||||
{
|
||||
public function authorize(): bool
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
/** @return array<string, list<string>> */
|
||||
public function rules(): array
|
||||
{
|
||||
return [
|
||||
'q' => ['sometimes', 'nullable', 'string', 'max:255'],
|
||||
'page' => ['sometimes', 'integer', 'min:1'],
|
||||
'per_page' => ['sometimes', 'integer', 'min:1', 'max:100'],
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Ticket\Resources\AdminApp;
|
||||
|
||||
use App\Domains\Ticket\Services\AdminAppTicketResult;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Http\Resources\Json\ResourceCollection;
|
||||
|
||||
class AdminAppTicketCollection extends ResourceCollection
|
||||
{
|
||||
/** @var class-string<AdminAppTicketResource> */
|
||||
public $collects = AdminAppTicketResource::class;
|
||||
|
||||
private readonly int $scannedTickets;
|
||||
|
||||
private readonly int $totalTickets;
|
||||
|
||||
private readonly string $refundedTotal;
|
||||
|
||||
public function __construct(AdminAppTicketResult $result)
|
||||
{
|
||||
parent::__construct($result->tickets);
|
||||
|
||||
$this->scannedTickets = $result->scannedTickets;
|
||||
$this->totalTickets = $result->totalTickets;
|
||||
$this->refundedTotal = $result->refundedTotal;
|
||||
}
|
||||
|
||||
/** @return array{scanned_tickets: int, total_tickets: int, refunded_total: string} */
|
||||
public function with(Request $request): array
|
||||
{
|
||||
return [
|
||||
'scanned_tickets' => $this->scannedTickets,
|
||||
'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'],
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Ticket\Resources\AdminApp;
|
||||
|
||||
use App\Domains\Ticket\Models\Ticket;
|
||||
use App\Domains\Ticket\Resources\TicketResource;
|
||||
use App\Domains\Ticket\Services\AdminAppTicketRowService;
|
||||
use Illuminate\Http\Request;
|
||||
|
||||
/** @mixin Ticket */
|
||||
class AdminAppTicketResource extends TicketResource
|
||||
{
|
||||
/** @return array<string, mixed> */
|
||||
public function toArray(Request $request): array
|
||||
{
|
||||
$rowService = app(AdminAppTicketRowService::class);
|
||||
$details = $rowService->details($this->resource);
|
||||
|
||||
return [
|
||||
...parent::toArray($request),
|
||||
...$details,
|
||||
'allow_refund' => $this->resource->allow_refund(),
|
||||
'is_active' => $this->resource->is_active(),
|
||||
'can_cancel' => $this->resource->can_cancel(),
|
||||
'can_refund' => $this->resource->can_refund(),
|
||||
'refund' => $this->resource->refund === null ? null : [
|
||||
'type' => $this->resource->refund->type,
|
||||
'type_label' => $this->resource->refund->typeLabel(),
|
||||
'amount' => $this->resource->refund->amount,
|
||||
'created_at' => $this->resource->refund->created_at,
|
||||
'created_by' => $this->resource->refund->createdBy?->nombre_apellido,
|
||||
],
|
||||
'values' => $rowService->values($this->resource, $details),
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Ticket\Resources\Scanner;
|
||||
|
||||
use App\Domains\Ticket\Enums\ScanAttemptResult;
|
||||
use App\Domains\Ticket\Models\ScanAttempt;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Http\Resources\Json\JsonResource;
|
||||
|
||||
/** @mixin ScanAttempt */
|
||||
class ScanAttemptResource extends JsonResource
|
||||
{
|
||||
/** @return array<string, mixed> */
|
||||
public function toArray(Request $request): array
|
||||
{
|
||||
return [
|
||||
'id' => $this->id,
|
||||
'data' => $this->data,
|
||||
'ticket_id' => $this->ticket_id,
|
||||
'ticket' => $this->ticket?->ticket,
|
||||
'category' => $this->ticket?->sourceCatalogItem?->category?->nombre,
|
||||
'attempted_at' => $this->created_at,
|
||||
'resolved_at' => $this->resolved_at,
|
||||
'result' => $this->result->value,
|
||||
'result_label' => match ($this->result) {
|
||||
ScanAttemptResult::Accepted => 'Verificado',
|
||||
ScanAttemptResult::AlreadyScanned => 'Usado',
|
||||
ScanAttemptResult::Expired => 'Vencido',
|
||||
default => 'Error',
|
||||
},
|
||||
'result_detail_label' => match ($this->result) {
|
||||
ScanAttemptResult::Processing => 'Error',
|
||||
ScanAttemptResult::Accepted => 'Verificado',
|
||||
ScanAttemptResult::InvalidQr => 'QR no pertenece al evento',
|
||||
ScanAttemptResult::TicketNotFound => 'Error',
|
||||
ScanAttemptResult::CategoryForbidden => 'Error',
|
||||
ScanAttemptResult::AlreadyScanned => 'Usado',
|
||||
ScanAttemptResult::Expired => 'Vencido',
|
||||
ScanAttemptResult::NotValid => 'No válido',
|
||||
ScanAttemptResult::UnexpectedError => 'Error',
|
||||
},
|
||||
'can_view_ticket' => $this->ticket !== null
|
||||
&& $this->result !== ScanAttemptResult::CategoryForbidden,
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Ticket\Resources\Scanner;
|
||||
|
||||
use App\Domains\Ticket\Models\ScanAttempt;
|
||||
use App\Domains\Ticket\Resources\TicketResource;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Http\Resources\Json\JsonResource;
|
||||
|
||||
/** @mixin ScanAttempt */
|
||||
class ScannerScanResultResource extends JsonResource
|
||||
{
|
||||
/** @return array<string, mixed> */
|
||||
public function toArray(Request $request): array
|
||||
{
|
||||
$ticket = $this->ticket;
|
||||
$client = $ticket?->user;
|
||||
|
||||
return [
|
||||
'scan_attempt' => ScanAttemptResource::make($this->resource),
|
||||
'ticket' => $ticket === null ? null : TicketResource::make($ticket),
|
||||
'client' => $client === null ? null : [
|
||||
'id' => $client->id,
|
||||
'nombre_apellido' => $client->nombre_apellido,
|
||||
],
|
||||
];
|
||||
}
|
||||
}
|
||||
42
app/Domains/Ticketing/Ticket/Resources/TicketResource.php
Normal file
42
app/Domains/Ticketing/Ticket/Resources/TicketResource.php
Normal file
@@ -0,0 +1,42 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Ticket\Resources;
|
||||
|
||||
use App\Domains\Ticket\Models\Ticket;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Http\Resources\Json\JsonResource;
|
||||
|
||||
/** @mixin Ticket */
|
||||
class TicketResource extends JsonResource
|
||||
{
|
||||
/** @return array<string, mixed> */
|
||||
public function toArray(Request $request): array
|
||||
{
|
||||
return [
|
||||
'id' => $this->id,
|
||||
'tenant_code' => $this->tenant_code,
|
||||
'ticket' => $this->ticket,
|
||||
'status' => $this->status,
|
||||
'status_label' => $this->status_label,
|
||||
'refund' => $this->whenLoaded('refund', fn (): ?array => $this->refund === null ? null : [
|
||||
'type' => $this->refund->type,
|
||||
'type_label' => $this->refund->typeLabel(),
|
||||
'amount' => $this->refund->amount,
|
||||
'created_at' => $this->refund->created_at,
|
||||
]),
|
||||
'name' => $this->name,
|
||||
'description' => $this->description,
|
||||
'client' => $this->user?->nombre_apellido,
|
||||
'category' => $this->sourceCatalogItem?->category?->nombre,
|
||||
'source_catalog_item_id' => $this->source_catalog_item_id,
|
||||
'source_variant_id' => $this->source_variant_id,
|
||||
'starts_at' => $this->getEffectiveStartsAt(),
|
||||
'expires_at' => $this->getEffectiveExpiresAt(),
|
||||
'used_at' => $this->used_at,
|
||||
'scanner_user_id' => $this->scanner_user_id,
|
||||
'is_valid' => $this->is_valid,
|
||||
'is_expired' => $this->is_expired,
|
||||
'is_used' => $this->is_used,
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Ticket\Resources;
|
||||
|
||||
use App\Domains\Ticket\Enums\ValidityTimeType;
|
||||
use App\Domains\Ticket\Models\ValidityTime;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Http\Resources\Json\JsonResource;
|
||||
|
||||
/** @mixin ValidityTime */
|
||||
class ValidityTimeResource extends JsonResource
|
||||
{
|
||||
/** @return array<string, mixed> */
|
||||
public function toArray(Request $request): array
|
||||
{
|
||||
$fields = match ($this->type) {
|
||||
ValidityTimeType::TimeWindow => [
|
||||
'start_time' => $this->start_time,
|
||||
'end_time' => $this->end_time,
|
||||
],
|
||||
ValidityTimeType::FixedWindow => [
|
||||
'fixed_starts_at' => $this->fixed_starts_at,
|
||||
'fixed_expires_at' => $this->fixed_expires_at,
|
||||
],
|
||||
};
|
||||
|
||||
return [
|
||||
'id' => $this->id,
|
||||
'type' => $this->type->value,
|
||||
'is_valid' => $this->isValid(),
|
||||
...array_filter($fields, fn (mixed $value): bool => $value !== null),
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Ticket\Services;
|
||||
|
||||
use App\Domains\Tenant\Models\Tenant;
|
||||
|
||||
class AdminAppTicketColumnService
|
||||
{
|
||||
private const FIESTA_FUTBOL_INFANTIL = 'fiesta_futbol_infantil';
|
||||
|
||||
/** @return list<array{key: string, label: string, type: string, sortable: bool, sort_param: string, width: string, excel_width: int}> */
|
||||
public function columns(Tenant $tenant): array
|
||||
{
|
||||
$keys = $tenant->codigo === self::FIESTA_FUTBOL_INFANTIL
|
||||
? ['order_number', 'category', 'product', 'type', 'date', 'size', 'amount', 'client', 'id', 'status', 'scanned_by']
|
||||
: ['order_number', 'product', 'amount', 'client', 'id', 'status', 'scanned_by'];
|
||||
|
||||
$columns = array_map(fn (string $key): array => $this->definitions()[$key], $keys);
|
||||
|
||||
if ($tenant->codigo === self::FIESTA_FUTBOL_INFANTIL) {
|
||||
$columns = array_map(function (array $column): array {
|
||||
if (in_array($column['key'], ['product', 'type', 'date', 'size'], true)) {
|
||||
$column['sortable'] = false;
|
||||
}
|
||||
|
||||
return $column;
|
||||
}, $columns);
|
||||
} else {
|
||||
$widths = [
|
||||
'order_number' => '11%',
|
||||
'product' => '15%',
|
||||
'amount' => '10%',
|
||||
'client' => '15%',
|
||||
'id' => '8%',
|
||||
'status' => '8%',
|
||||
'scanned_by' => '11%',
|
||||
];
|
||||
$columns = array_map(function (array $column) use ($widths): array {
|
||||
$column['width'] = $widths[$column['key']];
|
||||
|
||||
return $column;
|
||||
}, $columns);
|
||||
}
|
||||
|
||||
return $columns;
|
||||
}
|
||||
|
||||
/** @return list<array{key: string, label: string, type: string, sortable: bool, sort_param: string, width: string}> */
|
||||
public function publicColumns(Tenant $tenant): array
|
||||
{
|
||||
return array_map(function (array $column): array {
|
||||
unset($column['excel_width']);
|
||||
|
||||
return $column;
|
||||
}, $this->columns($tenant));
|
||||
}
|
||||
|
||||
/** @return list<string> */
|
||||
public function sortableKeys(Tenant $tenant): array
|
||||
{
|
||||
return array_values(array_map(
|
||||
fn (array $column): string => $column['sort_param'],
|
||||
array_filter($this->columns($tenant), fn (array $column): bool => $column['sortable']),
|
||||
));
|
||||
}
|
||||
|
||||
/** @return array<string, array{key: string, label: string, type: string, sortable: bool, sort_param: string, width: string, excel_width: int}> */
|
||||
private function definitions(): array
|
||||
{
|
||||
return [
|
||||
'order_number' => $this->column('order_number', 'N° de orden', 'order_number', '10.5%', 14),
|
||||
'category' => $this->column('category', 'Categoría', 'text', '11%', 18),
|
||||
'product' => $this->column('product', 'Producto', 'text', '11%', 22),
|
||||
'type' => $this->column('type', 'Tipo', 'text', '8%', 18),
|
||||
'date' => $this->column('date', 'Fecha', 'text', '7%', 14),
|
||||
'size' => $this->column('size', 'Talle', 'text', '6%', 12),
|
||||
'amount' => $this->column('amount', 'Importe', 'currency', '8%', 15),
|
||||
'client' => $this->column('client', 'Cliente', 'text', '11%', 30),
|
||||
'id' => $this->column('id', 'ID', 'text', '6%', 12),
|
||||
'status' => $this->column('status', 'Estado', 'status', '7%', 13),
|
||||
'scanned_by' => $this->column('scanned_by', 'Escaneado por', 'text', '8%', 28),
|
||||
];
|
||||
}
|
||||
|
||||
/** @return array{key: string, label: string, type: string, sortable: bool, sort_param: string, width: string, excel_width: int} */
|
||||
private function column(
|
||||
string $key,
|
||||
string $label,
|
||||
string $type,
|
||||
string $width,
|
||||
int $excelWidth,
|
||||
): array {
|
||||
return [
|
||||
'key' => $key,
|
||||
'label' => $label,
|
||||
'type' => $type,
|
||||
'sortable' => true,
|
||||
'sort_param' => $key,
|
||||
'width' => $width,
|
||||
'excel_width' => $excelWidth,
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Ticket\Services;
|
||||
|
||||
use App\Domains\Tenant\Models\Tenant;
|
||||
use App\Domains\Ticket\Models\Ticket;
|
||||
use Carbon\CarbonInterface;
|
||||
use Illuminate\Support\Collection;
|
||||
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
|
||||
use PhpOffice\PhpSpreadsheet\Cell\DataType;
|
||||
use PhpOffice\PhpSpreadsheet\Shared\Date;
|
||||
use PhpOffice\PhpSpreadsheet\Spreadsheet;
|
||||
use PhpOffice\PhpSpreadsheet\Style\Alignment;
|
||||
use PhpOffice\PhpSpreadsheet\Style\Fill;
|
||||
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
|
||||
use Symfony\Component\HttpFoundation\StreamedResponse;
|
||||
|
||||
class AdminAppTicketExcelService
|
||||
{
|
||||
public function __construct(
|
||||
private readonly AdminAppTicketReportService $reportService,
|
||||
private readonly AdminAppTicketColumnService $columnService,
|
||||
) {}
|
||||
|
||||
/** @param Collection<int, Ticket> $tickets */
|
||||
public function download(Tenant $tenant, Collection $tickets, string $timeZone): StreamedResponse
|
||||
{
|
||||
$generatedAt = now();
|
||||
$rows = $this->reportService->rows($tickets);
|
||||
$columns = $this->columnService->columns($tenant);
|
||||
$spreadsheet = new Spreadsheet;
|
||||
$spreadsheet->getProperties()
|
||||
->setCreator('Shopit')
|
||||
->setTitle('Listado de tickets')
|
||||
->setSubject($tenant->nombre);
|
||||
$sheet = $spreadsheet->getActiveSheet();
|
||||
$sheet->setTitle('Tickets');
|
||||
$sheet->fromArray([array_column($columns, 'label')], null, 'A1');
|
||||
|
||||
foreach ($rows as $index => $ticket) {
|
||||
$row = $index + 2;
|
||||
foreach ($columns as $columnIndex => $column) {
|
||||
$coordinate = Coordinate::stringFromColumnIndex($columnIndex + 1).$row;
|
||||
$value = $column['type'] === 'status'
|
||||
? ($ticket['status_label'] ?? $ticket[$column['key']] ?? null)
|
||||
: ($ticket[$column['key']] ?? null);
|
||||
|
||||
if ($column['type'] === 'currency' && $value !== null) {
|
||||
$sheet->setCellValue($coordinate, (float) $value);
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
if ($column['type'] === 'date' && $value instanceof CarbonInterface) {
|
||||
$sheet->setCellValue(
|
||||
$coordinate,
|
||||
Date::dateTimeToExcel($value->copy()->timezone($timeZone)),
|
||||
);
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
$sheet->setCellValueExplicit(
|
||||
$coordinate,
|
||||
$this->reportService->displayValue($value, $column['type'], $timeZone),
|
||||
DataType::TYPE_STRING,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
$lastRow = max(2, $rows->count() + 1);
|
||||
$lastColumn = Coordinate::stringFromColumnIndex(count($columns));
|
||||
foreach ($columns as $columnIndex => $column) {
|
||||
$letter = Coordinate::stringFromColumnIndex($columnIndex + 1);
|
||||
if ($column['type'] === 'currency') {
|
||||
$sheet->getStyle("{$letter}2:{$letter}{$lastRow}")
|
||||
->getNumberFormat()->setFormatCode('$ #,##0.00');
|
||||
}
|
||||
if ($column['type'] === 'date') {
|
||||
$sheet->getStyle("{$letter}2:{$letter}{$lastRow}")
|
||||
->getNumberFormat()->setFormatCode('dd/mm/yyyy hh:mm');
|
||||
}
|
||||
$sheet->getColumnDimension($letter)->setWidth($column['excel_width']);
|
||||
}
|
||||
$sheet->getStyle("A1:{$lastColumn}1")->applyFromArray([
|
||||
'font' => ['bold' => true, 'color' => ['rgb' => 'FFFFFF']],
|
||||
'fill' => [
|
||||
'fillType' => Fill::FILL_SOLID,
|
||||
'startColor' => ['rgb' => '26382E'],
|
||||
],
|
||||
'alignment' => ['vertical' => Alignment::VERTICAL_CENTER],
|
||||
]);
|
||||
$sheet->getRowDimension(1)->setRowHeight(24);
|
||||
$sheet->freezePane('A2');
|
||||
$sheet->setAutoFilter("A1:{$lastColumn}{$lastRow}");
|
||||
|
||||
$filename = 'tickets_'.$tenant->codigo.'_'
|
||||
.$generatedAt->copy()->timezone($timeZone)->format('Ymd_His').'.xlsx';
|
||||
|
||||
return response()->streamDownload(function () use ($spreadsheet): void {
|
||||
(new Xlsx($spreadsheet))->save('php://output');
|
||||
$spreadsheet->disconnectWorksheets();
|
||||
}, $filename, [
|
||||
'Content-Type' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
|
||||
]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Ticket\Services;
|
||||
|
||||
use App\Domains\Tenant\Models\Tenant;
|
||||
use App\Domains\Ticket\Models\Ticket;
|
||||
use Barryvdh\DomPDF\Facade\Pdf;
|
||||
use Barryvdh\DomPDF\PDF as DomPdf;
|
||||
use Illuminate\Http\Response;
|
||||
use Illuminate\Support\Collection;
|
||||
|
||||
class AdminAppTicketPdfService
|
||||
{
|
||||
public function __construct(
|
||||
private readonly AdminAppTicketReportService $reportService,
|
||||
private readonly AdminAppTicketColumnService $columnService,
|
||||
) {}
|
||||
|
||||
/** @param Collection<int, Ticket> $tickets */
|
||||
public function download(Tenant $tenant, Collection $tickets, string $timeZone): Response
|
||||
{
|
||||
$generatedAt = now();
|
||||
$columns = $this->columnService->columns($tenant);
|
||||
$rows = $this->reportService->rows($tickets);
|
||||
$pdf = Pdf::loadView('pdf.adminapp.tickets', [
|
||||
'tenant' => $tenant,
|
||||
'columns' => $columns,
|
||||
'tickets' => $this->reportService->displayRows($rows, $columns, $timeZone),
|
||||
'generatedAt' => $generatedAt,
|
||||
'timeZone' => $timeZone,
|
||||
])->setPaper('a3', 'landscape');
|
||||
|
||||
$this->addPageNumbers($pdf);
|
||||
|
||||
return $pdf->download(
|
||||
'tickets_'.$tenant->codigo.'_'
|
||||
.$generatedAt->copy()->timezone($timeZone)->format('Ymd_His').'.pdf'
|
||||
);
|
||||
}
|
||||
|
||||
private function addPageNumbers(DomPdf $pdf): void
|
||||
{
|
||||
$pdf->render();
|
||||
$domPdf = $pdf->getDomPDF();
|
||||
$font = $domPdf->getFontMetrics()->getFont('DejaVu Sans');
|
||||
|
||||
$domPdf->getCanvas()->page_text(
|
||||
565,
|
||||
805,
|
||||
'Página {PAGE_NUM} de {PAGE_COUNT}',
|
||||
$font,
|
||||
7,
|
||||
[0.48, 0.52, 0.49],
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Ticket\Services;
|
||||
|
||||
use App\Domains\Ticket\Models\Ticket;
|
||||
use Illuminate\Support\Collection;
|
||||
|
||||
class AdminAppTicketReportService
|
||||
{
|
||||
public function __construct(private readonly AdminAppTicketRowService $rowService) {}
|
||||
|
||||
/**
|
||||
* @param Collection<int, Ticket> $tickets
|
||||
* @return Collection<int, array<string, mixed>>
|
||||
*/
|
||||
public function rows(Collection $tickets): Collection
|
||||
{
|
||||
return $this->rowService->rows($tickets);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param Collection<int, array<string, mixed>> $rows
|
||||
* @param list<array<string, mixed>> $columns
|
||||
* @return Collection<int, array<string, string>>
|
||||
*/
|
||||
public function displayRows(Collection $rows, array $columns, string $timeZone): Collection
|
||||
{
|
||||
return $this->rowService->displayRows($rows, $columns, $timeZone);
|
||||
}
|
||||
|
||||
public function displayValue(mixed $value, string $type, string $timeZone): string
|
||||
{
|
||||
return $this->rowService->displayValue($value, $type, $timeZone);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Ticket\Services;
|
||||
|
||||
use App\Domains\Ticket\Models\Ticket;
|
||||
use Illuminate\Pagination\LengthAwarePaginator;
|
||||
|
||||
final readonly class AdminAppTicketResult
|
||||
{
|
||||
/** @param LengthAwarePaginator<Ticket> $tickets */
|
||||
public function __construct(
|
||||
public LengthAwarePaginator $tickets,
|
||||
public int $scannedTickets,
|
||||
public int $totalTickets,
|
||||
public string $refundedTotal,
|
||||
) {}
|
||||
}
|
||||
@@ -0,0 +1,216 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Ticket\Services;
|
||||
|
||||
use App\Domains\Catalog\Models\ItemAttribute;
|
||||
use App\Domains\Event\Models\EventDate;
|
||||
use App\Domains\Ticket\Models\Ticket;
|
||||
use Illuminate\Support\Collection;
|
||||
|
||||
class AdminAppTicketRowService
|
||||
{
|
||||
private const FIESTA_FUTBOL_INFANTIL = 'fiesta_futbol_infantil';
|
||||
|
||||
private const CATEGORY_PRESENTATIONS = [
|
||||
'alojamientos' => ['category' => 'Camping', 'product' => 'tipo_alojamiento', 'type' => null, 'size' => null],
|
||||
'camping' => ['category' => null, 'product' => 'tipo_alojamiento', 'type' => null, 'size' => null],
|
||||
'entradas' => ['category' => null, 'product' => 'product', 'type' => null, 'size' => null],
|
||||
'comidas' => ['category' => 'Comida', 'product' => 'horario', 'type' => 'servicio', 'size' => null],
|
||||
'comida' => ['category' => null, 'product' => 'horario', 'type' => 'servicio', 'size' => null],
|
||||
'merchandising' => ['category' => null, 'product' => 'product', 'type' => 'color', 'size' => 'talle'],
|
||||
];
|
||||
|
||||
/** @return array<string, mixed> */
|
||||
public function details(Ticket $ticket): array
|
||||
{
|
||||
$purchaseItem = $ticket->sourcePurchaseItem;
|
||||
$refund = $ticket->refund;
|
||||
|
||||
return [
|
||||
'source_purchase_item_id' => $ticket->source_purchase_item_id,
|
||||
'order_number' => $purchaseItem?->compra_id,
|
||||
'product' => $purchaseItem?->item_nombre
|
||||
?? $ticket->sourceCatalogItem?->nombre
|
||||
?? $ticket->name,
|
||||
'amount' => $purchaseItem?->precio_unitario,
|
||||
'refund_type' => $refund?->type,
|
||||
'refund_type_label' => $refund?->typeLabel(),
|
||||
'client' => $purchaseItem?->purchase?->nombre_apellido ?? $ticket->user?->nombre_apellido,
|
||||
'status' => $ticket->status,
|
||||
'scanned_by' => $ticket->scannerUser?->nombre_apellido,
|
||||
'variant_properties' => $this->variantProperties($ticket),
|
||||
'allow_refund' => $ticket->allow_refund(),
|
||||
];
|
||||
}
|
||||
|
||||
/** @param array<string, mixed>|null $details */
|
||||
public function values(Ticket $ticket, ?array $details = null): array
|
||||
{
|
||||
$details ??= $this->details($ticket);
|
||||
$presentation = $this->presentation($ticket, $details);
|
||||
|
||||
return [
|
||||
'order_number' => $details['order_number'],
|
||||
'category' => $presentation['category'],
|
||||
'product' => $presentation['product'],
|
||||
'type' => $presentation['type'],
|
||||
'date' => $presentation['date'],
|
||||
'size' => $presentation['size'],
|
||||
'amount' => $details['amount'] === null ? null : (float) $details['amount'],
|
||||
'client' => $details['client'] ?? 'Sin nombre',
|
||||
'id' => $ticket->id,
|
||||
'status' => $details['status'],
|
||||
'status_label' => $ticket->status_label,
|
||||
'scanned_by' => $details['scanned_by'] ?? '-',
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* @param Collection<int, Ticket> $tickets
|
||||
* @return Collection<int, array<string, mixed>>
|
||||
*/
|
||||
public function rows(Collection $tickets): Collection
|
||||
{
|
||||
return $tickets->values()->map(fn (Ticket $ticket): array => $this->values($ticket));
|
||||
}
|
||||
|
||||
/**
|
||||
* @param Collection<int, array<string, mixed>> $rows
|
||||
* @param list<array<string, mixed>> $columns
|
||||
* @return Collection<int, array<string, string>>
|
||||
*/
|
||||
public function displayRows(Collection $rows, array $columns, string $timeZone): Collection
|
||||
{
|
||||
return $rows->map(fn (array $row): array => collect($columns)
|
||||
->mapWithKeys(fn (array $column): array => [
|
||||
$column['key'] => $this->displayValue(
|
||||
$column['type'] === 'status'
|
||||
? ($row['status_label'] ?? $row[$column['key']] ?? null)
|
||||
: ($row[$column['key']] ?? null),
|
||||
$column['type'],
|
||||
$timeZone,
|
||||
),
|
||||
])
|
||||
->all());
|
||||
}
|
||||
|
||||
public function displayValue(mixed $value, string $type, string $timeZone): string
|
||||
{
|
||||
if ($value === null || $value === '') {
|
||||
return '-';
|
||||
}
|
||||
|
||||
return match ($type) {
|
||||
'order_number' => '#'.$value,
|
||||
'currency' => '$'.number_format((float) $value, 2, ',', '.'),
|
||||
'status' => Ticket::statusLabel((string) $value),
|
||||
default => (string) $value,
|
||||
};
|
||||
}
|
||||
|
||||
/** @param array<string, mixed> $details */
|
||||
private function presentation(Ticket $ticket, array $details): array
|
||||
{
|
||||
$sourceCategory = trim((string) ($ticket->sourceCatalogItem?->category?->nombre ?? '')) ?: '-';
|
||||
$effectiveDates = $this->effectiveEventDateLabels($ticket) ?: '-';
|
||||
|
||||
if ($ticket->tenant_code !== self::FIESTA_FUTBOL_INFANTIL) {
|
||||
return [
|
||||
'category' => $sourceCategory,
|
||||
'product' => (string) ($details['product'] ?: $ticket->name ?: '-'),
|
||||
'type' => $this->allPropertyLabels($details) ?: '-',
|
||||
'date' => $effectiveDates,
|
||||
'size' => '-',
|
||||
];
|
||||
}
|
||||
|
||||
$configuration = self::CATEGORY_PRESENTATIONS[mb_strtolower($sourceCategory)] ?? null;
|
||||
if ($configuration === null) {
|
||||
return [
|
||||
'category' => $sourceCategory,
|
||||
'product' => (string) ($details['product'] ?: $ticket->name ?: '-'),
|
||||
'type' => $this->allPropertyLabels($details) ?: '-',
|
||||
'date' => $effectiveDates,
|
||||
'size' => '-',
|
||||
];
|
||||
}
|
||||
|
||||
return [
|
||||
'category' => $configuration['category'] ?? $sourceCategory,
|
||||
'product' => $configuration['product'] === 'product'
|
||||
? (string) ($details['product'] ?: $ticket->name ?: '-')
|
||||
: ($this->propertyLabels($details, $configuration['product']) ?: '-'),
|
||||
'type' => $configuration['type'] === null
|
||||
? '-'
|
||||
: ($this->propertyLabels($details, $configuration['type']) ?: '-'),
|
||||
'date' => $effectiveDates,
|
||||
'size' => $configuration['size'] === null
|
||||
? '-'
|
||||
: ($this->propertyLabels($details, $configuration['size']) ?: '-'),
|
||||
];
|
||||
}
|
||||
|
||||
private function effectiveEventDateLabels(Ticket $ticket): string
|
||||
{
|
||||
return $ticket->sourceVariant?->selectedEventDates()
|
||||
->map(fn (EventDate $date): ?EventDate => $date->effectiveDate())
|
||||
->filter()
|
||||
->unique(fn (EventDate $date): int => $date->getKey())
|
||||
->sortBy(fn (EventDate $date): string => $date->date->format('Y-m-d'))
|
||||
->map(fn (EventDate $date): string => $date->date->format('d/m'))
|
||||
->implode(', ') ?? '';
|
||||
}
|
||||
|
||||
/** @param array<string, mixed> $details */
|
||||
private function propertyLabels(array $details, string $code): string
|
||||
{
|
||||
$property = collect($details['variant_properties'] ?? [])->firstWhere('code', $code);
|
||||
$labels = collect($property['values'] ?? [])->pluck('label')->filter();
|
||||
|
||||
return $labels->implode(', ');
|
||||
}
|
||||
|
||||
/** @param array<string, mixed> $details */
|
||||
private function allPropertyLabels(array $details): string
|
||||
{
|
||||
return collect($details['variant_properties'] ?? [])
|
||||
->flatMap(fn (array $property): array => $property['values'] ?? [])
|
||||
->pluck('label')
|
||||
->filter()
|
||||
->implode(', ');
|
||||
}
|
||||
|
||||
/** @return list<array{code: string, label: string, values: list<array{value: string, label: string}>}> */
|
||||
private function variantProperties(Ticket $ticket): array
|
||||
{
|
||||
$variant = $ticket->sourceVariant;
|
||||
if ($variant === null) {
|
||||
return [];
|
||||
}
|
||||
|
||||
$itemAttributes = $variant->definitions
|
||||
->map(fn ($definition) => $definition->itemAttribute)
|
||||
->filter()
|
||||
->merge($variant->catalogItem?->itemAttributes ?? collect())
|
||||
->unique('id')
|
||||
->values();
|
||||
|
||||
return $variant->selectionOptions($itemAttributes)
|
||||
->map(function (array $selection, string $attributeCode) use ($itemAttributes): array {
|
||||
$itemAttribute = $itemAttributes->first(
|
||||
fn (ItemAttribute $itemAttribute): bool => $itemAttribute->attribute?->codigo
|
||||
=== $attributeCode,
|
||||
);
|
||||
$values = array_is_list($selection) ? $selection : [$selection];
|
||||
|
||||
return [
|
||||
'code' => $attributeCode,
|
||||
'label' => $itemAttribute?->attribute?->nombre
|
||||
?? ($attributeCode === 'event_date' ? 'Fecha' : $attributeCode),
|
||||
'values' => array_values($values),
|
||||
];
|
||||
})
|
||||
->values()
|
||||
->all();
|
||||
}
|
||||
}
|
||||
694
app/Domains/Ticketing/Ticket/Services/AdminAppTicketService.php
Normal file
694
app/Domains/Ticketing/Ticket/Services/AdminAppTicketService.php
Normal file
@@ -0,0 +1,694 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Ticket\Services;
|
||||
|
||||
use App\Domains\Auth\Models\User;
|
||||
use App\Domains\Catalog\Enums\InventoryPolicy;
|
||||
use App\Domains\Catalog\Models\Inventory;
|
||||
use App\Domains\Catalog\Models\Variant;
|
||||
use App\Domains\Purchase\Models\PurchaseItem;
|
||||
use App\Domains\Purchase\Services\PurchaseRefundSummaryService;
|
||||
use App\Domains\Tenant\Models\Tenant;
|
||||
use App\Domains\Ticket\Models\Ticket;
|
||||
use App\Domains\Ticket\Models\TicketRefund;
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
use Illuminate\Pagination\LengthAwarePaginator;
|
||||
use Illuminate\Support\Collection;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
|
||||
class AdminAppTicketService
|
||||
{
|
||||
private const RELATIONS = [
|
||||
...TicketValidityResolver::RELATIONS,
|
||||
...TicketPresentationResolver::RELATIONS,
|
||||
'tenant',
|
||||
'user',
|
||||
'scannerUser',
|
||||
'sourceCatalogItem.category',
|
||||
'sourcePurchaseItem.purchase',
|
||||
'refund.createdBy',
|
||||
];
|
||||
|
||||
public function __construct(
|
||||
private readonly AdminAppTicketColumnService $columnService,
|
||||
private readonly AdminAppTicketRowService $rowService,
|
||||
private readonly PurchaseRefundSummaryService $refundSummaryService,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* @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, sort_by?: string|null, sort_direction?: string|null} $filters
|
||||
*/
|
||||
public function search(Tenant $tenant, array $filters = []): AdminAppTicketResult
|
||||
{
|
||||
$query = $this->baseQuery($tenant, $filters);
|
||||
$countQuery = clone $query;
|
||||
|
||||
$databaseSorted = $this->applyDatabaseSort($query, $tenant, $filters);
|
||||
|
||||
if (($filters['sort_by'] ?? null) && ! $databaseSorted) {
|
||||
$matchingTickets = (clone $query)
|
||||
->with(self::RELATIONS)
|
||||
->get();
|
||||
$matchingTickets = $this->sortTickets($matchingTickets, $tenant, $filters);
|
||||
$tickets = $this->paginate($matchingTickets, $filters);
|
||||
$scannedTickets = $matchingTickets
|
||||
->filter(fn (Ticket $ticket): bool => $ticket->status === Ticket::STATUS_USED)
|
||||
->count();
|
||||
$activeTickets = $matchingTickets
|
||||
->filter(fn (Ticket $ticket): bool => $ticket->is_active())
|
||||
->count();
|
||||
$totalTickets = $activeTickets + $scannedTickets;
|
||||
} else {
|
||||
$tickets = (clone $query)
|
||||
->with(self::RELATIONS)
|
||||
->when(! $databaseSorted, fn (Builder $query): Builder => $query->orderByDesc('id'))
|
||||
->paginateFromRequest()
|
||||
->withQueryString();
|
||||
|
||||
$counts = $this->calculateTicketCounts($countQuery);
|
||||
$scannedTickets = $counts['scanned'];
|
||||
$totalTickets = $counts['total'];
|
||||
}
|
||||
|
||||
return new AdminAppTicketResult(
|
||||
tickets: $tickets,
|
||||
scannedTickets: $scannedTickets,
|
||||
totalTickets: $totalTickets,
|
||||
refundedTotal: $this->refundSummaryService->totalForTenant($tenant),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array{q?: string|null, category?: string|null, product?: string|null, type?: string|null, date?: string|null, size?: string|null, status?: string|null, sort_by?: string|null, sort_direction?: string|null} $filters
|
||||
* @return Collection<int, Ticket>
|
||||
*/
|
||||
public function ticketsForExport(Tenant $tenant, array $filters = []): Collection
|
||||
{
|
||||
$query = $this->baseQuery($tenant, $filters);
|
||||
$databaseSorted = $this->applyDatabaseSort($query, $tenant, $filters);
|
||||
$tickets = $query
|
||||
->with(self::RELATIONS)
|
||||
->when(! $databaseSorted, fn (Builder $query): Builder => $query->orderByDesc('id'))
|
||||
->get();
|
||||
|
||||
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 = $this->refundedAmountForPurchaseItem($purchaseItem);
|
||||
$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,
|
||||
?User $createdBy = null,
|
||||
): Ticket {
|
||||
$this->ensureRefundIsAllowed($tenant, $refundType);
|
||||
|
||||
return DB::transaction(function () use ($tenant, $ticketId, $refundType, $createdBy): 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(
|
||||
$this->refundedAmountForPurchaseItem($purchaseItem) + $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();
|
||||
|
||||
TicketRefund::query()->create([
|
||||
'ticket_id' => $ticket->id,
|
||||
'purchase_item_id' => $purchaseItem->id,
|
||||
'created_by_user_id' => $createdBy?->id,
|
||||
'type' => $refundType,
|
||||
'amount' => number_format($refundAmount, 2, '.', ''),
|
||||
]);
|
||||
|
||||
$this->restoreInventory($ticket, $purchaseItem);
|
||||
|
||||
return $ticket->refresh()->load(self::RELATIONS);
|
||||
});
|
||||
}
|
||||
|
||||
private function restoreInventory(Ticket $ticket, PurchaseItem $purchaseItem): void
|
||||
{
|
||||
$catalogItem = $ticket->sourceCatalogItem;
|
||||
if ($catalogItem === null) {
|
||||
throw ValidationException::withMessages([
|
||||
'ticket' => 'El ticket no tiene un producto con inventario reponible.',
|
||||
]);
|
||||
}
|
||||
|
||||
// Bundle components need a per-ticket allocation before they can be restored.
|
||||
if ($catalogItem->isBundle() || $purchaseItem->sourceCatalogItem?->isBundle()) {
|
||||
return;
|
||||
}
|
||||
|
||||
$inventoryId = $catalogItem->inventory_id;
|
||||
if ($ticket->source_variant_id !== null) {
|
||||
$variant = Variant::withTrashed()->find($ticket->source_variant_id);
|
||||
if ($variant === null) {
|
||||
throw ValidationException::withMessages(['ticket' => 'No se encontró la variante del ticket.']);
|
||||
}
|
||||
|
||||
// A replacement can move the sellable inventory to a newer variant.
|
||||
$visited = [];
|
||||
while ($variant->replaced_by_variant_id !== null) {
|
||||
if (isset($visited[$variant->id])) {
|
||||
throw new \LogicException('La cadena de reemplazos de variantes es circular.');
|
||||
}
|
||||
$visited[$variant->id] = true;
|
||||
$variant = Variant::withTrashed()->findOrFail($variant->replaced_by_variant_id);
|
||||
}
|
||||
$inventoryId = $variant->inventory_id;
|
||||
}
|
||||
|
||||
$inventory = Inventory::query()->lockForUpdate()->find($inventoryId);
|
||||
if ($inventory === null) {
|
||||
throw ValidationException::withMessages(['ticket' => 'No se encontró el inventario del ticket.']);
|
||||
}
|
||||
|
||||
if ($catalogItem->inventory_policy === InventoryPolicy::Tracked) {
|
||||
$inventory->real_stock++;
|
||||
}
|
||||
$inventory->refunded_units++;
|
||||
$inventory->save();
|
||||
}
|
||||
|
||||
private function refundedAmountForPurchaseItem(PurchaseItem $purchaseItem): float
|
||||
{
|
||||
return round((float) TicketRefund::query()
|
||||
->where('purchase_item_id', $purchaseItem->id)
|
||||
->sum('amount'), 2);
|
||||
}
|
||||
|
||||
private function ensureRefundIsAllowed(Tenant $tenant, string $refundType): void
|
||||
{
|
||||
$isAllowed = match ($refundType) {
|
||||
TicketRefund::TYPE_PARTIAL => $tenant->allow_refund() && $tenant->allow_partial_refund(),
|
||||
TicketRefund::TYPE_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) {
|
||||
TicketRefund::TYPE_PARTIAL => round($ticketAmount * (float) $tenant->ticket_partial_refund_percentage / 100, 2),
|
||||
TicketRefund::TYPE_TOTAL => $ticketAmount,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array{q?: string|null, category?: string|null, product?: string|null, type?: string|null, date?: string|null, size?: string|null, status?: string|null, page?: int, per_page?: int} $filters
|
||||
* @return Builder<Ticket>
|
||||
*/
|
||||
private function baseQuery(Tenant $tenant, array $filters): Builder
|
||||
{
|
||||
$search = trim((string) ($filters['q'] ?? ''));
|
||||
|
||||
$query = Ticket::query()
|
||||
->where('tenant_code', $tenant->codigo)
|
||||
->when($search !== '', function (Builder $query) use ($search): void {
|
||||
$this->applySearchFilter($query, $search);
|
||||
})
|
||||
->when($filters['category'] ?? null, function (Builder $query, string $category): void {
|
||||
$query->whereHas('sourceCatalogItem.category', fn (Builder $categoryQuery): Builder => $categoryQuery
|
||||
->whereRaw('LOWER(nombre) = ?', [mb_strtolower(trim($category))]));
|
||||
})
|
||||
->when($filters['product'] ?? null, function (Builder $query, string $product) use ($filters): void {
|
||||
$this->applyProductFilter($query, (string) ($filters['category'] ?? ''), $product);
|
||||
})
|
||||
->when($filters['type'] ?? null, function (Builder $query, string $type) use ($filters): void {
|
||||
$this->applyTypeFilter($query, (string) ($filters['category'] ?? ''), $type);
|
||||
})
|
||||
->when($filters['date'] ?? null, function (Builder $query, string $date) use ($tenant): void {
|
||||
if ($tenant->codigo === 'fiesta_futbol_infantil') {
|
||||
$this->applyEventDateFilter($query, $date);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$query->whereHas('sourcePurchaseItem.purchase', fn (Builder $purchaseQuery): Builder => $purchaseQuery
|
||||
->whereDate('created_at', $date));
|
||||
})
|
||||
->when($filters['size'] ?? null, function (Builder $query, string $size) use ($filters): void {
|
||||
$this->applySizeFilter($query, (string) ($filters['category'] ?? ''), $size);
|
||||
});
|
||||
|
||||
$this->applyStatusFilter($query, $filters['status'] ?? null);
|
||||
|
||||
return $query;
|
||||
}
|
||||
|
||||
/** @param Builder<Ticket> $query */
|
||||
private function applySearchFilter(Builder $query, string $search): void
|
||||
{
|
||||
$containsPattern = '%'.mb_strtolower($search).'%';
|
||||
$amount = $this->searchAmount($search);
|
||||
|
||||
$query->where(function (Builder $searchQuery) use ($search, $containsPattern, $amount): void {
|
||||
$searchQuery
|
||||
->where(function (Builder $clientQuery) use ($containsPattern): void {
|
||||
$clientQuery
|
||||
->whereHas('sourcePurchaseItem.purchase', fn (Builder $purchaseQuery): Builder => $purchaseQuery
|
||||
->whereRaw('LOWER(nombre_apellido) LIKE ?', [$containsPattern]))
|
||||
->orWhere(function (Builder $fallbackClientQuery) use ($containsPattern): void {
|
||||
$fallbackClientQuery
|
||||
->where(function (Builder $missingPurchaseClientQuery): void {
|
||||
$missingPurchaseClientQuery
|
||||
->whereDoesntHave('sourcePurchaseItem.purchase')
|
||||
->orWhereHas('sourcePurchaseItem.purchase', fn (Builder $purchaseQuery): Builder => $purchaseQuery
|
||||
->whereNull('nombre_apellido'));
|
||||
})
|
||||
->whereHas('user', fn (Builder $userQuery): Builder => $userQuery
|
||||
->whereRaw('LOWER(nombre_apellido) LIKE ?', [$containsPattern]));
|
||||
});
|
||||
})
|
||||
->orWhereHas('scannerUser', fn (Builder $scannerQuery): Builder => $scannerQuery
|
||||
->whereRaw('LOWER(nombre_apellido) LIKE ?', [$containsPattern]));
|
||||
|
||||
if (ctype_digit($search)) {
|
||||
$searchQuery
|
||||
->orWhere('tickets.id', (int) $search)
|
||||
->orWhereHas('sourcePurchaseItem', fn (Builder $purchaseItemQuery): Builder => $purchaseItemQuery
|
||||
->where('compra_id', (int) $search));
|
||||
}
|
||||
|
||||
if ($amount !== null) {
|
||||
$searchQuery->orWhereHas('sourcePurchaseItem', fn (Builder $purchaseItemQuery): Builder => $purchaseItemQuery
|
||||
->where('precio_unitario', $amount));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private function searchAmount(string $search): ?string
|
||||
{
|
||||
$value = preg_replace('/[\s$]/u', '', trim($search));
|
||||
if ($value === null || $value === '') {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (preg_match('/^\d{1,3}(?:\.\d{3})+(?:,\d{1,2})?$/', $value) === 1) {
|
||||
$value = str_replace(['.', ','], ['', '.'], $value);
|
||||
} elseif (preg_match('/^\d{1,3}(?:,\d{3})+(?:\.\d{1,2})?$/', $value) === 1) {
|
||||
$value = str_replace(',', '', $value);
|
||||
} elseif (preg_match('/^\d+(?:[.,]\d{1,2})?$/', $value) === 1) {
|
||||
$value = str_replace(',', '.', $value);
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
|
||||
return number_format((float) $value, 2, '.', '');
|
||||
}
|
||||
|
||||
/** @param Builder<Ticket> $query */
|
||||
private function applyProductFilter(Builder $query, string $category, string $product): void
|
||||
{
|
||||
$category = $this->normalizedCategory($category);
|
||||
|
||||
if (in_array($category, ['alojamientos', 'camping'], true)) {
|
||||
$this->whereVariantDefinition($query, 'tipo_alojamiento', $product);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
if (in_array($category, ['comidas', 'comida'], true)) {
|
||||
$this->whereVariantDefinition($query, 'horario', $product);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$query->whereHas('sourceCatalogItem', fn (Builder $itemQuery): Builder => $itemQuery
|
||||
->where('slug', $product));
|
||||
}
|
||||
|
||||
/** @param Builder<Ticket> $query */
|
||||
private function applyTypeFilter(Builder $query, string $category, string $type): void
|
||||
{
|
||||
$attribute = match ($this->normalizedCategory($category)) {
|
||||
'comidas', 'comida' => 'servicio',
|
||||
'merchandising' => 'color',
|
||||
default => null,
|
||||
};
|
||||
|
||||
if ($attribute !== null) {
|
||||
$this->whereVariantDefinition($query, $attribute, $type);
|
||||
}
|
||||
}
|
||||
|
||||
/** @param Builder<Ticket> $query */
|
||||
private function applyEventDateFilter(Builder $query, string $date): void
|
||||
{
|
||||
$query
|
||||
->whereHas('sourceCatalogItem.category', fn (Builder $categoryQuery): Builder => $categoryQuery
|
||||
->whereRaw('LOWER(nombre) IN (?, ?)', ['comidas', 'comida']))
|
||||
->whereHas('sourceVariant', function (Builder $variantQuery) use ($date): void {
|
||||
$variantQuery->where(function (Builder $dateQuery) use ($date): void {
|
||||
$dateQuery
|
||||
->whereHas('eventDate', fn (Builder $eventDateQuery): Builder => $eventDateQuery
|
||||
->whereDate('date', $date))
|
||||
->orWhereHas('eventDates', fn (Builder $eventDateQuery): Builder => $eventDateQuery
|
||||
->whereDate('date', $date));
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/** @param Builder<Ticket> $query */
|
||||
private function applySizeFilter(Builder $query, string $category, string $size): void
|
||||
{
|
||||
if ($this->normalizedCategory($category) === 'merchandising') {
|
||||
$this->whereVariantDefinition($query, 'talle', $size);
|
||||
}
|
||||
}
|
||||
|
||||
/** @param Builder<Ticket> $query */
|
||||
private function whereVariantDefinition(Builder $query, string $attribute, string $value): void
|
||||
{
|
||||
$query->whereHas('sourceVariant.definitions', fn (Builder $definitionQuery): Builder => $definitionQuery
|
||||
->where('value', $value)
|
||||
->whereHas('itemAttribute.attribute', fn (Builder $attributeQuery): Builder => $attributeQuery
|
||||
->where('codigo', $attribute)));
|
||||
}
|
||||
|
||||
/** @param Builder<Ticket> $query */
|
||||
private function applyStatusFilter(Builder $query, ?string $status): void
|
||||
{
|
||||
if ($status === null || $status === '') {
|
||||
return;
|
||||
}
|
||||
|
||||
if ($status === Ticket::STATUS_USED) {
|
||||
$query
|
||||
->whereNotNull('used_at')
|
||||
->whereNull('disabled_at')
|
||||
->whereNull('cancelled_at')
|
||||
->whereNull('refunded_at');
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$timestampColumn = match ($status) {
|
||||
Ticket::STATUS_DISABLED => 'disabled_at',
|
||||
Ticket::STATUS_CANCELLED => 'cancelled_at',
|
||||
Ticket::STATUS_REFUNDED => 'refunded_at',
|
||||
default => null,
|
||||
};
|
||||
|
||||
if ($timestampColumn !== null) {
|
||||
$query->whereNotNull($timestampColumn);
|
||||
|
||||
if ($status === Ticket::STATUS_DISABLED) {
|
||||
$query->whereNull('cancelled_at')->whereNull('refunded_at');
|
||||
}
|
||||
|
||||
if ($status === Ticket::STATUS_CANCELLED) {
|
||||
$query->whereNull('refunded_at');
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$matchingIds = (clone $query)
|
||||
->whereNull('used_at')
|
||||
->whereNull('disabled_at')
|
||||
->whereNull('cancelled_at')
|
||||
->whereNull('refunded_at')
|
||||
->with(TicketValidityResolver::RELATIONS)
|
||||
->get()
|
||||
->filter(fn (Ticket $ticket): bool => $ticket->status === $status)
|
||||
->pluck('id');
|
||||
|
||||
$query->whereIn('tickets.id', $matchingIds);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param Builder<Ticket> $countQuery
|
||||
* @return array{scanned: int, total: int}
|
||||
*/
|
||||
private function calculateTicketCounts(Builder $countQuery): array
|
||||
{
|
||||
$scannedTickets = (clone $countQuery)
|
||||
->whereNotNull('used_at')
|
||||
->whereNull('disabled_at')
|
||||
->whereNull('cancelled_at')
|
||||
->whereNull('refunded_at')
|
||||
->count();
|
||||
|
||||
$activeTickets = (clone $countQuery)
|
||||
->whereNull('used_at')
|
||||
->whereNull('disabled_at')
|
||||
->whereNull('cancelled_at')
|
||||
->whereNull('refunded_at')
|
||||
->with(TicketValidityResolver::RELATIONS)
|
||||
->get()
|
||||
->filter(fn (Ticket $ticket): bool => $ticket->is_active())
|
||||
->count();
|
||||
|
||||
return [
|
||||
'scanned' => $scannedTickets,
|
||||
'total' => $activeTickets + $scannedTickets,
|
||||
];
|
||||
}
|
||||
|
||||
private function normalizedCategory(string $category): string
|
||||
{
|
||||
return mb_strtolower(trim($category));
|
||||
}
|
||||
|
||||
/**
|
||||
* @param Builder<Ticket> $query
|
||||
* @param array{sort_by?: string|null, sort_direction?: string|null} $filters
|
||||
*/
|
||||
private function applyDatabaseSort(Builder $query, Tenant $tenant, array $filters): bool
|
||||
{
|
||||
$sortBy = (string) ($filters['sort_by'] ?? '');
|
||||
if ($sortBy === '') {
|
||||
return false;
|
||||
}
|
||||
|
||||
$direction = ($filters['sort_direction'] ?? 'asc') === 'desc' ? 'desc' : 'asc';
|
||||
|
||||
$sortExpression = match ($sortBy) {
|
||||
'order_number' => $this->purchaseItemColumnQuery('compra_id'),
|
||||
'id' => 'tickets.id',
|
||||
'amount' => $this->purchaseItemColumnQuery('precio_unitario'),
|
||||
'scanned_by' => User::query()
|
||||
->withTrashed()
|
||||
->select('nombre_apellido')
|
||||
->whereColumn('users.id', 'tickets.scanner_user_id'),
|
||||
'product' => $tenant->codigo === 'fiesta_futbol_infantil'
|
||||
? null
|
||||
: $this->purchaseItemColumnQuery('item_nombre'),
|
||||
default => null,
|
||||
};
|
||||
|
||||
if ($sortExpression === null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$query->orderBy($sortExpression, $direction)->orderByDesc('tickets.id');
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/** @return Builder<PurchaseItem> */
|
||||
private function purchaseItemColumnQuery(string $column): Builder
|
||||
{
|
||||
return PurchaseItem::query()
|
||||
->select($column)
|
||||
->whereColumn('compra_items.id', 'tickets.source_purchase_item_id')
|
||||
->limit(1);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param Collection<int, Ticket> $tickets
|
||||
* @param array{sort_by?: string|null, sort_direction?: string|null} $filters
|
||||
* @return Collection<int, Ticket>
|
||||
*/
|
||||
private function sortTickets(Collection $tickets, Tenant $tenant, array $filters): Collection
|
||||
{
|
||||
$sortBy = (string) ($filters['sort_by'] ?? '');
|
||||
if ($sortBy === '') {
|
||||
return $tickets;
|
||||
}
|
||||
|
||||
$column = collect($this->columnService->columns($tenant))
|
||||
->firstWhere('sort_param', $sortBy);
|
||||
if ($column === null) {
|
||||
return $tickets;
|
||||
}
|
||||
|
||||
$direction = ($filters['sort_direction'] ?? 'asc') === 'desc' ? -1 : 1;
|
||||
$values = $tickets->mapWithKeys(fn (Ticket $ticket): array => [
|
||||
$ticket->getKey() => $this->rowService->values($ticket)[$column['key']] ?? null,
|
||||
]);
|
||||
|
||||
return $tickets->sort(function (Ticket $left, Ticket $right) use ($column, $direction, $values): int {
|
||||
$leftValue = $values->get($left->getKey());
|
||||
$rightValue = $values->get($right->getKey());
|
||||
|
||||
if ($leftValue === null || $leftValue === '') {
|
||||
return $rightValue === null || $rightValue === '' ? $right->id <=> $left->id : 1;
|
||||
}
|
||||
if ($rightValue === null || $rightValue === '') {
|
||||
return -1;
|
||||
}
|
||||
|
||||
$comparison = $this->compareValues($leftValue, $rightValue, $column['type']);
|
||||
|
||||
return $comparison === 0
|
||||
? $right->id <=> $left->id
|
||||
: $comparison * $direction;
|
||||
})->values();
|
||||
}
|
||||
|
||||
private function compareValues(mixed $left, mixed $right, string $type): int
|
||||
{
|
||||
if (in_array($type, ['currency', 'order_number'], true)) {
|
||||
return (float) $left <=> (float) $right;
|
||||
}
|
||||
|
||||
if ($type === 'date') {
|
||||
$leftTimestamp = $left instanceof \DateTimeInterface ? $left->getTimestamp() : strtotime((string) $left);
|
||||
$rightTimestamp = $right instanceof \DateTimeInterface ? $right->getTimestamp() : strtotime((string) $right);
|
||||
|
||||
return $leftTimestamp <=> $rightTimestamp;
|
||||
}
|
||||
|
||||
if ($type === 'status') {
|
||||
$left = $this->rowService->displayValue($left, $type, 'UTC');
|
||||
$right = $this->rowService->displayValue($right, $type, 'UTC');
|
||||
}
|
||||
|
||||
return strnatcasecmp((string) $left, (string) $right);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param Collection<int, Ticket> $tickets
|
||||
* @param array{page?: int, per_page?: int} $filters
|
||||
* @return LengthAwarePaginator<Ticket>
|
||||
*/
|
||||
private function paginate(Collection $tickets, array $filters): LengthAwarePaginator
|
||||
{
|
||||
$page = (int) ($filters['page'] ?? 1);
|
||||
$perPage = (int) ($filters['per_page'] ?? 15);
|
||||
|
||||
return (new LengthAwarePaginator(
|
||||
$tickets->forPage($page, $perPage)->values(),
|
||||
$tickets->count(),
|
||||
$perPage,
|
||||
$page,
|
||||
['path' => request()->url()],
|
||||
))->withQueryString();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,121 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Ticket\Services;
|
||||
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
use RuntimeException;
|
||||
|
||||
class BackfillRefundedUnitsService
|
||||
{
|
||||
/** @return array<string, int> */
|
||||
public function run(): array
|
||||
{
|
||||
$summary = DB::transaction(function (): array {
|
||||
if (DB::table('inventories')->where('refunded_units', '>', 0)->exists()) {
|
||||
throw new RuntimeException('El backfill requiere que refunded_units sea cero en todos los inventarios.');
|
||||
}
|
||||
|
||||
$counts = [];
|
||||
$variants = [];
|
||||
$refundsSeen = 0;
|
||||
$bundlesSkipped = 0;
|
||||
|
||||
DB::table('ticket_refunds as refunds')
|
||||
->join('tickets', 'tickets.id', '=', 'refunds.ticket_id')
|
||||
->join('compra_items as purchase_items', 'purchase_items.id', '=', 'refunds.purchase_item_id')
|
||||
->leftJoin('catalog_items as purchase_catalog', 'purchase_catalog.id', '=', 'purchase_items.source_catalog_item_id')
|
||||
->leftJoin('catalog_items as ticket_catalog', 'ticket_catalog.id', '=', 'tickets.source_catalog_item_id')
|
||||
->select([
|
||||
'refunds.id',
|
||||
'refunds.ticket_id',
|
||||
'tickets.source_variant_id',
|
||||
'ticket_catalog.inventory_id',
|
||||
'ticket_catalog.inventory_policy',
|
||||
'ticket_catalog.type as ticket_catalog_type',
|
||||
'purchase_catalog.type as purchase_catalog_type',
|
||||
])
|
||||
->chunkById(500, function ($refunds) use (&$counts, &$variants, &$refundsSeen, &$bundlesSkipped): void {
|
||||
foreach ($refunds as $refund) {
|
||||
$refundsSeen++;
|
||||
if ($refund->ticket_catalog_type === 'bundle' || $refund->purchase_catalog_type === 'bundle') {
|
||||
$bundlesSkipped++;
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
if ($refund->inventory_policy === null) {
|
||||
throw new RuntimeException("El reembolso {$refund->id} no tiene un producto de catálogo asociado.");
|
||||
}
|
||||
|
||||
$inventoryId = $refund->source_variant_id === null
|
||||
? $refund->inventory_id
|
||||
: $this->currentVariantInventoryId((int) $refund->source_variant_id, $variants);
|
||||
|
||||
if ($inventoryId === null) {
|
||||
throw new RuntimeException("El reembolso {$refund->id} no tiene un inventario asociado.");
|
||||
}
|
||||
|
||||
$counts[$inventoryId]['refunded'] = ($counts[$inventoryId]['refunded'] ?? 0) + 1;
|
||||
if ($refund->inventory_policy === 'tracked') {
|
||||
$counts[$inventoryId]['stock'] = ($counts[$inventoryId]['stock'] ?? 0) + 1;
|
||||
}
|
||||
}
|
||||
}, 'refunds.id', 'id');
|
||||
|
||||
foreach ($counts as $inventoryId => $count) {
|
||||
$updates = ['refunded_units' => DB::raw('refunded_units + '.$count['refunded'])];
|
||||
if (($count['stock'] ?? 0) > 0) {
|
||||
$updates['real_stock'] = DB::raw('real_stock + '.$count['stock']);
|
||||
}
|
||||
|
||||
if (DB::table('inventories')->where('id', $inventoryId)->update($updates) !== 1) {
|
||||
throw new RuntimeException("No se encontró el inventario {$inventoryId} para reponerlo.");
|
||||
}
|
||||
}
|
||||
|
||||
$refundedUnitsAdded = array_sum(array_column($counts, 'refunded'));
|
||||
|
||||
return [
|
||||
'refunds_seen' => $refundsSeen,
|
||||
'refunds_applied' => $refundedUnitsAdded,
|
||||
'bundles_skipped' => $bundlesSkipped,
|
||||
'inventories_updated' => count($counts),
|
||||
'refunded_units_added' => $refundedUnitsAdded,
|
||||
'real_stock_added' => array_sum(array_column($counts, 'stock')),
|
||||
];
|
||||
});
|
||||
|
||||
Log::info('inventory.refunded_units_backfill.completed', $summary);
|
||||
|
||||
return $summary;
|
||||
}
|
||||
|
||||
/** @param array<int, object|null> $variants */
|
||||
private function currentVariantInventoryId(int $variantId, array &$variants): ?int
|
||||
{
|
||||
$visited = [];
|
||||
|
||||
while (true) {
|
||||
if (isset($visited[$variantId])) {
|
||||
throw new RuntimeException("La cadena de reemplazos de la variante {$variantId} es circular.");
|
||||
}
|
||||
$visited[$variantId] = true;
|
||||
|
||||
if (! array_key_exists($variantId, $variants)) {
|
||||
$variants[$variantId] = DB::table('variantes')
|
||||
->where('id', $variantId)
|
||||
->first(['inventory_id', 'replaced_by_variant_id']);
|
||||
}
|
||||
$variant = $variants[$variantId];
|
||||
if ($variant === null) {
|
||||
throw new RuntimeException("No se encontró la variante {$variantId} de un ticket reembolsado.");
|
||||
}
|
||||
if ($variant->replaced_by_variant_id === null) {
|
||||
return $variant->inventory_id === null ? null : (int) $variant->inventory_id;
|
||||
}
|
||||
|
||||
$variantId = (int) $variant->replaced_by_variant_id;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,229 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Ticket\Services;
|
||||
|
||||
use App\Domains\Auth\Models\User;
|
||||
use App\Domains\Authorization\Enums\RoleCode;
|
||||
use App\Domains\Catalog\Enums\CatalogItemType;
|
||||
use App\Domains\Catalog\Models\CatalogItem;
|
||||
use App\Domains\Catalog\Models\Variant;
|
||||
use App\Domains\Tenant\Models\Tenant;
|
||||
use Illuminate\Support\Collection;
|
||||
use Illuminate\Support\Str;
|
||||
use InvalidArgumentException;
|
||||
|
||||
class LoadTestTicketDatasetService
|
||||
{
|
||||
public function __construct(
|
||||
private readonly TicketGeneratorService $ticketGenerator,
|
||||
private readonly TicketValidityResolver $validityResolver,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* @return array{
|
||||
* run_id: string,
|
||||
* tenant_code: string,
|
||||
* catalog_item_id: int,
|
||||
* variant_id: int|null,
|
||||
* tickets: int,
|
||||
* scanners: int,
|
||||
* owners: int,
|
||||
* rows: array<int, array{scanner_token: string, ticket_uuid: string, expected_status: int}>
|
||||
* }
|
||||
*/
|
||||
public function prepare(
|
||||
string $tenantCode,
|
||||
int $ticketCount,
|
||||
int $scannerCount,
|
||||
int $ownerCount,
|
||||
?int $catalogItemId = null,
|
||||
?int $variantId = null,
|
||||
?string $runId = null,
|
||||
): array {
|
||||
$this->validateInput($tenantCode, $ticketCount, $scannerCount, $ownerCount);
|
||||
|
||||
$tenant = Tenant::query()->where('codigo', $tenantCode)->firstOrFail();
|
||||
$catalogItem = $this->resolveCatalogItem($tenant, $catalogItemId);
|
||||
$variant = $this->resolveVariant($catalogItem, $variantId);
|
||||
$runId ??= now()->format('Ymd-His').'-'.Str::lower(Str::random(6));
|
||||
|
||||
if (preg_match('/\A[a-zA-Z0-9][a-zA-Z0-9._-]{0,63}\z/', $runId) !== 1) {
|
||||
throw new InvalidArgumentException('run_id contiene caracteres inválidos o es demasiado largo.');
|
||||
}
|
||||
|
||||
if ($variant !== null && ! $this->validityResolver->resolveVariant($variant)->isValid()) {
|
||||
throw new InvalidArgumentException(
|
||||
'La variante seleccionada no tiene una vigencia activa y resoluble.'
|
||||
);
|
||||
}
|
||||
|
||||
$scanners = $this->scanners($tenant, $catalogItem, $scannerCount);
|
||||
$owners = $this->owners($tenant, $ownerCount);
|
||||
$tokens = $scanners->map(function (User $scanner): string {
|
||||
$scanner->tokens()->where('name', 'load-test-scanner')->delete();
|
||||
|
||||
return $scanner->createToken(
|
||||
'load-test-scanner',
|
||||
['scanner'],
|
||||
now()->addMinutes((int) config('sanctum.expiration', 720)),
|
||||
)->plainTextToken;
|
||||
})->values();
|
||||
|
||||
$rows = [];
|
||||
$remaining = $ticketCount;
|
||||
$ownerIndex = 0;
|
||||
$scannerIndex = 0;
|
||||
$batchSize = min(500, max(1, (int) ceil($ticketCount / $ownerCount)));
|
||||
|
||||
while ($remaining > 0) {
|
||||
$quantity = min($batchSize, $remaining);
|
||||
$owner = $owners[$ownerIndex % $owners->count()];
|
||||
$tickets = $this->ticketGenerator->generate(
|
||||
$catalogItem,
|
||||
$owner,
|
||||
$quantity,
|
||||
$variant?->getKey(),
|
||||
);
|
||||
|
||||
foreach ($tickets as $ticket) {
|
||||
if (! $ticket->is_valid) {
|
||||
throw new InvalidArgumentException(
|
||||
'La configuración seleccionada genera tickets que no están vigentes.'
|
||||
);
|
||||
}
|
||||
|
||||
$rows[] = [
|
||||
'scanner_token' => $tokens[$scannerIndex % $tokens->count()],
|
||||
'ticket_uuid' => $ticket->ticket,
|
||||
'expected_status' => 200,
|
||||
];
|
||||
$scannerIndex++;
|
||||
}
|
||||
|
||||
$remaining -= $quantity;
|
||||
$ownerIndex++;
|
||||
}
|
||||
|
||||
return [
|
||||
'run_id' => $runId,
|
||||
'tenant_code' => $tenant->codigo,
|
||||
'catalog_item_id' => $catalogItem->getKey(),
|
||||
'variant_id' => $variant?->getKey(),
|
||||
'tickets' => count($rows),
|
||||
'scanners' => $scanners->count(),
|
||||
'owners' => $owners->count(),
|
||||
'rows' => $rows,
|
||||
];
|
||||
}
|
||||
|
||||
private function validateInput(
|
||||
string $tenantCode,
|
||||
int $ticketCount,
|
||||
int $scannerCount,
|
||||
int $ownerCount,
|
||||
): void {
|
||||
foreach ([
|
||||
'tickets' => [$ticketCount, 100_000],
|
||||
'scanners' => [$scannerCount, 10_000],
|
||||
'owners' => [$ownerCount, 100_000],
|
||||
] as $name => [$value, $maximum]) {
|
||||
if ($value < 1 || $value > $maximum) {
|
||||
throw new InvalidArgumentException("{$name} debe estar entre 1 y {$maximum}.");
|
||||
}
|
||||
}
|
||||
|
||||
if ($scannerCount > $ticketCount || $ownerCount > $ticketCount) {
|
||||
throw new InvalidArgumentException(
|
||||
'La cantidad de scanners y propietarios no puede superar la cantidad de tickets.'
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
private function resolveCatalogItem(Tenant $tenant, ?int $catalogItemId): CatalogItem
|
||||
{
|
||||
$query = $tenant->catalogItems()
|
||||
->where('has_tickets', true)
|
||||
->where('type', CatalogItemType::Standard->value);
|
||||
|
||||
if ($catalogItemId !== null) {
|
||||
$query->whereKey($catalogItemId);
|
||||
}
|
||||
|
||||
$catalogItem = $query->first();
|
||||
|
||||
if ($catalogItem === null) {
|
||||
throw new InvalidArgumentException(
|
||||
'No se encontró un producto estándar con tickets habilitados para el tenant.'
|
||||
);
|
||||
}
|
||||
|
||||
if ($tenant->requiresScannerCategoryValidation() && $catalogItem->category_id === null) {
|
||||
throw new InvalidArgumentException(
|
||||
'El producto debe tener una categoría para autorizar a los scanners.'
|
||||
);
|
||||
}
|
||||
|
||||
return $catalogItem;
|
||||
}
|
||||
|
||||
private function resolveVariant(CatalogItem $catalogItem, ?int $variantId): ?Variant
|
||||
{
|
||||
if ($variantId === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$variant = $catalogItem->variants()->whereKey($variantId)->first();
|
||||
|
||||
if ($variant === null) {
|
||||
throw new InvalidArgumentException('La variante no pertenece al producto seleccionado.');
|
||||
}
|
||||
|
||||
return $variant;
|
||||
}
|
||||
|
||||
/** @return Collection<int, User> */
|
||||
private function scanners(Tenant $tenant, CatalogItem $catalogItem, int $count): Collection
|
||||
{
|
||||
return Collection::times($count, function (int $number) use ($tenant, $catalogItem): User {
|
||||
$scanner = User::query()->updateOrCreate(
|
||||
['email' => $this->email($tenant, 'scanner', $number)],
|
||||
[
|
||||
'nombre_apellido' => "Load test scanner {$number}",
|
||||
'password' => Str::password(32),
|
||||
'rol_codigo' => RoleCode::Scanner->value,
|
||||
'tenant_codigo' => $tenant->codigo,
|
||||
],
|
||||
);
|
||||
if ($tenant->requiresScannerCategoryValidation()) {
|
||||
$scanner->scanCategories()->syncWithoutDetaching([$catalogItem->category_id]);
|
||||
}
|
||||
|
||||
return $scanner;
|
||||
});
|
||||
}
|
||||
|
||||
/** @return Collection<int, User> */
|
||||
private function owners(Tenant $tenant, int $count): Collection
|
||||
{
|
||||
return Collection::times($count, function (int $number) use ($tenant): User {
|
||||
$owner = User::query()->updateOrCreate(
|
||||
['email' => $this->email($tenant, 'owner', $number)],
|
||||
[
|
||||
'nombre_apellido' => "Load test owner {$number}",
|
||||
'password' => Str::password(32),
|
||||
'rol_codigo' => RoleCode::User->value,
|
||||
'tenant_codigo' => $tenant->codigo,
|
||||
],
|
||||
);
|
||||
|
||||
return $owner;
|
||||
});
|
||||
}
|
||||
|
||||
private function email(Tenant $tenant, string $kind, int $number): string
|
||||
{
|
||||
$tenantSlug = Str::lower(preg_replace('/[^a-z0-9]+/i', '-', $tenant->codigo));
|
||||
|
||||
return "loadtest+{$tenantSlug}.{$kind}.{$number}@shopit.test";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Ticket\Services;
|
||||
|
||||
use Carbon\CarbonInterface;
|
||||
use Illuminate\Support\Collection;
|
||||
|
||||
/**
|
||||
* Resultado completo de resolver la vigencia de un ticket.
|
||||
*
|
||||
* Cada ResolvedValidityGroup contiene condiciones AND. Entre los grupos se
|
||||
* aplica OR, por lo que alcanza con que uno de ellos esté activo.
|
||||
*/
|
||||
final readonly class ResolvedTicketValidity
|
||||
{
|
||||
/** @param Collection<int, ResolvedValidityGroup> $groups */
|
||||
public function __construct(
|
||||
public Collection $groups,
|
||||
public bool $isResolvable = true,
|
||||
public bool $isUnrestricted = false,
|
||||
) {}
|
||||
|
||||
/** No existe ninguna restricción temporal configurada. */
|
||||
public static function unrestricted(): self
|
||||
{
|
||||
return new self(collect(), isUnrestricted: true);
|
||||
}
|
||||
|
||||
/** La configuración fuente está incompleta o es inconsistente. */
|
||||
public static function unresolvable(): self
|
||||
{
|
||||
return new self(collect(), isResolvable: false);
|
||||
}
|
||||
|
||||
/** Es válido cuando no tiene restricciones o algún grupo OR está activo. */
|
||||
public function isValid(?CarbonInterface $at = null): bool
|
||||
{
|
||||
if (! $this->isResolvable) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return $this->isUnrestricted || $this->groups->contains(
|
||||
fn (ResolvedValidityGroup $group): bool => $group->isValid($at)
|
||||
);
|
||||
}
|
||||
|
||||
/** Sólo está vencido cuando todos los grupos OR ya vencieron. */
|
||||
public function isExpired(?CarbonInterface $at = null): bool
|
||||
{
|
||||
return $this->isResolvable
|
||||
&& ! $this->isUnrestricted
|
||||
&& $this->groups->isNotEmpty()
|
||||
&& $this->groups->every(
|
||||
fn (ResolvedValidityGroup $group): bool => $group->isExpired($at)
|
||||
);
|
||||
}
|
||||
|
||||
/** Inicio más temprano de todas las alternativas, usado como resumen. */
|
||||
public function effectiveStartsAt(?CarbonInterface $at = null): ?CarbonInterface
|
||||
{
|
||||
return $this->groups
|
||||
->map(fn (ResolvedValidityGroup $group): ?CarbonInterface => $group->effectiveStartsAt($at))
|
||||
->filter()
|
||||
->sortBy(fn (CarbonInterface $startsAt): int => $startsAt->getTimestamp())
|
||||
->first();
|
||||
}
|
||||
|
||||
/** Vencimiento más tardío de todas las alternativas, usado como resumen. */
|
||||
public function effectiveExpiresAt(?CarbonInterface $at = null): ?CarbonInterface
|
||||
{
|
||||
return $this->groups
|
||||
->map(fn (ResolvedValidityGroup $group): ?CarbonInterface => $group->effectiveExpiresAt($at))
|
||||
->filter()
|
||||
->sortByDesc(fn (CarbonInterface $expiresAt): int => $expiresAt->getTimestamp())
|
||||
->first();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Ticket\Services;
|
||||
|
||||
use App\Domains\Ticket\Enums\ValidityTimeType;
|
||||
use App\Domains\Ticket\Models\ValidityTime;
|
||||
use Carbon\CarbonInterface;
|
||||
use Illuminate\Support\Collection;
|
||||
|
||||
/**
|
||||
* Representa una intersección de vigencias: todos los ValidityTime del grupo
|
||||
* deben cumplirse simultáneamente (AND).
|
||||
*
|
||||
* Ejemplo: [fecha del evento, horario de almuerzo] significa que el ticket
|
||||
* solamente es válido durante la intersección de ambas ventanas.
|
||||
*/
|
||||
final readonly class ResolvedValidityGroup
|
||||
{
|
||||
/** @param Collection<int, ValidityTime> $validityTimes */
|
||||
public function __construct(public Collection $validityTimes) {}
|
||||
|
||||
/** Comprueba si el instante pertenece a la intersección efectiva del grupo. */
|
||||
public function isValid(?CarbonInterface $at = null): bool
|
||||
{
|
||||
$at ??= now();
|
||||
$startsAt = $this->effectiveStartsAt($at);
|
||||
$expiresAt = $this->effectiveExpiresAt($at);
|
||||
|
||||
return $this->validityTimes->isNotEmpty()
|
||||
&& ($startsAt === null || $startsAt->lessThanOrEqualTo($at))
|
||||
&& ($expiresAt === null || $expiresAt->greaterThan($at));
|
||||
}
|
||||
|
||||
/** Un grupo vence cuando termina su intersección efectiva. */
|
||||
public function isExpired(?CarbonInterface $at = null): bool
|
||||
{
|
||||
$at ??= now();
|
||||
$expiresAt = $this->effectiveExpiresAt($at);
|
||||
|
||||
return $expiresAt !== null && $expiresAt->lessThanOrEqualTo($at);
|
||||
}
|
||||
|
||||
/**
|
||||
* En un AND, la intersección comienza en el inicio más tardío.
|
||||
* Por ejemplo, fecha 00:00 + horario 12:00 comienza a las 12:00.
|
||||
*/
|
||||
public function effectiveStartsAt(?CarbonInterface $at = null): ?CarbonInterface
|
||||
{
|
||||
$at ??= now();
|
||||
$anchor = $this->dateAnchor() ?? $at;
|
||||
|
||||
return $this->validityTimes
|
||||
->map(fn (ValidityTime $validityTime): ?CarbonInterface => $validityTime->startsAt($anchor))
|
||||
->filter()
|
||||
->sortByDesc(fn (CarbonInterface $startsAt): int => $startsAt->getTimestamp())
|
||||
->first();
|
||||
}
|
||||
|
||||
/**
|
||||
* En un AND, la intersección termina en el vencimiento más temprano.
|
||||
* Los horarios cuyo fin no supera al inicio se interpretan como nocturnos.
|
||||
*/
|
||||
public function effectiveExpiresAt(?CarbonInterface $at = null): ?CarbonInterface
|
||||
{
|
||||
$at ??= now();
|
||||
$anchor = $this->dateAnchor() ?? $at;
|
||||
|
||||
return $this->validityTimes
|
||||
->map(function (ValidityTime $validityTime) use ($anchor): ?CarbonInterface {
|
||||
$startsAt = $validityTime->startsAt($anchor);
|
||||
$expiresAt = $validityTime->expiresAt($anchor);
|
||||
|
||||
if ($startsAt !== null && $expiresAt !== null && $expiresAt->lessThanOrEqualTo($startsAt)) {
|
||||
return $expiresAt->addDay();
|
||||
}
|
||||
|
||||
return $expiresAt;
|
||||
})
|
||||
->filter()
|
||||
->sortBy(fn (CarbonInterface $expiresAt): int => $expiresAt->getTimestamp())
|
||||
->first();
|
||||
}
|
||||
|
||||
/**
|
||||
* Usa la fecha de un fixed_window como ancla para convertir ventanas que
|
||||
* sólo contienen horas (time_window) en instantes concretos.
|
||||
*/
|
||||
private function dateAnchor(): ?CarbonInterface
|
||||
{
|
||||
return $this->validityTimes
|
||||
->filter(fn (ValidityTime $validityTime): bool => $validityTime->type === ValidityTimeType::FixedWindow)
|
||||
->map(fn (ValidityTime $validityTime): ?CarbonInterface => $validityTime->fixed_starts_at)
|
||||
->filter()
|
||||
->sortByDesc(fn (CarbonInterface $startsAt): int => $startsAt->getTimestamp())
|
||||
->first();
|
||||
}
|
||||
}
|
||||
335
app/Domains/Ticketing/Ticket/Services/ScannerTicketService.php
Normal file
335
app/Domains/Ticketing/Ticket/Services/ScannerTicketService.php
Normal file
@@ -0,0 +1,335 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Ticket\Services;
|
||||
|
||||
use App\Domains\Auth\Models\User;
|
||||
use App\Domains\Ticket\Enums\ScanAttemptResult;
|
||||
use App\Domains\Ticket\Models\ScanAttempt;
|
||||
use App\Domains\Ticket\Models\Ticket;
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
use Illuminate\Database\Eloquent\ModelNotFoundException;
|
||||
use Illuminate\Pagination\LengthAwarePaginator;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Str;
|
||||
use Throwable;
|
||||
|
||||
class ScannerTicketService
|
||||
{
|
||||
/**
|
||||
* @param array{q?: string|null, page?: int, per_page?: int} $filters
|
||||
* @return LengthAwarePaginator<ScanAttempt>
|
||||
*/
|
||||
public function attemptsBy(User $scanner, array $filters = []): LengthAwarePaginator
|
||||
{
|
||||
$search = trim((string) ($filters['q'] ?? ''));
|
||||
|
||||
return ScanAttempt::query()
|
||||
->with('ticket.sourceCatalogItem.category')
|
||||
->where('tenant_code', $scanner->tenant_codigo)
|
||||
->where('scanner_user_id', $scanner->getKey())
|
||||
->when($search !== '', function (Builder $query) use ($search): void {
|
||||
$attemptedAtDate = $this->parseSearchDate($search);
|
||||
|
||||
$query->where(function (Builder $searchQuery) use ($search, $attemptedAtDate): void {
|
||||
$searchQuery->where('data', 'like', "%{$search}%");
|
||||
|
||||
if (ctype_digit($search)) {
|
||||
$searchQuery->orWhere('id', (int) $search);
|
||||
}
|
||||
|
||||
if ($attemptedAtDate !== null) {
|
||||
$searchQuery->orWhereDate('created_at', $attemptedAtDate);
|
||||
}
|
||||
});
|
||||
})
|
||||
->orderByDesc('created_at')
|
||||
->orderByDesc('id')
|
||||
->paginateFromRequest()
|
||||
->withQueryString();
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array{q?: string|null, page?: int, per_page?: int} $filters
|
||||
* @return LengthAwarePaginator<ScanAttempt>
|
||||
*/
|
||||
public function attemptsByStaff(User $scanner, array $filters = []): LengthAwarePaginator
|
||||
{
|
||||
$search = trim((string) ($filters['q'] ?? ''));
|
||||
|
||||
return ScanAttempt::query()
|
||||
->with('ticket.sourceCatalogItem.category')
|
||||
->where('tenant_code', $scanner->tenant_codigo)
|
||||
->where('scanner_user_id', $scanner->getKey())
|
||||
->when($search !== '', function (Builder $query) use ($search): void {
|
||||
$attemptedAtDate = $this->parseSearchDate($search);
|
||||
$attemptedAtDayMonth = $this->parseSearchDayMonth($search);
|
||||
|
||||
$query->where(function (Builder $searchQuery) use (
|
||||
$search,
|
||||
$attemptedAtDate,
|
||||
$attemptedAtDayMonth,
|
||||
): void {
|
||||
$searchQuery
|
||||
->whereHas(
|
||||
'ticket.sourceCatalogItem.category',
|
||||
fn (Builder $categoryQuery): Builder => $categoryQuery
|
||||
->where('nombre', 'like', "%{$search}%")
|
||||
)
|
||||
->orWhere('created_at', 'like', "%{$search}%");
|
||||
|
||||
if (ctype_digit($search)) {
|
||||
$searchQuery->orWhere('ticket_id', (int) $search);
|
||||
}
|
||||
|
||||
if ($attemptedAtDate !== null) {
|
||||
$searchQuery->orWhereDate('created_at', $attemptedAtDate);
|
||||
}
|
||||
|
||||
if ($attemptedAtDayMonth !== null) {
|
||||
$searchQuery->orWhere(function (Builder $dateQuery) use ($attemptedAtDayMonth): void {
|
||||
$dateQuery
|
||||
->whereDay('created_at', $attemptedAtDayMonth['day'])
|
||||
->whereMonth('created_at', $attemptedAtDayMonth['month']);
|
||||
});
|
||||
}
|
||||
});
|
||||
})
|
||||
->orderByDesc('created_at')
|
||||
->orderByDesc('id')
|
||||
->paginateFromRequest()
|
||||
->withQueryString();
|
||||
}
|
||||
|
||||
public function scanAttemptDetail(User $scanner, int $scanAttemptId): ScanAttempt
|
||||
{
|
||||
$scanAttempt = ScanAttempt::query()
|
||||
->with('ticket')
|
||||
->where('tenant_code', $scanner->tenant_codigo)
|
||||
->where('scanner_user_id', $scanner->getKey())
|
||||
->findOrFail($scanAttemptId);
|
||||
|
||||
$scanAttempt->ticket?->loadMissing($this->relations());
|
||||
|
||||
return $scanAttempt;
|
||||
}
|
||||
|
||||
private function parseSearchDate(string $search): ?string
|
||||
{
|
||||
if (preg_match('/^(\d{4})-(\d{2})-(\d{2})$/', $search, $matches) === 1) {
|
||||
[$year, $month, $day] = array_map('intval', array_slice($matches, 1));
|
||||
|
||||
if (checkdate($month, $day, $year)) {
|
||||
return sprintf('%04d-%02d-%02d', $year, $month, $day);
|
||||
}
|
||||
}
|
||||
|
||||
if (preg_match('/^(\d{2})\/(\d{2})\/(\d{2}|\d{4})$/', $search, $matches) === 1) {
|
||||
$day = (int) $matches[1];
|
||||
$month = (int) $matches[2];
|
||||
$year = (int) $matches[3];
|
||||
$year = strlen($matches[3]) === 2 ? 2000 + $year : $year;
|
||||
|
||||
if (checkdate($month, $day, $year)) {
|
||||
return sprintf('%04d-%02d-%02d', $year, $month, $day);
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/** @return array{day: int, month: int}|null */
|
||||
private function parseSearchDayMonth(string $search): ?array
|
||||
{
|
||||
if (preg_match('/^(\d{1,2})\/(\d{1,2})$/', $search, $matches) !== 1) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$day = (int) $matches[1];
|
||||
$month = (int) $matches[2];
|
||||
|
||||
return checkdate($month, $day, 2000) ? compact('day', 'month') : null;
|
||||
}
|
||||
|
||||
public function detail(User $scanner, string $ticketUuid): Ticket
|
||||
{
|
||||
$query = $this->baseQuery()
|
||||
->where('tenant_code', $scanner->tenant_codigo)
|
||||
->where('ticket', $ticketUuid);
|
||||
|
||||
if ($this->requiresCategoryValidation($scanner)) {
|
||||
$categoryIds = $this->scannerCategoryIds($scanner);
|
||||
|
||||
$query->where(function (Builder $query) use ($scanner, $categoryIds): void {
|
||||
$query
|
||||
->where('scanner_user_id', $scanner->getKey())
|
||||
->orWhereHas(
|
||||
'sourceCatalogItem',
|
||||
fn (Builder $catalogItemQuery): Builder => $catalogItemQuery
|
||||
->whereIn('category_id', $categoryIds)
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
return $query->firstOrFail();
|
||||
}
|
||||
|
||||
public function scan(User $scanner, mixed $scannedData): ScanAttempt
|
||||
{
|
||||
$scanAttempt = ScanAttempt::query()->create([
|
||||
'tenant_code' => $scanner->tenant_codigo,
|
||||
'scanner_user_id' => $scanner->getKey(),
|
||||
'data' => $this->serializeScannedData($scannedData),
|
||||
'result' => ScanAttemptResult::Processing,
|
||||
]);
|
||||
|
||||
if (! is_string($scannedData) || ! Str::isUuid($scannedData)) {
|
||||
$this->resolveScanAttempt($scanAttempt, ScanAttemptResult::InvalidQr);
|
||||
|
||||
return $scanAttempt->refresh();
|
||||
}
|
||||
|
||||
$ticketId = null;
|
||||
|
||||
try {
|
||||
return DB::transaction(function () use (
|
||||
$scanner,
|
||||
$scannedData,
|
||||
$scanAttempt,
|
||||
&$ticketId,
|
||||
): ScanAttempt {
|
||||
$ticket = $this->baseQuery()
|
||||
->where('tenant_code', $scanner->tenant_codigo)
|
||||
->where('ticket', $scannedData)
|
||||
->lockForUpdate()
|
||||
->firstOrFail();
|
||||
$ticketId = (int) $ticket->getKey();
|
||||
|
||||
if (! $this->scannerCanScan($scanner, $ticket)) {
|
||||
$this->resolveScanAttempt(
|
||||
$scanAttempt,
|
||||
ScanAttemptResult::CategoryForbidden,
|
||||
$ticketId,
|
||||
);
|
||||
|
||||
return $scanAttempt->refresh()->setRelation('ticket', $ticket);
|
||||
}
|
||||
|
||||
if ($ticket->is_used) {
|
||||
$this->resolveScanAttempt(
|
||||
$scanAttempt,
|
||||
ScanAttemptResult::AlreadyScanned,
|
||||
$ticketId,
|
||||
);
|
||||
|
||||
return $scanAttempt->refresh()->setRelation('ticket', $ticket);
|
||||
}
|
||||
|
||||
if (! $ticket->is_valid) {
|
||||
$result = $ticket->is_expired
|
||||
? ScanAttemptResult::Expired
|
||||
: ScanAttemptResult::NotValid;
|
||||
$this->resolveScanAttempt($scanAttempt, $result, $ticketId);
|
||||
|
||||
return $scanAttempt->refresh()->setRelation('ticket', $ticket);
|
||||
}
|
||||
|
||||
$ticket->forceFill([
|
||||
'used_at' => now(),
|
||||
'scanner_user_id' => $scanner->getKey(),
|
||||
])->save();
|
||||
|
||||
$this->resolveScanAttempt(
|
||||
$scanAttempt,
|
||||
ScanAttemptResult::Accepted,
|
||||
$ticketId,
|
||||
);
|
||||
|
||||
$ticket = $ticket->refresh()->load($this->relations());
|
||||
|
||||
return $scanAttempt->refresh()->setRelation('ticket', $ticket);
|
||||
});
|
||||
} catch (ModelNotFoundException) {
|
||||
$this->resolveScanAttempt($scanAttempt, ScanAttemptResult::TicketNotFound);
|
||||
|
||||
return $scanAttempt->refresh();
|
||||
} catch (Throwable $exception) {
|
||||
report($exception);
|
||||
$this->resolveScanAttempt($scanAttempt, ScanAttemptResult::UnexpectedError, $ticketId);
|
||||
|
||||
return $scanAttempt->refresh();
|
||||
}
|
||||
}
|
||||
|
||||
private function resolveScanAttempt(
|
||||
ScanAttempt $scanAttempt,
|
||||
ScanAttemptResult $result,
|
||||
?int $ticketId = null,
|
||||
): void {
|
||||
$scanAttempt->forceFill([
|
||||
'ticket_id' => $ticketId,
|
||||
'result' => $result,
|
||||
'resolved_at' => now(),
|
||||
])->save();
|
||||
}
|
||||
|
||||
private function serializeScannedData(mixed $scannedData): ?string
|
||||
{
|
||||
if ($scannedData === null || is_string($scannedData)) {
|
||||
return $scannedData;
|
||||
}
|
||||
|
||||
$encoded = json_encode(
|
||||
$scannedData,
|
||||
JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_INVALID_UTF8_SUBSTITUTE,
|
||||
);
|
||||
|
||||
return $encoded === false ? get_debug_type($scannedData) : $encoded;
|
||||
}
|
||||
|
||||
/** @return Builder<Ticket> */
|
||||
private function baseQuery(): Builder
|
||||
{
|
||||
return Ticket::query()->with($this->relations());
|
||||
}
|
||||
|
||||
/** @return array<int, string> */
|
||||
private function relations(): array
|
||||
{
|
||||
return [
|
||||
...TicketValidityResolver::RELATIONS,
|
||||
...TicketPresentationResolver::RELATIONS,
|
||||
'sourceCatalogItem.category',
|
||||
'sourceVariant.eventDate',
|
||||
'sourceVariant.catalogItem',
|
||||
'user',
|
||||
];
|
||||
}
|
||||
|
||||
/** @return array<int, int> */
|
||||
private function scannerCategoryIds(User $scanner): array
|
||||
{
|
||||
return $scanner->scanCategories()
|
||||
->pluck('categorias.id')
|
||||
->map(fn (mixed $id): int => (int) $id)
|
||||
->all();
|
||||
}
|
||||
|
||||
private function scannerCanScan(User $scanner, Ticket $ticket): bool
|
||||
{
|
||||
if (! $this->requiresCategoryValidation($scanner)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
$categoryId = $ticket->sourceCatalogItem?->category_id;
|
||||
|
||||
return $categoryId !== null
|
||||
&& $scanner->scanCategories()
|
||||
->where('categorias.id', $categoryId)
|
||||
->exists();
|
||||
}
|
||||
|
||||
private function requiresCategoryValidation(User $scanner): bool
|
||||
{
|
||||
return $scanner->tenant()->firstOrFail()->requiresScannerCategoryValidation();
|
||||
}
|
||||
}
|
||||
153
app/Domains/Ticketing/Ticket/Services/TicketGeneratorService.php
Normal file
153
app/Domains/Ticketing/Ticket/Services/TicketGeneratorService.php
Normal file
@@ -0,0 +1,153 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Ticket\Services;
|
||||
|
||||
use App\Domains\Auth\Models\User;
|
||||
use App\Domains\Catalog\Models\CatalogItem;
|
||||
use App\Domains\Catalog\Models\Variant;
|
||||
use App\Domains\Ticket\Exceptions\TicketGenerationException;
|
||||
use App\Domains\Ticket\Models\Ticket;
|
||||
use Illuminate\Support\Collection;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Str;
|
||||
|
||||
class TicketGeneratorService
|
||||
{
|
||||
public function __construct(private readonly TicketValidityResolver $validityResolver) {}
|
||||
|
||||
/**
|
||||
* @return Collection<int, Ticket>
|
||||
*/
|
||||
public function generate(
|
||||
CatalogItem $catalogItem,
|
||||
User $user,
|
||||
int $quantity = 1,
|
||||
?int $sourceVariantId = null,
|
||||
?int $sourcePurchaseItemId = null,
|
||||
): Collection {
|
||||
if ($quantity < 1) {
|
||||
throw TicketGenerationException::invalidQuantity();
|
||||
}
|
||||
|
||||
return DB::transaction(function () use ($catalogItem, $user, $quantity, $sourceVariantId, $sourcePurchaseItemId): Collection {
|
||||
$targets = $this->resolveTargets(
|
||||
$catalogItem,
|
||||
$quantity,
|
||||
$sourceVariantId,
|
||||
);
|
||||
|
||||
return $targets->map(function (array $target) use (
|
||||
$sourcePurchaseItemId,
|
||||
$user,
|
||||
): Ticket {
|
||||
$item = $target['catalog_item'];
|
||||
$variant = $target['variant'];
|
||||
$ticket = Ticket::query()->create([
|
||||
'tenant_code' => $item->tenant_code,
|
||||
'ticket' => (string) Str::uuid(),
|
||||
'source_purchase_item_id' => $sourcePurchaseItemId,
|
||||
'source_catalog_item_id' => $item->getKey(),
|
||||
'source_variant_id' => $variant?->getKey(),
|
||||
'used_at' => null,
|
||||
'user_id' => $user->getKey(),
|
||||
]);
|
||||
|
||||
return $ticket;
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/** @return Collection<int, array{catalog_item: CatalogItem, variant: Variant|null}> */
|
||||
private function resolveTargets(
|
||||
CatalogItem $catalogItem,
|
||||
int $quantity,
|
||||
?int $sourceVariantId,
|
||||
): Collection {
|
||||
if (! $catalogItem->isBundle()) {
|
||||
$variant = $this->resolveVariant($catalogItem, $sourceVariantId);
|
||||
$this->validateTarget($catalogItem, $variant);
|
||||
|
||||
return $this->targetsForVariant($catalogItem, $variant, $quantity);
|
||||
}
|
||||
|
||||
$catalogItem->loadMissing([
|
||||
'bundleComponents.catalogItem',
|
||||
'bundleComponents.variant.catalogItem',
|
||||
]);
|
||||
|
||||
if ($catalogItem->bundleComponents->isEmpty()) {
|
||||
throw TicketGenerationException::emptyBundle($catalogItem);
|
||||
}
|
||||
|
||||
return $catalogItem->bundleComponents
|
||||
->flatMap(function ($component) use ($quantity): Collection {
|
||||
$componentItem = $component->catalogItem;
|
||||
$variant = $component->variant;
|
||||
$this->validateTarget($componentItem, $variant);
|
||||
|
||||
return $this->targetsForVariant(
|
||||
$componentItem,
|
||||
$variant,
|
||||
$quantity * $component->quantity,
|
||||
);
|
||||
})
|
||||
->values();
|
||||
}
|
||||
|
||||
/** @return Collection<int, array{catalog_item: CatalogItem, variant: Variant|null}> */
|
||||
private function targetsForVariant(
|
||||
CatalogItem $catalogItem,
|
||||
?Variant $variant,
|
||||
int $quantity,
|
||||
): Collection {
|
||||
if ($variant === null) {
|
||||
return Collection::times($quantity, fn (): array => [
|
||||
'catalog_item' => $catalogItem,
|
||||
'variant' => null,
|
||||
]);
|
||||
}
|
||||
|
||||
$variant->loadMissing(['eventDates.validityTime', 'eventDate.validityTime']);
|
||||
if (! $this->validityResolver->resolveVariant($variant)->isResolvable) {
|
||||
throw TicketGenerationException::invalidValidityConfiguration($catalogItem, $variant);
|
||||
}
|
||||
|
||||
return Collection::times($quantity, fn (): array => [
|
||||
'catalog_item' => $catalogItem,
|
||||
'variant' => $variant,
|
||||
]);
|
||||
}
|
||||
|
||||
private function resolveVariant(
|
||||
CatalogItem $catalogItem,
|
||||
?int $sourceVariantId,
|
||||
): ?Variant {
|
||||
if ($sourceVariantId === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$variant = $catalogItem->variants()
|
||||
->whereKey($sourceVariantId)
|
||||
->first();
|
||||
|
||||
if ($variant === null) {
|
||||
throw TicketGenerationException::variantNotFound(
|
||||
$catalogItem,
|
||||
$sourceVariantId,
|
||||
);
|
||||
}
|
||||
|
||||
$variant->setRelation('catalogItem', $catalogItem);
|
||||
|
||||
return $variant;
|
||||
}
|
||||
|
||||
private function validateTarget(
|
||||
CatalogItem $catalogItem,
|
||||
?Variant $variant,
|
||||
): void {
|
||||
if (! $catalogItem->has_tickets) {
|
||||
throw TicketGenerationException::ticketsDisabled($catalogItem);
|
||||
}
|
||||
}
|
||||
}
|
||||
109
app/Domains/Ticketing/Ticket/Services/TicketPdfService.php
Normal file
109
app/Domains/Ticketing/Ticket/Services/TicketPdfService.php
Normal file
@@ -0,0 +1,109 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Ticket\Services;
|
||||
|
||||
use App\Domains\Tenant\Models\Tenant;
|
||||
use App\Domains\Ticket\Models\Ticket;
|
||||
use Barryvdh\DomPDF\Facade\Pdf;
|
||||
use Barryvdh\DomPDF\PDF as DomPdf;
|
||||
use Endroid\QrCode\ErrorCorrectionLevel;
|
||||
use Endroid\QrCode\QrCode;
|
||||
use Endroid\QrCode\Writer\PngWriter;
|
||||
use Illuminate\Http\Response;
|
||||
use Illuminate\Support\Collection;
|
||||
use Illuminate\Support\Facades\Storage;
|
||||
use Throwable;
|
||||
|
||||
class TicketPdfService
|
||||
{
|
||||
/**
|
||||
* @param Collection<int, Ticket> $tickets
|
||||
*/
|
||||
public function download(Tenant $tenant, Collection $tickets): Response
|
||||
{
|
||||
return $this->pdf($tenant, $tickets)->download($this->filename($tickets));
|
||||
}
|
||||
|
||||
/**
|
||||
* @param Collection<int, Ticket> $tickets
|
||||
*/
|
||||
public function contents(Tenant $tenant, Collection $tickets): string
|
||||
{
|
||||
return $this->pdf($tenant, $tickets)->output();
|
||||
}
|
||||
|
||||
/**
|
||||
* @param Collection<int, Ticket> $tickets
|
||||
*/
|
||||
public function filename(Collection $tickets): string
|
||||
{
|
||||
return 'tickets_'.$tickets->pluck('id')->implode('_').'.pdf';
|
||||
}
|
||||
|
||||
/**
|
||||
* @param Collection<int, Ticket> $tickets
|
||||
*/
|
||||
private function pdf(Tenant $tenant, Collection $tickets): DomPdf
|
||||
{
|
||||
$tenant->loadMissing('headerLogo');
|
||||
$primaryColor = $this->color($tenant->primary_color, '#009933');
|
||||
$headerBackgroundColor = $this->color($tenant->header_bg_color, $primaryColor);
|
||||
|
||||
return Pdf::loadView('pdf.tickets', [
|
||||
'tenant' => $tenant,
|
||||
'tickets' => $tickets,
|
||||
'logoDataUri' => $this->logoDataUri($tenant),
|
||||
'primaryColor' => $primaryColor,
|
||||
'headerBackgroundColor' => $headerBackgroundColor,
|
||||
'headerTextColor' => $this->contrastingTextColor($headerBackgroundColor),
|
||||
'qrCodes' => $tickets->mapWithKeys(
|
||||
fn (Ticket $ticket): array => [$ticket->id => $this->qrCodeDataUri($ticket->ticket)]
|
||||
),
|
||||
])->setPaper('a4');
|
||||
}
|
||||
|
||||
private function qrCodeDataUri(string $value): string
|
||||
{
|
||||
$qrCode = new QrCode(
|
||||
data: $value,
|
||||
errorCorrectionLevel: ErrorCorrectionLevel::Medium,
|
||||
size: 700,
|
||||
margin: 10,
|
||||
);
|
||||
|
||||
return (new PngWriter)->write($qrCode)->getDataUri();
|
||||
}
|
||||
|
||||
private function logoDataUri(Tenant $tenant): ?string
|
||||
{
|
||||
$logo = $tenant->headerLogo;
|
||||
if ($logo === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
$contents = Storage::disk('s3')->get($logo->path);
|
||||
} catch (Throwable) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return 'data:'.($logo->mime_type ?: 'image/png').';base64,'.base64_encode($contents);
|
||||
}
|
||||
|
||||
private function color(?string $color, string $fallback): string
|
||||
{
|
||||
return is_string($color) && preg_match('/^#[0-9A-Fa-f]{6}$/', $color)
|
||||
? $color
|
||||
: $fallback;
|
||||
}
|
||||
|
||||
private function contrastingTextColor(string $backgroundColor): string
|
||||
{
|
||||
$red = hexdec(substr($backgroundColor, 1, 2));
|
||||
$green = hexdec(substr($backgroundColor, 3, 2));
|
||||
$blue = hexdec(substr($backgroundColor, 5, 2));
|
||||
$luminance = ($red * 299 + $green * 587 + $blue * 114) / 1000;
|
||||
|
||||
return $luminance > 160 ? '#17211b' : '#ffffff';
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Ticket\Services;
|
||||
|
||||
use App\Domains\Event\Models\EventDate;
|
||||
use App\Domains\Event\Services\EffectiveEventDateResolver;
|
||||
use App\Domains\Ticket\Models\Ticket;
|
||||
|
||||
class TicketPresentationResolver
|
||||
{
|
||||
public function __construct(private readonly EffectiveEventDateResolver $effectiveEventDateResolver) {}
|
||||
|
||||
/** Relaciones necesarias para calcular nombre y descripción sin consultas N+1. */
|
||||
public const RELATIONS = [
|
||||
'sourceCatalogItem',
|
||||
'sourceVariant.catalogItem.itemAttributes.attribute.options',
|
||||
'sourceVariant.definitions.itemAttribute.attribute.options',
|
||||
'sourceVariant.eventDates',
|
||||
'sourceVariant.eventDate',
|
||||
];
|
||||
|
||||
public function name(Ticket $ticket): string
|
||||
{
|
||||
$ticket->loadMissing(self::RELATIONS);
|
||||
$catalogItem = $ticket->sourceCatalogItem;
|
||||
|
||||
if ($catalogItem === null) {
|
||||
return '';
|
||||
}
|
||||
|
||||
$variant = $ticket->sourceVariant;
|
||||
if ($variant === null) {
|
||||
return $catalogItem->nombre;
|
||||
}
|
||||
|
||||
$itemAttributes = $variant->catalogItem->itemAttributes;
|
||||
$eventDateLabels = $variant->selectedEventDates()
|
||||
->map(fn (EventDate $date): EventDate => $this->effectiveEventDateResolver->resolveLatest($date) ?? $date)
|
||||
->unique(fn (EventDate $date): int => $date->getKey())
|
||||
->map(fn (EventDate $date): string => $date->date->format('d/m/Y'))
|
||||
->implode(', ');
|
||||
|
||||
$properties = $variant->selectionOptions($itemAttributes)
|
||||
->map(function (array $option, string $attributeCode) use ($itemAttributes, $eventDateLabels): ?string {
|
||||
$labels = $attributeCode === 'event_date' ? $eventDateLabels : collect(array_is_list($option) ? $option : [$option])
|
||||
->pluck('label')
|
||||
->filter(fn ($label): bool => is_string($label) && $label !== '')
|
||||
->implode(', ');
|
||||
|
||||
if ($labels === '') {
|
||||
return null;
|
||||
}
|
||||
|
||||
$ticketLabel = $itemAttributes->first(
|
||||
fn ($itemAttribute): bool => $itemAttribute->attribute?->codigo === $attributeCode,
|
||||
)?->ticket_label;
|
||||
|
||||
return is_string($ticketLabel) && trim($ticketLabel) !== ''
|
||||
? trim($ticketLabel).' '.$labels
|
||||
: $labels;
|
||||
})
|
||||
->filter()
|
||||
->values();
|
||||
|
||||
return $properties->isEmpty()
|
||||
? $catalogItem->nombre
|
||||
: $catalogItem->nombre.' ('.$properties->implode(', ').')';
|
||||
}
|
||||
|
||||
public function description(Ticket $ticket): string
|
||||
{
|
||||
$ticket->loadMissing(self::RELATIONS);
|
||||
|
||||
return (string) ($ticket->sourceVariant?->getDescription()
|
||||
?? $ticket->sourceCatalogItem?->descripcion
|
||||
?? '');
|
||||
}
|
||||
}
|
||||
155
app/Domains/Ticketing/Ticket/Services/TicketValidityResolver.php
Normal file
155
app/Domains/Ticketing/Ticket/Services/TicketValidityResolver.php
Normal file
@@ -0,0 +1,155 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Ticket\Services;
|
||||
|
||||
use App\Domains\Catalog\Models\Variant;
|
||||
use App\Domains\Catalog\Models\VariantDefinition;
|
||||
use App\Domains\Event\Models\EventDate;
|
||||
use App\Domains\Event\Services\EffectiveEventDateResolver;
|
||||
use App\Domains\Ticket\Models\Ticket;
|
||||
use App\Domains\Ticket\Models\ValidityTime;
|
||||
use Illuminate\Support\Collection;
|
||||
|
||||
/**
|
||||
* Deriva la expresión temporal de un ticket desde su variante.
|
||||
*
|
||||
* Las selecciones alternativas de una misma dimensión (varias fechas u opciones
|
||||
* multiselección) se interpretan como OR. Las dimensiones diferentes se combinan
|
||||
* mediante AND usando un producto cartesiano.
|
||||
*/
|
||||
class TicketValidityResolver
|
||||
{
|
||||
private readonly EffectiveEventDateResolver $effectiveEventDateResolver;
|
||||
|
||||
public function __construct(?EffectiveEventDateResolver $effectiveEventDateResolver = null)
|
||||
{
|
||||
$this->effectiveEventDateResolver = $effectiveEventDateResolver
|
||||
?? new EffectiveEventDateResolver;
|
||||
}
|
||||
|
||||
/** Relaciones necesarias para resolver tickets sin consultas N+1. */
|
||||
public const RELATIONS = [
|
||||
'sourceVariant.eventDates.validityTime',
|
||||
'sourceVariant.eventDate.validityTime',
|
||||
'sourceVariant.definitions.itemAttribute.attribute.options.validityTime',
|
||||
];
|
||||
|
||||
/**
|
||||
* Resuelve la variante fuente del ticket. Un ticket creado legítimamente sin
|
||||
* variante es irrestricto; una referencia esperada pero rota es irresoluble.
|
||||
*/
|
||||
public function resolveTicket(Ticket $ticket): ResolvedTicketValidity
|
||||
{
|
||||
if ($ticket->source_variant_id === null) {
|
||||
return ResolvedTicketValidity::unrestricted();
|
||||
}
|
||||
|
||||
$ticket->loadMissing(self::RELATIONS);
|
||||
|
||||
if ($ticket->sourceVariant === null) {
|
||||
return ResolvedTicketValidity::unresolvable();
|
||||
}
|
||||
|
||||
return $this->resolveVariant($ticket->sourceVariant);
|
||||
}
|
||||
|
||||
/**
|
||||
* Convierte las fechas y definiciones temporales de la variante en grupos
|
||||
* normalizados: AND dentro de cada grupo y OR entre grupos.
|
||||
*/
|
||||
public function resolveVariant(Variant $variant): ResolvedTicketValidity
|
||||
{
|
||||
$variant->loadMissing([
|
||||
'eventDates.validityTime',
|
||||
'eventDate.validityTime',
|
||||
'definitions.itemAttribute.attribute.options.validityTime',
|
||||
]);
|
||||
|
||||
$dimensions = collect();
|
||||
$selectedEventDates = $variant->selectedEventDates();
|
||||
$eventDates = $selectedEventDates
|
||||
->map(fn (EventDate $eventDate): ?EventDate => $this->effectiveEventDateResolver->resolve($eventDate))
|
||||
->filter()
|
||||
->unique(fn (EventDate $eventDate): int => $eventDate->getKey() ?? spl_object_id($eventDate))
|
||||
->values();
|
||||
|
||||
if ($selectedEventDates->isNotEmpty() && $eventDates->isEmpty()) {
|
||||
return ResolvedTicketValidity::unresolvable();
|
||||
}
|
||||
|
||||
$eventDates->each->loadMissing('validityTime');
|
||||
|
||||
if ($eventDates->contains(fn ($eventDate): bool => $eventDate->validityTime === null)) {
|
||||
return ResolvedTicketValidity::unresolvable();
|
||||
}
|
||||
|
||||
if ($eventDates->isNotEmpty()) {
|
||||
// Todas las fechas pertenecen a una misma dimensión alternativa:
|
||||
// fecha 1 OR fecha 2 OR fecha 3.
|
||||
$dimensions->push(
|
||||
$eventDates->map(fn ($eventDate): Collection => collect([$eventDate->validityTime]))
|
||||
);
|
||||
}
|
||||
|
||||
foreach ($variant->definitions->groupBy('item_attribute_id') as $definitions) {
|
||||
$itemAttribute = $definitions->first()?->itemAttribute;
|
||||
$attribute = $itemAttribute?->attribute;
|
||||
|
||||
if ($itemAttribute === null || $attribute === null) {
|
||||
return ResolvedTicketValidity::unresolvable();
|
||||
}
|
||||
|
||||
if (! $attribute->type->supportsOptions() || $attribute->type->usesDynamicOptions()) {
|
||||
// Texto, números y demás atributos no temporales no restringen
|
||||
// la vigencia. EventDate se procesó arriba mediante su relación.
|
||||
continue;
|
||||
}
|
||||
|
||||
if (! $itemAttribute->allow_multi_select && $definitions->count() > 1) {
|
||||
return ResolvedTicketValidity::unresolvable();
|
||||
}
|
||||
|
||||
$alternatives = $definitions->map(function (VariantDefinition $definition) use ($attribute): ?Collection {
|
||||
$option = $attribute->options->firstWhere('value', $definition->value);
|
||||
|
||||
if ($option === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return collect([$option->validityTime])->filter()->values();
|
||||
});
|
||||
|
||||
if ($alternatives->contains(null)) {
|
||||
return ResolvedTicketValidity::unresolvable();
|
||||
}
|
||||
|
||||
if ($alternatives->contains(fn (Collection $alternative): bool => $alternative->isNotEmpty())) {
|
||||
// Las opciones elegidas del mismo atributo son alternativas OR.
|
||||
$dimensions->push($alternatives->values());
|
||||
}
|
||||
}
|
||||
|
||||
if ($dimensions->isEmpty()) {
|
||||
return ResolvedTicketValidity::unrestricted();
|
||||
}
|
||||
|
||||
$groups = collect([collect()]);
|
||||
|
||||
foreach ($dimensions as $alternatives) {
|
||||
// El producto cartesiano agrega cada dimensión como una condición
|
||||
// AND y conserva sus opciones internas como alternativas OR.
|
||||
$groups = $groups->flatMap(
|
||||
fn (Collection $group): Collection => $alternatives->map(
|
||||
fn (Collection $alternative): Collection => $group
|
||||
->merge($alternative)
|
||||
->unique(fn (ValidityTime $time): int => $time->getKey() ?? spl_object_id($time))
|
||||
->values()
|
||||
)
|
||||
)->values();
|
||||
}
|
||||
|
||||
return new ResolvedTicketValidity(
|
||||
$groups->map(fn (Collection $times): ResolvedValidityGroup => new ResolvedValidityGroup($times))
|
||||
);
|
||||
}
|
||||
}
|
||||
71
app/Domains/Ticketing/Ticket/documentacion/README.md
Normal file
71
app/Domains/Ticketing/Ticket/documentacion/README.md
Normal file
@@ -0,0 +1,71 @@
|
||||
# Dominio Ticket
|
||||
|
||||
## Propósito
|
||||
|
||||
Genera, valida, consulta y exporta entradas asociadas a compras pagadas de productos o variantes ticketables.
|
||||
|
||||
## Modelo
|
||||
|
||||
- `Ticket`: pertenece a tenant y usuario, y conserva referencias al ítem de compra que lo generó, producto,
|
||||
variante y usuario escáner. La compra se obtiene a través de su ítem.
|
||||
- El nombre y la descripción se calculan dinámicamente desde el producto y la variante; los tickets no
|
||||
persisten una copia de esos textos.
|
||||
- `ValidityTime`: define ventanas absolutas o relativas de vigencia para fechas de evento y opciones de atributos.
|
||||
- `ValidityTimeType`: enum de estrategias de vigencia.
|
||||
|
||||
`TicketValidityResolver` deriva la vigencia desde la variante asociada. Las alternativas de un mismo atributo
|
||||
se combinan con OR y las dimensiones diferentes se combinan con AND. El modelo calcula si un ticket está
|
||||
vigente, vencido o usado, y resuelve sus fechas efectivas de inicio y fin sin persistir vigencias en el ticket.
|
||||
|
||||
## Flujo de generación
|
||||
|
||||
1. `Purchase` emite `PurchasePaid` al confirmarse el pago.
|
||||
2. `GenerateTicketsForPaidPurchase` atiende el evento.
|
||||
3. `TicketGeneratorService` crea los tickets requeridos según ítems, cantidades y vigencia.
|
||||
4. `Notification` envía la confirmación de compra después de la generación y adjunta los tickets cuando existen.
|
||||
|
||||
## Datos descartables para pruebas de carga
|
||||
|
||||
En ambientes `local`, `testing`, `staging`, `homo` u `homologation`, el comando siguiente crea tickets
|
||||
válidos, identidades scanner con tokens Sanctum y un dataset JSON importable por Postman:
|
||||
|
||||
```bash
|
||||
php artisan load-test:tickets:prepare loadtest-evento \
|
||||
--tickets=40000 \
|
||||
--scanners=100 \
|
||||
--owners=1000 \
|
||||
--catalog-item=123 \
|
||||
--run=evento-001
|
||||
```
|
||||
|
||||
El tenant debe existir y se recomienda que sea exclusivo para carga. Si no se indica `--catalog-item`,
|
||||
se usa el primer producto estándar del tenant con tickets habilitados. `--variant`
|
||||
es opcional; al indicarlo, su configuración de vigencia debe estar activa y ser resoluble. Sin variante,
|
||||
los tickets tienen vigencia irrestricta.
|
||||
|
||||
El archivo se escribe por defecto en `storage/app/private/load-tests/` y contiene tokens secretos, por
|
||||
lo que no debe versionarse. Para limpiar el tenant después de la ejecución:
|
||||
|
||||
```bash
|
||||
php artisan tenants:reset-transactions loadtest-evento --dry-run
|
||||
php artisan tenants:reset-transactions loadtest-evento
|
||||
```
|
||||
|
||||
## Endpoints
|
||||
|
||||
Bajo `/tenants/{tenant:codigo}`, protegidos por `auth:sanctum`:
|
||||
|
||||
- `GET /tickets`.
|
||||
- `POST /tickets/pdf`.
|
||||
|
||||
Bajo `/v1/adminapp/tenant`, protegido por `auth:sanctum`, `adminapp.tenant` y el menú
|
||||
`adminapp.tickets`:
|
||||
|
||||
- `GET /tickets`, paginado y con búsqueda opcional mediante `q`. La respuesta incluye
|
||||
`scanned_tickets` y `total_tickets` para el tenant autenticado.
|
||||
|
||||
`TicketPdfService` genera la descarga y `TicketResource`/`ValidityTimeResource` definen las respuestas.
|
||||
|
||||
## Dependencias y reglas
|
||||
|
||||
Depende de `Purchase`, `Catalog`, `Tenant` y `Auth`. La generación debe ser idempotente ante reintentos del evento. `TicketNotAvailableException` y `TicketGenerationException` separan indisponibilidad de errores de generación.
|
||||
30
app/Domains/Ticketing/Ticket/routes/adminapp.php
Normal file
30
app/Domains/Ticketing/Ticket/routes/adminapp.php
Normal file
@@ -0,0 +1,30 @@
|
||||
<?php
|
||||
|
||||
use App\Domains\Ticket\Controllers\AdminApp\TicketController;
|
||||
use Illuminate\Support\Facades\Route;
|
||||
|
||||
Route::prefix('v1/adminapp/tenant')
|
||||
->middleware(['auth:sanctum', 'adminapp.tenant'])
|
||||
->group(function (): void {
|
||||
Route::get('tickets', [TicketController::class, 'index'])
|
||||
->middleware('tenant.menu:adminapp.tickets')
|
||||
->name('adminapp.tickets.index');
|
||||
Route::post('tickets/{ticket}/cancel', [TicketController::class, 'cancel'])
|
||||
->whereNumber('ticket')
|
||||
->middleware('tenant.menu:adminapp.tickets')
|
||||
->name('adminapp.tickets.cancel');
|
||||
Route::get('tickets/{ticket}/refund', [TicketController::class, 'calculateRefund'])
|
||||
->whereNumber('ticket')
|
||||
->middleware('tenant.menu:adminapp.tickets')
|
||||
->name('adminapp.tickets.calculate-refund');
|
||||
Route::post('tickets/{ticket}/refund', [TicketController::class, 'refund'])
|
||||
->whereNumber('ticket')
|
||||
->middleware('tenant.menu:adminapp.tickets')
|
||||
->name('adminapp.tickets.refund');
|
||||
Route::get('tickets/pdf', [TicketController::class, 'downloadPdf'])
|
||||
->middleware('tenant.menu:adminapp.tickets')
|
||||
->name('adminapp.tickets.pdf');
|
||||
Route::get('tickets/excel', [TicketController::class, 'downloadExcel'])
|
||||
->middleware('tenant.menu:adminapp.tickets')
|
||||
->name('adminapp.tickets.excel');
|
||||
});
|
||||
14
app/Domains/Ticketing/Ticket/routes/api.php
Normal file
14
app/Domains/Ticketing/Ticket/routes/api.php
Normal file
@@ -0,0 +1,14 @@
|
||||
<?php
|
||||
|
||||
use App\Domains\Ticket\Controllers\TicketController;
|
||||
use Illuminate\Support\Facades\Route;
|
||||
|
||||
Route::prefix('tenants/{tenant:codigo}')
|
||||
->middleware('auth:sanctum')
|
||||
->group(function (): void {
|
||||
Route::get('tickets', [TicketController::class, 'index']);
|
||||
Route::post('tickets/pdf', [TicketController::class, 'downloadPdf']);
|
||||
});
|
||||
|
||||
require __DIR__.'/scanner.php';
|
||||
require __DIR__.'/adminapp.php';
|
||||
18
app/Domains/Ticketing/Ticket/routes/scanner.php
Normal file
18
app/Domains/Ticketing/Ticket/routes/scanner.php
Normal file
@@ -0,0 +1,18 @@
|
||||
<?php
|
||||
|
||||
use App\Domains\Ticket\Controllers\Scanner\ScanAttemptController;
|
||||
use App\Domains\Ticket\Controllers\Scanner\TicketController;
|
||||
use Illuminate\Support\Facades\Route;
|
||||
|
||||
Route::middleware(['auth:sanctum', 'scanner.tenant'])
|
||||
->group(function (): void {
|
||||
Route::get('v1/scanner/attempts', ScanAttemptController::class);
|
||||
Route::get('v1/scanner/attempts/{scanAttempt}', [ScanAttemptController::class, 'show'])
|
||||
->whereNumber('scanAttempt');
|
||||
|
||||
Route::prefix('v1/scanner/tickets')->group(function (): void {
|
||||
Route::post('scan', [TicketController::class, 'scan']);
|
||||
Route::get('{ticketUuid}', [TicketController::class, 'show'])
|
||||
->whereUuid('ticketUuid');
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user