Files
AgendaPro/server/lib/time.ts
T
AgendaPro DevandClaude Opus 5 f48a9ac3bf fix: anclar la agenda a la zona horaria del negocio, no a la del proceso
La reserva pública no ofrecía horarios en producción. La ventana laboral se
construía con `new Date(y, m, d, hh, mm)`, que resuelve el reloj de pared en la
tz del proceso. El Dockerfile no fijaba TZ y node:22-slim arranca en UTC,
mientras que la máquina de desarrollo está en America/Mexico_City: por eso solo
fallaba desplegado. Un negocio de 09:00-20:00 se publicaba como 09:00-20:00 UTC
(03:00-14:00 de México), y como el generador descarta lo anterior a ahora+30min,
a partir de la 1 PM la lista quedaba vacía.

Toda la API de scheduling.ts lleva ahora `tz` explícita y resuelve el reloj de
pared con wallToUtcDate/bizDateISO de time.ts, que ya existían para esto.

Arrastraba cinco defectos más en la misma ruta:

- getExistingBusy acotaba el día concatenando `${fecha}T00:00:00`. Como start_at
  se guarda en UTC, una cita de las 19:00 de México vive en el día UTC siguiente
  y quedaba fuera del rango: el guard anti doble-reserva no veía la tarde entera.
  Ahora usa bizDayBoundsIsoFor.
- Un negocio recién sembrado nacía con working_hours y slug en NULL, o sea con
  cero franjas agendables y /b/:slug en 404: el backfill vivía solo dentro de las
  migraciones, que corren antes de que exista la fila. Los defaults se fijan en el
  INSERT (server/lib/businessDefaults.ts) en los tres sitios que crean negocios, y
  migrateV4ToV5 repara los ya rotos. El demo usa slug fijo `mi-negocio-demo`
  porque es la URL ya publicada y el volumen se recrea en cada despliegue.
- El chip mostraba la hora formateada por el servidor y el resumen la del
  navegador: dos horas distintas para el mismo slot. Ambas salen ahora del
  instante resuelto en la tz del negocio.
- La separación mañana/tarde usaba /PM/i sobre un texto ya localizado, y es-MX
  rinde "05:00 p.m." con puntos: nunca casaba, así que el grupo "Tarde"
  desaparecía y toda la tarde se agrupaba bajo "Mañana".
- MonthCalendar comparaba canPrev contra el día 1 del mes visible en vez de
  contra minDate, de modo que la flecha de mes anterior nunca se podía pulsar.

Las guardas de migración comparaban la versión como texto ("10" >= "2" es false),
lo que habría reejecutado migrateV1ToV2 y su DROP TABLE users al llegar a dos
dígitos; ahora comparan números.

Verificación: scheduling.test.ts fija TZ=UTC y usa negocios en America/Mexico_City
para que la tz del proceso y la del negocio nunca coincidan; el Dockerfile fija
ENV TZ=UTC por lo mismo. 43 unitarias + 33 e2e + 12 booking + 17 admin en verde
con el servidor en UTC y base recién sembrada; typecheck limpio. booking-e2e.mjs
busca el próximo día abierto en vez de asumir "mañana", que lo hacía fallar cada
viernes y sábado por calendario.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
2026-08-28 10:47:59 -06:00

