feat(deploy): empaquetar platform/ y desplegarlo en el server E3

Prepara el backend Postgres para producción y lo despliega como stack de Swarm
en el servidor de Consultoría E3, detrás de Traefik.

## Lo que le faltaba al proyecto para poder empaquetarse

- **`platform/` importaba de `server/`.** `routes/dayClose.ts` traía los helpers
  de zona horaria de `../../server/lib/time.ts`, contradiciendo lo que el propio
  README declara. El typecheck pasaba limpio porque en el equipo de desarrollo
  el archivo existe; solo se vio al contenerizar, cuando el proceso murió al
  arrancar con ERR_MODULE_NOT_FOUND. Ahora hay `platform/lib/time.ts`, copia
  deliberada —misma decisión que `businessDefaults.ts`— y una prueba que impide
  que vuelva a colarse una importación cruzada.
- **No había endpoint de salud.** `/api/health` consulta la base: uno que solo
  responde `{ok:true}` sigue en verde con Postgres caído, justo cuando el
  orquestador debería reiniciar.
- **No servía el frontend.** Ahora sirve `dist/` con fallback de SPA que excluye
  `/api/`, para que una ruta de API inexistente devuelva 404 y no el index.
- **No había apagado ordenado.** Sin él, cada redespliegue corta las peticiones
  en vuelo. Verificado: la tarea vieja registra el SIGTERM y cierra.

## Imagen

`platform/Dockerfile`, multi-etapa. Corre como `USER node`, fija `TZ=UTC` —la
agenda saca la zona de `businesses.timezone`, y dejar la del proceso en México
haría que una recaída pasara desapercibida— y **no** ejecuta las migraciones al
arrancar: se lanzan como paso explícito del despliegue, porque hacerlo al inicio
deja el esquema a medias si el arranque falla.

`tsx` pasa de devDependencies a dependencies: este backend corre TypeScript
directo y arrancar con `npx tsx` lo bajaría de npm en cada arranque, sin versión
fijada y sobre todo el código del servidor.

## Estado en el servidor

- Base `agendapro` con rol `agendapro_app` de mínimo privilegio, `PUBLIC`
  revocado. Verificado: el rol no ve ninguna tabla de las otras bases.
- Clave maestra de cifrado **generada en el servidor**, nunca copiada de
  desarrollo.
- Stack `agendapro` desplegado, 1/1 réplicas, 5 migraciones aplicadas, 17 tablas.
- Salud, SPA y API de administración verificadas desde dentro de la red overlay.

## Pendiente y bloqueante para el acceso externo

El A-record `agendapro.consultoriae3.com` -> 157.173.205.217 hay que crearlo a
mano en SiteGround. Sin él no hay certificado, porque Let's Encrypt valida por
HTTP-01.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
This commit is contained in:
AgendaPro Dev
2026-08-30 15:33:28 -06:00
co-authored by Claude Opus 5
parent 6d67b23e55
commit 2437012c46
10 changed files with 514 additions and 3 deletions
+156
View File
@@ -0,0 +1,156 @@
// platform/lib/time.ts
//
// Helpers puros de zona horaria del negocio.
//
// Son una COPIA de `server/lib/time.ts`, y es deliberado: los dos backends
// conviven sin compartir código —misma decisión que `businessDefaults.ts`— y
// cruzarlos ataría la evolución de uno a la del otro. El coste es duplicar unas
// líneas de funciones puras; el beneficio es que `platform/` se pueda empaquetar
// solo, sin arrastrar el backend de demo dentro de su imagen.
//
// Se descubrió al contenerizar: `dayClose.ts` importaba de `../../server/`, la
// imagen no copiaba `server/`, y el proceso moría al arrancar con
// ERR_MODULE_NOT_FOUND. Un typecheck limpio no lo detecta.
/** 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)),
};
}