mirror of
https://github.com/MBombeck/HealthLog.git
synced 2026-11-18 08:02:12 +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,209 @@
|
||||
/**
|
||||
* v1.4.15 Phase B2 — Settings → Integrations status surface tests.
|
||||
*
|
||||
* The four states this file locks in (one assertion each):
|
||||
* 1. connected → no banner, "Connected" badge only
|
||||
* 2. error_transient → banner with "{count}/{threshold}"
|
||||
* counter, last-error message visible
|
||||
* 3. error_reauth → "Reconnect required" badge surfaces
|
||||
* 4. disconnected → "Disconnected" badge surfaces (used
|
||||
* after the user clicks "Disconnect")
|
||||
*
|
||||
* We test by rendering only the IntegrationsSection with a TanStack
|
||||
* Query mock that returns the desired status. The other queries
|
||||
* (withings status, moodlog status, global services) are stubbed to
|
||||
* stable defaults — the test isn't about those surfaces.
|
||||
*/
|
||||
import { describe, expect, it, vi, beforeEach } from "vitest";
|
||||
import { renderToStaticMarkup } from "react-dom/server";
|
||||
|
||||
vi.mock("next/navigation", () => ({
|
||||
useRouter: () => ({ push: vi.fn(), replace: vi.fn() }),
|
||||
usePathname: () => "/settings/integrations",
|
||||
}));
|
||||
|
||||
vi.mock("@/hooks/use-auth", () => ({
|
||||
useAuth: () => ({
|
||||
user: { id: "u1", role: "USER" },
|
||||
isAuthenticated: true,
|
||||
isLoading: false,
|
||||
refetch: vi.fn(),
|
||||
}),
|
||||
}));
|
||||
|
||||
// Per-test mock — we'll rewrite the integration-status payload between
|
||||
// cases via `setIntegrationStatus()`. Withings + moodlog status return
|
||||
// stable defaults so the cards render their connect-CTA branch (the
|
||||
// banner is what we actually assert on).
|
||||
let integrationStatusPayload: unknown = null;
|
||||
function setIntegrationStatus(payload: unknown) {
|
||||
integrationStatusPayload = payload;
|
||||
}
|
||||
|
||||
vi.mock("@tanstack/react-query", () => ({
|
||||
useQuery: ({ queryKey }: { queryKey: unknown[] }) => {
|
||||
const key = Array.isArray(queryKey) ? queryKey.join("/") : "";
|
||||
if (key === "integrations/status") {
|
||||
return { data: integrationStatusPayload, isLoading: false };
|
||||
}
|
||||
if (key === "settings/global-services") {
|
||||
return {
|
||||
data: {
|
||||
telegramGlobal: true,
|
||||
ntfyGlobal: true,
|
||||
webPushGlobal: true,
|
||||
apiGlobal: true,
|
||||
moodLogGlobal: true,
|
||||
},
|
||||
isLoading: false,
|
||||
};
|
||||
}
|
||||
if (key === "withings/status") {
|
||||
return {
|
||||
data: { connected: false, configured: false },
|
||||
isLoading: false,
|
||||
};
|
||||
}
|
||||
if (key === "moodlog-status") {
|
||||
return {
|
||||
data: {
|
||||
configured: false,
|
||||
enabled: false,
|
||||
lastSyncedAt: null,
|
||||
entryCount: 0,
|
||||
webhookSecret: null,
|
||||
},
|
||||
isLoading: false,
|
||||
refetch: vi.fn(),
|
||||
};
|
||||
}
|
||||
return { data: null, isLoading: false, refetch: vi.fn() };
|
||||
},
|
||||
useMutation: () => ({ mutate: vi.fn(), isPending: false }),
|
||||
useQueryClient: () => ({ invalidateQueries: vi.fn() }),
|
||||
}));
|
||||
|
||||
import { I18nProvider } from "@/lib/i18n/context";
|
||||
import { IntegrationsSection } from "../integrations-section";
|
||||
|
||||
function render() {
|
||||
return renderToStaticMarkup(
|
||||
<I18nProvider initialLocale="en">
|
||||
<IntegrationsSection />
|
||||
</I18nProvider>,
|
||||
);
|
||||
}
|
||||
|
||||
describe("IntegrationsSection — status surface", () => {
|
||||
beforeEach(() => {
|
||||
integrationStatusPayload = null;
|
||||
});
|
||||
|
||||
it("renders no error banner when both integrations are healthy", () => {
|
||||
setIntegrationStatus({
|
||||
threshold: 3,
|
||||
integrations: [
|
||||
{
|
||||
integration: "withings",
|
||||
state: "connected",
|
||||
lastSuccessAt: "2026-05-09T18:00:00.000Z",
|
||||
lastAttemptAt: "2026-05-09T18:00:00.000Z",
|
||||
lastError: null,
|
||||
consecutiveFailures: 0,
|
||||
},
|
||||
{
|
||||
integration: "moodlog",
|
||||
state: "connected",
|
||||
lastSuccessAt: null,
|
||||
lastAttemptAt: null,
|
||||
lastError: null,
|
||||
consecutiveFailures: 0,
|
||||
},
|
||||
],
|
||||
});
|
||||
const html = render();
|
||||
expect(html).not.toContain("Reconnect required");
|
||||
expect(html).not.toContain("integration-status-error");
|
||||
});
|
||||
|
||||
it("surfaces an error banner with last-error and {n}/{threshold} when transient failure", () => {
|
||||
setIntegrationStatus({
|
||||
threshold: 3,
|
||||
integrations: [
|
||||
{
|
||||
integration: "withings",
|
||||
state: "error_transient",
|
||||
lastSuccessAt: "2026-05-09T08:00:00.000Z",
|
||||
lastAttemptAt: "2026-05-09T18:00:00.000Z",
|
||||
lastError: "Withings refresh error: 503 - upstream",
|
||||
consecutiveFailures: 2,
|
||||
},
|
||||
{
|
||||
integration: "moodlog",
|
||||
state: "connected",
|
||||
lastSuccessAt: null,
|
||||
lastAttemptAt: null,
|
||||
lastError: null,
|
||||
consecutiveFailures: 0,
|
||||
},
|
||||
],
|
||||
});
|
||||
const html = render();
|
||||
expect(html).toContain("2/3 consecutive failures");
|
||||
expect(html).toContain("Withings refresh error: 503 - upstream");
|
||||
expect(html).toContain("integration-status-banner");
|
||||
});
|
||||
|
||||
it("surfaces 'Reconnect required' when a refresh-token grant has revoked", () => {
|
||||
setIntegrationStatus({
|
||||
threshold: 3,
|
||||
integrations: [
|
||||
{
|
||||
integration: "withings",
|
||||
state: "error_reauth",
|
||||
lastSuccessAt: "2026-05-08T12:00:00.000Z",
|
||||
lastAttemptAt: "2026-05-09T18:00:00.000Z",
|
||||
lastError: "Withings refresh error: 100 - invalid_grant",
|
||||
consecutiveFailures: 1,
|
||||
},
|
||||
{
|
||||
integration: "moodlog",
|
||||
state: "connected",
|
||||
lastSuccessAt: null,
|
||||
lastAttemptAt: null,
|
||||
lastError: null,
|
||||
consecutiveFailures: 0,
|
||||
},
|
||||
],
|
||||
});
|
||||
const html = render();
|
||||
expect(html).toContain("Reconnect required");
|
||||
});
|
||||
|
||||
it("renders the disconnected tombstone state without error styling", () => {
|
||||
setIntegrationStatus({
|
||||
threshold: 3,
|
||||
integrations: [
|
||||
{
|
||||
integration: "withings",
|
||||
state: "connected",
|
||||
lastSuccessAt: null,
|
||||
lastAttemptAt: null,
|
||||
lastError: null,
|
||||
consecutiveFailures: 0,
|
||||
},
|
||||
{
|
||||
integration: "moodlog",
|
||||
state: "disconnected",
|
||||
lastSuccessAt: "2026-05-08T10:00:00.000Z",
|
||||
lastAttemptAt: "2026-05-08T10:00:00.000Z",
|
||||
lastError: null,
|
||||
consecutiveFailures: 0,
|
||||
},
|
||||
],
|
||||
});
|
||||
const html = render();
|
||||
expect(html).toContain("Disconnected");
|
||||
expect(html).not.toContain("Reconnect required");
|
||||
});
|
||||
});
|
||||
@@ -3,6 +3,7 @@
|
||||
import { useState } from "react";
|
||||
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
import {
|
||||
AlertCircle,
|
||||
Download,
|
||||
Link2,
|
||||
Loader2,
|
||||
@@ -50,6 +51,162 @@ interface GlobalServiceAvailability {
|
||||
moodLogGlobal: boolean;
|
||||
}
|
||||
|
||||
// v1.4.15 Phase B2: shared status payload for both integration cards.
|
||||
// Mirrors the `IntegrationViewModel` shape returned by
|
||||
// `GET /api/integrations/status` (single roundtrip, two integrations).
|
||||
type IntegrationKey = "withings" | "moodlog";
|
||||
type IntegrationState =
|
||||
| "connected"
|
||||
| "error_transient"
|
||||
| "error_reauth"
|
||||
| "disconnected";
|
||||
|
||||
interface IntegrationStatusViewModel {
|
||||
integration: IntegrationKey;
|
||||
state: IntegrationState;
|
||||
lastSuccessAt: string | null;
|
||||
lastAttemptAt: string | null;
|
||||
lastError: string | null;
|
||||
consecutiveFailures: number;
|
||||
configured?: boolean;
|
||||
connected?: boolean;
|
||||
connectedAt?: string | null;
|
||||
legacyLastSyncedAt?: string | null;
|
||||
tokenExpiresAt?: string | null;
|
||||
tokenExpired?: boolean | null;
|
||||
enabled?: boolean;
|
||||
}
|
||||
|
||||
interface IntegrationStatusEnvelope {
|
||||
threshold: number;
|
||||
integrations: IntegrationStatusViewModel[];
|
||||
}
|
||||
|
||||
/**
|
||||
* Shared status fetch for the Settings → Integrations card. Returns
|
||||
* the per-integration view-model AND the global threshold so the
|
||||
* "{n}/{threshold} consecutive failures" string in the UI is single-
|
||||
* sourced from the server.
|
||||
*/
|
||||
function useIntegrationStatuses(enabled: boolean) {
|
||||
return useQuery({
|
||||
queryKey: ["integrations", "status"],
|
||||
queryFn: async () => {
|
||||
const res = await fetch("/api/integrations/status");
|
||||
if (!res.ok) throw new Error("Failed");
|
||||
return (await res.json()).data as IntegrationStatusEnvelope;
|
||||
},
|
||||
enabled,
|
||||
// The status endpoint is light (one DB read per integration) and
|
||||
// the user typically lands here right after a sync — refetching
|
||||
// on focus avoids a stale "last sync 5 min ago" reading.
|
||||
refetchOnWindowFocus: true,
|
||||
});
|
||||
}
|
||||
|
||||
function pickStatus(
|
||||
envelope: IntegrationStatusEnvelope | undefined,
|
||||
integration: IntegrationKey,
|
||||
): IntegrationStatusViewModel | undefined {
|
||||
return envelope?.integrations.find((i) => i.integration === integration);
|
||||
}
|
||||
|
||||
/**
|
||||
* Connection-state badge + "X consecutive failures" + last-error
|
||||
* surface. Renders nothing when the integration has no history yet
|
||||
* AND is connected — there's nothing useful to show in that case.
|
||||
*/
|
||||
function IntegrationStatusBanner({
|
||||
status,
|
||||
threshold,
|
||||
}: {
|
||||
status: IntegrationStatusViewModel | undefined;
|
||||
threshold: number | undefined;
|
||||
}) {
|
||||
const { t } = useTranslations();
|
||||
if (!status) return null;
|
||||
|
||||
const showBanner =
|
||||
status.state !== "connected" ||
|
||||
status.consecutiveFailures > 0 ||
|
||||
!!status.lastError ||
|
||||
!!status.lastAttemptAt;
|
||||
if (!showBanner) return null;
|
||||
|
||||
return (
|
||||
<div
|
||||
data-testid="integration-status-banner"
|
||||
className="bg-muted/40 border-border space-y-2 rounded-md border p-3 text-xs"
|
||||
>
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<StatusBadge state={status.state} />
|
||||
{status.state !== "connected" && (
|
||||
<Badge variant="outline" className="text-xs">
|
||||
{t("settings.integrationStatus.consecutiveFailures", {
|
||||
count: status.consecutiveFailures,
|
||||
threshold: threshold ?? 3,
|
||||
})}
|
||||
</Badge>
|
||||
)}
|
||||
</div>
|
||||
<dl className="text-muted-foreground grid gap-1 sm:grid-cols-2">
|
||||
{status.lastSuccessAt && (
|
||||
<div>
|
||||
<dt className="font-medium">
|
||||
{t("settings.integrationStatus.lastSuccess")}
|
||||
</dt>
|
||||
<dd>{formatDateTime(status.lastSuccessAt)}</dd>
|
||||
</div>
|
||||
)}
|
||||
{status.lastAttemptAt && (
|
||||
<div>
|
||||
<dt className="font-medium">
|
||||
{t("settings.integrationStatus.lastAttempt")}
|
||||
</dt>
|
||||
<dd>{formatDateTime(status.lastAttemptAt)}</dd>
|
||||
</div>
|
||||
)}
|
||||
</dl>
|
||||
{status.lastError && (
|
||||
<div className="text-destructive flex items-start gap-1.5">
|
||||
<AlertCircle className="mt-0.5 h-3.5 w-3.5 shrink-0" />
|
||||
<span data-testid="integration-status-error">{status.lastError}</span>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function StatusBadge({ state }: { state: IntegrationState }) {
|
||||
const { t } = useTranslations();
|
||||
switch (state) {
|
||||
case "connected":
|
||||
return (
|
||||
<Badge className="border-dracula-green/30 bg-dracula-green/15 text-dracula-green text-xs">
|
||||
{t("settings.integrationStatus.stateConnected")}
|
||||
</Badge>
|
||||
);
|
||||
case "error_reauth":
|
||||
return (
|
||||
<Badge variant="destructive" className="text-xs">
|
||||
{t("settings.integrationStatus.stateReauthRequired")}
|
||||
</Badge>
|
||||
);
|
||||
case "error_transient":
|
||||
return (
|
||||
<Badge variant="destructive" className="text-xs">
|
||||
{t("settings.integrationStatus.stateError")}
|
||||
</Badge>
|
||||
);
|
||||
case "disconnected":
|
||||
return (
|
||||
<Badge variant="outline" className="text-xs">
|
||||
{t("settings.integrationStatus.stateDisconnected")}
|
||||
</Badge>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export function IntegrationsSection() {
|
||||
const { t } = useTranslations();
|
||||
const { isAuthenticated } = useAuth();
|
||||
@@ -64,6 +221,8 @@ export function IntegrationsSection() {
|
||||
enabled: isAuthenticated,
|
||||
});
|
||||
|
||||
const { data: integrationStatus } = useIntegrationStatuses(isAuthenticated);
|
||||
|
||||
const moodLogEnabled = globalServices?.moodLogGlobal ?? true;
|
||||
|
||||
return (
|
||||
@@ -83,13 +242,36 @@ export function IntegrationsSection() {
|
||||
</p>
|
||||
</header>
|
||||
|
||||
<WithingsCard isAuthenticated={isAuthenticated} />
|
||||
{moodLogEnabled && <MoodLogCard />}
|
||||
<WithingsCard
|
||||
isAuthenticated={isAuthenticated}
|
||||
statusBanner={
|
||||
<IntegrationStatusBanner
|
||||
status={pickStatus(integrationStatus, "withings")}
|
||||
threshold={integrationStatus?.threshold}
|
||||
/>
|
||||
}
|
||||
/>
|
||||
{moodLogEnabled && (
|
||||
<MoodLogCard
|
||||
statusBanner={
|
||||
<IntegrationStatusBanner
|
||||
status={pickStatus(integrationStatus, "moodlog")}
|
||||
threshold={integrationStatus?.threshold}
|
||||
/>
|
||||
}
|
||||
/>
|
||||
)}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
function WithingsCard({ isAuthenticated }: { isAuthenticated: boolean }) {
|
||||
function WithingsCard({
|
||||
isAuthenticated,
|
||||
statusBanner,
|
||||
}: {
|
||||
isAuthenticated: boolean;
|
||||
statusBanner: React.ReactNode;
|
||||
}) {
|
||||
const { t } = useTranslations();
|
||||
const [syncing, setSyncing] = useState(false);
|
||||
const [syncMsg, setSyncMsg] = useState<string | null>(null);
|
||||
@@ -129,6 +311,7 @@ function WithingsCard({ isAuthenticated }: { isAuthenticated: boolean }) {
|
||||
},
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ["withings"] });
|
||||
queryClient.invalidateQueries({ queryKey: ["integrations", "status"] });
|
||||
},
|
||||
});
|
||||
|
||||
@@ -153,6 +336,7 @@ function WithingsCard({ isAuthenticated }: { isAuthenticated: boolean }) {
|
||||
);
|
||||
setSyncMsgType("success");
|
||||
void invalidateKeys(queryClient, measurementDependentKeys);
|
||||
queryClient.invalidateQueries({ queryKey: ["integrations", "status"] });
|
||||
} else {
|
||||
setSyncMsg(json.error || t("settings.withingsSyncFailed"));
|
||||
setSyncMsgType("error");
|
||||
@@ -239,6 +423,7 @@ function WithingsCard({ isAuthenticated }: { isAuthenticated: boolean }) {
|
||||
</p>
|
||||
|
||||
<div className="mt-4 space-y-4">
|
||||
{statusBanner}
|
||||
<div className="space-y-3">
|
||||
<h3 className="text-sm font-medium">
|
||||
{t("settings.withingsCredentials")}
|
||||
@@ -417,8 +602,9 @@ function WithingsCard({ isAuthenticated }: { isAuthenticated: boolean }) {
|
||||
);
|
||||
}
|
||||
|
||||
function MoodLogCard() {
|
||||
function MoodLogCard({ statusBanner }: { statusBanner: React.ReactNode }) {
|
||||
const { t } = useTranslations();
|
||||
const queryClient = useQueryClient();
|
||||
const [url, setUrl] = useState("");
|
||||
const [apiKey, setApiKey] = useState("");
|
||||
const [saving, setSaving] = useState(false);
|
||||
@@ -450,6 +636,7 @@ function MoodLogCard() {
|
||||
setUrl("");
|
||||
setApiKey("");
|
||||
await refetchStatus();
|
||||
queryClient.invalidateQueries({ queryKey: ["integrations", "status"] });
|
||||
} else {
|
||||
const json = await res.json();
|
||||
setMsg(json.error || t("settings.savingError"));
|
||||
@@ -477,6 +664,7 @@ function MoodLogCard() {
|
||||
);
|
||||
setMsgType("success");
|
||||
await refetchStatus();
|
||||
queryClient.invalidateQueries({ queryKey: ["integrations", "status"] });
|
||||
} else {
|
||||
setMsg(t("settings.moodLogSyncFailed"));
|
||||
setMsgType("error");
|
||||
@@ -494,6 +682,7 @@ function MoodLogCard() {
|
||||
setMsg(t("settings.moodLogDisconnected"));
|
||||
setMsgType("success");
|
||||
await refetchStatus();
|
||||
queryClient.invalidateQueries({ queryKey: ["integrations", "status"] });
|
||||
}
|
||||
}
|
||||
|
||||
@@ -525,6 +714,8 @@ function MoodLogCard() {
|
||||
{t("settings.moodLogDescription")}
|
||||
</p>
|
||||
|
||||
{statusBanner}
|
||||
|
||||
<form onSubmit={handleSave} className="space-y-3">
|
||||
<div>
|
||||
<Label>{t("settings.moodLogUrl")}</Label>
|
||||
|
||||
Reference in new issue
Block a user