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(backup): resolve stage-type status by value on import, reseed stage types from a pre-stages file and seed them in the round-trip helper
Khuram Niazb574d802df6f
diff --git a/__tests__/backupRoundTrip.spec.ts b/__tests__/backupRoundTrip.spec.tsindex be4cb18..e50ae49 100644--- a/__tests__/backupRoundTrip.spec.ts+++ b/__tests__/backupRoundTrip.spec.ts@@ -2,7 +2,7 @@import fs from "fs";import path from "path";import { PrismaClient } from "@prisma/client";-import { APP_CONSTANTS, CONTACT_ROLES } from "@/lib/constants";+import { APP_CONSTANTS, CONTACT_ROLES, JOB_STAGES } from "@/lib/constants";import { buildBackupZip } from "@/lib/backup/export";import { importBackup } from "@/lib/backup/import";import { listSnapshots, readSnapshot } from "@/lib/backup/snapshot";@@ -149,7 +149,29 @@ async function seedFullAccount() {const question = await prisma.question.create({data: { question: "Why us?", createdBy: userId, tags: { connect: { id: tag.id } } },});- expect(question.id).toBeTruthy();++ const onsiteType = await prisma.jobStageType.findFirstOrThrow({+ where: { createdBy: userId, value: "final / onsite interview" },+ });+ const stage = await prisma.jobStage.create({+ data: {+ jobId: job.id,+ stageTypeId: onsiteType.id,+ occurredAt: new Date("2026-09-24T14:00:00.000Z"),+ isCurrent: true,+ outcome: "scheduled",+ notes: "Bring laptop",+ durationMins: 90,+ format: "On-site",+ location: "Acme HQ, Bldg 3",+ },+ });+ await prisma.jobStageInterviewer.create({+ data: { stageId: stage.id, contactId: contact.id },+ });+ await prisma.jobStagePrepQuestion.create({+ data: { stageId: stage.id, questionId: question.id, asked: true, askedAt: new Date() },+ });const activityType = await prisma.activityType.create({data: { label: "Applying", value: "applying", createdBy: userId },@@ -339,15 +361,70 @@ describe("backup round trip", () => {expect(await prisma.contactRole.count({ where: { createdBy: userId } })).toBe(5);});+ it("round-trips a job's timeline, its interviewer and its prep question", async () => {+ const restored = await prisma.jobStage.findFirstOrThrow({+ where: { Job: { userId } },+ include: {+ StageType: { include: { Status: true } },+ interviewers: { include: { Contact: true } },+ prepQuestions: { include: { Question: true } },+ Job: true,+ },+ });++ expect(restored.StageType.value).toBe("final / onsite interview");+ expect(restored.StageType.Status.value).toBe("interview");+ expect(restored.isCurrent).toBe(true);+ expect(restored.durationMins).toBe(90);+ expect(restored.location).toBe("Acme HQ, Bldg 3");+ expect(restored.Job.userId).toBe(userId);+ expect(restored.interviewers[0].Contact.name).toBe("Pat Lee");+ expect(restored.prepQuestions[0].asked).toBe(true);+ expect(restored.prepQuestions[0].Question.question).toBe("Why us?");++ // Lookup, like ContactRole: the seeded types came back once, not doubled.+ expect(+ await prisma.jobStageType.count({ where: { createdBy: userId } }),+ ).toBe(14);+ });++ // D3: the file carries no JobStatus ids, so every restored type has to have+ // been re-pointed at this database's own status rows.+ it("re-points every restored stage type at a real local status", async () => {+ const types = await prisma.jobStageType.findMany({+ where: { createdBy: userId },+ include: { Status: true },+ });+ expect(types).toHaveLength(14);+ for (const type of types) {+ expect(type.Status).not.toBeNull();+ }+ const withdrawn = types.find((t) => t.value === "withdrawn")!;+ // Withdrawn is the case the export's widened jobStatuses query exists for:+ // no job holds it, so it would otherwise never reach the file.+ expect(withdrawn.Status.value).toBe("withdrawn");+ });+it("reseeds the default contact roles when restoring a pre-contacts backup", async () => {const { buffer } = await buildBackupZip(userId, "[email protected]");// Reshape into what v1.1.19 wrote: no contact groups, no counts for them.+ // The stage groups go too — that release predates stages as well, and+ // JobStageInterviewer.contactId is a required FK, so leaving it behind+ // would abort the import on a contact the file no longer carries.const JSZip = (await import("jszip")).default;const zip = await JSZip.loadAsync(buffer);const data = JSON.parse(await zip.file("data.json")!.async("string"));const manifest = JSON.parse(await zip.file("manifest.json")!.async("string"));- for (const group of ["Contact", "ContactRole", "JobContact"]) {+ for (const group of [+ "Contact",+ "ContactRole",+ "JobContact",+ "JobStageType",+ "JobStage",+ "JobStageInterviewer",+ "JobStagePrepQuestion",+ ]) {delete data[group];delete manifest.counts[group];}@@ -363,6 +440,36 @@ describe("backup round trip", () => {);}, 120_000);+ it("reseeds the default stage types when restoring a pre-stages backup", async () => {+ const { buffer } = await buildBackupZip(userId, "[email protected]");++ const JSZip = (await import("jszip")).default;+ const zip = await JSZip.loadAsync(buffer);+ const data = JSON.parse(await zip.file("data.json")!.async("string"));+ const manifest = JSON.parse(await zip.file("manifest.json")!.async("string"));+ for (const group of [+ "JobStageType",+ "JobStage",+ "JobStageInterviewer",+ "JobStagePrepQuestion",+ ]) {+ delete data[group];+ delete manifest.counts[group];+ }+ zip.file("data.json", JSON.stringify(data));+ zip.file("manifest.json", JSON.stringify(manifest));+ const legacy = await zip.generateAsync({ type: "nodebuffer" });++ await importBackup(legacy, userId, "[email protected]", true);++ const types = await prisma.jobStageType.findMany({ where: { createdBy: userId } });+ expect(types.map((t) => t.value).sort()).toEqual(+ JOB_STAGES.map((s) => s.value).sort(),+ );+ // Decision 22: restored jobs come back stageless, and stay that way.+ expect(await prisma.jobStage.count({ where: { Job: { userId } } })).toBe(0);+ }, 120_000);+it("does not demand confirmWipe on a freshly signed-up account", async () => {const freshUserId = await seedAccount(prisma, "[email protected]");const { buffer } = await buildBackupZip(userId, "[email protected]");diff --git a/__tests__/helpers/backupTestDb.ts b/__tests__/helpers/backupTestDb.tsindex 2ab6481..4838c1f 100644--- a/__tests__/helpers/backupTestDb.ts+++ b/__tests__/helpers/backupTestDb.ts@@ -4,7 +4,12 @@ import path from "path";import { execFileSync } from "child_process";import { randomUUID } from "crypto";import type { PrismaClient } from "@prisma/client";-import { CONTACT_ROLES, JOB_SOURCES, JOB_STATUSES } from "@/lib/constants";+import {+ CONTACT_ROLES,+ JOB_SOURCES,+ JOB_STAGES,+ JOB_STATUSES,+} from "@/lib/constants";export function makeTestDbUrl(): { url: string; dir: string } {const dir = fs.mkdtempSync(path.join(os.tmpdir(), "jobsync-backup-"));@@ -53,5 +58,19 @@ export async function seedAccount(})),});+ const statusRows = await prisma.jobStatus.findMany({+ select: { id: true, value: true },+ });+ const statusIdByValue = new Map(statusRows.map((s) => [s.value, s.id]));+ await prisma.jobStageType.createMany({+ data: JOB_STAGES.map((stage) => ({+ label: stage.label,+ value: stage.value,+ statusId: statusIdByValue.get(stage.status)!,+ sortOrder: stage.sortOrder,+ createdBy: user.id,+ })),+ });+return user.id;}diff --git a/src/lib/backup/import.ts b/src/lib/backup/import.tsindex 2f53db7..bafcbb9 100644--- a/src/lib/backup/import.ts+++ b/src/lib/backup/import.ts@@ -2,7 +2,7 @@ import fs from "fs/promises";import path from "path";import type JSZip from "jszip";import db from "@/lib/db";-import { APP_CONSTANTS, CONTACT_ROLES } from "@/lib/constants";+import { APP_CONSTANTS, CONTACT_ROLES, JOB_STAGES } from "@/lib/constants";import { IdMap, buildCreateData } from "./idmap";import { BackupError, openBackupZip, readManifest } from "./manifest";import {@@ -147,12 +147,32 @@ async function insertLookups(data: BackupData,idMap: IdMap,userId: string,+ statusByValue: Map<string, string>,): Promise<void> {for (const model of LOOKUP_MODELS) {const spec = MODEL_SPECS[model];for (const row of (data as unknown as Record<string, { id: string; value: string }[]>)[model]) {const newId = idMap.mint(row.id);const { id: _old, ...rest } = row;++ // The only lookup model with a foreign key. JobStatus is global and its+ // ids differ between installs, so the file carries the value (D3).+ if (model === "JobStageType") {+ const { statusValue, ...typeRest } = rest as typeof rest & { statusValue: string };+ const statusId = statusByValue.get(statusValue);+ // Refusing beats defaulting: a wrong parent status would put the+ // derived-status invariant permanently out of step on every job.+ if (!statusId) {+ throw new BackupError(+ `Stage type "${row.value}" names status "${statusValue}", which is not in the backup.`,+ );+ }+ await tx[spec.delegate].create({+ data: { ...typeRest, id: newId, statusId, createdBy: userId },+ });+ continue;+ }+await tx[spec.delegate].create({data: { ...rest, id: newId, createdBy: userId },});@@ -306,7 +326,7 @@ export async function importBackup(const tx = transaction as unknown as Tx;await wipe(tx, userId);- await insertLookups(tx, data, idMap, userId);+ await insertLookups(tx, data, idMap, userId, statusByValue);// A backup from before contacts carries no roles, and the wipe above// just deleted the seeded ones — reseed rather than leave none.@@ -320,6 +340,25 @@ export async function importBackup(});}+ // A backup from before stages carries no stage types, and the wipe+ // above just deleted the seeded ones — reseed rather than leave none,+ // or Add Stage and every status dropdown has nothing to resolve.+ if (manifest.counts.JobStageType === undefined && data.JobStageType.length === 0) {+ const stageStatuses = (await tx.jobStatus.findMany({+ select: { id: true, value: true },+ })) as unknown as { id: string; value: string }[];+ const stageStatusIds = new Map(stageStatuses.map((s) => [s.value, s.id]));+ await tx.jobStageType.createMany({+ data: JOB_STAGES.map((stage) => ({+ label: stage.label,+ value: stage.value,+ statusId: stageStatusIds.get(stage.status)!,+ sortOrder: stage.sortOrder,+ createdBy: userId,+ })),+ });+ }+for (const model of INSERT_ORDER) {if (MODEL_SPECS[model].lookup) continue;const spec = MODEL_SPECS[model];