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: add backup export with ownership-scoped payload assembly and download route
Khuram Niaz2de8a70771f8
diff --git a/__tests__/backupExport.spec.ts b/__tests__/backupExport.spec.tsnew file mode 100644index 0000000..7dc34f6--- /dev/null+++ b/__tests__/backupExport.spec.ts@@ -0,0 +1,128 @@+import db from "@/lib/db";+import { collectBackupData } from "@/lib/backup/export";+import { MODEL_SPECS, INSERT_ORDER } from "@/lib/backup/ordering";++vi.mock("@/lib/db", () => {+ const delegate = () => ({ findMany: vi.fn().mockResolvedValue([]) });+ const mock: Record<string, unknown> = {+ // $transaction receives an array of already-resolved promises here because+ // the mocked delegates return plain promises.+ $transaction: vi.fn((ops: Promise<unknown>[]) => Promise.all(ops)),+ user: { findUnique: vi.fn().mockResolvedValue({ defaultResumeId: null }) },+ jobStatus: { findMany: vi.fn().mockResolvedValue([]) },+ };+ for (const key of [+ "company", "jobTitle", "location", "jobSource", "tag", "activityType",+ "profile", "file", "resume", "contactInfo", "summary", "resumeSection",+ "workExperience", "education", "licenseOrCertification", "otherSection",+ "skill", "coverLetter", "automation", "job", "note", "interview",+ "contact", "task", "activity", "question", "automationRun", "userSettings",+ ]) {+ mock[key] = delegate();+ }+ return { default: mock };+});++const mockDb = db as unknown as Record<string, { findMany: ReturnType<typeof vi.fn> }>;++describe("collectBackupData", () => {+ it("scopes every read to the user with the model's ownership chain", async () => {+ await collectBackupData("user-1");+ for (const model of INSERT_ORDER) {+ const spec = MODEL_SPECS[model];+ const call = mockDb[spec.delegate].findMany.mock.calls[0][0];+ expect(call.where, `${model} was not scoped`).toEqual(+ spec.scope("user-1"),+ );+ }+ });++ it("replaces Job.statusId with the status value and drops userId", async () => {+ mockDb.job.findMany.mockResolvedValueOnce([+ {+ id: "j1",+ userId: "user-1",+ statusId: "status-row-1",+ Status: { value: "applied" },+ description: "d",+ jobType: "full-time",+ workplaceType: null,+ jobUrl: null,+ createdAt: new Date("2026-01-01"),+ applied: true,+ appliedDate: null,+ dueDate: null,+ jobTitleId: "t1",+ companyId: "c1",+ jobSourceId: null,+ salaryRange: null,+ locationId: null,+ resumeId: null,+ coverLetterId: null,+ automationId: null,+ matchScore: null,+ matchData: null,+ discoveryStatus: null,+ discoveredAt: null,+ createdVia: null,+ descriptionCompleteness: null,+ tags: [{ id: "tag-1" }],+ },+ ]);++ const data = await collectBackupData("user-1");++ expect(data.Job[0].statusValue).toBe("applied");+ expect(data.Job[0]).not.toHaveProperty("statusId");+ expect(data.Job[0]).not.toHaveProperty("userId");+ expect(data.Job[0]).not.toHaveProperty("Status");+ expect(data.Job[0]).not.toHaveProperty("tags");+ });++ it("lifts job and question tag links into the join-table groups", async () => {+ mockDb.job.findMany.mockResolvedValueOnce([+ {+ id: "j1", userId: "u", statusId: "s", Status: { value: "new" },+ description: "d", jobType: "full-time", workplaceType: null, jobUrl: null,+ createdAt: new Date(), applied: false, appliedDate: null, dueDate: null,+ jobTitleId: "t1", companyId: "c1", jobSourceId: null, salaryRange: null,+ locationId: null, resumeId: null, coverLetterId: null, automationId: null,+ matchScore: null, matchData: null, discoveryStatus: null,+ discoveredAt: null, createdVia: null, descriptionCompleteness: null,+ tags: [{ id: "tag-1" }, { id: "tag-2" }],+ },+ ]);+ mockDb.question.findMany.mockResolvedValueOnce([+ {+ id: "q1", createdBy: "u", question: "why?", answer: null,+ createdAt: new Date(), updatedAt: new Date(), createdVia: null,+ tags: [{ id: "tag-2" }],+ },+ ]);++ const data = await collectBackupData("user-1");++ expect(data._JobToTag).toEqual([+ { jobId: "j1", tagId: "tag-1" },+ { jobId: "j1", tagId: "tag-2" },+ ]);+ expect(data._QuestionToTag).toEqual([{ questionId: "q1", tagId: "tag-2" }]);+ expect(data.Question[0]).not.toHaveProperty("tags");+ });++ it("carries the referenced job statuses as label/value pairs", async () => {+ (db as unknown as { jobStatus: { findMany: ReturnType<typeof vi.fn> } })+ .jobStatus.findMany.mockResolvedValueOnce([+ { label: "Applied", value: "applied" },+ ]);+ const data = await collectBackupData("user-1");+ expect(data.jobStatuses).toEqual([{ label: "Applied", value: "applied" }]);+ });++ it("carries defaultResumeId in its own group", async () => {+ (db as unknown as { user: { findUnique: ReturnType<typeof vi.fn> } })+ .user.findUnique.mockResolvedValueOnce({ defaultResumeId: "r1" });+ const data = await collectBackupData("user-1");+ expect(data.user).toEqual({ defaultResumeId: "r1" });+ });+});diff --git a/src/app/api/backup/export/route.ts b/src/app/api/backup/export/route.tsnew file mode 100644index 0000000..dc77f28--- /dev/null+++ b/src/app/api/backup/export/route.ts@@ -0,0 +1,30 @@+import { auth } from "@/auth";+import { NextResponse } from "next/server";+import { buildBackupZip } from "@/lib/backup/export";++// A route handler rather than a server action: server actions cannot return a+// binary stream. Covered by the /api/* middleware matcher; auth() here is+// defense in depth.+export async function GET() {+ const session = await auth();+ if (!session?.user?.id) {+ return NextResponse.json({ error: "Not authenticated" }, { status: 401 });+ }++ try {+ const { buffer, fileName } = await buildBackupZip(+ session.user.id,+ session.user.email ?? "",+ );+ return new NextResponse(new Uint8Array(buffer), {+ headers: {+ "Content-Type": "application/zip",+ "Content-Disposition": `attachment; filename="${fileName}"`,+ "Content-Length": String(buffer.length),+ },+ });+ } catch (error) {+ console.error("[Backup] Export failed:", error);+ return NextResponse.json({ error: "Export failed" }, { status: 500 });+ }+}diff --git a/src/lib/backup/export.ts b/src/lib/backup/export.tsnew file mode 100644index 0000000..954a2b7--- /dev/null+++ b/src/lib/backup/export.ts@@ -0,0 +1,126 @@+import fs from "fs/promises";+import path from "path";+import JSZip from "jszip";+import db from "@/lib/db";+import { INSERT_ORDER, MODEL_SPECS, type BackupModel } from "./ordering";+import { BackupDataSchema, type BackupData } from "./schema";+import { buildManifest } from "./manifest";++type Row = Record<string, unknown>;++// Job and Question need their tag ids, which are not columns; everything else+// reads as-is. Prisma's implicit m2m tables are not models, so this include is+// the only way the join rows reach the file at all.+const TAG_INCLUDE: Partial<Record<BackupModel, Record<string, unknown>>> = {+ Job: { Status: { select: { value: true } }, tags: { select: { id: true } } },+ Question: { tags: { select: { id: true } } },+};++function stripOwnership(model: BackupModel, row: Row): Row {+ const owner = MODEL_SPECS[model].owner;+ if (!owner) return row;+ const { [owner]: _dropped, ...rest } = row;+ return rest;+}++export async function collectBackupData(userId: string): Promise<BackupData> {+ // Array form: a read-only batch that sees one snapshot without the 5s+ // interactive-transaction timeout. See the spec's Snapshot consistency note.+ const reads = INSERT_ORDER.map((model) => {+ const spec = MODEL_SPECS[model];+ const delegate = (db as unknown as Record<string, { findMany: (a: unknown) => Promise<Row[]> }>)[+ spec.delegate+ ];+ const include = TAG_INCLUDE[model];+ return delegate.findMany(+ include ? { where: spec.scope(userId), include } : { where: spec.scope(userId) },+ );+ });++ // These two ride inside the same batch, not alongside it. defaultResumeId is+ // exactly the field likely to move mid-export, and a backup naming a resume+ // the file does not contain is the dangling reference the snapshot exists to+ // prevent.+ const batch = [+ ...reads,+ db.user.findUnique({+ where: { id: userId },+ select: { defaultResumeId: true },+ }),+ db.jobStatus.findMany({+ where: { jobs: { some: { userId } } },+ select: { label: true, value: true },+ }),+ ];++ const batchResults = (await db.$transaction(batch as never)) as unknown as unknown[];+ const results = batchResults.slice(0, INSERT_ORDER.length) as Row[][];+ const userRow = batchResults[INSERT_ORDER.length] as { defaultResumeId: string | null } | null;+ const statuses = batchResults[INSERT_ORDER.length + 1] as { label: string; value: string }[];++ const raw: Record<string, unknown> = {};+ const jobToTag: { jobId: string; tagId: string }[] = [];+ const questionToTag: { questionId: string; tagId: string }[] = [];++ INSERT_ORDER.forEach((model, index) => {+ raw[model] = results[index].map((row) => {+ const clean = stripOwnership(model, row);++ if (model === "Job") {+ const { statusId, Status, tags, ...rest } = clean as Row & {+ Status: { value: string };+ tags: { id: string }[];+ };+ for (const tag of tags ?? []) jobToTag.push({ jobId: rest.id as string, tagId: tag.id });+ return { ...rest, statusValue: Status.value };+ }++ if (model === "Question") {+ const { tags, ...rest } = clean as Row & { tags: { id: string }[] };+ for (const tag of tags ?? []) {+ questionToTag.push({ questionId: rest.id as string, tagId: tag.id });+ }+ return rest;+ }++ return clean;+ });+ });++ raw._JobToTag = jobToTag;+ raw._QuestionToTag = questionToTag;+ raw.jobStatuses = statuses;+ raw.user = { defaultResumeId: userRow?.defaultResumeId ?? null };++ return BackupDataSchema.parse(raw);+}++export async function buildBackupZip(+ userId: string,+ sourceEmail: string,+): Promise<{ buffer: Buffer; fileName: string }> {+ const data = await collectBackupData(userId);++ // File bytes are read outside the read transaction. A row committed inside+ // the snapshot whose bytes land later is covered by the fileMissing marker.+ const zip = new JSZip();+ for (const file of data.File) {+ try {+ const bytes = await fs.readFile(file.filePath);+ zip.file(`files/${file.id}/${path.basename(file.filePath)}`, bytes);+ } catch {+ file.fileMissing = true;+ }+ }++ const manifest = buildManifest(data, sourceEmail);+ zip.file("manifest.json", JSON.stringify(manifest, null, 2));+ zip.file("data.json", JSON.stringify(data));++ const buffer = await zip.generateAsync({+ type: "nodebuffer",+ compression: "DEFLATE",+ });+ const stamp = new Date().toISOString().slice(0, 10);+ return { buffer, fileName: `jobsync-backup-${stamp}.zip` };+}diff --git a/src/lib/backup/index.ts b/src/lib/backup/index.tsnew file mode 100644index 0000000..03bb68c--- /dev/null+++ b/src/lib/backup/index.ts@@ -0,0 +1,4 @@+export { BackupError, buildManifest, countRows, openBackupZip, readManifest } from "./manifest";+export { buildBackupZip, collectBackupData } from "./export";+export { BACKUP_FORMAT_VERSION, BackupDataSchema, ManifestSchema } from "./schema";+export type { BackupData, BackupManifest } from "./schema";