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.
TypeScript ai-agentai-resume-analyzerapplication-trackerapplication-tracking-systematscareerjob-applicationjob-automationjob-huntingjob-searchjob-seeker-toolsjob-trackerjob-trackingjobsearchjobseekersmcpollamaresumeresume-reviewself-hosted
fix(timeline): hold the derived-status invariant, make the job and interviewer writes atomic, keep dialog state across reloads, and scope the DatePicker and ComboBox changes
Khuram Niaz1a57ac356020
diff --git a/__tests__/createJobStage.spec.ts b/__tests__/createJobStage.spec.tsindex af4f9ce..ab33582 100644--- a/__tests__/createJobStage.spec.ts+++ b/__tests__/createJobStage.spec.ts@@ -49,7 +49,15 @@ describe("createJobRecord", () => {userId: "u1",} as any);- expect(db.jobStage.create).toHaveBeenCalledTimes(1);- expect(db.jobStage.create.mock.calls[0][0].data.isCurrent).toBe(true);+ // Nested in the job.create, never a second statement: a job must not be+ // able to commit without its first stage.+ expect(db.jobStage.create).not.toHaveBeenCalled();+ expect(db.job.create.mock.calls[0][0].data.stages).toEqual({+ create: {+ stageTypeId: "t-draft",+ occurredAt: expect.any(Date),+ isCurrent: true,+ },+ });});});diff --git a/__tests__/job.actions.spec.ts b/__tests__/job.actions.spec.tsindex b1472ed..0f8576f 100644--- a/__tests__/job.actions.spec.ts+++ b/__tests__/job.actions.spec.ts@@ -1066,6 +1066,13 @@ describe("jobActions", () => {jobUrl: jobData.jobUrl,applied: jobData.applied,resumeId: jobData.resume,+ stages: {+ create: {+ stageTypeId: "stage-type-id",+ occurredAt: expect.any(Date),+ isCurrent: true,+ },+ },},});});@@ -1095,6 +1102,13 @@ describe("jobActions", () => {userId: mockUser.id,applied: jobData.applied,resumeId: jobData.resume,+ stages: {+ create: {+ stageTypeId: "stage-type-id",+ occurredAt: expect.any(Date),+ isCurrent: true,+ },+ },},});expect(result).toEqual({ data: jobData, success: true });diff --git a/__tests__/jobStageInterviewers.spec.ts b/__tests__/jobStageInterviewers.spec.tsindex ea86ea0..0d53694 100644--- a/__tests__/jobStageInterviewers.spec.ts+++ b/__tests__/jobStageInterviewers.spec.ts@@ -6,8 +6,8 @@ import { getCurrentUser } from "@/utils/user.utils";import prisma from "@/lib/db";import { resolveContactRole } from "@/lib/jobs/resolve";-vi.mock("@/lib/db", () => ({- default: {+vi.mock("@/lib/db", () => {+ const mock: Record<string, unknown> = {jobStage: { findFirst: vi.fn() },contact: { count: vi.fn() },jobStageInterviewer: {@@ -16,8 +16,10 @@ vi.mock("@/lib/db", () => ({deleteMany: vi.fn(),},jobContact: { findFirst: vi.fn(), create: vi.fn() },- },-}));+ $transaction: vi.fn(async (fn: (tx: unknown) => Promise<unknown>) => fn(mock)),+ };+ return { default: mock };+});vi.mock("@/utils/user.utils", () => ({ getCurrentUser: vi.fn() }));vi.mock("@/lib/jobs/resolve", () => ({ resolveContactRole: vi.fn() }));diff --git a/__tests__/jobStageType.actions.spec.ts b/__tests__/jobStageType.actions.spec.tsindex 97e9564..7b6da7e 100644--- a/__tests__/jobStageType.actions.spec.ts+++ b/__tests__/jobStageType.actions.spec.ts@@ -2,6 +2,7 @@ import {getAllJobStageTypes,getJobStageTypeList,createJobStageType,+ updateJobStageType,deleteJobStageTypeById,} from "@/actions/jobStageType.actions";import { getCurrentUser } from "@/utils/user.utils";@@ -12,12 +13,14 @@ vi.mock("@/lib/db", () => ({default: {jobStageType: {findMany: vi.fn(),+ findFirst: vi.fn(),count: vi.fn(),update: vi.fn(),delete: vi.fn(),},jobStage: { count: vi.fn() },- jobStatus: { count: vi.fn() },+ jobStatus: { findUnique: vi.fn(), findMany: vi.fn() },+ job: { findMany: vi.fn(), update: vi.fn() },},}));vi.mock("@/utils/user.utils", () => ({ getCurrentUser: vi.fn() }));@@ -30,7 +33,18 @@ beforeEach(() => {vi.clearAllMocks();(getCurrentUser as any).mockResolvedValue(user);db.jobStage.count.mockResolvedValue(0);- db.jobStatus.count.mockResolvedValue(1);+ db.jobStatus.findUnique.mockResolvedValue({+ id: "s-int",+ label: "Interview",+ value: "interview",+ });+ db.jobStatus.findMany.mockResolvedValue([+ { label: "Draft" },+ { label: "Applied" },+ { label: "Interview" },+ ]);+ db.jobStageType.findFirst.mockResolvedValue(null);+ db.job.findMany.mockResolvedValue([]);});describe("getAllJobStageTypes", () => {@@ -62,7 +76,7 @@ describe("getJobStageTypeList", () => {describe("createJobStageType", () => {it("refuses a status that does not exist", async () => {- db.jobStatus.count.mockResolvedValue(0);+ db.jobStatus.findUnique.mockResolvedValue(null);const res = await createJobStageType("Panel", "nope");@@ -78,6 +92,68 @@ describe("createJobStageType", () => {expect(res.success).toBe(true);expect(resolveJobStageType).toHaveBeenCalledWith(" Panel ", user.id, "s-int");});++ // The resolver returns an existing type by name and ignores the requested+ // status, so without this the call reports success having done nothing.+ it("refuses a name already taken under a different status", async () => {+ db.jobStageType.findFirst.mockResolvedValue({+ label: "Applied",+ Status: { label: "Applied" },+ });++ const res = await createJobStageType("Applied", "s-int");++ expect(res.success).toBe(false);+ expect(res.message).toContain("Applied");+ expect(resolveJobStageType).not.toHaveBeenCalled();+ });+});++describe("updateJobStageType", () => {+ // The status menus resolve through these by name, so a retarget would make+ // every later status change write a stage contradicting Job.statusId.+ it("refuses to move a status-named type under another status", async () => {+ db.jobStageType.findFirst.mockResolvedValue({+ value: "interview",+ statusId: "s-app",+ });++ const res = await updateJobStageType("t1", "Interview", "s-int", 3);++ expect(res.success).toBe(false);+ expect(db.jobStageType.update).not.toHaveBeenCalled();+ });++ it("re-derives the jobs sitting on a custom type it moves", async () => {+ db.jobStageType.findFirst.mockResolvedValue({+ value: "take-home",+ statusId: "s-app",+ });+ db.job.findMany.mockResolvedValue([+ {+ id: "j1",+ appliedDate: null,+ stages: [{ occurredAt: new Date("2026-09-01T00:00:00Z") }],+ },+ ]);++ const res = await updateJobStageType("t1", "Take-home", "s-int", 3);++ expect(res.success).toBe(true);+ expect(db.job.update.mock.calls[0][0].data.statusId).toBe("s-int");+ });++ it("leaves jobs alone when only the label and order change", async () => {+ db.jobStageType.findFirst.mockResolvedValue({+ value: "take-home",+ statusId: "s-int",+ });++ const res = await updateJobStageType("t1", "Take-home Task", "s-int", 4);++ expect(res.success).toBe(true);+ expect(db.job.findMany).not.toHaveBeenCalled();+ });});describe("deleteJobStageTypeById", () => {diff --git a/__tests__/persistDiscoveredJobStage.spec.ts b/__tests__/persistDiscoveredJobStage.spec.tsindex 6555914..6b022e7 100644--- a/__tests__/persistDiscoveredJobStage.spec.ts+++ b/__tests__/persistDiscoveredJobStage.spec.ts@@ -40,21 +40,18 @@ describe("persistDiscoveredJob", () => {expect(res.saved).toBe(true);expect(resolveStageTypeForStatusId).toHaveBeenCalledWith("s-new", "u1");- expect(mockDb.jobStage.create.mock.calls[0][0].data).toEqual({- jobId: "j1",- stageTypeId: "t-new",- occurredAt: createdAt,- isCurrent: true,+ expect(mockDb.job.create.mock.calls[0][0].data.stages).toEqual({+ create: { stageTypeId: "t-new", occurredAt: createdAt, isCurrent: true },});});- // A concurrent run won the dedup race, so there is no job to stage.- it("writes no stage when the unique index refuses the job", async () => {+ // A concurrent run won the dedup race. The stage rides on the same+ // statement, so it goes down with the job rather than orphaning.+ it("saves nothing when the unique index refuses the job", async () => {mockDb.job.create.mockRejectedValue({ code: "P2002" });const res = await persistDiscoveredJob(automation, job, 50, {}, []);expect(res.saved).toBe(false);- expect(mockDb.jobStage.create).not.toHaveBeenCalled();});});diff --git a/src/actions/job/queries.ts b/src/actions/job/queries.tsindex 304deb6..f45892c 100644--- a/src/actions/job/queries.ts+++ b/src/actions/job/queries.ts@@ -5,6 +5,7 @@ import { JOB_TYPES } from "@/models/job.model";import { APP_CONSTANTS } from "@/lib/constants";import { requireUser } from "../shared";import { hideUnanalyzedScore } from "./shared";+import { STAGE_DETAIL_INCLUDE } from "../jobStage/shared";const JOB_LIST_SELECT = {id: true,@@ -71,37 +72,7 @@ const JOB_DETAILS_INCLUDE = {},orderBy: { createdAt: "asc" as const },},- // Duplicates STAGE_DETAIL_INCLUDE rather than importing it: this is a- // "use server" module and that const lives in another action directory.- stages: {- include: {- StageType: { include: { Status: true } },- interviewers: {- include: {- Contact: {- select: {- id: true,- name: true,- title: true,- email: true,- phone: true,- linkedinUrl: true,- Company: { select: { id: true, label: true } },- },- },- },- orderBy: { createdAt: "asc" as const },- },- prepQuestions: {- include: {- Question: {- select: { id: true, question: true, answer: true, tags: true },- },- },- orderBy: { createdAt: "asc" as const },- },- },- },+ stages: { include: STAGE_DETAIL_INCLUDE },};type JobsListFilters = {diff --git a/src/actions/job/shared.ts b/src/actions/job/shared.tsindex 3b1b950..b6deb80 100644--- a/src/actions/job/shared.ts+++ b/src/actions/job/shared.ts@@ -41,7 +41,18 @@ export async function appendStatusStage(StageType: { select: { statusId: true, Status: { select: { value: true } } } },},});- if (current?.StageType.statusId === statusId) return;+ // With no current stage the job's own status is the one it holds. A+ // stage-less job (a pre-feature backup restore) must not collect a stage+ // dated today every time Edit Job is saved with the status untouched.+ const held = current+ ? current.StageType.statusId+ : (+ await tx.job.findFirst({+ where: { id: jobId, userId },+ select: { statusId: true },+ })+ )?.statusId;+ if (held === statusId) return;const stage = await tx.jobStage.create({data: { jobId, stageTypeId, occurredAt: new Date(), isCurrent: false },diff --git a/src/actions/jobStage/interviewers.ts b/src/actions/jobStage/interviewers.tsindex 51d1e09..734571d 100644--- a/src/actions/jobStage/interviewers.ts+++ b/src/actions/jobStage/interviewers.ts@@ -37,23 +37,29 @@ export const linkStageInterviewer = async (if (contact === 0) throw new Error("Contact not found");assertInterviewStage(stage);- const data = await prisma.jobStageInterviewer.create({- data: { stageId, contactId },- include: INTERVIEWER_INCLUDE,- });-// The job's Contacts tab stays the single roster of everyone involved.- // Resolve-or-create: the seeded role is renameable and deletable.+ // Resolve-or-create: the seeded role is renameable and deletable. Resolved+ // outside the transaction, which it must never run inside (D4).const role = await resolveContactRole(INTERVIEWER_ROLE_LABEL, user.id);- const existing = await prisma.jobContact.findFirst({- where: { jobId: stage.jobId, contactId, roleId: role.id },- select: { id: true },- });- if (!existing) {- await prisma.jobContact.create({- data: { jobId: stage.jobId, contactId, roleId: role.id },++ // Both writes together: a stage link without its roster entry leaves the+ // Contacts tab disagreeing with the stage's interviewers for good.+ const data = await prisma.$transaction(async (tx: any) => {+ const link = await tx.jobStageInterviewer.create({+ data: { stageId, contactId },+ include: INTERVIEWER_INCLUDE,});- }+ const existing = await tx.jobContact.findFirst({+ where: { jobId: stage.jobId, contactId, roleId: role.id },+ select: { id: true },+ });+ if (!existing) {+ await tx.jobContact.create({+ data: { jobId: stage.jobId, contactId, roleId: role.id },+ });+ }+ return link;+ });return { success: true, data };} catch (error: any) {diff --git a/src/actions/jobStage/mutations.ts b/src/actions/jobStage/mutations.tsindex 63c3aad..99943b7 100644--- a/src/actions/jobStage/mutations.ts+++ b/src/actions/jobStage/mutations.ts@@ -105,6 +105,30 @@ export const updateJobStage = async (const existing = await assertStageOwned(values.id, user.id);const stageType = await resolveStageType(parsed, user.id);+ // Interviewers and prep questions only have a UI on an interview stage, so+ // retyping away from one would strand them: invisible, unremovable, and+ // still enough to block deleting the question.+ if (+ existing.StageType.Status.value === "interview" &&+ !stageType.isInterview+ ) {+ const [interviewers, prepQuestions] = await Promise.all([+ prisma.jobStageInterviewer.count({ where: { stageId: values.id } }),+ prisma.jobStagePrepQuestion.count({ where: { stageId: values.id } }),+ ]);+ if (interviewers + prepQuestions > 0) {+ const parts = [+ interviewers > 0 &&+ `${interviewers} interviewer${interviewers === 1 ? "" : "s"}`,+ prepQuestions > 0 &&+ `${prepQuestions} prep question${prepQuestions === 1 ? "" : "s"}`,+ ].filter(Boolean);+ throw new Error(+ `"${existing.StageType.label}" still has ${parts.join(" and ")}. Remove them before changing it to a non-interview stage.`,+ );+ }+ }+const updated = await prisma.$transaction(async (tx: any) => {await tx.jobStage.update({where: { id: values.id },diff --git a/src/actions/jobStageType.actions.ts b/src/actions/jobStageType.actions.tsindex 80e2cea..7718be6 100644--- a/src/actions/jobStageType.actions.ts+++ b/src/actions/jobStageType.actions.ts@@ -4,6 +4,8 @@ import { handleError } from "@/lib/utils";import { requireUser } from "./shared";import { APP_CONSTANTS } from "@/lib/constants";import { resolveJobStageType } from "@/lib/jobs/resolve";+import { canonicalizeEntityValue } from "@/lib/jobs/canonicalize";+import { jobFieldsForStage } from "./jobStage/shared";export const getAllJobStageTypes = async (): Promise<any | undefined> => {try {@@ -50,8 +52,21 @@ export const getJobStageTypeList = async (};const assertStatusExists = async (statusId: string) => {- const status = await prisma.jobStatus.count({ where: { id: statusId } });- if (status === 0) throw new Error("Job status not found");+ const status = await prisma.jobStatus.findUnique({+ where: { id: statusId },+ select: { id: true, label: true, value: true },+ });+ if (!status) throw new Error("Job status not found");+ return status;+};++// The types named after a job status are the lookup table the status menus+// resolve through (resolveStageTypeForStatusId keys on the status LABEL), so+// moving one under a different status would make every later status change+// write a stage whose status contradicts Job.statusId.+const isStatusNamedType = async (value: string): Promise<boolean> => {+ const statuses = await prisma.jobStatus.findMany({ select: { label: true } });+ return statuses.some((s) => canonicalizeEntityValue(s.label) === value);};export const createJobStageType = async (@@ -61,6 +76,23 @@ export const createJobStageType = async (try {const user = await requireUser();await assertStatusExists(statusId);++ // resolveJobStageType returns an existing type by name and ignores the+ // requested status, which would report success having done nothing.+ const clash = await prisma.jobStageType.findFirst({+ where: {+ value: canonicalizeEntityValue(label.trim()),+ createdBy: user.id,+ NOT: { statusId },+ },+ select: { label: true, Status: { select: { label: true } } },+ });+ if (clash) {+ throw new Error(+ `"${clash.label}" already exists under the ${clash.Status.label} status.`,+ );+ }+const data = await resolveJobStageType(label, user.id, statusId);return { success: true, data };} catch (error) {@@ -76,13 +108,58 @@ export const updateJobStageType = async (): Promise<any | undefined> => {try {const user = await requireUser();- await assertStatusExists(statusId);+ const status = await assertStatusExists(statusId);++ const existing = await prisma.jobStageType.findFirst({+ where: { id, createdBy: user.id },+ select: { value: true, statusId: true },+ });+ if (!existing) throw new Error("Stage type not found");++ const statusChanged = existing.statusId !== statusId;+ if (statusChanged && (await isStatusNamedType(existing.value))) {+ throw new Error(+ `"${label.trim()}" is the stage the status menus resolve to, so its status cannot be changed.`,+ );+ }+// value is left alone on rename: it is the reverse-lookup key that a// status resolves through, and rewriting it would orphan the mapping.await prisma.jobStageType.update({where: { id, createdBy: user.id },data: { label: label.trim(), statusId, sortOrder },});++ // A job's status is derived from its current stage's type, so retargeting+ // a type in use has to re-derive every job now sitting on it.+ if (statusChanged) {+ const affected = await prisma.job.findMany({+ where: {+ userId: user.id,+ stages: { some: { stageTypeId: id, isCurrent: true } },+ },+ select: {+ id: true,+ appliedDate: true,+ stages: {+ where: { stageTypeId: id, isCurrent: true },+ select: { occurredAt: true },+ },+ },+ });+ for (const job of affected) {+ await prisma.job.update({+ where: { id: job.id, userId: user.id },+ data: jobFieldsForStage(+ status.value,+ statusId,+ job.stages[0]?.occurredAt ?? null,+ job.appliedDate,+ ),+ });+ }+ }+return { success: true };} catch (error) {return handleError(error, "Failed to update stage type.");diff --git a/src/components/ComboBox.tsx b/src/components/ComboBox.tsxindex 5094a91..7406d5f 100644--- a/src/components/ComboBox.tsx+++ b/src/components/ComboBox.tsx@@ -29,7 +29,6 @@ import { toastError } from "@/lib/toast";import { createActivityType } from "@/actions/activity.actions";import { createJobSource } from "@/actions/job.actions";import { createContactRole } from "@/actions/contactRole.actions";-import { createTag } from "@/actions/tag.actions";interface ComboboxProps {options: any[];@@ -123,14 +122,6 @@ export function Combobox({}response = roleRes.data;break;- case "questionCategory":- const tagRes = await createTag(label);- if (!tagRes.success) {- toastError(tagRes.message);- return;- }- response = tagRes.data;- break;case "activityType":response = await createActivityType(label);break;diff --git a/src/components/DatePicker.tsx b/src/components/DatePicker.tsxindex f14e026..27c4a43 100644--- a/src/components/DatePicker.tsx+++ b/src/components/DatePicker.tsx@@ -33,6 +33,9 @@ interface DatePickerProps {// Opt out of the default fixed trigger width when the field sits in a gridfullWidth?: boolean;disableFuture?: boolean;+ // Years past today the dropdown reaches. Opt-in: the default cap is the+ // current month, so a picker for a past-only field stays that way.+ futureYears?: number;}export function DatePicker({@@ -42,6 +45,7 @@ export function DatePicker({captionLayout,fullWidth,disableFuture,+ futureYears,}: DatePickerProps) {const [isPopoverOpen, setIsPopoverOpen] = useState<boolean>(false);@@ -88,9 +92,9 @@ export function DatePicker({startMonth={captionLayout ? new Date(1970, 0) : undefined}endMonth={captionLayout- ? disableFuture+ ? disableFuture || !futureYears? new Date()- : addYears(new Date(), 10)+ : addYears(new Date(), futureYears): undefined}selected={field.value}diff --git a/src/components/myjobs/job-details/timeline/AddStageDialog.tsx b/src/components/myjobs/job-details/timeline/AddStageDialog.tsxindex a14f762..05d35cf 100644--- a/src/components/myjobs/job-details/timeline/AddStageDialog.tsx+++ b/src/components/myjobs/job-details/timeline/AddStageDialog.tsx@@ -215,6 +215,7 @@ export function AddStageDialog({presets={false}isEnabledcaptionLayout+ futureYears={10}fullWidth/><FormMessage />diff --git a/src/components/myjobs/job-details/timeline/LinkInterviewersDialog.tsx b/src/components/myjobs/job-details/timeline/LinkInterviewersDialog.tsxindex 504fc73..35f73bc 100644--- a/src/components/myjobs/job-details/timeline/LinkInterviewersDialog.tsx+++ b/src/components/myjobs/job-details/timeline/LinkInterviewersDialog.tsx@@ -75,13 +75,20 @@ export function LinkInterviewersDialog({})();}, [open]);+ // Transient state only, keyed on stage?.id: a link reloads the stages and+ // hands back a new object, which would wipe the search and the draft.useEffect(() => {if (!open) return;setSearch("");setLinkedCount(0);setNewContact(EMPTY_NEW);+ }, [open, stage?.id]);++ // Re-seeded on every reload, so a link that failed server-side corrects+ // itself rather than reading as linked until the page reloads.+ useEffect(() => {setLinkedIds((stage?.interviewers ?? []).map((iv) => iv.contactId));- }, [open, stage]);+ }, [stage]);if (!stage) return null;diff --git a/src/components/myjobs/job-details/timeline/StagePrepList.tsx b/src/components/myjobs/job-details/timeline/StagePrepList.tsxindex d3f617e..406dfc2 100644--- a/src/components/myjobs/job-details/timeline/StagePrepList.tsx+++ b/src/components/myjobs/job-details/timeline/StagePrepList.tsx@@ -49,6 +49,11 @@ export function StagePrepList({success: next ? "Marked as asked" : "Marked as not asked",onSuccess: onChanged,});+ // Rolled back only on failure: on success the reload lands on the same+ // value, so dropping it early would flash the old state.+ if (!res?.success) {+ setPending(({ [linkId]: _rolledBack, ...rest }) => rest);+ }});};diff --git a/src/lib/jobs/createJobRecord.ts b/src/lib/jobs/createJobRecord.tsindex 7d2f29c..76f38dd 100644--- a/src/lib/jobs/createJobRecord.ts+++ b/src/lib/jobs/createJobRecord.ts@@ -5,9 +5,20 @@ type StageClient = {jobStage: { create: (args: any) => Promise<any> };};-// There is no single choke point for job creation: the scraper and the mock-// generator write jobs directly. Each calls this so a job added after the-// backfill is never left without the timeline a backfilled job has.+// The nested payload that writes the job and its first stage as one statement,+// so a job can never commit without its timeline. The stage type is resolved+// BEFORE the create on purpose: a nested create is an implicit transaction,+// and the resolver writes through the base client (D4).+export async function firstStageCreate(+ statusId: string,+ userId: string,+ occurredAt: Date,+) {+ const stageTypeId = await resolveStageTypeForStatusId(statusId, userId);+ return { create: { stageTypeId, occurredAt, isCurrent: true } };+}++// The separate-statement form, still used by the dev-only mock generator.export async function createFirstStage(client: StageClient,jobId: string,@@ -44,13 +55,13 @@ export async function createJobRecord(fields: {}) {const { tagIds = [], ...rest } = fields;const createdAt = new Date();- const job = await prisma.job.create({+ const stages = await firstStageCreate(fields.statusId, fields.userId, createdAt);+ return await prisma.job.create({data: {...rest,createdAt,...(tagIds.length > 0 ? { tags: { connect: tagIds.map((id) => ({ id })) } } : {}),+ stages,},});- await createFirstStage(prisma, job.id, fields.statusId, fields.userId, createdAt);- return job;}diff --git a/src/lib/scraper/automation-run/persist.ts b/src/lib/scraper/automation-run/persist.tsindex 7fa93f6..5124e25 100644--- a/src/lib/scraper/automation-run/persist.ts+++ b/src/lib/scraper/automation-run/persist.ts@@ -3,7 +3,7 @@ import { APP_CONSTANTS } from "@/lib/constants";import type { Automation, ScrapedJobData } from "@/models/automation.model";import type { JobDetails } from "../types";import { mapScrapedJobToJobRecord } from "../mapper";-import { createFirstStage } from "@/lib/jobs/createJobRecord";+import { firstStageCreate } from "@/lib/jobs/createJobRecord";import { normalizeJobUrl } from "../utils";import type { SkillTerm } from "./skillTags";@@ -52,15 +52,14 @@ export async function persistDiscoveredJob(skillTerms,});+ const stages = await firstStageCreate(+ jobRecord.statusId,+ automation.userId,+ jobRecord.createdAt,+ );+try {- const created = await db.job.create({ data: jobRecord });- await createFirstStage(- db,- created.id,- jobRecord.statusId,- automation.userId,- jobRecord.createdAt,- );+ await db.job.create({ data: { ...jobRecord, stages } });return { saved: true, tagsApplied: jobRecord.tags?.connect.length ?? 0 };} catch (err: any) {if (err?.code === "P2002") return { saved: false, tagsApplied: 0 };diff --git a/wiki/timeline.md b/wiki/timeline.mdindex 608ff8d..e459e54 100644--- a/wiki/timeline.md+++ b/wiki/timeline.md@@ -27,7 +27,7 @@ Pick a **stage** from the list — *New*, *Draft*, *Applied*, *Interview*, *1st**Date** and **Time** start on today and the current time, since a stage you add is usually one that just happened; click the selected day again to clear the date if you don't know it yet. **Notes** is free text. If the stage's parent status is *Interview*, three more fields appear: **Format**, **Duration** and **Location** — use Location for a meeting link as happily as for a street address. **Set as current stage** is ticked by default; leave it ticked when you are recording where the job is now, and untick it when you are backfilling something that already happened.-Editing a stage later opens the same dialog with one extra field, **Outcome**: *Scheduled*, *Completed*, *Passed*, *Failed*, *No-show* or *Cancelled*. Outcome reads back on the stage's **Overview** tab, above the notes box, and location, format and duration join it there on an interview stage. Switching a stage away from *Interview* clears those three, since nothing shows them on a non-interview stage.+Editing a stage later opens the same dialog with one extra field, **Outcome**: *Scheduled*, *Completed*, *Passed*, *Failed*, *No-show* or *Cancelled*. Outcome reads back on the stage's **Overview** tab, above the notes box, and location, format and duration join it there on an interview stage. Switching a stage away from *Interview* clears those three, since nothing shows them on a non-interview stage. The switch is refused while interviewers or prep questions remain.## How do I delete a stage?@@ -47,7 +47,7 @@ Marking a job *Applied* or *Interview* this way also sets its **Applied** flag,Stages are laid out in the order **Library → Stages** gives their types, not by date, so a job you added weeks after applying to it still reads New then Applied. Dates decide the order only between stages of the same type — two interview rounds of the same kind, say.-That means a job added long after you applied can show its New stage with a later date than its Applied stage. Nothing is wrong: the New date records when the job entered JobSync, which really was after you applied.+So a job added long after you applied can show its New stage dated after its Applied stage — the New date records when it entered JobSync.## Why does a stage show a dash instead of a date?@@ -85,7 +85,7 @@ One knock-on effect: a question that is on any prep list cannot be deleted fromBecause the stage they would act on is not an interview stage. Both items are gated on the *kind* of stage, never on its timing — an interview three weeks away is still an interview stage, and you can link its panel and prep for it from the day it is scheduled.-The menu tells you which stage it is targeting and why: it reads **"Applied is not an interview stage"** when the selected stage is not one, and **"Add a stage first"** when the job has no stages at all. Both items act on the stage you have selected on the Timeline tab, falling back to the current stage — so if the job's current stage is *Applied* and you want to link an interviewer, add or select the interview stage first.+The menu tells you which stage it is targeting and why: it reads **"Applied is not an interview stage"** when the selected stage is not one, and **"Add a stage first"** when the job has no stages at all. Both items act on the stage you have selected on the Timeline tab, falling back to the current stage, so select the interview stage first.A stage counts as an interview stage when its parent status is *Interview*. That is true of the three seeded interview rounds, and of any custom stage type you created under the Interview status.@@ -93,6 +93,8 @@ A stage counts as an interview stage when its parent status is *Interview*. ThatYes — **Library → Stages** holds the full list, and the stage types there are yours. **New Stage** adds one, and the **⋮** menu on a row has **Edit** to rename it or change which status it means, plus **Move Up** and **Move Down** to reorder them — that order drives both the list the Add Stage dialog shows you and the order stages appear in on every job's timeline. A new stage type you type into the Add Stage dialog slots in after the last type of the same parent status, so it lands beside its siblings rather than at the bottom of the list. A **Stages** column tells you how many job stages currently use each type.+A stage type named after a status can be renamed and reordered but not moved under another status — that name is how a status change finds it. Your own types move freely, jobs following along.+A stage type that is in use cannot be deleted: the tab refuses and tells you how many job stages are using it. Change or remove those stages first, then delete the type.Two near-identical names stay two separate types — *On-site* and *Onsite* are different entries, because matching folds case and accents but not punctuation. If you end up with a duplicate, rename or delete one here.