refactor(backend): reorganize domains into Core, Commerce, Ticketing and Shared
This commit is contained in:
@@ -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))
|
||||
);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user