Skip to content

Job application tracker and AI-powered job search assistant. Helps job seekers manage their search journey with AI resume review, job matching, task logging, and application analytics, all while keeping your data private.

fix: automation schedule conflict

Khuram Niazb35c2a3bb3b4
diff --git a/__tests__/automationSchedule.actions.spec.ts b/__tests__/automationSchedule.actions.spec.ts
new file mode 100644
index 0000000..273598f
--- /dev/null
+++ b/__tests__/automationSchedule.actions.spec.ts
@@ -0,0 +1,138 @@
+import { createAutomation, updateAutomation } from "@/actions/automation.actions";
+import { getCurrentUser } from "@/utils/user.utils";
+import { PrismaClient } from "@prisma/client";
+
+const prisma = new PrismaClient();
+
+vi.mock("@prisma/client", () => {
+ const mPrismaClient = {
+ automation: {
+ count: vi.fn(),
+ findFirst: vi.fn(),
+ create: vi.fn(),
+ update: vi.fn(),
+ },
+ resume: {
+ findFirst: vi.fn(),
+ },
+ };
+ return {
+ PrismaClient: vi.fn(function () {
+ return mPrismaClient;
+ }),
+ };
+});
+
+vi.mock("@/utils/user.utils", () => ({
+ getCurrentUser: vi.fn(),
+}));
+
+// syncSchedulerState boots node-cron and hits the DB; stub it out.
+vi.mock("@/lib/scheduler", () => ({
+ syncSchedulerState: vi.fn(),
+}));
+
+const RESUME_ID = "11111111-1111-4111-8111-111111111111";
+
+function baseInput(overrides: Record<string, unknown> = {}) {
+ return {
+ name: "Test Automation",
+ jobBoard: "jsearch",
+ keywords: "engineer",
+ location: "New York",
+ resumeId: RESUME_ID,
+ matchThreshold: 80,
+ scheduleHour: 8,
+ ...overrides,
+ } as any;
+}
+
+describe("createAutomation schedule-hour uniqueness", () => {
+ const mockUser = { id: "user-1" };
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+ (getCurrentUser as any).mockResolvedValue(mockUser);
+ (prisma.automation.count as any).mockResolvedValue(1);
+ (prisma.resume.findFirst as any).mockResolvedValue({ id: RESUME_ID });
+ (prisma.automation.create as any).mockResolvedValue({ id: "auto-1" });
+ });
+
+ it("rejects a create when another automation already uses the same hour", async () => {
+ (prisma.automation.findFirst as any).mockResolvedValue({ id: "other" });
+
+ const result = await createAutomation(baseInput());
+
+ expect(result.success).toBe(false);
+ expect(result.message).toMatch(/08:00/);
+ expect(prisma.automation.create).not.toHaveBeenCalled();
+ });
+
+ it("scopes the clash check to the current user and chosen hour", async () => {
+ (prisma.automation.findFirst as any).mockResolvedValue(null);
+
+ await createAutomation(baseInput({ scheduleHour: 14 }));
+
+ const where = (prisma.automation.findFirst as any).mock.calls[0][0].where;
+ expect(where).toMatchObject({ userId: "user-1", scheduleHour: 14 });
+ });
+
+ it("creates the automation when the hour is free", async () => {
+ (prisma.automation.findFirst as any).mockResolvedValue(null);
+
+ const result = await createAutomation(baseInput());
+
+ expect(result.success).toBe(true);
+ expect(prisma.automation.create).toHaveBeenCalled();
+ });
+});
+
+describe("updateAutomation schedule-hour uniqueness", () => {
+ const mockUser = { id: "user-1" };
+ const AUTO_ID = "auto-1";
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+ (getCurrentUser as any).mockResolvedValue(mockUser);
+ (prisma.resume.findFirst as any).mockResolvedValue({ id: RESUME_ID });
+ (prisma.automation.update as any).mockResolvedValue({ id: AUTO_ID });
+ });
+
+ it("rejects when another automation already uses the target hour", async () => {
+ (prisma.automation.findFirst as any)
+ .mockResolvedValueOnce({ id: AUTO_ID, scheduleHour: 8 }) // ownership lookup
+ .mockResolvedValueOnce({ id: "sibling" }); // clash check
+
+ const result = await updateAutomation(AUTO_ID, baseInput({ scheduleHour: 9 }));
+
+ expect(result.success).toBe(false);
+ expect(result.message).toMatch(/09:00/);
+ expect(prisma.automation.update).not.toHaveBeenCalled();
+ });
+
+ it("excludes the automation being edited from the clash query", async () => {
+ (prisma.automation.findFirst as any)
+ .mockResolvedValueOnce({ id: AUTO_ID, scheduleHour: 8 })
+ .mockResolvedValueOnce(null);
+
+ await updateAutomation(AUTO_ID, baseInput({ scheduleHour: 8 }));
+
+ const clashWhere = (prisma.automation.findFirst as any).mock.calls[1][0].where;
+ expect(clashWhere).toMatchObject({
+ userId: "user-1",
+ scheduleHour: 8,
+ id: { not: AUTO_ID },
+ });
+ });
+
+ it("updates when no other automation uses the hour", async () => {
+ (prisma.automation.findFirst as any)
+ .mockResolvedValueOnce({ id: AUTO_ID, scheduleHour: 8 })
+ .mockResolvedValueOnce(null);
+
+ const result = await updateAutomation(AUTO_ID, baseInput({ scheduleHour: 10 }));
+
+ expect(result.success).toBe(true);
+ expect(prisma.automation.update).toHaveBeenCalled();
+ });
+});
diff --git a/e2e/automations.spec.ts b/e2e/automations.spec.ts
index 9847fd0..dc34798 100644
--- a/e2e/automations.spec.ts
+++ b/e2e/automations.spec.ts
@@ -58,14 +58,27 @@ async function createResumeForMatching(
});
}
+// Opens the Schedule step's time picker and selects the given hour. Matches the
+// option by an anchored label so it works whether or not the hour carries the
+// "In use" suffix.
+async function selectScheduleHour(page: Page, dialog: Locator, hour: number) {
+ const label = `${String(hour).padStart(2, "0")}:00`;
+ await dialog.getByRole("combobox").click();
+ await page.getByRole("option", { name: new RegExp(`^${label}`) }).click();
+}
+
// Walks the 6-step wizard for a Greenhouse automation. Company selection uses
// the seeded companies.json typeahead (a local filter, no network), picking the
-// first browse result so it stays robust to seed changes.
+// first browse result so it stays robust to seed changes. The schedule hour
+// defaults to the worker's parallelIndex: every spec shares the admin user and
+// only one automation may run per hour, so a worker-unique hour keeps parallel
+// specs from colliding on that rule.
async function createGreenhouseAutomation(
page: Page,
name: string,
resumeTitle: string,
cleanup: CleanupRegistry,
+ hour: number = test.info().parallelIndex,
) {
await page.goto("/dashboard/automations");
await page.getByRole("button", { name: "Create Automation" }).click();
@@ -91,8 +104,11 @@ async function createGreenhouseAutomation(
await page.getByRole("option", { name: resumeTitle }).click();
await dialog.getByRole("button", { name: "Next" }).click();
- // Step 4: Matching (default threshold) and Step 5: Schedule (default hour)
+ // Step 4: Matching (default threshold)
await dialog.getByRole("button", { name: "Next" }).click();
+
+ // Step 5: Schedule — worker-unique hour (see fn doc)
+ await selectScheduleHour(page, dialog, hour);
await dialog.getByRole("button", { name: "Next" }).click();
// Step 6: Review -> submit
@@ -271,4 +287,71 @@ test.describe("Automations", () => {
}
await submitWizard(page, dialog, /Update Automation/, editedName);
});
+
+ test("should mark in-use hours, block a duplicate schedule, and allow a free hour", async ({
+ page,
+ cleanup,
+ }) => {
+ const resumeTitle = uniqueName("Automation Resume");
+ const nameA = uniqueName("Schedule A");
+ const nameB = uniqueName("Schedule B");
+ // parallelIndex is 0..3 locally / 0 in CI. Base and +12 stay disjoint from
+ // every other worker's base hour, so nothing else claims these two hours.
+ const idx = test.info().parallelIndex;
+ const hourA = idx;
+ const hourB = idx + 12;
+ const labelA = `${String(hourA).padStart(2, "0")}:00`;
+
+ await createResumeForMatching(page, resumeTitle, cleanup);
+ await createGreenhouseAutomation(page, nameA, resumeTitle, cleanup, hourA);
+
+ // Open a second Create wizard and walk to the Schedule step.
+ cleanup.automation(nameB);
+ await page.getByRole("button", { name: "Create Automation" }).click();
+ const dialog = page.getByRole("dialog");
+ await dialog
+ .getByPlaceholder("e.g., Full Stack Jobs Calgary")
+ .fill(nameB);
+ await dialog.getByRole("button", { name: "Next" }).click();
+
+ await dialog.getByRole("button", { name: /Search companies/ }).click();
+ await expect(page.getByRole("option").first()).toBeVisible();
+ await page.getByRole("option").first().click();
+ await page.keyboard.press("Escape");
+ await dialog.getByRole("button", { name: "Next" }).click();
+
+ await dialog.getByRole("combobox").click();
+ await page.getByRole("option", { name: resumeTitle }).click();
+ await dialog.getByRole("button", { name: "Next" }).click();
+
+ // Matching -> Schedule
+ await dialog.getByRole("button", { name: "Next" }).click();
+
+ // hourA (taken by automation A) is flagged "In use" in the picker.
+ await dialog.getByRole("combobox").click();
+ await expect(
+ page
+ .getByRole("option")
+ .filter({ hasText: labelA })
+ .filter({ hasText: "In use" }),
+ ).toBeVisible();
+
+ // Picking the taken hour and clicking Next surfaces the clash error and
+ // keeps the wizard on the Schedule step.
+ await page.getByRole("option").filter({ hasText: labelA }).click();
+ await dialog.getByRole("button", { name: "Next" }).click();
+ await expect(
+ dialog.getByText(/Another automation already runs at/),
+ ).toBeVisible();
+ await expect(dialog.getByText("Step 5 of 6")).toBeVisible();
+
+ // Switching to a free hour clears the error and lets the wizard proceed.
+ await selectScheduleHour(page, dialog, hourB);
+ await expect(
+ dialog.getByText(/Another automation already runs at/),
+ ).not.toBeVisible();
+ await dialog.getByRole("button", { name: "Next" }).click();
+ await expect(dialog.getByText("Step 6 of 6")).toBeVisible();
+ await submitWizard(page, dialog, /Create Automation/, nameB);
+ });
});
diff --git a/src/actions/automation.actions.ts b/src/actions/automation.actions.ts
index 916510c..1db7167 100644
--- a/src/actions/automation.actions.ts
+++ b/src/actions/automation.actions.ts
@@ -145,6 +145,19 @@ export async function createAutomation(input: CreateAutomationInput): Promise<{
};
}
+ const scheduleClash = await db.automation.findFirst({
+ where: { userId: user.id, scheduleHour: validated.scheduleHour },
+ select: { id: true },
+ });
+ if (scheduleClash) {
+ return {
+ success: false,
+ message: `Another automation already runs at ${validated.scheduleHour
+ .toString()
+ .padStart(2, "0")}:00. Please choose a different time.`,
+ };
+ }
+
const resume = await db.resume.findFirst({
where: {
id: validated.resumeId,
@@ -247,6 +260,22 @@ export async function updateAutomation(
}
if (validated.scheduleHour !== undefined) {
+ const scheduleClash = await db.automation.findFirst({
+ where: {
+ userId: user.id,
+ scheduleHour: validated.scheduleHour,
+ id: { not: id },
+ },
+ select: { id: true },
+ });
+ if (scheduleClash) {
+ return {
+ success: false,
+ message: `Another automation already runs at ${validated.scheduleHour
+ .toString()
+ .padStart(2, "0")}:00. Please choose a different time.`,
+ };
+ }
updateData.nextRunAt = calculateNextRunAt(validated.scheduleHour);
}
diff --git a/src/app/dashboard/automations/[id]/page.tsx b/src/app/dashboard/automations/[id]/page.tsx
index 22cb8d8..5f67b71 100644
--- a/src/app/dashboard/automations/[id]/page.tsx
+++ b/src/app/dashboard/automations/[id]/page.tsx
@@ -44,6 +44,7 @@ import {
} from "lucide-react";
import {
getAutomationById,
+ getAutomationsList,
getDiscoveredJobs,
getAutomationRuns,
pauseAutomation,
@@ -136,6 +137,9 @@ export default function AutomationDetailPage() {
const [detailOpen, setDetailOpen] = useState(false);
const [runKey, setRunKey] = useState(0);
const [resumes, setResumes] = useState<{ id: string; title: string }[]>([]);
+ const [allAutomations, setAllAutomations] = useState<AutomationWithResume[]>(
+ [],
+ );
const [wizardOpen, setWizardOpen] = useState(false);
const [deleteConfirmOpen, setDeleteConfirmOpen] = useState(false);
const [isDeleting, setIsDeleting] = useState(false);
@@ -238,6 +242,9 @@ export default function AutomationDetailPage() {
}
},
);
+ getAutomationsList().then((result) => {
+ if (result?.data) setAllAutomations(result.data);
+ });
}, []);
// Subscribe to the live log/status stream at the page level so it persists
@@ -934,6 +941,7 @@ export default function AutomationDetailPage() {
open={wizardOpen}
onOpenChange={setWizardOpen}
resumes={resumes}
+ automations={allAutomations}
onSuccess={() => loadData()}
editAutomation={automation}
/>
diff --git a/src/components/automations/AutomationContainer.tsx b/src/components/automations/AutomationContainer.tsx
index 5497d7f..215e038 100644
--- a/src/components/automations/AutomationContainer.tsx
+++ b/src/components/automations/AutomationContainer.tsx
@@ -96,6 +96,7 @@ export function AutomationContainer({ resumes }: AutomationContainerProps) {
open={wizardOpen}
onOpenChange={handleWizardClose}
resumes={resumes}
+ automations={automations}
onSuccess={handleSuccess}
editAutomation={editAutomation}
/>
diff --git a/src/components/automations/AutomationWizard.tsx b/src/components/automations/AutomationWizard.tsx
index c8c3598..ddcfa09 100644
--- a/src/components/automations/AutomationWizard.tsx
+++ b/src/components/automations/AutomationWizard.tsx
@@ -79,6 +79,7 @@ interface AutomationWizardProps {
open: boolean;
onOpenChange: (open: boolean) => void;
resumes: Resume[];
+ automations: AutomationWithResume[];
onSuccess: () => void;
editAutomation?: AutomationWithResume | null;
}
@@ -101,6 +102,7 @@ export function AutomationWizard({
open,
onOpenChange,
resumes,
+ automations,
onSuccess,
editAutomation,
}: AutomationWizardProps) {
@@ -205,7 +207,25 @@ export function AutomationWizard({
}
};
+ // Hours already claimed by the user's other automations. Only one automation
+ // may run per hourly slot, so the schedule step rejects a taken hour.
+ const takenHours = new Set(
+ automations
+ .filter((a) => a.id !== editAutomation?.id)
+ .map((a) => a.scheduleHour),
+ );
+
const nextStep = () => {
+ if (step === 4 && takenHours.has(formValues.scheduleHour)) {
+ form.setError("scheduleHour", {
+ message: `Another automation already runs at ${(
+ formValues.scheduleHour ?? 8
+ )
+ .toString()
+ .padStart(2, "0")}:00. Please choose a different time.`,
+ });
+ return;
+ }
if (step < STEPS.length - 1) {
setStep(step + 1);
}
@@ -422,7 +442,10 @@ export function AutomationWizard({
<FormItem>
<FormLabel>Daily Run Time</FormLabel>
<Select
- onValueChange={(val) => field.onChange(parseInt(val))}
+ onValueChange={(val) => {
+ field.onChange(parseInt(val));
+ form.clearErrors("scheduleHour");
+ }}
value={field.value.toString()}
>
<FormControl>
@@ -437,6 +460,11 @@ export function AutomationWizard({
value={hour.value.toString()}
>
{hour.label}
+ {takenHours.has(hour.value) && (
+ <span className="ml-2 text-xs text-muted-foreground">
+ In use
+ </span>
+ )}
</SelectItem>
))}
</SelectContent>