149 lines
5.2 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// server/lib/time.ts
// Pure timezone helpers for business-local ("biz") date math.
// Mexico is UTC-6, so SQLite date('now') (= UTC) misattributes the evening rush.
// All functions are deterministic given an explicit instant (default = new Date()).
/** Returns the calendar date (YYYY-MM-DD) of the given instant in the given IANA tz. */
export function bizDateISO(instant: Date, tz: string): string {
return new Intl.DateTimeFormat("en-CA", {
timeZone: tz || "UTC",
year: "numeric",
month: "2-digit",
day: "2-digit",
}).format(instant); // en-CA yields "YYYY-MM-DD"
}
/** Business "today" (YYYY-MM-DD) for a tz, at the given instant (default: server now). */
export function bizTodayISO(tz: string, now: Date = new Date()): string {
return bizDateISO(now, tz);
}
/** tz offset (in minutes) of the given instant, east of UTC positive. */
function tzOffsetMinutes(instant: Date, tz: string): number {
const parts = new Intl.DateTimeFormat("en-US", {
timeZone: tz || "UTC",
timeZoneName: "longOffset",
}).formatToParts(instant);
const off = parts.find((p) => p.type === "timeZoneName")?.value ?? "GMT+00:00";
// e.g. "GMT-06:00", "GMT+05:30", "GMT+00:00", or bare "GMT" for UTC
const m = off.match(/GMT([+-])(\d{1,2})(?::(\d{2}))?/);
if (!m) return 0; // bare "GMT" → UTC
const sign = m[1] === "-" ? -1 : 1;
const h = parseInt(m[2], 10);
const min = m[3] ? parseInt(m[3], 10) : 0;
return sign * (h * 60 + min);
}
/**
* Convert a business-local wall-clock (year, month, day, hh, mm, ss) in `tz` to a UTC Date.
* We first treat the wall-clock as if it were UTC, read the tz offset at that instant,
* then subtract the offset: a west tz (negative offset) is "behind" UTC, so the same
* wall-clock happens later in UTC → UTC = wall − offset.
*/
export function wallToUtcDate(
tz: string,
y: number,
mo: number,
d: number,
hh: number,
mm: number,
ss: number
): Date {
const guess = new Date(Date.UTC(y, mo - 1, d, hh, mm, ss));
const offsetMin = tzOffsetMinutes(guess, tz);
return new Date(guess.getTime() - offsetMin * 60000);
}
/** Business-day UTC bounds (start = local 00:00:00, end = local 23:59:59) for today +/- offset. */
export function bizDayBounds(
tz: string,
dayOffset = 0,
now: Date = new Date()
): { start: Date; end: Date } {
const today = bizDateISO(now, tz);
const [y, m, d] = today.split("-").map(Number);
const base = new Date(Date.UTC(y, m - 1, d));
base.setUTCDate(base.getUTCDate() + dayOffset);
const ty = base.getUTCFullYear();
const tm = base.getUTCMonth() + 1;
const td = base.getUTCDate();
return {
start: wallToUtcDate(tz, ty, tm, td, 0, 0, 0),
end: wallToUtcDate(tz, ty, tm, td, 23, 59, 59),
};
}
/** Format a UTC instant as SQLite canonical "YYYY-MM-DD HH:MM:SS" (matches datetime() output). */
export function toSqliteUtc(d: Date): string {
return d.toISOString().slice(0, 19).replace("T", " ");
}
/** Format a UTC instant as ISO "YYYY-MM-DDTHH:MM:SSZ" (matches the stored start_at format). */
export function toIsoUtc(d: Date): string {
return d.toISOString().slice(0, 19) + "Z";
}
/** Business-day bounds in SQLite canonical format — pair with `datetime(column) >= ?`. */
export function bizDayBoundsSqlite(
tz: string,
dayOffset = 0,
now: Date = new Date()
): { start: string; end: string } {
const b = bizDayBounds(tz, dayOffset, now);
return { start: toSqliteUtc(b.start), end: toSqliteUtc(b.end) };
}
/** Business-day bounds in ISO-Z format — pair with raw `start_at >= ?`. */
export function bizDayBoundsIso(
tz: string,
dayOffset = 0,
now: Date = new Date()
): { start: string; end: string } {
const b = bizDayBounds(tz, dayOffset, now);
return { start: toIsoUtc(b.start), end: toIsoUtc(b.end) };
}
/** Convenience: convert a business-local wall-clock to a UTC ISO string. */
export function wallToUtcISO(
tz: string,
y: number,
mo: number,
d: number,
hh: number,
mm: number,
ss: number
): string {
return wallToUtcDate(tz, y, mo, d, hh, mm, ss).toISOString();
}
/** Zona horaria por defecto de los negocios (México). Única definición. */
export const DEFAULT_TZ = "America/Mexico_City";
/**
* Día ISO de la semana (1=Lun … 7=Dom) de una fecha natural "YYYY-MM-DD".
* Deriva del string, nunca de un `Date` local, así que es independiente de
* la tz del proceso (en un contenedor UTC `new Date("…").getDay()` puede
* caer en el día anterior).
*/
export function isoDowFromDateStr(dateIso: string): number {
const [y, m, d] = dateIso.split("-").map(Number);
const j = new Date(Date.UTC(y, m - 1, d)).getUTCDay(); // 0=Dom..6=Sáb
return j === 0 ? 7 : j;
}
/**
* Límites UTC del día natural `dateIso` **en la tz del negocio**, en formato
* ISO-Z. Emparéjalo con `start_at >= ? AND start_at <= ?` (comparación
* lexicográfica sobre el formato canónico almacenado).
*
* A diferencia de `bizDayBoundsIso`, que trabaja con desplazamientos respecto
* de "hoy", este acepta la fecha explícita que pide el cliente.
*/
export function bizDayBoundsIsoFor(tz: string, dateIso: string): { start: string; end: string } {
const [y, m, d] = dateIso.split("-").map(Number);
return {
start: toIsoUtc(wallToUtcDate(tz || DEFAULT_TZ, y, m, d, 0, 0, 0)),
end: toIsoUtc(wallToUtcDate(tz || DEFAULT_TZ, y, m, d, 23, 59, 59)),
};
}