mirror of
https://github.com/MBombeck/HealthLog.git
synced 2026-11-18 16:12:11 +00:00
feat(integrations): connection-state + sync-error UI in Settings → Integrations
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>
This commit is contained in:
1 parent
7c32d6344d
commit
4db72a8c2e
8 files changed
+1382
-5
No files matched your search
@@ -0,0 +1,111 @@
|
||||
/**
|
||||
* Combined status endpoint for the Settings → Integrations card.
|
||||
*
|
||||
* Returns a snapshot per integration containing:
|
||||
* - the IntegrationStatus row (state, last-success, last-attempt,
|
||||
* decrypted last-error, consecutive failures, threshold)
|
||||
* - integration-specific extras the UI already shows (Withings:
|
||||
* credentials configured, token expiry, OAuth-connected; moodLog:
|
||||
* credentials configured, enabled flag)
|
||||
*
|
||||
* Combining both into one fetch removes a third round-trip from the
|
||||
* Settings page. The legacy /api/withings/status and
|
||||
* /api/integrations/moodlog/status remain for the existing UI/tests
|
||||
* — we add this in addition rather than rewriting them.
|
||||
*/
|
||||
import { prisma } from "@/lib/db";
|
||||
import { apiHandler, requireAuth } from "@/lib/api-handler";
|
||||
import { apiSuccess } from "@/lib/api-response";
|
||||
import { annotate } from "@/lib/logging/context";
|
||||
import {
|
||||
getIntegrationStatus,
|
||||
getPersistentFailureThreshold,
|
||||
type IntegrationKey,
|
||||
} from "@/lib/integrations/status";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
export const GET = apiHandler(async () => {
|
||||
const { user } = await requireAuth();
|
||||
annotate({ action: { name: "integrations.status" } });
|
||||
|
||||
const [withingsStatus, moodLogStatus, dbUser, withingsConn] =
|
||||
await Promise.all([
|
||||
getIntegrationStatus(user.id, "withings"),
|
||||
getIntegrationStatus(user.id, "moodlog"),
|
||||
prisma.user.findUnique({
|
||||
where: { id: user.id },
|
||||
select: {
|
||||
withingsClientIdEncrypted: true,
|
||||
withingsClientSecretEncrypted: true,
|
||||
moodLogUrlEncrypted: true,
|
||||
moodLogApiKeyEncrypted: true,
|
||||
moodLogEnabled: true,
|
||||
moodLogLastSyncedAt: true,
|
||||
},
|
||||
}),
|
||||
prisma.withingsConnection.findUnique({
|
||||
where: { userId: user.id },
|
||||
select: {
|
||||
tokenExpiresAt: true,
|
||||
lastSyncedAt: true,
|
||||
createdAt: true,
|
||||
},
|
||||
}),
|
||||
]);
|
||||
|
||||
const now = Date.now();
|
||||
|
||||
return apiSuccess({
|
||||
threshold: getPersistentFailureThreshold(),
|
||||
integrations: [
|
||||
{
|
||||
...withingsStatus,
|
||||
configured:
|
||||
!!dbUser?.withingsClientIdEncrypted &&
|
||||
!!dbUser?.withingsClientSecretEncrypted,
|
||||
connected: !!withingsConn,
|
||||
connectedAt: withingsConn?.createdAt?.toISOString() ?? null,
|
||||
// Surface the connection row's success time too so the UI
|
||||
// can fall back to it when no IntegrationStatus row exists
|
||||
// yet (legacy connections established before this feature).
|
||||
legacyLastSyncedAt: withingsConn?.lastSyncedAt?.toISOString() ?? null,
|
||||
tokenExpiresAt: withingsConn?.tokenExpiresAt?.toISOString() ?? null,
|
||||
tokenExpired: withingsConn
|
||||
? withingsConn.tokenExpiresAt.getTime() <= now
|
||||
: null,
|
||||
} satisfies IntegrationViewModel & WithingsExtras,
|
||||
{
|
||||
...moodLogStatus,
|
||||
configured:
|
||||
!!dbUser?.moodLogUrlEncrypted && !!dbUser?.moodLogApiKeyEncrypted,
|
||||
enabled: dbUser?.moodLogEnabled ?? false,
|
||||
legacyLastSyncedAt: dbUser?.moodLogLastSyncedAt?.toISOString() ?? null,
|
||||
} satisfies IntegrationViewModel & MoodLogExtras,
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
interface IntegrationViewModel {
|
||||
integration: IntegrationKey;
|
||||
state: string;
|
||||
lastSuccessAt: string | null;
|
||||
lastAttemptAt: string | null;
|
||||
lastError: string | null;
|
||||
consecutiveFailures: number;
|
||||
}
|
||||
|
||||
interface WithingsExtras {
|
||||
configured: boolean;
|
||||
connected: boolean;
|
||||
connectedAt: string | null;
|
||||
legacyLastSyncedAt: string | null;
|
||||
tokenExpiresAt: string | null;
|
||||
tokenExpired: boolean | null;
|
||||
}
|
||||
|
||||
interface MoodLogExtras {
|
||||
configured: boolean;
|
||||
enabled: boolean;
|
||||
legacyLastSyncedAt: string | null;
|
||||
}
|
||||
Reference in new issue
Block a user