Compare commits

...
Sign in to create a new pull request.

3 commits

Author SHA1 Message Date
Ullrich Schäfer
3af63c677f
Fix bulk import stuck in pending state in dev mode
In dev (Vite), runKomootBulkImport was fire-and-forgotten with .catch(()=>{})
which silently swallowed all errors, leaving the batch frozen at "pending".

Fix:
- Pre-mark the batch as "running" before firing the detached promise so the
  UI immediately transitions out of the pending state
- On failure, update the batch to "failed" with the error message instead of
  swallowing it, so the UI shows the error and offers a retry

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-23 18:57:00 +02:00
Ullrich Schäfer
6a441675b9
Fix import action crashing in dev when pg-boss is not initialized
The action was doing an internal self-fetch to /api/sync/komoot/import,
which returned plain text on error (boss not initialized) — the JSON.parse
then threw "Unexpected token U". Fix: inline the action logic directly in
the route and fall back to a fire-and-forget runKomootBulkImport call when
pg-boss is unavailable (i.e. dev mode with Vite, not the custom server).

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-23 18:55:18 +02:00
Ullrich Schäfer
600ecc6685
Match Komoot import page layout to Wahoo import page
- Switch to max-w-4xl to match the generic import page
- Move the trigger button to the header row (title on left, action on right)
- Show progress inline as "X / Y" in the header while running
- Progress card only appears once a batch exists; empty state is a
  centered paragraph like the generic page's "no workouts" message
- Link to /activities on completion instead of a separate paragraph

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-23 18:48:14 +02:00

View file

