Skip to content

Open source alternative to Semrush and Ahrefs

Show failed rank checks as Not checked and count completion per device (EVE-411) (#902)

Carter Smith21283294b1f1
diff --git a/src/client/features/rank-tracking/RankTrackingHistoryMatrix.tsx b/src/client/features/rank-tracking/RankTrackingHistoryMatrix.tsx
index caa550fc..0444ddaf 100644
--- a/src/client/features/rank-tracking/RankTrackingHistoryMatrix.tsx
+++ b/src/client/features/rank-tracking/RankTrackingHistoryMatrix.tsx
@@ -1,4 +1,5 @@
import { useMemo } from "react";
+import { CircleSlash } from "lucide-react";
import { sort } from "remeda";
import type { RankPositionMatrixCell } from "@/serverFunctions/rank-tracking";
import { EmptyState } from "@/client/components/EmptyState";
@@ -12,6 +13,11 @@ import {
TableHeader,
TableRow,
} from "@/client/components/ui/table";
+import {
+ Tooltip,
+ TooltipContent,
+ TooltipTrigger,
+} from "@/client/components/ui/tooltip";
/**
* "By date" view: keyword rows × recent check columns, each cell the position
@@ -72,12 +78,22 @@ export function RankTrackingHistoryMatrix({
{kw.keyword}
</TableCell>
{runs.map((r, i) => {
+ // No row for a run after the keyword's first result means
+ // that check failed. Before the first result, the keyword
+ // was not tracked yet.
+ const notChecked =
+ !byRun?.has(r.runId) &&
+ runs.slice(0, i).some((prev) => byRun?.has(prev.runId));
const position = byRun?.get(r.runId) ?? null;
const previous =
i > 0 ? (byRun?.get(runs[i - 1].runId) ?? null) : undefined;
return (
<TableCell key={r.runId} className="text-right">
- <MatrixCell position={position} previous={previous} />
+ {notChecked ? (
+ <NotCheckedCell />
+ ) : (
+ <MatrixCell position={position} previous={previous} />
+ )}
</TableCell>
);
})}
@@ -90,6 +106,27 @@ export function RankTrackingHistoryMatrix({
);
}
+function NotCheckedCell() {
+ return (
+ <Tooltip>
+ <TooltipTrigger
+ render={
+ // An icon fits the numeric column.
+ <span
+ aria-label="Not checked"
+ className="inline-flex cursor-help align-middle text-muted-foreground"
+ />
+ }
+ >
+ <CircleSlash className="size-3.5" aria-hidden />
+ </TooltipTrigger>
+ <TooltipContent>
+ Not checked: check failed, no position recorded.
+ </TooltipContent>
+ </Tooltip>
+ );
+}
+
function MatrixCell({
position,
previous,
diff --git a/src/client/features/rank-tracking/RankTrackingOverview.tsx b/src/client/features/rank-tracking/RankTrackingOverview.tsx
index c7d097dc..816b8b53 100644
--- a/src/client/features/rank-tracking/RankTrackingOverview.tsx
+++ b/src/client/features/rank-tracking/RankTrackingOverview.tsx
@@ -4,6 +4,11 @@ import { Area, AreaChart } from "recharts";
import { getRankConfigTrend } from "@/serverFunctions/rank-tracking";
import { QueryState } from "@/client/components/QueryState";
import { Skeleton } from "@/client/components/ui/skeleton";
+import {
+ Tooltip,
+ TooltipContent,
+ TooltipTrigger,
+} from "@/client/components/ui/tooltip";
import {
ChartGrid,
ChartXAxis,
@@ -27,6 +32,14 @@ const BUCKETS = [
{ key: "top4to10", label: "4–10", color: "#2563eb" },
{ key: "top11to20", label: "11–20", color: "#f59e0b" },
{ key: "notRanking", label: "Not in top 20", color: "#6b7280" },
+ // Missing data, not a ranking: lighter fill so it doesn't read as lost
+ // positions.
+ {
+ key: "notChecked",
+ label: "Not checked",
+ color: "#d1d5db",
+ hint: "Check failed, no position recorded.",
+ },
] as const;
const chartConfig: ChartConfig = Object.fromEntries(
@@ -61,6 +74,7 @@ export function RankTrackingOverview({
top4to10: p.top4to10,
top11to20: p.top11to20,
notRanking: p.notRanking,
+ notChecked: p.notChecked,
})),
[trend],
);
@@ -74,18 +88,34 @@ export function RankTrackingOverview({
</div>
<div className="flex flex-wrap gap-x-3 gap-y-1">
- {BUCKETS.map((b) => (
- <span
- key={b.key}
- className="inline-flex items-center gap-1 text-[11px] text-muted-foreground"
- >
+ {BUCKETS.map((b) => {
+ const className =
+ "inline-flex items-center gap-1 text-[11px] text-muted-foreground";
+ const swatch = (
<span
className="size-2 rounded-sm"
style={{ backgroundColor: b.color }}
/>
- {b.label}
- </span>
- ))}
+ );
+ return "hint" in b ? (
+ <Tooltip key={b.key}>
+ <TooltipTrigger
+ render={<span className={`${className} cursor-help`} />}
+ >
+ {swatch}
+ <span className="underline decoration-dotted underline-offset-2">
+ {b.label}
+ </span>
+ </TooltipTrigger>
+ <TooltipContent>{b.hint}</TooltipContent>
+ </Tooltip>
+ ) : (
+ <span key={b.key} className={className}>
+ {swatch}
+ {b.label}
+ </span>
+ );
+ })}
</div>
<QueryState
diff --git a/src/server/features/rank-tracking/repositories/RankTrackingRepository.query.test.ts b/src/server/features/rank-tracking/repositories/RankTrackingRepository.query.test.ts
index 8acbcd1d..0d1ecb89 100644
--- a/src/server/features/rank-tracking/repositories/RankTrackingRepository.query.test.ts
+++ b/src/server/features/rank-tracking/repositories/RankTrackingRepository.query.test.ts
@@ -67,6 +67,24 @@ beforeAll(async () => {
pinned_at TEXT,
created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP
);
+ CREATE TABLE rank_check_runs (
+ id TEXT PRIMARY KEY,
+ config_id TEXT NOT NULL,
+ project_id TEXT NOT NULL,
+ status TEXT NOT NULL,
+ keywords_total INTEGER NOT NULL DEFAULT 0,
+ is_subset_run INTEGER NOT NULL DEFAULT 0,
+ started_at TEXT NOT NULL
+ );
+ CREATE TABLE rank_snapshots (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ run_id TEXT NOT NULL,
+ tracking_keyword_id TEXT NOT NULL,
+ keyword TEXT NOT NULL,
+ device TEXT NOT NULL,
+ position INTEGER,
+ checked_at TEXT NOT NULL
+ );
`);
({ RankTrackingRepository } = await import("./RankTrackingRepository"));
@@ -78,6 +96,8 @@ afterAll(() => {
beforeEach(async () => {
await client.executeMultiple(`
+ DELETE FROM rank_snapshots;
+ DELETE FROM rank_check_runs;
DELETE FROM rank_tracking_keywords;
DELETE FROM rank_tracking_configs;
DELETE FROM projects;
@@ -313,3 +333,41 @@ describe("setKeywordsPinned", () => {
expect(await pinnedIds()).toEqual([]);
});
});
+
+function daysAgo(days: number) {
+ return new Date(Date.now() - days * 24 * 60 * 60 * 1000)
+ .toISOString()
+ .slice(0, 19)
+ .replace("T", " ");
+}
+
+describe("getConfigTrend", () => {
+ it("keeps every row of a run inside the range and drops a run that started before it", async () => {
+ // run_b started before the 30-day cutoff, but one snapshot is after it.
+ for (const [runId, startedAt, snapshotTimes] of [
+ ["run_a", daysAgo(10), [daysAgo(10), daysAgo(10)]],
+ ["run_b", daysAgo(30.01), [daysAgo(30.01), daysAgo(29.99)]],
+ ] as const) {
+ await client.execute({
+ sql: "INSERT INTO rank_check_runs (id, config_id, project_id, status, keywords_total, started_at) VALUES (?, 'cfg_a', 'proj_1', 'completed', 2, ?)",
+ args: [runId, startedAt],
+ });
+ for (const [index, checkedAt] of snapshotTimes.entries()) {
+ await client.execute({
+ sql: "INSERT INTO rank_snapshots (run_id, tracking_keyword_id, keyword, device, position, checked_at) VALUES (?, ?, 'kw', 'desktop', 5, ?)",
+ args: [runId, `kw${index}`, checkedAt],
+ });
+ }
+ }
+
+ const trend = await RankTrackingRepository.getConfigTrend(
+ "cfg_a",
+ "desktop",
+ 30,
+ );
+
+ expect(trend).toMatchObject([
+ { runId: "run_a", keywordsTotal: 2, total: 2 },
+ ]);
+ });
+});
diff --git a/src/server/features/rank-tracking/repositories/snapshotQueries.ts b/src/server/features/rank-tracking/repositories/snapshotQueries.ts
index 76d643cc..4d1ae6f5 100644
--- a/src/server/features/rank-tracking/repositories/snapshotQueries.ts
+++ b/src/server/features/rank-tracking/repositories/snapshotQueries.ts
@@ -65,7 +65,8 @@ export async function getKeywordHistory(
* by runId (not checkedAt — snapshots in a run don't share an exact insert
* time); the run's startedAt is the x-axis timestamp. The buckets are disjoint
* and cover every tracked keyword: a position past 20, or null (not found in
- * the tracked depth), falls into "not ranking" (derived from `total`).
+ * the tracked depth), falls into "not ranking" (derived from `total`), and a
+ * keyword whose check failed has no row, so it is `keywordsTotal - total`.
*/
export async function getConfigTrend(
configId: string,
@@ -76,6 +77,7 @@ export async function getConfigTrend(
.select({
runId: rankSnapshots.runId,
checkedAt: rankCheckRuns.startedAt,
+ keywordsTotal: rankCheckRuns.keywordsTotal,
total: count(),
top3: sql<number>`sum(case when ${rankSnapshots.position} between 1 and 3 then 1 else 0 end)`,
top4to10: sql<number>`sum(case when ${rankSnapshots.position} between 4 and 10 then 1 else 0 end)`,
@@ -89,10 +91,16 @@ export async function getConfigTrend(
eq(rankCheckRuns.status, "completed"),
eq(rankCheckRuns.isSubsetRun, false),
eq(rankSnapshots.device, device),
- gte(rankSnapshots.checkedAt, cutoffTimestamp(sinceDays)),
+ // Filter on the run, not the snapshot: a run that spans the cutoff
+ // must keep all its rows, or they would count as not checked.
+ gte(rankCheckRuns.startedAt, cutoffTimestamp(sinceDays)),
),
)
- .groupBy(rankSnapshots.runId, rankCheckRuns.startedAt)
+ .groupBy(
+ rankSnapshots.runId,
+ rankCheckRuns.startedAt,
+ rankCheckRuns.keywordsTotal,
+ )
.orderBy(asc(rankCheckRuns.startedAt));
}
diff --git a/src/server/workflows/RankCheckWorkflow.test.ts b/src/server/workflows/RankCheckWorkflow.test.ts
index 491ad420..53e504bc 100644
--- a/src/server/workflows/RankCheckWorkflow.test.ts
+++ b/src/server/workflows/RankCheckWorkflow.test.ts
@@ -76,7 +76,7 @@ const payload = {
domain: "example.com",
locationCode: 2840,
languageCode: "en",
- devices: "desktop" as const,
+ devices: "desktop" as "desktop" | "mobile" | "both",
serpDepth: 10,
trigger: "manual" as const,
};
@@ -175,4 +175,25 @@ describe("rank check finalization", () => {
);
expect(mocks.updateConfig).not.toHaveBeenCalled();
});
+
+ it("reports a run that missed a whole device as partial", async () => {
+ mocks.getSnapshotsForRun.mockResolvedValue(
+ keywords(3).map((kw) => ({
+ trackingKeywordId: kw.id,
+ device: "desktop",
+ })),
+ );
+
+ await runWorkflow({ devices: "both" });
+
+ expect(mocks.updateRun).toHaveBeenCalledWith(
+ "run_1",
+ expect.objectContaining({
+ status: "completed",
+ keywordsChecked: 3,
+ errorMessage:
+ "Checked 3 of 3 desktop and 0 of 3 mobile keyword(s): Invalid Field: 'location_name'.",
+ }),
+ );
+ });
});
diff --git a/src/server/workflows/RankCheckWorkflow.ts b/src/server/workflows/RankCheckWorkflow.ts
index c0f2cdc9..1a60e43f 100644
--- a/src/server/workflows/RankCheckWorkflow.ts
+++ b/src/server/workflows/RankCheckWorkflow.ts
@@ -141,6 +141,7 @@ async function finalizeRankCheckRun(input: {
projectId: string;
billingCustomer: BillingCustomerContext;
trigger: RankCheckParams["trigger"];
+ devices: RankCheckParams["devices"];
batchError: string | null;
queueStats: QueuedCheckStats | null;
}) {
@@ -157,27 +158,44 @@ async function finalizeRankCheckRun(input: {
const nowIso = new Date().toISOString();
- // Snapshots were written incrementally by each batch step.
- // Count from DB to get the authoritative keyword count.
+ // Snapshots were written incrementally by each batch step. Count from the
+ // DB: a keyword is checked when any device has a snapshot, but the run is
+ // partial when any device is missing one, so a lost device still shows.
const snapshots = await RankTrackingRepository.getSnapshotsForRun(
input.runId,
);
const keywordsChecked = new Set(snapshots.map((s) => s.trackingKeywordId))
.size;
+ const devices: Array<"desktop" | "mobile"> =
+ input.devices === "both" ? ["desktop", "mobile"] : [input.devices];
+ const checkedByDevice = devices.map((device) => ({
+ device,
+ count: new Set(
+ snapshots
+ .filter((s) => s.device === device)
+ .map((s) => s.trackingKeywordId),
+ ).size,
+ }));
const keywordsTotal = run.keywordsTotal || keywordsChecked;
- const incompleteCount = keywordsTotal - keywordsChecked;
+ const isPartial = checkedByDevice.some((d) => d.count < keywordsTotal);
// Batch steps record the first per-keyword rejection on the run as it
// happens, so a failed run shows the vendor's reason rather than a count.
const keywordError = run.errorMessage ?? input.batchError;
const status =
keywordsChecked === 0 && keywordsTotal > 0 ? "failed" : "completed";
+ const checkedSummary =
+ checkedByDevice.length > 1
+ ? checkedByDevice
+ .map(({ device, count }) => `${count} of ${keywordsTotal} ${device}`)
+ .join(" and ")
+ : `${keywordsChecked} of ${keywordsTotal}`;
const errorMessage =
status === "failed"
? (keywordError ?? "No keywords could be checked.")
- : incompleteCount > 0
- ? `Checked ${keywordsChecked} of ${keywordsTotal} keyword(s)${keywordError ? `: ${keywordError}` : ""}`
+ : isPartial
+ ? `Checked ${checkedSummary} keyword(s)${keywordError ? `: ${keywordError}` : ""}`
: null;
// Flipping status away from 'pending'/'running' is what releases the
@@ -379,6 +397,7 @@ export class RankCheckWorkflow extends WorkflowEntrypoint<
projectId,
billingCustomer,
trigger,
+ devices,
batchError,
queueStats,
}),
diff --git a/src/serverFunctions/rank-tracking.ts b/src/serverFunctions/rank-tracking.ts
index 4b1cdd89..d68fc77d 100644
--- a/src/serverFunctions/rank-tracking.ts
+++ b/src/serverFunctions/rank-tracking.ts
@@ -37,6 +37,7 @@ interface RankConfigTrendPoint {
top4to10: number;
top11to20: number;
notRanking: number;
+ notChecked: number;
}
export interface RankPositionMatrixCell {
@@ -326,7 +327,9 @@ export const getRankConfigTrend = createServerFn({ method: "POST" })
data.sinceDays,
);
// SQLite sum()/count() can return strings; coerce and derive "not ranking"
- // (position > 20 or null) as the remainder so the buckets cover every kw.
+ // (position > 20 or null) as the remainder of the checked keywords, and
+ // "not checked" (the check failed, so no row) as the remainder of the
+ // run's keywords, so the buckets cover every tracked keyword.
return rows.map((row) => {
const top3 = Number(row.top3) || 0;
const top4to10 = Number(row.top4to10) || 0;
@@ -339,6 +342,7 @@ export const getRankConfigTrend = createServerFn({ method: "POST" })
top4to10,
top11to20,
notRanking: Math.max(0, total - top3 - top4to10 - top11to20),
+ notChecked: Math.max(0, row.keywordsTotal - total),
};
});
});