trails/apps/journal/app/lib/connected-services/providers/wahoo/importer.test.ts
Ullrich Schäfer 8e5b6d6fe9
Wahoo capability adapters + caller migration (groups 3-5)
Implements tasks 1.3, 3.2-3.3, 4.1-4.4, 5.1-5.6, 6.1 of
deepen-connected-services. Built TDD: contract test red, adapter green
for each capability seam.

Capability adapters (providers/wahoo/):
- importer.ts: Importer seam — listImportable + importOne against
  Wahoo /v1/workouts. Filters fitness_app_id >= 1000 (Wahoo doesn't
  share third-party data). 2 contract tests green.
- pusher.ts: RoutePusher seam — pushRoute(ctx, input) -> {remoteId,
  version}. FIT-Course conversion, route:<id> external_id, PUT-vs-POST
  decision, PUT->POST-on-404 fallback all internal to the adapter
  (per ADR-0003). Idempotency via sync_pushes preserved. 4 contract
  tests green.
- webhook.ts: WebhookReceiver seam — parseWebhook + handle. Routes
  events to local users via provider_user_id; unknown user returns
  silently. 6 contract tests green.
- manifest.ts: declares credential_kind=oauth, OAuth config, scopes,
  buildAuthUrl, exchangeCode, and references each capability adapter.

Module shape:
- connected-services/index.ts: side-effect imports providers/index.ts
  to register manifests, then re-exports manager + registry + types.
- connected-services/providers/index.ts: barrel that calls
  registerManifest(wahooManifest).
- connected-services/oauth-state.server.ts: OAuth state encode/decode
  (extracted from legacy pushes.server.ts).
- connected-services/push-action.server.ts: orchestration above the
  RoutePusher seam — load route, ownership check, scope check, build
  RoutePushInput, invoke pusher, return PushOutcome union. Replaces
  the legacy pushRouteToProvider in lib/sync/pushes.server.ts.

Caller migration (group 5):
- api.sync.connect.$provider.ts -> manifest.buildAuthUrl
- api.sync.callback.$provider.ts -> manifest.exchangeCode + link()
- api.sync.disconnect.$provider.ts -> unlinkByUserProvider (calls
  best-effort revoke via the credential adapter, then deletes locally)
- api.sync.webhook.$provider.ts -> manifest.webhookReceiver dispatch
- api.sync.push.$provider.$routeId.ts -> push-action.pushRouteToProvider
- sync.import.$provider.tsx -> manifest.importer.listImportable +
  inline FIT->GPX in the action (form-supplied metadata bypasses the
  Importer seam which is reserved for automatic / webhook imports)
- routes.$id.tsx -> getService instead of getConnection
- settings.connections.tsx -> getAllManifests instead of legacy registry

Legacy lib/sync/ deleted except imports.server.ts (which manages the
sync_imports table, untouched by this change).

DB migration verified locally (task 1.3): pnpm db:migrate-data renamed
the table and backfilled credentials JSONB; pnpm db:push then dropped
the legacy access_token/refresh_token/expires_at columns. Final shape
matches the schema; check constraints + unique index in place.

Test status (task 6.1):
- pnpm typecheck: green across all 15 workspaces
- pnpm lint: green
- @trails-cool/journal: 112 passed, 31 skipped — 12 fewer tests than
  before because pushes.server.test.ts and the legacy wahoo.test.ts
  were deleted. Their coverage is replaced by the new contract tests
  (importer/pusher/webhook) plus manager.test.ts + oauth.test.ts.

Remaining: 6.2 (e2e), 6.3-6.4 (manual smoke + staging migration test),
7.1-7.3 (followups + spec deltas at archive).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-08 01:25:33 +02:00

102 lines
3.1 KiB
TypeScript

// Contract tests for the Wahoo Importer capability adapter.
//
// The seam under test is `Importer` from registry.ts:
// listImportable(ctx, page) -> ImportableList
// importOne(ctx, workoutId) -> ImportResult
//
// Internals (FIT parsing, Wahoo HTTP details) are tested via the legacy
// wahoo.test.ts and follow the code as it's reorganized.
import { describe, it, expect, beforeEach, vi } from "vitest";
import type { CapabilityContext } from "../../registry.ts";
import type { OAuthCredentials } from "../../types.ts";
const fetchSpy = vi.fn();
beforeEach(() => {
fetchSpy.mockReset();
globalThis.fetch = fetchSpy as unknown as typeof fetch;
});
const stubCreds: OAuthCredentials = {
access_token: "fake-token",
refresh_token: "rt",
expires_at: new Date(Date.now() + 3600_000).toISOString(),
};
function ctxWith(creds: OAuthCredentials = stubCreds): CapabilityContext {
return {
serviceId: "svc-1",
withFreshCredentials: async (fn) => fn(creds),
};
}
// Importer is loaded after the implementation file exists. Using a dynamic
// import isolates the test from module load order during initial red.
const { wahooImporter } = await import("./importer.ts");
describe("wahooImporter.listImportable", () => {
it("calls Wahoo /v1/workouts with the access token from withFreshCredentials", async () => {
fetchSpy.mockResolvedValueOnce(
new Response(
JSON.stringify({
workouts: [
{
id: 42,
name: "Morning ride",
workout_type: "biking",
starts: "2026-05-01T07:00:00Z",
workout_summary: {
duration_active_accum: 3600,
distance_accum: 25000,
file: { url: "https://cdn.example/42.fit" },
},
},
],
total: 1,
page: 1,
per_page: 30,
}),
{ status: 200 },
),
);
const result = await wahooImporter.listImportable(ctxWith(), 1);
const [url, init] = fetchSpy.mock.calls[0]!;
expect(String(url)).toContain("/v1/workouts");
expect(((init as RequestInit).headers as Record<string, string>).Authorization).toBe(
"Bearer fake-token",
);
expect(result.workouts).toHaveLength(1);
expect(result.workouts[0]!.id).toBe("42");
expect(result.workouts[0]!.fileUrl).toBe("https://cdn.example/42.fit");
expect(result.total).toBe(1);
});
it("filters out third-party workouts (fitness_app_id >= 1000)", async () => {
fetchSpy.mockResolvedValueOnce(
new Response(
JSON.stringify({
workouts: [
{ id: 1, name: "Wahoo native", workout_type: "biking", starts: "2026-05-01T07:00:00Z" },
{
id: 2,
name: "Third-party",
workout_type: "biking",
starts: "2026-05-01T08:00:00Z",
fitness_app_id: 1234,
},
],
total: 2,
page: 1,
per_page: 30,
}),
{ status: 200 },
),
);
const result = await wahooImporter.listImportable(ctxWith(), 1);
expect(result.workouts.map((w) => w.id)).toEqual(["1"]);
});
});