@ -50,16 +50,54 @@ export async function action({ request }: Route.ActionArgs) {
const user = await getSessionUser(request); const user = await getSessionUser(request);
if (!user) return redirect("/auth/login"); if (!user) return redirect("/auth/login");
// Delegate to the API route — just redirect so the page reloads with const { randomUUID } = await import("node:crypto");
// the new batch after the POST. const { getDb } = await import("~/lib/db");
const resp = await fetch( const { importBatches } = await import("@trails-cool/db/schema/journal");
new URL("/api/sync/komoot/import", new URL(request.url).origin),
{ method: "POST", headers: { cookie: request.headers.get("cookie") ?? "" } }, const service = await getService(user.id, "komoot");
); if (!service) return redirect("/settings/connections/komoot");
if (!resp.ok) {
const body = (await resp.json()) as { error?: string }; const db = getDb();
return data({ error: body.error ?? "failed" }, { status: resp.status }); const batchId = randomUUID();
await db.insert(importBatches).values({
id: batchId,
userId: user.id,
connectionId: service.id,
provider: "komoot",
status: "pending",
});
const { runKomootBulkImport } = await import("~/lib/komoot-bulk-import.server");
const creds = service.credentials as Parameters<typeof runKomootBulkImport>[2];
// Try to enqueue via pg-boss (production / custom server.ts).
// In dev (Vite), boss is never initialized — fall back to an inline
// fire-and-forget so the redirect still happens immediately.
let enqueued = false;
try {
const { getBoss } = await import("~/lib/boss.server");
const boss = getBoss();
await boss.send("komoot-bulk-import", { batchId, userId: user.id, creds });
enqueued = true;
} catch {
// pg-boss not available
} }
if (!enqueued) {
// Mark the batch running before returning so the UI doesn't stay frozen
// if the detached promise fails to start.
const { eq } = await import("drizzle-orm");
await db.update(importBatches).set({ status: "running" }).where(eq(importBatches.id, batchId));
void runKomootBulkImport(batchId, user.id, creds).catch(async (err) => {
const { eq: eq2 } = await import("drizzle-orm");
await db.update(importBatches).set({
status: "failed",
errorMessage: err instanceof Error ? err.message : String(err),
completedAt: new Date(),
}).where(eq2(importBatches.id, batchId));
});
}
return redirect("/sync/import/komoot"); return redirect("/sync/import/komoot");
} }
@ -78,59 +116,62 @@ export default function KomootImportPage({ loaderData }: Route.ComponentProps) {
const pollingRef = useRef<ReturnType<typeof setInterval> | null>(null); const pollingRef = useRef<ReturnType<typeof setInterval> | null>(null);
const isActive = batch?.status === "pending" || batch?.status === "running"; const isActive = batch?.status === "pending" || batch?.status === "running";
const isIdle = triggerFetcher.state === "idle";
useEffect(() => { useEffect(() => {
if (isActive) { if (isActive) {
pollingRef.current = setInterval(() => { pollingRef.current = setInterval(() => revalidator.revalidate(), 2000);
revalidator.revalidate();
}, 2000);
} }
return () => { return () => { if (pollingRef.current) clearInterval(pollingRef.current); };
if (pollingRef.current) clearInterval(pollingRef.current);
};
}, [isActive]); }, [isActive]);
const elapsedSeconds = batch const elapsedSeconds = batch
? Math.floor( ? Math.floor(
(batch.completedAt ((batch.completedAt ? new Date(batch.completedAt) : new Date()).getTime()
? new Date(batch.completedAt).getTime() - new Date(batch.startedAt).getTime()) / 1000,
: Date.now()) - new Date(batch.startedAt).getTime(), )
) / 1000
: 0; : 0;
return ( return (
<div className="mx-auto max-w-2xl px-4 py-8"> <div className="mx-auto max-w-4xl px-4 py-8">
{/* Header row — mirrors sync.import.$provider layout */}
<div className="flex items-center justify-between">
<h1 className="text-2xl font-bold text-gray-900"> <h1 className="text-2xl font-bold text-gray-900">
{t("sync.importFrom", { provider: "Komoot" })} {t("sync.importFrom", { provider: "Komoot" })}
</h1> </h1>
<div className="mt-6 rounded-lg border border-gray-200 p-6"> {isActive ? (
{!batch && ( <span className="text-sm text-gray-500">
<div className="text-center"> {batch.totalFound > 0
<p className="text-gray-600">{t("komoot.import.noImportYet")}</p> ? t("sync.importingProgress", {
<triggerFetcher.Form method="post" className="mt-4"> current: batch.importedCount + batch.duplicateCount,
total: batch.totalFound,
})
: t("komoot.import.status.running")}
</span>
) : (
<triggerFetcher.Form method="post">
<button <button
type="submit" type="submit"
disabled={triggerFetcher.state !== "idle"} disabled={!isIdle}
className="rounded-md bg-blue-600 px-5 py-2 text-sm font-medium text-white hover:bg-blue-700 disabled:opacity-50" className="rounded-md border border-gray-300 px-3 py-1.5 text-sm text-gray-700 hover:bg-gray-50 disabled:opacity-50"
> >
{triggerFetcher.state !== "idle" {!isIdle ? t("komoot.import.starting") : t("komoot.import.startImport")}
? t("komoot.import.starting")
: t("komoot.import.startImport")}
</button> </button>
</triggerFetcher.Form> </triggerFetcher.Form>
</div>
)} )}
</div>
{/* Progress card — shown once a batch exists */}
{batch && ( {batch && (
<div className="space-y-4"> <div className="mt-6 rounded-lg border border-gray-200 p-6">
<div className="flex items-center justify-between"> <div className="flex items-center justify-between">
<StatusBadge status={batch.status} t={t} /> <StatusBadge status={batch.status} t={t} />
{(batch.status === "completed" || batch.status === "failed") && ( {(batch.status === "completed" || batch.status === "failed") && (
<triggerFetcher.Form method="post"> <triggerFetcher.Form method="post">
<button <button
type="submit" type="submit"
disabled={triggerFetcher.state !== "idle"} disabled={!isIdle}
className="text-sm text-blue-600 hover:underline disabled:opacity-50" className="text-sm text-blue-600 hover:underline disabled:opacity-50"
> >
{t("komoot.import.runAgain")} {t("komoot.import.runAgain")}
@ -140,7 +181,7 @@ export default function KomootImportPage({ loaderData }: Route.ComponentProps) {
</div> </div>
{isActive && ( {isActive && (
<div className="h-2 w-full overflow-hidden rounded-full bg-gray-100"> <div className="mt-4 h-2 w-full overflow-hidden rounded-full bg-gray-100">
<div <div
className="h-2 rounded-full bg-blue-500 transition-all duration-500" className="h-2 rounded-full bg-blue-500 transition-all duration-500"
style={{ style={{
@ -152,33 +193,33 @@ export default function KomootImportPage({ loaderData }: Route.ComponentProps) {
</div> </div>
)} )}
<dl className="grid grid-cols-3 gap-4 text-center"> <dl className="mt-4 grid grid-cols-3 gap-4 text-center">
<StatBox label={t("komoot.import.found")} value={batch.totalFound} /> <StatBox label={t("komoot.import.found")} value={batch.totalFound} />
<StatBox label={t("komoot.import.imported")} value={batch.importedCount} /> <StatBox label={t("komoot.import.imported")} value={batch.importedCount} />
<StatBox label={t("komoot.import.skipped")} value={batch.duplicateCount} /> <StatBox label={t("komoot.import.skipped")} value={batch.duplicateCount} />
</dl> </dl>
{batch.status === "completed" && ( {batch.status === "completed" && (
<p className="text-sm text-gray-500"> <p className="mt-3 text-sm text-gray-500">
{t("komoot.import.completedIn", { duration: formatDuration(elapsedSeconds) })} {t("komoot.import.completedIn", { duration: formatDuration(elapsedSeconds) })}
{" · "}
<a href="/activities" className="text-blue-600 hover:underline">
{t("komoot.import.viewActivities")}
</a>
</p> </p>
)} )}
{batch.status === "failed" && batch.errorMessage && ( {batch.status === "failed" && batch.errorMessage && (
<p className="rounded-md border border-red-200 bg-red-50 px-3 py-2 text-sm text-red-700"> <p className="mt-3 rounded-md border border-red-200 bg-red-50 px-3 py-2 text-sm text-red-700">
{batch.errorMessage} {batch.errorMessage}
</p> </p>
)} )}
</div> </div>
)} )}
</div>
{batch?.status === "completed" && ( {/* Empty state — no batch yet */}
<p className="mt-4 text-center text-sm text-gray-500"> {!batch && (
<a href={`/users/me`} className="text-blue-600 hover:underline"> <p className="mt-8 text-center text-gray-500">{t("komoot.import.noImportYet")}</p>
{t("komoot.import.viewActivities")}
</a>
</p>
)} )}
</div> </div>
); );