feat(ticketing): add service and command for converting validity times to UTC
This commit is contained in:
@@ -0,0 +1,77 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Ticketing\Ticket\Services;
|
||||
|
||||
use Carbon\CarbonImmutable;
|
||||
use DateTimeZone;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use InvalidArgumentException;
|
||||
|
||||
class ConvertValidityTimesToUtcService
|
||||
{
|
||||
/**
|
||||
* IDs or the all flag select values the operator has confirmed are still local.
|
||||
* UTC cannot be inferred reliably from a timezone-less database timestamp.
|
||||
*
|
||||
* @param array<int, int> $ids
|
||||
* @return array<int, array<string, mixed>>
|
||||
*/
|
||||
public function run(array $ids, string $timezone, bool $apply = false, bool $all = false): array
|
||||
{
|
||||
if (! in_array($timezone, DateTimeZone::listIdentifiers(DateTimeZone::ALL_WITH_BC), true)) {
|
||||
throw new InvalidArgumentException('Zona horaria de origen inválida.');
|
||||
}
|
||||
if ($all && $ids !== []) {
|
||||
throw new InvalidArgumentException('Usar --all o --ids, no ambos.');
|
||||
}
|
||||
if (! $all && $ids === []) {
|
||||
throw new InvalidArgumentException('Indicar --all para todos los fixed_window o --ids para una selección.');
|
||||
}
|
||||
|
||||
return DB::transaction(function () use ($ids, $timezone, $apply): array {
|
||||
$query = DB::table('validity_times')->orderBy('id');
|
||||
if ($ids === []) {
|
||||
$query->where('type', 'fixed_window');
|
||||
} else {
|
||||
$query->whereIn('id', $ids);
|
||||
}
|
||||
if ($apply) {
|
||||
$query->lockForUpdate();
|
||||
}
|
||||
$rows = $query->get();
|
||||
if ($ids !== [] && $rows->count() !== count(array_unique($ids))) {
|
||||
throw new InvalidArgumentException('Uno o más IDs no existen. No se modificó ningún registro.');
|
||||
}
|
||||
if ($rows->contains(fn ($row): bool => $row->type !== 'fixed_window')) {
|
||||
throw new InvalidArgumentException('Sólo se admiten IDs de fixed_window. No se modificó ningún registro.');
|
||||
}
|
||||
$result = [];
|
||||
foreach ($rows as $row) {
|
||||
$start = $this->convert($row->fixed_starts_at, $timezone);
|
||||
$end = $this->convert($row->fixed_expires_at, $timezone);
|
||||
$result[] = [
|
||||
'id' => $row->id,
|
||||
'status' => $apply ? 'convertido' : 'propuesta; verificar origen local',
|
||||
'original_start' => $row->fixed_starts_at,
|
||||
'original_end' => $row->fixed_expires_at,
|
||||
'utc_start' => $start,
|
||||
'utc_end' => $end,
|
||||
];
|
||||
if (! $apply) {
|
||||
continue;
|
||||
}
|
||||
DB::table('validity_times')->where('id', $row->id)->update([
|
||||
'fixed_starts_at' => $start,
|
||||
'fixed_expires_at' => $end,
|
||||
]);
|
||||
}
|
||||
|
||||
return $result;
|
||||
});
|
||||
}
|
||||
|
||||
private function convert(?string $value, string $timezone): ?string
|
||||
{
|
||||
return $value === null ? null : CarbonImmutable::parse($value, $timezone)->utc()->format('Y-m-d H:i:s');
|
||||
}
|
||||
}
|
||||
@@ -92,3 +92,32 @@ Bajo `/v1/adminapp/tenant`, protegido por `auth:sanctum`, `adminapp.tenant` y el
|
||||
## Dependencias y reglas
|
||||
|
||||
Depende de `Purchase`, `Catalog`, `Tenant` y `Auth`. La generación debe ser idempotente ante reintentos del evento. `TicketNotAvailableException` y `TicketGenerationException` separan indisponibilidad de errores de generación.
|
||||
|
||||
## Conversión de datos históricos a UTC (homo / producción)
|
||||
|
||||
El comando no requiere migraciones adicionales ni crea una tabla de registro.
|
||||
Para convertir todos los registros de tipo `fixed_window` desde hora argentina:
|
||||
|
||||
```bash
|
||||
# Vista previa: no escribe en la base
|
||||
php artisan tickets:convert-validity-times-to-utc --all
|
||||
# Aplicar a todos los fixed_window
|
||||
php artisan tickets:convert-validity-times-to-utc --all --apply
|
||||
```
|
||||
|
||||
También permite seleccionar IDs específicos (los siguientes son ejemplos):
|
||||
|
||||
```bash
|
||||
php artisan tickets:convert-validity-times-to-utc --ids=41,42
|
||||
php artisan tickets:convert-validity-times-to-utc --ids=41,42 --apply
|
||||
```
|
||||
|
||||
`--all` y `--ids` son excluyentes. El origen por defecto es
|
||||
`America/Argentina/Buenos_Aires`; se puede indicar otra zona IANA con `--source-timezone`.
|
||||
Cada extremo conserva su fecha original y se convierte por separado, incluso si la ventana abarca
|
||||
varios días. Los límites nulos y los `time_window` no se modifican. La aplicación es transaccional.
|
||||
|
||||
No hay registro ni detección automática de conversiones anteriores: repetir `--apply` vuelve a
|
||||
convertir los valores actuales. La migración original `2026_09_21_040000_add_timezone_to_tenants.php`
|
||||
ya convierte las ventanas asociadas a eventos; no ejecutar este comando sobre esas ventanas si
|
||||
ya fueron convertidas. `--all` incluye absolutamente todos los `fixed_window`, sin esa distinción.
|
||||
|
||||
Reference in New Issue
Block a user