mirror of
https://github.com/MBombeck/HealthLog.git
synced 2026-11-08 20:42:43 +00:00
v1.4.15 Phase B2, criterion 1. Until this release the Settings →
Integrations card showed "Connected / Last sync 23 min ago" and
nothing else. A user whose Withings refresh token had revoked saw a
green badge; a user whose moodLog instance was down saw the same
green badge with a slightly older timestamp. The signal was useless.
This commit adds:
- New `IntegrationStatus` table (`integration_statuses` migration
`0029`). One row per (user, integration) capturing `state`
(`connected | error_transient | error_reauth | disconnected`),
`lastSuccessAt`, `lastAttemptAt`, encrypted `lastError`,
`consecutiveFailures` counter, `alertedAt` window-guard.
- `src/lib/integrations/status.ts` — the only writers
(`recordSyncSuccess`, `recordSyncFailure`, `markReauthRequired`,
`markReconnected`, `markDisconnected`) plus a read-only
`getIntegrationStatus()` for the API. The error column is
AES-256-GCM encrypted at rest because Withings/moodLog 401s can
echo URL/apiKey fragments — we can't ship that into a future
backup tarball.
- `GET /api/integrations/status` — single roundtrip returns both
Withings and moodLog snapshots plus the global threshold (so the
UI's "{n}/{threshold}" string is server-sourced and rotates with
the env var).
- Settings → Integrations cards both gain an
`IntegrationStatusBanner` row above the credentials form: state
badge ("Connected" / "Reconnect required" / "Error" /
"Disconnected"), `{n}/{threshold} consecutive failures` chip,
last-success / last-attempt times, and a destructive-toned
last-error line. The banner is suppressed entirely when the
integration is fresh-connected with no history (no false alarms).
Tests: +20 unit (status helper threshold + alert-window state machine,
banner rendering across all four states) + 8 integration
(`tests/integration/integration-status.test.ts`) confirming
encrypted-at-rest, audit-log row shape, alert idempotency window,
and CASCADE-delete on User. 116 files / 883 unit pass, 11 integration
files / 39 pass.
Encryption uses the existing `src/lib/crypto.ts` AES-256-GCM helper —
no new key material. The `consecutive_failures` counter and
`alerted_at` window are wired to the dispatcher in the next commit
(`feat(integrations): admin Telegram alert on persistent sync
failure`).
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
73 lines
2.3 KiB
TypeScript
73 lines
2.3 KiB
TypeScript
/**
|
|
* Per-test helpers for the integration suite. The Postgres testcontainer
|
|
* is started ONCE in `global-setup.ts` and torn down at the end of the
|
|
* run, so test files only need:
|
|
*
|
|
* import { getPrismaClient, truncateAllTables } from "./setup";
|
|
*
|
|
* beforeEach(async () => { await truncateAllTables(getPrismaClient()); });
|
|
*
|
|
* No beforeAll(startTestDb) / afterAll(stopTestDb) is needed — the
|
|
* container is alive whenever the test file is loaded, and Vitest's
|
|
* worker inherits `process.env.DATABASE_URL` from globalSetup so the
|
|
* application's Prisma singleton (`src/lib/db.ts`) connects to the
|
|
* testcontainer transparently.
|
|
*/
|
|
import { prisma } from "@/lib/db";
|
|
import type { PrismaClient } from "@/generated/prisma/client";
|
|
|
|
/**
|
|
* The application's Prisma singleton. Tests use this so any code
|
|
* imported via `await import("@/lib/...")` shares the exact same client
|
|
* instance — no risk of a divergent connection pool reading stale
|
|
* truncation state.
|
|
*/
|
|
export function getPrismaClient(): PrismaClient {
|
|
return prisma;
|
|
}
|
|
|
|
/**
|
|
* Truncate every user-facing table in dependency-safe order using
|
|
* `TRUNCATE … RESTART IDENTITY CASCADE`. Call from beforeEach() to make
|
|
* tests independent. The list mirrors `prisma/schema.prisma` minus
|
|
* prisma-internal tables (_prisma_migrations).
|
|
*/
|
|
export async function truncateAllTables(client: PrismaClient): Promise<void> {
|
|
// CASCADE means we only need to enumerate the tables; FK chains are
|
|
// handled by Postgres. Listed alphabetically for diff stability.
|
|
const tables = [
|
|
"api_tokens",
|
|
"app_settings",
|
|
"audit_logs",
|
|
"auth_challenges",
|
|
"data_backups",
|
|
"devices",
|
|
"feedback",
|
|
"idempotency_keys",
|
|
"integration_statuses",
|
|
"measurements",
|
|
"medication_intake_events",
|
|
"medication_schedules",
|
|
"medications",
|
|
"mood_entries",
|
|
"notification_channels",
|
|
"notification_preferences",
|
|
"passkeys",
|
|
"push_subscriptions",
|
|
"rate_limits",
|
|
"refresh_tokens",
|
|
"reminder_phase_configs",
|
|
"sessions",
|
|
"telegram_reminder_messages",
|
|
"telegram_scheduled_deletions",
|
|
"user_achievements",
|
|
"users",
|
|
"withings_connections",
|
|
];
|
|
|
|
const quoted = tables.map((t) => `"${t}"`).join(", ");
|
|
await client.$executeRawUnsafe(
|
|
`TRUNCATE TABLE ${quoted} RESTART IDENTITY CASCADE;`,
|
|
);
|
|
}
|