Skip to content

Open source alternative to Semrush and Ahrefs

Let users pick the day and time scheduled rank checks run (EVE-163) (#651)

Carter Smithb36cb7853a5f
diff --git a/src/client/features/rank-tracking/RankTrackingConfigModal.tsx b/src/client/features/rank-tracking/RankTrackingConfigModal.tsx
index a58d0628..d031b1c2 100644
--- a/src/client/features/rank-tracking/RankTrackingConfigModal.tsx
+++ b/src/client/features/rank-tracking/RankTrackingConfigModal.tsx
@@ -20,6 +20,12 @@ import { useProjectMarket } from "@/client/features/projects/useProjectMarket";
import { SearchTargetingField } from "./SearchTargetingField";
import { KeywordSuggestionStep } from "./KeywordSuggestionStep";
import { useSaveConfigMutations } from "./useSaveConfigMutations";
+import { ScheduleField } from "./ScheduleField";
+import {
+ localScheduleTimeFrom,
+ randomScheduleDate,
+ withBrowserTimeZone,
+} from "./scheduleTime";
type Props = {
projectId: string;
@@ -98,6 +104,22 @@ function RankTrackingConfigModalContent({
existingConfig?.locationName ?? undefined,
);
const [createdConfigId, setCreatedConfigId] = useState<string | null>(null);
+ // Shown and edited in the browser's timezone; the server converts it to UTC.
+ const [scheduleTime, setScheduleTime] = useState(() =>
+ localScheduleTimeFrom(
+ existingConfig?.nextCheckAt
+ ? new Date(existingConfig.nextCheckAt)
+ : randomScheduleDate(),
+ ),
+ );
+ const [scheduleTimeEdited, setScheduleTimeEdited] = useState(false);
+ // An untouched edit leaves the stored run time alone; anything that changes
+ // the schedule sends the time on screen so it is the one that gets saved.
+ const sendScheduleTime =
+ schedule !== "manual" &&
+ (!existingConfig ||
+ scheduleTimeEdited ||
+ schedule !== existingConfig.scheduleInterval);
const selectedCountryCode = useMemo(
() => getIsoCountryCode(locationCode),
@@ -115,6 +137,9 @@ function RankTrackingConfigModalContent({
targetingMode,
locationName,
schedule,
+ scheduleTime: sendScheduleTime
+ ? withBrowserTimeZone(scheduleTime)
+ : undefined,
},
onCreated: (configId) => {
setCreatedConfigId(configId);
@@ -289,37 +314,15 @@ function RankTrackingConfigModalContent({
)}
</div>
- <div className="form-control">
- <label className="label">
- <span className="label-text font-medium">Schedule</span>
- </label>
- <select
- className="select select-bordered w-full"
- value={schedule}
- onChange={(e) => {
- const value = e.target.value;
- if (
- value === "daily" ||
- value === "weekly" ||
- value === "monthly" ||
- value === "manual"
- ) {
- setSchedule(value);
- }
- }}
- >
- <option value="daily">Daily</option>
- <option value="weekly">Weekly</option>
- <option value="monthly">Monthly (end of month)</option>
- <option value="manual">Manual only</option>
- </select>
- {schedule === "daily" && (
- <div className="mt-1.5 flex items-start gap-1.5 text-xs text-warning">
- <Info className="size-3.5 shrink-0 mt-0.5" />
- <span>Daily checks use 7x more credits than weekly</span>
- </div>
- )}
- </div>
+ <ScheduleField
+ schedule={schedule}
+ onScheduleChange={setSchedule}
+ scheduleTime={scheduleTime}
+ onScheduleTimeChange={(time) => {
+ setScheduleTime(time);
+ setScheduleTimeEdited(true);
+ }}
+ />
<div className="form-control">
<label className="label">
diff --git a/src/client/features/rank-tracking/RankTrackingDetailHeader.tsx b/src/client/features/rank-tracking/RankTrackingDetailHeader.tsx
index a1a906f6..2f4891eb 100644
--- a/src/client/features/rank-tracking/RankTrackingDetailHeader.tsx
+++ b/src/client/features/rank-tracking/RankTrackingDetailHeader.tsx
@@ -2,6 +2,7 @@ import { Monitor, Plus, Settings, Smartphone } from "lucide-react";
import { SegmentedToggle } from "@/client/components/SegmentedToggle";
import { LOCATIONS } from "@/client/features/keywords/locations";
import { devicesLabel, scheduleLabel } from "@/shared/rank-tracking";
+import { formatNextCheck } from "./scheduleTime";
import { formatLocationLabel } from "@/shared/keyword-locations";
import type {
ComparePeriod,
@@ -51,6 +52,9 @@ export function RankTrackingDetailHeader({
: (LOCATIONS[config.locationCode] ?? "US")}{" "}
&middot; {devicesLabel(config.devices)} &middot;{" "}
{scheduleLabel(config.scheduleInterval)}
+ {config.scheduleInterval !== "manual" && config.nextCheckAt && (
+ <> &middot; Next: {formatNextCheck(config.nextCheckAt)}</>
+ )}
{run?.lastCheckedAt && (
<>
{" "}
diff --git a/src/client/features/rank-tracking/RankTrackingDomainList.tsx b/src/client/features/rank-tracking/RankTrackingDomainList.tsx
index 6186dc57..c8f84e0c 100644
--- a/src/client/features/rank-tracking/RankTrackingDomainList.tsx
+++ b/src/client/features/rank-tracking/RankTrackingDomainList.tsx
@@ -16,6 +16,7 @@ import {
updateRankTrackingConfig,
} from "@/serverFunctions/rank-tracking";
import { devicesLabel, scheduleLabel } from "@/shared/rank-tracking";
+import { formatNextCheck } from "./scheduleTime";
import { formatLocationLabel } from "@/shared/keyword-locations";
import { Modal } from "@/client/components/Modal";
import {
@@ -220,6 +221,9 @@ function DomainRow({
: (LOCATIONS[summary.locationCode] ?? "US")}{" "}
&middot; {devicesLabel(summary.devices)} &middot;{" "}
{scheduleLabel(summary.scheduleInterval)}
+ {summary.scheduleInterval !== "manual" && summary.nextCheckAt && (
+ <> &middot; Next: {formatNextCheck(summary.nextCheckAt)}</>
+ )}
{summary.lastRunCompletedAt && (
<>
{" "}
diff --git a/src/client/features/rank-tracking/ScheduleField.tsx b/src/client/features/rank-tracking/ScheduleField.tsx
new file mode 100644
index 00000000..34acc63d
--- /dev/null
+++ b/src/client/features/rank-tracking/ScheduleField.tsx
@@ -0,0 +1,117 @@
+import { useState } from "react";
+import { Info } from "lucide-react";
+import type { RankTrackingConfig } from "@/types/schemas/rank-tracking";
+import {
+ WEEKDAYS,
+ browserTimeZoneLabel,
+ describeSchedule,
+ type LocalScheduleTime,
+} from "./scheduleTime";
+
+type Props = {
+ schedule: RankTrackingConfig["scheduleInterval"];
+ onScheduleChange: (schedule: RankTrackingConfig["scheduleInterval"]) => void;
+ scheduleTime: LocalScheduleTime;
+ onScheduleTimeChange: (scheduleTime: LocalScheduleTime) => void;
+};
+
+export function ScheduleField({
+ schedule,
+ onScheduleChange,
+ scheduleTime,
+ onScheduleTimeChange,
+}: Props) {
+ const [showScheduleTime, setShowScheduleTime] = useState(false);
+
+ return (
+ <div className="form-control">
+ <label className="label">
+ <span className="label-text font-medium">Schedule</span>
+ </label>
+ <select
+ className="select select-bordered w-full"
+ value={schedule}
+ onChange={(e) => {
+ const value = e.target.value;
+ if (
+ value === "daily" ||
+ value === "weekly" ||
+ value === "monthly" ||
+ value === "manual"
+ ) {
+ onScheduleChange(value);
+ }
+ }}
+ >
+ <option value="daily">Daily</option>
+ <option value="weekly">Weekly</option>
+ <option value="monthly">Monthly (end of month)</option>
+ <option value="manual">Manual only</option>
+ </select>
+ {schedule !== "manual" && (
+ <div className="mt-1.5 text-xs text-base-content/60">
+ {describeSchedule(schedule, scheduleTime)}
+ {!showScheduleTime && (
+ <>
+ {" "}
+ &middot;{" "}
+ <button
+ type="button"
+ className="link"
+ onClick={() => setShowScheduleTime(true)}
+ >
+ change
+ </button>
+ </>
+ )}
+ </div>
+ )}
+ {schedule !== "manual" && showScheduleTime && (
+ <>
+ <div className="mt-2 flex gap-2">
+ {schedule === "weekly" && (
+ <select
+ className="select select-bordered select-sm"
+ aria-label="Day of week"
+ value={scheduleTime.weekday}
+ onChange={(e) =>
+ onScheduleTimeChange({
+ ...scheduleTime,
+ weekday: Number(e.target.value),
+ })
+ }
+ >
+ {WEEKDAYS.map((day, index) => (
+ <option key={day} value={index}>
+ {day}
+ </option>
+ ))}
+ </select>
+ )}
+ <input
+ type="time"
+ className="input input-bordered input-sm"
+ aria-label="Time of day"
+ value={`${String(scheduleTime.hour).padStart(2, "0")}:${String(scheduleTime.minute).padStart(2, "0")}`}
+ onChange={(e) => {
+ const [hour, minute] = e.target.value.split(":").map(Number);
+ // Clearing the field yields "", which has no time to keep.
+ if (Number.isNaN(hour) || Number.isNaN(minute)) return;
+ onScheduleTimeChange({ ...scheduleTime, hour, minute });
+ }}
+ />
+ </div>
+ <div className="mt-1.5 text-xs text-base-content/50">
+ In your local timezone: {browserTimeZoneLabel()}
+ </div>
+ </>
+ )}
+ {schedule === "daily" && (
+ <div className="mt-1.5 flex items-start gap-1.5 text-xs text-warning">
+ <Info className="size-3.5 shrink-0 mt-0.5" />
+ <span>Daily checks use 7x more credits than weekly</span>
+ </div>
+ )}
+ </div>
+ );
+}
diff --git a/src/client/features/rank-tracking/scheduleTime.ts b/src/client/features/rank-tracking/scheduleTime.ts
new file mode 100644
index 00000000..8360c68d
--- /dev/null
+++ b/src/client/features/rank-tracking/scheduleTime.ts
@@ -0,0 +1,106 @@
+import type {
+ RankCheckScheduleTime,
+ RankTrackingConfig,
+} from "@/types/schemas/rank-tracking";
+
+export const WEEKDAYS = [
+ "Sunday",
+ "Monday",
+ "Tuesday",
+ "Wednesday",
+ "Thursday",
+ "Friday",
+ "Saturday",
+];
+
+/** A weekday and time as the user picks it, in the browser's timezone. */
+export type LocalScheduleTime = {
+ weekday: number;
+ hour: number;
+ minute: number;
+};
+
+export function localScheduleTimeFrom(date: Date): LocalScheduleTime {
+ return {
+ weekday: date.getDay(),
+ hour: date.getHours(),
+ minute: date.getMinutes(),
+ };
+}
+
+/** Same default the server picks: a random minute between 04:00 and 10:00 UTC. */
+export function randomScheduleDate(): Date {
+ const date = new Date();
+ date.setUTCHours(
+ 4 + Math.floor(Math.random() * 6),
+ Math.floor(Math.random() * 60),
+ 0,
+ 0,
+ );
+ return date;
+}
+
+function nextLocalOccurrence(time: LocalScheduleTime): Date {
+ const date = new Date();
+ date.setHours(time.hour, time.minute, 0, 0);
+ date.setDate(date.getDate() + ((time.weekday - date.getDay() + 7) % 7));
+ return date;
+}
+
+/** The server converts to UTC, so it needs the timezone the pick was made in. */
+export function withBrowserTimeZone(
+ time: LocalScheduleTime,
+): RankCheckScheduleTime {
+ return {
+ ...time,
+ timeZone: Intl.DateTimeFormat().resolvedOptions().timeZone,
+ };
+}
+
+/** City part of the IANA name plus today's offset: "Los Angeles (UTC-7)". */
+export function browserTimeZoneLabel(): string {
+ const { timeZone } = Intl.DateTimeFormat().resolvedOptions();
+ const city = timeZone.slice(timeZone.lastIndexOf("/") + 1);
+ const offsetMinutes = -new Date().getTimezoneOffset();
+ const hours = Math.floor(Math.abs(offsetMinutes) / 60);
+ const minutes = Math.abs(offsetMinutes) % 60;
+ const offset = `${offsetMinutes < 0 ? "-" : "+"}${hours}${minutes ? `:${String(minutes).padStart(2, "0")}` : ""}`;
+ return `${city.replaceAll("_", " ")} (UTC${offset})`;
+}
+
+export function describeSchedule(
+ interval: Exclude<RankTrackingConfig["scheduleInterval"], "manual">,
+ time: LocalScheduleTime,
+): string {
+ const date = nextLocalOccurrence(time);
+ const localTime = date.toLocaleTimeString([], {
+ hour: "numeric",
+ minute: "2-digit",
+ });
+ const utcTime = date.toLocaleTimeString("en-GB", {
+ timeZone: "UTC",
+ hour: "2-digit",
+ minute: "2-digit",
+ });
+ const utcWeekday =
+ interval === "weekly" && date.getUTCDay() !== date.getDay()
+ ? `${WEEKDAYS[date.getUTCDay()].slice(0, 3)} `
+ : "";
+ const when =
+ interval === "daily"
+ ? "daily"
+ : interval === "weekly"
+ ? `weekly on ${WEEKDAYS[time.weekday]}s`
+ : "on the last day of each month";
+ return `Runs ${when} at ${localTime} (${utcWeekday}${utcTime} UTC)`;
+}
+
+export function formatNextCheck(nextCheckAt: string): string {
+ return new Date(nextCheckAt).toLocaleString([], {
+ weekday: "short",
+ month: "short",
+ day: "numeric",
+ hour: "numeric",
+ minute: "2-digit",
+ });
+}
diff --git a/src/client/features/rank-tracking/useSaveConfigMutations.ts b/src/client/features/rank-tracking/useSaveConfigMutations.ts
index 1fff7e77..51c8e6dc 100644
--- a/src/client/features/rank-tracking/useSaveConfigMutations.ts
+++ b/src/client/features/rank-tracking/useSaveConfigMutations.ts
@@ -6,7 +6,10 @@ import {
} from "@/serverFunctions/rank-tracking";
import { getStandardErrorMessage } from "@/client/lib/error-messages";
import { captureClientEvent } from "@/client/lib/posthog";
-import type { RankTrackingConfig } from "@/types/schemas/rank-tracking";
+import type {
+ RankCheckScheduleTime,
+ RankTrackingConfig,
+} from "@/types/schemas/rank-tracking";
type ConfigFields = {
devices: "both" | "desktop" | "mobile";
@@ -16,6 +19,7 @@ type ConfigFields = {
targetingMode: "national" | "local";
locationName: string | undefined;
schedule: RankTrackingConfig["scheduleInterval"];
+ scheduleTime: RankCheckScheduleTime | undefined;
};
export function useSaveConfigMutations(input: {
@@ -32,6 +36,7 @@ export function useSaveConfigMutations(input: {
locationCode: fields.locationCode,
languageCode: fields.languageCode,
scheduleInterval: fields.schedule,
+ scheduleTime: fields.scheduleTime,
};
const createMutation = useMutation({
diff --git a/src/server/features/rank-tracking/services/RankTrackingService.test.ts b/src/server/features/rank-tracking/services/RankTrackingService.test.ts
index b998123e..95137b85 100644
--- a/src/server/features/rank-tracking/services/RankTrackingService.test.ts
+++ b/src/server/features/rank-tracking/services/RankTrackingService.test.ts
@@ -235,3 +235,58 @@ describe("RankTrackingService.createConfig", () => {
expect(mocks.createConfig).not.toHaveBeenCalled();
});
});
+
+describe("RankTrackingService.updateConfig schedule", () => {
+ beforeEach(() => {
+ mocks.getConfigById.mockResolvedValue({
+ ...archivedConfig,
+ isActive: true,
+ nextCheckAt: "2026-03-15T21:00:00.000Z",
+ });
+ });
+
+ it("keeps the run time when a save resends an unchanged interval", async () => {
+ await RankTrackingService.updateConfig("config_archived", "project_1", {
+ devices: "mobile",
+ scheduleInterval: "weekly",
+ });
+
+ expect(mocks.updateConfig.mock.calls[0][2]).toEqual({ devices: "mobile" });
+ });
+
+ it("moves the run time to a chosen time", async () => {
+ vi.useFakeTimers();
+ // A Tuesday.
+ vi.setSystemTime(new Date("2026-03-10T12:00:00.000Z"));
+
+ await RankTrackingService.updateConfig("config_archived", "project_1", {
+ scheduleTime: { weekday: 1, hour: 9, minute: 30 },
+ });
+ vi.useRealTimers();
+
+ expect(mocks.updateConfig).toHaveBeenCalledWith(
+ "config_archived",
+ "project_1",
+ { scheduleInterval: "weekly", nextCheckAt: "2026-03-16T09:30:00.000Z" },
+ );
+ });
+
+ it("rejects a weekly time without a weekday", async () => {
+ await expect(
+ RankTrackingService.updateConfig("config_archived", "project_1", {
+ scheduleTime: { hour: 9, minute: 30 },
+ }),
+ ).rejects.toMatchObject({ code: "VALIDATION_ERROR" });
+ expect(mocks.updateConfig).not.toHaveBeenCalled();
+ });
+
+ it("rejects a chosen time on a manual schedule", async () => {
+ await expect(
+ RankTrackingService.updateConfig("config_archived", "project_1", {
+ scheduleInterval: "manual",
+ scheduleTime: { hour: 9, minute: 30 },
+ }),
+ ).rejects.toMatchObject({ code: "VALIDATION_ERROR" });
+ expect(mocks.updateConfig).not.toHaveBeenCalled();
+ });
+});
diff --git a/src/server/features/rank-tracking/services/RankTrackingService.ts b/src/server/features/rank-tracking/services/RankTrackingService.ts
index 87ece4e6..58e69338 100644
--- a/src/server/features/rank-tracking/services/RankTrackingService.ts
+++ b/src/server/features/rank-tracking/services/RankTrackingService.ts
@@ -12,6 +12,7 @@ import { assertSerpLocationNameAccepted } from "@/server/lib/dataforseo/serp-loc
import { AppError } from "@/server/lib/errors";
import { isHostedServerAuthMode } from "@/server/lib/runtime-env";
import type {
+ RankCheckScheduleTime,
RankTrackingConfig,
RankCheckTriggerResult,
} from "@/types/schemas/rank-tracking";
@@ -49,6 +50,7 @@ async function createConfig(input: {
devices?: RankTrackingConfig["devices"];
serpDepth: number;
scheduleInterval?: RankTrackingConfig["scheduleInterval"];
+ scheduleTime?: RankCheckScheduleTime;
}) {
const normalizedDomain = normalizeDomain(input.domain);
@@ -57,9 +59,7 @@ async function createConfig(input: {
input.projectMarket,
);
const scheduleInterval = input.scheduleInterval ?? "weekly";
- const nextCheckAt = isScheduledRankTrackingInterval(scheduleInterval)
- ? computeNextCheckAt(scheduleInterval)
- : null;
+ const nextCheckAt = resolveNextCheckAt(scheduleInterval, input.scheduleTime);
const locationName = input.locationName ?? null;
// Before the duplicate/limit checks so an unusable location name is the
@@ -155,10 +155,13 @@ async function updateConfig(
devices?: RankTrackingConfig["devices"];
serpDepth?: number;
scheduleInterval?: RankTrackingConfig["scheduleInterval"];
+ scheduleTime?: RankCheckScheduleTime;
isActive?: boolean;
},
) {
- const updates: typeof input & { nextCheckAt?: string | null } = {};
+ const { scheduleTime, ...fields } = input;
+ const updates: typeof fields & { nextCheckAt?: string | null } = {};
+ const existing = await getValidatedConfig(configId, projectId);
// A location name is only valid together with its market, so re-check the
// resulting (name, language, country) whenever any of the three changes.
@@ -167,7 +170,6 @@ async function updateConfig(
input.locationCode !== undefined ||
input.languageCode !== undefined;
if (marketChanged) {
- const existing = await getValidatedConfig(configId, projectId);
const locationName =
input.locationName === undefined
? existing.locationName
@@ -195,18 +197,49 @@ async function updateConfig(
if (input.serpDepth !== undefined) updates.serpDepth = input.serpDepth;
if (input.isActive !== undefined) updates.isActive = input.isActive;
- if (input.scheduleInterval !== undefined) {
- updates.scheduleInterval = input.scheduleInterval;
- if (input.scheduleInterval === "manual") {
- updates.nextCheckAt = null;
- } else {
- updates.nextCheckAt = computeNextCheckAt(input.scheduleInterval);
- }
+ const scheduleInterval = input.scheduleInterval ?? existing.scheduleInterval;
+ // The config modal resends the interval on every save, so only move the
+ // anchor when the schedule really changed — otherwise editing, say, devices
+ // would re-randomize the run time.
+ if (
+ scheduleTime ||
+ scheduleInterval !== existing.scheduleInterval ||
+ (scheduleInterval !== "manual" && !existing.nextCheckAt)
+ ) {
+ updates.scheduleInterval = scheduleInterval;
+ updates.nextCheckAt = resolveNextCheckAt(scheduleInterval, scheduleTime);
}
await RankTrackingRepository.updateConfig(configId, projectId, updates);
}
+function resolveNextCheckAt(
+ scheduleInterval: RankTrackingConfig["scheduleInterval"],
+ scheduleTime: RankCheckScheduleTime | undefined,
+): string | null {
+ if (isScheduledRankTrackingInterval(scheduleInterval)) {
+ // Without one the check would quietly repeat on whatever day today is.
+ if (
+ scheduleInterval === "weekly" &&
+ scheduleTime &&
+ scheduleTime.weekday === undefined
+ ) {
+ throw new AppError(
+ "VALIDATION_ERROR",
+ "A weekly schedule time needs a weekday",
+ );
+ }
+ return computeNextCheckAt(scheduleInterval, null, scheduleTime);
+ }
+ if (scheduleTime) {
+ throw new AppError(
+ "VALIDATION_ERROR",
+ "A schedule time needs a daily, weekly, or monthly schedule",
+ );
+ }
+ return null;
+}
+
// ---------------------------------------------------------------------------
// Trigger a manual check
// ---------------------------------------------------------------------------
diff --git a/src/server/mcp/tools/create-rank-tracker.ts b/src/server/mcp/tools/create-rank-tracker.ts
index c06ef2f7..5e19ba6d 100644
--- a/src/server/mcp/tools/create-rank-tracker.ts
+++ b/src/server/mcp/tools/create-rank-tracker.ts
@@ -16,6 +16,7 @@ import {
projectIdSchema,
} from "@/server/mcp/schemas";
import { domainField } from "@/types/schemas/domain";
+import { scheduleTimeSchema } from "@/types/schemas/rank-tracking";
const inputSchema = {
projectId: projectIdSchema,
@@ -53,6 +54,11 @@ const inputSchema = {
.describe(
"Check schedule. Defaults to manual so creating a tracker cannot cause future credit spend. Scheduled checks may use credits later.",
),
+ scheduleTime: scheduleTimeSchema
+ .optional()
+ .describe(
+ "When scheduled checks run. Pass the user's timeZone with it so their local time is converted for you; the schedule is then fixed in UTC and shifts an hour when their clocks change. Omit it unless the user asks for a specific time: the default spreads checks across quiet hours. Daily runs at this time every day, weekly on the given weekday, monthly at this time on the last day of the month. Checks start within about 15 minutes of the chosen time. Not valid with a manual schedule.",
+ ),
} as const;
type Args = z.infer<z.ZodObject<typeof inputSchema>>;
@@ -96,6 +102,7 @@ export const createRankTrackerTool = {
devices: args.devices ?? "mobile",
serpDepth: args.serpDepth ?? 40,
scheduleInterval: args.scheduleInterval ?? "manual",
+ scheduleTime: args.scheduleTime,
});
waitUntil(
captureServerEvent({
@@ -113,7 +120,7 @@ export const createRankTrackerTool = {
);
return mcpResponse({
- text: `Created rank tracker ${config.id} for ${config.domain} (${config.devices}, top ${config.serpDepth}, ${config.scheduleInterval}). No keywords were added, no check was started, and no credits were used.${config.locationName ? ` Local tracking for ${config.locationName}.` : ""}${config.scheduleInterval === "manual" ? "" : " Scheduled checks will spend credits after keywords are added; estimate and obtain approval before adding them."}`,
+ text: `Created rank tracker ${config.id} for ${config.domain} (${config.devices}, top ${config.serpDepth}, ${config.scheduleInterval}). No keywords were added, no check was started, and no credits were used.${config.locationName ? ` Local tracking for ${config.locationName}.` : ""}${config.nextCheckAt ? ` First scheduled check: ${config.nextCheckAt}.` : ""}${config.scheduleInterval === "manual" ? "" : " Scheduled checks will spend credits after keywords are added; estimate and obtain approval before adding them."}`,
meta: buildProjectMeta(
context,
args.projectId,
diff --git a/src/serverFunctions/rank-tracking.ts b/src/serverFunctions/rank-tracking.ts
index 36957f37..3f0012b5 100644
--- a/src/serverFunctions/rank-tracking.ts
+++ b/src/serverFunctions/rank-tracking.ts
@@ -83,6 +83,7 @@ export const createRankTrackingConfig = createServerFn({ method: "POST" })
devices: data.devices,
serpDepth: data.serpDepth,
scheduleInterval: data.scheduleInterval,
+ scheduleTime: data.scheduleTime,
});
waitUntil(
@@ -114,6 +115,7 @@ export const updateRankTrackingConfig = createServerFn({ method: "POST" })
devices: data.devices,
serpDepth: data.serpDepth,
scheduleInterval: data.scheduleInterval,
+ scheduleTime: data.scheduleTime,
isActive: data.isActive,
});
return { success: true };
diff --git a/src/shared/rank-tracking.test.ts b/src/shared/rank-tracking.test.ts
index 1884e2b3..03e96bca 100644
--- a/src/shared/rank-tracking.test.ts
+++ b/src/shared/rank-tracking.test.ts
@@ -110,4 +110,88 @@ describe("rank tracking schedules", () => {
"2026-03-14T05:30:00.000Z",
);
});
+
+ it("starts a chosen weekly time on its next occurrence", () => {
+ vi.useFakeTimers();
+ // A Tuesday.
+ vi.setSystemTime(new Date("2026-03-10T12:00:00.000Z"));
+ const sunday9pm = { weekday: 0, hour: 21, minute: 0 };
+ const tuesday9am = { weekday: 2, hour: 9, minute: 0 };
+
+ expect(computeNextCheckAt("weekly", null, sunday9pm)).toBe(
+ "2026-03-15T21:00:00.000Z",
+ );
+ // Today's weekday but already past: a week out, not a run in the past.
+ expect(computeNextCheckAt("weekly", null, tuesday9am)).toBe(
+ "2026-03-17T09:00:00.000Z",
+ );
+ });
+
+ it("converts a time chosen in a timezone, weekday included", () => {
+ vi.useFakeTimers();
+ // Late in the minute: the seconds must not leak into the offset.
+ vi.setSystemTime(new Date("2026-03-10T12:00:45.000Z"));
+ const sunday9pm = { weekday: 0, hour: 21, minute: 0 };
+
+ // UTC-4 in March: Sunday 9 PM is Monday 01:00 UTC.
+ expect(
+ computeNextCheckAt("weekly", null, {
+ ...sunday9pm,
+ timeZone: "America/New_York",
+ }),
+ ).toBe("2026-03-16T01:00:00.000Z");
+ // UTC+5:30: Sunday 9 PM is still Sunday in UTC.
+ expect(
+ computeNextCheckAt("weekly", null, {
+ ...sunday9pm,
+ timeZone: "Asia/Kolkata",
+ }),
+ ).toBe("2026-03-15T15:30:00.000Z");
+ });
+
+ it("runs a chosen daily time later today when it is still ahead", () => {
+ vi.useFakeTimers();
+ vi.setSystemTime(new Date("2026-03-10T12:00:00.000Z"));
+
+ expect(computeNextCheckAt("daily", null, { hour: 21, minute: 15 })).toBe(
+ "2026-03-10T21:15:00.000Z",
+ );
+ });
+
+ it("keeps monthly on the user's last day when it is another UTC date", () => {
+ vi.useFakeTimers();
+ vi.setSystemTime(new Date("2026-02-10T12:00:00.000Z"));
+ // Feb 28, 9 PM in Los Angeles (UTC-8) is already March 1 in UTC.
+ const losAngeles = computeNextCheckAt("monthly", null, {
+ hour: 21,
+ minute: 0,
+ timeZone: "America/Los_Angeles",
+ });
+ expect(losAngeles).toBe("2026-03-01T05:00:00.000Z");
+ // Feb 28, 1 AM in Kolkata (UTC+5:30) is still February 27 in UTC.
+ const kolkata = computeNextCheckAt("monthly", null, {
+ hour: 1,
+ minute: 0,
+ timeZone: "Asia/Kolkata",
+ });
+ expect(kolkata).toBe("2026-02-27T19:30:00.000Z");
+
+ // Advancing keeps each anchor's relation to the month end.
+ vi.setSystemTime(new Date("2026-03-02T12:00:00.000Z"));
+ expect(computeNextCheckAt("monthly", losAngeles)).toBe(
+ "2026-04-01T05:00:00.000Z",
+ );
+ expect(computeNextCheckAt("monthly", kolkata)).toBe(
+ "2026-03-30T19:30:00.000Z",
+ );
+ });
+
+ it("keeps monthly on the last day when a time is chosen", () => {
+ vi.useFakeTimers();
+ vi.setSystemTime(new Date("2026-02-10T12:00:00.000Z"));
+
+ expect(
+ computeNextCheckAt("monthly", null, { weekday: 0, hour: 21, minute: 0 }),
+ ).toBe("2026-02-28T21:00:00.000Z");
+ });
});
diff --git a/src/shared/rank-tracking.ts b/src/shared/rank-tracking.ts
index 03fb4574..3f957485 100644
--- a/src/shared/rank-tracking.ts
+++ b/src/shared/rank-tracking.ts
@@ -3,7 +3,10 @@ import {
SEO_DATA_COST_MARKUP,
roundUsdForBilling,
} from "./billing";
-import type { RankTrackingConfig } from "@/types/schemas/rank-tracking";
+import type {
+ RankCheckScheduleTime,
+ RankTrackingConfig,
+} from "@/types/schemas/rank-tracking";
// ---------------------------------------------------------------------------
// Cost constants
@@ -148,21 +151,87 @@ export function isScheduledRankTrackingInterval(
return interval !== "manual";
}
-function endOfMonthWithTime(source: Date, monthOffset = 0): Date {
- const endOfMonth = new Date(
- Date.UTC(
- source.getUTCFullYear(),
- source.getUTCMonth() + monthOffset + 1,
- 0,
- ),
- );
- endOfMonth.setUTCHours(
- source.getUTCHours(),
- source.getUTCMinutes(),
- source.getUTCSeconds(),
- source.getUTCMilliseconds(),
+/**
+ * Monthly checks run on the last day of the month where the user is. That day
+ * can fall on a neighbouring UTC date, so the anchor sits `dayShift` days from
+ * the UTC month end: -1, 0, or +1.
+ */
+function monthEndWithTime(
+ year: number,
+ month: number,
+ dayShift: number,
+ time: { hour: number; minute: number },
+): Date {
+ // Day 0 of the following month is the last day of this one.
+ return new Date(Date.UTC(year, month + 1, dayShift, time.hour, time.minute));
+}
+
+/**
+ * Read the day shift back off a stored monthly anchor, so advancing it keeps
+ * the same relation to the month end without a column for it. Months have at
+ * least 28 days, so the 1st, the last day, and the day before never collide.
+ */
+function monthlyAnchorDayShift(anchor: Date): number {
+ if (anchor.getUTCDate() === 1) return 1;
+ const lastDay = new Date(
+ Date.UTC(anchor.getUTCFullYear(), anchor.getUTCMonth() + 1, 0),
+ ).getUTCDate();
+ return anchor.getUTCDate() === lastDay - 1 ? -1 : 0;
+}
+
+type UtcScheduleTime = {
+ weekday?: number;
+ hour: number;
+ minute: number;
+ /** Days the chosen date moved when converting to UTC: -1, 0, or +1. */
+ dayShift: number;
+};
+
+/**
+ * Shift a chosen time from its timezone to UTC, weekday included. Uses the
+ * zone's offset right now: the anchor is fixed in UTC afterwards anyway, so a
+ * pick made just before a clock change is an hour off from its first run on.
+ */
+function scheduleTimeInUtc(
+ scheduleTime: RankCheckScheduleTime,
+ now: number,
+): UtcScheduleTime {
+ if (!scheduleTime.timeZone) return { ...scheduleTime, dayShift: 0 };
+
+ const parts = new Intl.DateTimeFormat("en-US", {
+ timeZone: scheduleTime.timeZone,
+ hourCycle: "h23",
+ year: "numeric",
+ month: "numeric",
+ day: "numeric",
+ hour: "numeric",
+ minute: "numeric",
+ }).formatToParts(now);
+ const part = (type: Intl.DateTimeFormatPartTypes) =>
+ Number(parts.find((p) => p.type === type)?.value);
+ const wallClockAsUtc = Date.UTC(
+ part("year"),
+ part("month") - 1,
+ part("day"),
+ part("hour"),
+ part("minute"),
);
- return endOfMonth;
+ // The wall clock above has no seconds, so drop them from `now` too.
+ const offsetMinutes = (wallClockAsUtc - now + (now % 60_000)) / 60_000;
+
+ const utcMinutes =
+ scheduleTime.hour * 60 + scheduleTime.minute - offsetMinutes;
+ const dayShift = Math.floor(utcMinutes / 1440);
+ const minutesOfDay = utcMinutes - dayShift * 1440;
+ return {
+ weekday:
+ scheduleTime.weekday === undefined
+ ? undefined
+ : (scheduleTime.weekday + dayShift + 7) % 7,
+ hour: Math.floor(minutesOfDay / 60),
+ minute: minutesOfDay % 60,
+ dayShift,
+ };
}
/**
@@ -173,34 +242,50 @@ function endOfMonthWithTime(source: Date, monthOffset = 0): Date {
* when runs are delayed (e.g., a weekly config due Monday that fires on
* Wednesday will still schedule the next check for the following Monday).
*
- * Otherwise a random hour (04–09 UTC) and minute are chosen.
+ * Otherwise the first check lands on `chosenTime` when the user chose one, or
+ * on a random hour (04–09 UTC) and minute. The random default spreads load
+ * across the scheduler's ticks.
*/
export function computeNextCheckAt(
interval: ScheduledRankTrackingInterval,
previousNextCheckAt?: string | null,
+ chosenTime?: RankCheckScheduleTime,
): string {
const now = Date.now();
+ const scheduleTime = chosenTime && scheduleTimeInUtc(chosenTime, now);
if (interval === "monthly") {
if (previousNextCheckAt) {
const anchor = new Date(previousNextCheckAt);
- let monthOffset = 1;
- let nextDate = endOfMonthWithTime(anchor, monthOffset);
+ const year = anchor.getUTCFullYear();
+ const dayShift = monthlyAnchorDayShift(anchor);
+ const time = {
+ hour: anchor.getUTCHours(),
+ minute: anchor.getUTCMinutes(),
+ };
+ // A +1 anchor sits on the 1st, which belongs to the month before it.
+ let month = anchor.getUTCMonth() + (dayShift === 1 ? 0 : 1);
+ let nextDate = monthEndWithTime(year, month, dayShift, time);
while (nextDate.getTime() <= now) {
- monthOffset += 1;
- nextDate = endOfMonthWithTime(anchor, monthOffset);
+ month += 1;
+ nextDate = monthEndWithTime(year, month, dayShift, time);
}
return nextDate.toISOString();
}
- const hour = 4 + Math.floor(Math.random() * 6);
- const minute = Math.floor(Math.random() * 60);
- const nextDate = endOfMonthWithTime(new Date());
- nextDate.setUTCHours(hour, minute, 0, 0);
- if (nextDate.getTime() <= now) {
- const followingMonth = endOfMonthWithTime(nextDate, 1);
- followingMonth.setUTCHours(hour, minute, 0, 0);
- return followingMonth.toISOString();
+ const time = {
+ hour: scheduleTime?.hour ?? 4 + Math.floor(Math.random() * 6),
+ minute: scheduleTime?.minute ?? Math.floor(Math.random() * 60),
+ };
+ const dayShift = scheduleTime?.dayShift ?? 0;
+ const today = new Date(now);
+ const year = today.getUTCFullYear();
+ // Start a month back: a +1 shift puts last month's run early in this one.
+ let month = today.getUTCMonth() - 1;
+ let nextDate = monthEndWithTime(year, month, dayShift, time);
+ while (nextDate.getTime() <= now) {
+ month += 1;
+ nextDate = monthEndWithTime(year, month, dayShift, time);
}
return nextDate.toISOString();
}
@@ -214,6 +299,23 @@ export function computeNextCheckAt(
return new Date(anchor + steps * intervalMs).toISOString();
}
+ if (scheduleTime) {
+ // Next occurrence of the chosen time, so a pick later today runs today.
+ const nextDate = new Date(now);
+ nextDate.setUTCHours(scheduleTime.hour, scheduleTime.minute, 0, 0);
+ const weekday = interval === "weekly" ? scheduleTime.weekday : undefined;
+ if (weekday !== undefined) {
+ const daysUntilWeekday = (weekday - nextDate.getUTCDay() + 7) % 7;
+ nextDate.setUTCDate(nextDate.getUTCDate() + daysUntilWeekday);
+ }
+ if (nextDate.getTime() <= now) {
+ nextDate.setUTCDate(
+ nextDate.getUTCDate() + (weekday === undefined ? 1 : 7),
+ );
+ }
+ return nextDate.toISOString();
+ }
+
const nextDate = new Date();
nextDate.setUTCDate(nextDate.getUTCDate() + daysAhead);
const hour = 4 + Math.floor(Math.random() * 6);
diff --git a/src/types/schemas/rank-tracking.ts b/src/types/schemas/rank-tracking.ts
index f8ed5e9b..e1ac49cd 100644
--- a/src/types/schemas/rank-tracking.ts
+++ b/src/types/schemas/rank-tracking.ts
@@ -58,6 +58,40 @@ const languageCodeField = z
.max(10)
.refine(isSupportedLanguageCode, "Unsupported language code");
+function isTimeZone(timeZone: string): boolean {
+ try {
+ Intl.DateTimeFormat("en-US", { timeZone });
+ return true;
+ } catch {
+ return false;
+ }
+}
+
+// A user-chosen run time for scheduled checks, in their own timezone. It only
+// picks where the rank_tracking_configs.next_check_at anchor starts; the
+// anchor is UTC and advances in fixed steps, so the timezone is not stored.
+export const scheduleTimeSchema = z.object({
+ weekday: z
+ .number()
+ .int()
+ .min(0)
+ .max(6)
+ .optional()
+ .describe(
+ "Day of week, 0 = Sunday. Required for weekly schedules, ignored by the others.",
+ ),
+ hour: z.number().int().min(0).max(23).describe("Hour, 0-23."),
+ minute: z.number().int().min(0).max(59).describe("Minute, 0-59."),
+ timeZone: z
+ .string()
+ .refine(isTimeZone, "Unknown IANA timezone")
+ .optional()
+ .describe(
+ 'IANA timezone the weekday, hour, and minute are in, e.g. "America/New_York". Defaults to UTC.',
+ ),
+});
+export type RankCheckScheduleTime = z.infer<typeof scheduleTimeSchema>;
+
export const getConfigsSchema = z.object({
projectId: z.string().uuid(),
});
@@ -71,6 +105,7 @@ export const createConfigSchema = z.object({
devices: devicesEnum.optional(),
serpDepth: z.number().int().min(10).max(100).multipleOf(10),
scheduleInterval: scheduleEnum.optional(),
+ scheduleTime: scheduleTimeSchema.optional(),
});
export const updateConfigSchema = z.object({
@@ -83,6 +118,7 @@ export const updateConfigSchema = z.object({
devices: devicesEnum.optional(),
serpDepth: z.number().int().min(10).max(100).multipleOf(10).optional(),
scheduleInterval: scheduleEnum.optional(),
+ scheduleTime: scheduleTimeSchema.optional(),
isActive: z.boolean().optional(),
});