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
feat(stages): add the stage model types, form schema and the shared ordering/invariant helpers
Khuram Niaze633e5324796
diff --git a/__tests__/jobStageShared.spec.ts b/__tests__/jobStageShared.spec.tsnew file mode 100644index 0000000..3a2b28d--- /dev/null+++ b/__tests__/jobStageShared.spec.ts@@ -0,0 +1,89 @@+import { sortStages } from "@/lib/jobs/sortStages";+import { jobFieldsForStage } from "@/actions/jobStage/shared";++const at = (iso: string) => new Date(iso);++describe("sortStages", () => {+ // SQLite sorts NULL first on ASC and Prisma's nulls:"last" is unsupported+ // there, so ordering lives here and must not migrate into the query.+ it("orders by occurredAt ascending with undated stages last", () => {+ const stages = [+ { id: "c", occurredAt: null, createdAt: at("2026-01-01T00:00:00Z") },+ { id: "b", occurredAt: at("2026-09-10T00:00:00Z"), createdAt: at("2026-01-01T00:00:00Z") },+ { id: "a", occurredAt: at("2026-09-01T00:00:00Z"), createdAt: at("2026-01-01T00:00:00Z") },+ ];+ expect(sortStages(stages).map((s) => s.id)).toEqual(["a", "b", "c"]);+ });++ it("breaks ties on createdAt", () => {+ const same = at("2026-09-10T00:00:00Z");+ const stages = [+ { id: "second", occurredAt: same, createdAt: at("2026-02-01T00:00:00Z") },+ { id: "first", occurredAt: same, createdAt: at("2026-01-01T00:00:00Z") },+ ];+ expect(sortStages(stages).map((s) => s.id)).toEqual(["first", "second"]);+ });++ it("orders several undated stages by createdAt", () => {+ const stages = [+ { id: "later", occurredAt: null, createdAt: at("2026-03-01T00:00:00Z") },+ { id: "earlier", occurredAt: null, createdAt: at("2026-01-01T00:00:00Z") },+ ];+ expect(sortStages(stages).map((s) => s.id)).toEqual(["earlier", "later"]);+ });++ it("slots a backdated stage into the middle rather than rejecting it", () => {+ const stages = [+ { id: "new", occurredAt: at("2026-09-01T00:00:00Z"), createdAt: at("2026-09-01T00:00:00Z") },+ { id: "onsite", occurredAt: at("2026-09-24T00:00:00Z"), createdAt: at("2026-09-02T00:00:00Z") },+ { id: "backdated", occurredAt: at("2026-09-10T00:00:00Z"), createdAt: at("2026-09-30T00:00:00Z") },+ ];+ expect(sortStages(stages).map((s) => s.id)).toEqual(["new", "backdated", "onsite"]);+ });++ it("does not mutate its input", () => {+ const stages = [+ { id: "b", occurredAt: at("2026-09-10T00:00:00Z"), createdAt: at("2026-01-01T00:00:00Z") },+ { id: "a", occurredAt: at("2026-09-01T00:00:00Z"), createdAt: at("2026-01-01T00:00:00Z") },+ ];+ sortStages(stages);+ expect(stages.map((s) => s.id)).toEqual(["b", "a"]);+ });+});++describe("jobFieldsForStage", () => {+ it("writes only the status for a non-applied, non-interview stage", () => {+ expect(jobFieldsForStage("rejected", "s-rej", null, null)).toEqual({+ statusId: "s-rej",+ });+ });++ it("marks an interview stage as applied without touching appliedDate", () => {+ expect(jobFieldsForStage("interview", "s-int", null, null)).toEqual({+ statusId: "s-int",+ applied: true,+ });+ });++ it("sets appliedDate from the stage's own date when it has one", () => {+ const occurred = at("2026-09-03T00:00:00Z");+ expect(jobFieldsForStage("applied", "s-app", occurred, null)).toEqual({+ statusId: "s-app",+ applied: true,+ appliedDate: occurred,+ });+ });++ it("falls back to now for an undated applied stage", () => {+ const before = Date.now();+ const data = jobFieldsForStage("applied", "s-app", null, null) as any;+ expect(data.appliedDate.getTime()).toBeGreaterThanOrEqual(before);+ });++ it("never overwrites an appliedDate already on the job", () => {+ const existing = at("2026-08-01T00:00:00Z");+ expect(+ jobFieldsForStage("applied", "s-app", at("2026-09-03T00:00:00Z"), existing),+ ).toEqual({ statusId: "s-app", applied: true });+ });+});diff --git a/src/actions/jobStage/shared.ts b/src/actions/jobStage/shared.tsnew file mode 100644index 0000000..2ec951c--- /dev/null+++ b/src/actions/jobStage/shared.ts@@ -0,0 +1,168 @@+import prisma from "@/lib/db";++export { sortStages } from "@/lib/jobs/sortStages";++// Not a "use server" module: queries.ts, mutations.ts, interviewers.ts and+// prep.ts all use these, and exporting them from any of those would make each+// one a callable server-action endpoint.++export const STAGE_DETAIL_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, tags: true } },+ },+ orderBy: { createdAt: "asc" as const },+ },+};++// The applied/appliedDate rules updateJobStatus has always used, lifted out so+// every stage write path keeps the dashboard and CSV export in agreement.+export function jobFieldsForStage(+ statusValue: string,+ statusId: string,+ occurredAt: Date | null,+ existingAppliedDate: Date | null,+): Record<string, unknown> {+ const data: Record<string, unknown> = { statusId };+ if (statusValue === "applied" || statusValue === "interview") {+ data.applied = true;+ }+ if (statusValue === "applied" && !existingAppliedDate) {+ data.appliedDate = occurredAt ?? new Date();+ }+ return data;+}++export type StageOwnerRow = {+ id: string;+ jobId: string;+ occurredAt: Date | null;+ isCurrent: boolean;+ StageType: { id: string; label: string; statusId: string; Status: { value: string } };+};++// JobStage has no ownership column, so the chain is the only check there is.+export async function assertStageOwned(+ stageId: string,+ userId: string,+): Promise<StageOwnerRow> {+ const stage = await prisma.jobStage.findFirst({+ where: { id: stageId, Job: { userId } },+ select: {+ id: true,+ jobId: true,+ occurredAt: true,+ isCurrent: true,+ StageType: {+ select: {+ id: true,+ label: true,+ statusId: true,+ Status: { select: { value: true } },+ },+ },+ },+ });+ if (!stage) throw new Error("Stage not found");+ return stage;+}++// The gate is on stage KIND and never on stage timing: preparing for an+// interview a week out is the primary case (spec decision 10).+export function assertInterviewStage(stage: StageOwnerRow): void {+ if (stage.StageType.Status.value !== "interview") {+ throw new Error(+ `"${stage.StageType.label}" is not an interview stage, so it has no interviewers or prep list.`,+ );+ }+}++type StageTx = {+ jobStage: {+ updateMany: (args: any) => Promise<any>;+ findFirst: (args: any) => Promise<any>;+ };+ job: {+ findFirst: (args: any) => Promise<any>;+ update: (args: any) => Promise<any>;+ };+};++// Clear the old current row BEFORE setting the new one: the partial unique+// index JobStage_jobId_current_key refuses two live rows for one job.+//+// userId is in every where clause (D8). Callers check ownership first, but a+// helper that finds a row by id alone stays safe only until someone adds a+// caller that forgets, and CLAUDE.md's rule has no "the caller checked"+// exemption. updateMany, not update: a relation filter is not allowed in a+// single-row update's where.+export async function promoteStage(+ tx: StageTx,+ jobId: string,+ stageId: string,+ userId: string,+): Promise<void> {+ await tx.jobStage.updateMany({+ where: { jobId, isCurrent: true, NOT: { id: stageId }, Job: { userId } },+ data: { isCurrent: false },+ });+ const promoted = await tx.jobStage.updateMany({+ where: { id: stageId, Job: { userId } },+ data: { isCurrent: true },+ });+ if (promoted.count === 0) throw new Error("Stage not found");+}++// The derived-status invariant: Job.statusId always equals the current+// stage's type's statusId whenever a current stage exists.+export async function syncJobFromCurrentStage(+ tx: StageTx,+ jobId: string,+ stageId: string,+ userId: string,+): Promise<void> {+ const stage = await tx.jobStage.findFirst({+ where: { id: stageId, Job: { userId } },+ select: {+ occurredAt: true,+ StageType: {+ select: { statusId: true, Status: { select: { value: true } } },+ },+ },+ });+ if (!stage) throw new Error("Stage not found");++ const job = await tx.job.findFirst({+ where: { id: jobId, userId },+ select: { appliedDate: true },+ });++ // Prisma allows a non-unique field beside id in an update's where —+ // deleteJobById and updateJob both already do this.+ await tx.job.update({+ where: { id: jobId, userId },+ data: jobFieldsForStage(+ stage.StageType.Status.value,+ stage.StageType.statusId,+ stage.occurredAt,+ job?.appliedDate ?? null,+ ),+ });+}diff --git a/src/lib/jobs/sortStages.ts b/src/lib/jobs/sortStages.tsnew file mode 100644index 0000000..9c0444d--- /dev/null+++ b/src/lib/jobs/sortStages.ts@@ -0,0 +1,19 @@+// SQLite sorts NULL first on ASC and Prisma's nulls:"last" is unsupported on+// that connector, so undated-stages-last cannot live in the query. Both the+// server actions and the Timeline tab sort through this one comparator: the+// job-details page loads stages with no orderBy at all.+export function sortStages<+ T extends { occurredAt: Date | null; createdAt: Date },+>(stages: T[]): T[] {+ return [...stages].sort((a, b) => {+ if (a.occurredAt && b.occurredAt) {+ const diff = a.occurredAt.getTime() - b.occurredAt.getTime();+ if (diff !== 0) return diff;+ } else if (a.occurredAt) {+ return -1;+ } else if (b.occurredAt) {+ return 1;+ }+ return a.createdAt.getTime() - b.createdAt.getTime();+ });+}diff --git a/src/models/jobStage.model.ts b/src/models/jobStage.model.tsnew file mode 100644index 0000000..78019d2--- /dev/null+++ b/src/models/jobStage.model.ts@@ -0,0 +1,82 @@+import { z } from "zod";+import type { Tag } from "./job.model";+import type { ContactSummary } from "./contact.model";+import { STAGE_OUTCOMES } from "@/lib/constants";++export interface JobStageTypeRef {+ id: string;+ label: string;+ value: string;+ statusId: string;+ sortOrder: number;+ Status?: { id: string; label: string; value: string };+ _count?: { stages: number };+}++export interface JobStageInterviewerLink {+ id: string;+ stageId: string;+ contactId: string;+ Contact: ContactSummary;+}++export interface JobStagePrepQuestionLink {+ id: string;+ stageId: string;+ questionId: string;+ asked: boolean;+ askedAt: Date | null;+ Question: { id: string; question: string; tags: Tag[] };+}++export interface JobStage {+ id: string;+ jobId: string;+ stageTypeId: string;+ occurredAt: Date | null;+ isCurrent: boolean;+ outcome: string | null;+ notes: string | null;+ durationMins: number | null;+ format: string | null;+ location: string | null;+ createdAt: Date;+ updatedAt: Date;+ StageType: JobStageTypeRef;+ interviewers: JobStageInterviewerLink[];+ prepQuestions: JobStagePrepQuestionLink[];+}++const outcomeValues = STAGE_OUTCOMES.map((o) => o.value) as unknown as [+ string,+ ...string[],+];++// Either an existing type id or a custom name, never neither. A custom name+// also needs its parent status, which the dialog asks for in the same pass.+export const AddJobStageFormSchema = z+ .object({+ id: z.string().optional(),+ jobId: z.string().min(1),+ stageTypeId: z.string().optional(),+ customLabel: z.string().max(80).optional(),+ customStatusId: z.string().optional(),+ date: z.date().nullable().optional(),+ time: z.string().optional(),+ notes: z.string().max(2000).optional(),+ outcome: z.enum(outcomeValues).nullable().optional(),+ durationMins: z.number().int().positive().max(1440).nullable().optional(),+ format: z.string().max(60).optional(),+ location: z.string().max(200).optional(),+ setAsCurrent: z.boolean().default(true),+ })+ .refine((data) => !!data.stageTypeId || !!data.customLabel?.trim(), {+ message: "Pick a stage or enter a custom stage name.",+ path: ["stageTypeId"],+ })+ .refine(+ (data) => !data.customLabel?.trim() || !!data.customStatusId,+ { message: "Pick the status this custom stage means.", path: ["customStatusId"] },+ );++export type AddJobStageValues = z.infer<typeof AddJobStageFormSchema>;