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.

Add optional resume upload to profile

Khuram Niaz34189dd9b277
diff --git a/.gitignore b/.gitignore
index 020ffcf..111db47 100644
--- a/.gitignore
+++ b/.gitignore
@@ -44,3 +44,4 @@ dev.db-journal
/playwright-report/
/blob-report/
/playwright/.cache/
+data/files/resumes
diff --git a/prisma/migrations/20241103213832_resume_upload/migration.sql b/prisma/migrations/20241103213832_resume_upload/migration.sql
new file mode 100644
index 0000000..cfd1ece
--- /dev/null
+++ b/prisma/migrations/20241103213832_resume_upload/migration.sql
@@ -0,0 +1,56 @@
+-- CreateTable
+CREATE TABLE "File" (
+ "id" TEXT NOT NULL PRIMARY KEY,
+ "fileName" TEXT NOT NULL,
+ "filePath" TEXT NOT NULL,
+ "fileType" TEXT NOT NULL,
+ "uploadedAt" DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP
+);
+
+-- RedefineTables
+PRAGMA foreign_keys=OFF;
+CREATE TABLE "new_Resume" (
+ "id" TEXT NOT NULL PRIMARY KEY,
+ "profileId" TEXT NOT NULL,
+ "title" TEXT NOT NULL,
+ "createdAt" DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
+ "updatedAt" DATETIME NOT NULL,
+ "FileId" TEXT,
+ CONSTRAINT "Resume_profileId_fkey" FOREIGN KEY ("profileId") REFERENCES "Profile" ("id") ON DELETE RESTRICT ON UPDATE CASCADE,
+ CONSTRAINT "Resume_FileId_fkey" FOREIGN KEY ("FileId") REFERENCES "File" ("id") ON DELETE SET NULL ON UPDATE CASCADE
+);
+INSERT INTO "new_Resume" ("createdAt", "id", "profileId", "title", "updatedAt") SELECT "createdAt", "id", "profileId", "title", "updatedAt" FROM "Resume";
+DROP TABLE "Resume";
+ALTER TABLE "new_Resume" RENAME TO "Resume";
+CREATE UNIQUE INDEX "Resume_FileId_key" ON "Resume"("FileId");
+CREATE TABLE "new_Job" (
+ "id" TEXT NOT NULL PRIMARY KEY,
+ "userId" TEXT NOT NULL,
+ "jobUrl" TEXT,
+ "description" TEXT NOT NULL,
+ "jobType" TEXT NOT NULL,
+ "createdAt" DATETIME NOT NULL,
+ "applied" BOOLEAN NOT NULL DEFAULT false,
+ "appliedDate" DATETIME,
+ "dueDate" DATETIME,
+ "statusId" TEXT NOT NULL,
+ "jobTitleId" TEXT NOT NULL,
+ "companyId" TEXT NOT NULL,
+ "jobSourceId" TEXT,
+ "salaryRange" TEXT,
+ "locationId" TEXT,
+ "resumeId" TEXT,
+ CONSTRAINT "Job_userId_fkey" FOREIGN KEY ("userId") REFERENCES "User" ("id") ON DELETE RESTRICT ON UPDATE CASCADE,
+ CONSTRAINT "Job_statusId_fkey" FOREIGN KEY ("statusId") REFERENCES "JobStatus" ("id") ON DELETE RESTRICT ON UPDATE CASCADE,
+ CONSTRAINT "Job_jobTitleId_fkey" FOREIGN KEY ("jobTitleId") REFERENCES "JobTitle" ("id") ON DELETE RESTRICT ON UPDATE CASCADE,
+ CONSTRAINT "Job_companyId_fkey" FOREIGN KEY ("companyId") REFERENCES "Company" ("id") ON DELETE RESTRICT ON UPDATE CASCADE,
+ CONSTRAINT "Job_jobSourceId_fkey" FOREIGN KEY ("jobSourceId") REFERENCES "JobSource" ("id") ON DELETE SET NULL ON UPDATE CASCADE,
+ CONSTRAINT "Job_locationId_fkey" FOREIGN KEY ("locationId") REFERENCES "Location" ("id") ON DELETE SET NULL ON UPDATE CASCADE,
+ CONSTRAINT "Job_resumeId_fkey" FOREIGN KEY ("resumeId") REFERENCES "Resume" ("id") ON DELETE SET NULL ON UPDATE CASCADE
+);
+INSERT INTO "new_Job" ("applied", "appliedDate", "companyId", "createdAt", "description", "dueDate", "id", "jobSourceId", "jobTitleId", "jobType", "jobUrl", "locationId", "salaryRange", "statusId", "userId") SELECT "applied", "appliedDate", "companyId", "createdAt", "description", "dueDate", "id", "jobSourceId", "jobTitleId", "jobType", "jobUrl", "locationId", "salaryRange", "statusId", "userId" FROM "Job";
+DROP TABLE "Job";
+ALTER TABLE "new_Job" RENAME TO "Job";
+PRAGMA foreign_key_check("Resume");
+PRAGMA foreign_key_check("Job");
+PRAGMA foreign_keys=ON;
diff --git a/prisma/schema.prisma b/prisma/schema.prisma
index 77f47e7..26a2b78 100644
--- a/prisma/schema.prisma
+++ b/prisma/schema.prisma
@@ -42,6 +42,18 @@ model Resume {
ContactInfo ContactInfo?
ResumeSections ResumeSection[]
profile Profile @relation(fields: [profileId], references: [id])
+ File File? @relation(fields: [FileId], references: [id])
+ FileId String? @unique
+ Job Job[]
+}
+
+model File {
+ id String @id @default(uuid())
+ fileName String
+ filePath String
+ fileType String
+ uploadedAt DateTime @default(now())
+ Resume Resume?
}
model ResumeSection {
@@ -224,4 +236,6 @@ model Job {
Location Location? @relation(fields: [locationId], references: [id])
locationId String?
Interview Interview[]
+ Resume Resume? @relation(fields: [resumeId], references: [id])
+ resumeId String?
}
diff --git a/src/actions/profile.actions.ts b/src/actions/profile.actions.ts
index 736799a..efa8c26 100644
--- a/src/actions/profile.actions.ts
+++ b/src/actions/profile.actions.ts
@@ -165,7 +165,9 @@ export const updateContactInfo = async (
};
export const createResumeProfile = async (
- data: z.infer<typeof CreateResumeFormSchema>
+ title: string,
+ fileName: string,
+ filePath?: string
): Promise<any | undefined> => {
try {
const user = await getCurrentUser();
@@ -174,8 +176,6 @@ export const createResumeProfile = async (
throw new Error("Not authenticated");
}
- const { title } = data;
-
const profile = await prisma.profile.findFirst({
where: {
userId: user.id,
@@ -188,6 +188,9 @@ export const createResumeProfile = async (
data: {
profileId: profile!.id,
title,
+ FileId: fileName
+ ? await createFileEntry(fileName, filePath)
+ : null,
},
})
: await prisma.profile.create({
@@ -197,12 +200,14 @@ export const createResumeProfile = async (
create: [
{
title,
+ FileId: fileName
+ ? await createFileEntry(fileName, filePath)
+ : null,
},
],
},
},
});
- revalidatePath("/dashboard/profile");
return { success: true, data: res };
} catch (error) {
const msg = "Failed to create resume.";
@@ -210,6 +215,20 @@ export const createResumeProfile = async (
}
};
+const createFileEntry = async (
+ fileName: string | undefined,
+ filePath: string | undefined
+) => {
+ const newFileEntry = await prisma.file.create({
+ data: {
+ fileName: fileName!,
+ filePath: filePath!,
+ fileType: "resume",
+ },
+ });
+ return newFileEntry.id;
+};
+
export const editResume = async (
data: z.infer<typeof CreateResumeFormSchema>
): Promise<any | undefined> => {
diff --git a/src/app/api/profile/resume/route.ts b/src/app/api/profile/resume/route.ts
new file mode 100644
index 0000000..245f3e9
--- /dev/null
+++ b/src/app/api/profile/resume/route.ts
@@ -0,0 +1,56 @@
+import { auth } from "@/auth";
+import { NextRequest, NextResponse } from "next/server";
+import { NextApiRequest, NextApiResponse } from "next";
+import { createResumeProfile } from "@/actions/profile.actions";
+import path from "path";
+import fs from "fs";
+import { writeFile } from "fs/promises";
+import { getTimestampedFileName } from "@/lib/utils";
+
+export const POST = async (req: NextRequest, res: NextApiResponse) => {
+ const session = await auth();
+ const userId = session?.accessToken.sub;
+ let filePath;
+
+ try {
+ if (!session || !session.user) {
+ return res.status(401).json({ message: "Not Authenticated" });
+ }
+ const formData = await req.formData();
+ const title = formData.get("title") as string;
+ const file = formData.get("file") as File;
+
+ if (file && file.name) {
+ const bytes = await file.arrayBuffer();
+ const buffer = new Uint8Array(bytes);
+
+ const uploadDir = path.join("data", "files", "resumes");
+
+ if (!fs.existsSync(uploadDir)) {
+ fs.mkdirSync(uploadDir, { recursive: true });
+ }
+
+ const timestampedFileName = getTimestampedFileName(file.name);
+
+ filePath = path.join(uploadDir, timestampedFileName);
+
+ await writeFile(filePath, buffer);
+ }
+ const response = await createResumeProfile(
+ title,
+ file.name ?? null,
+ filePath
+ );
+ return NextResponse.json(response, { status: 201 });
+ } catch (error) {
+ console.error(error);
+ return NextResponse.json(
+ {
+ error: "File upload failed",
+ },
+ {
+ status: 500,
+ }
+ );
+ }
+};
diff --git a/src/components/profile/CreateResume.tsx b/src/components/profile/CreateResume.tsx
index ff9a741..d906ab8 100644
--- a/src/components/profile/CreateResume.tsx
+++ b/src/components/profile/CreateResume.tsx
@@ -8,7 +8,6 @@ import { zodResolver } from "@hookform/resolvers/zod";
import { useEffect, useTransition } from "react";
import {
Dialog,
- DialogClose,
DialogContent,
DialogFooter,
DialogHeader,
@@ -46,9 +45,15 @@ function CreateResume({
const form = useForm<z.infer<typeof CreateResumeFormSchema>>({
resolver: zodResolver(CreateResumeFormSchema),
+ mode: "onChange",
});
- const { reset, formState } = form;
+ const {
+ reset,
+ formState: { errors, isValid },
+ } = form;
+
+ const closeDialog = () => setResumeDialogOpen(false);
useEffect(() => {
if (resumeToEdit) {
@@ -65,15 +70,24 @@ function CreateResume({
}, [resumeToEdit, reset]);
const onSubmit = (data: z.infer<typeof CreateResumeFormSchema>) => {
+ const formData = new FormData();
+ formData.append("file", data.file as File);
+ formData.append("title", data.title);
+
startTransition(async () => {
const res = resumeToEdit
? await editResume(data)
- : await createResumeProfile(data);
- if (!res.success) {
+ : await fetch("/api/profile/resume", {
+ method: "POST",
+ body: formData,
+ });
+ const response = await res.json();
+ console.log("Response: ", response);
+ if (!response.success) {
toast({
variant: "destructive",
title: "Error!",
- description: res.message,
+ description: response.message,
});
} else {
reset();
@@ -114,23 +128,58 @@ function CreateResume({
placeholder="Ex: Full Stack Developer Angular, Java"
/>
</FormControl>
- <FormMessage />
+ <FormMessage>
+ {errors.title && (
+ <span className="text-red-500">
+ {errors.title.message}
+ </span>
+ )}
+ </FormMessage>
</FormItem>
)}
/>
</div>
+
+ {/* RESUME FILE */}
+ <div className="md:col-span-2">
+ <FormField
+ control={form.control}
+ name="file"
+ render={({ field }) => (
+ <FormItem>
+ <FormLabel>Upload Resume (Optional)</FormLabel>
+ <FormControl>
+ <Input
+ type="file"
+ accept=".pdf,.doc,.docx"
+ onChange={(e) => field.onChange(e.target.files?.[0])}
+ />
+ </FormControl>
+ <FormMessage>
+ {errors.file?.message && (
+ <span className="text-red-500">
+ {errors.file.message}
+ </span>
+ )}
+ </FormMessage>
+ </FormItem>
+ )}
+ />
+ </div>
+
<div className="md:col-span-2 mt-4">
<DialogFooter>
- <DialogClose>
+ <div>
<Button
type="reset"
variant="outline"
className="mt-2 md:mt-0 w-full"
+ onClick={closeDialog}
>
Cancel
</Button>
- </DialogClose>
- <Button type="submit" disabled={!formState.isDirty}>
+ </div>
+ <Button type="submit" disabled={!isValid}>
Save
{isPending && <Loader className="h-4 w-4 shrink-0 spinner" />}
</Button>
diff --git a/src/lib/utils.ts b/src/lib/utils.ts
index 3ae229f..aa00986 100644
--- a/src/lib/utils.ts
+++ b/src/lib/utils.ts
@@ -45,3 +45,15 @@ export function handleError(error: unknown, msg = "Server Error.") {
return { success: false, message: error.message || msg };
}
}
+
+export function getTimestampedFileName(originalName: string): string {
+ const timestamp = new Date()
+ .toISOString()
+ .replace(/:/g, "-") // Replace colons with dashes for file system compatibility
+ .replace(/\..+/, ""); // Remove milliseconds
+
+ const extension = originalName.split(".").pop();
+ const baseName = originalName.replace(`.${extension}`, "");
+
+ return `${baseName}_${timestamp}.${extension}`;
+}
diff --git a/src/models/createResumeForm.schema.ts b/src/models/createResumeForm.schema.ts
index 6cc9dcf..4517b17 100644
--- a/src/models/createResumeForm.schema.ts
+++ b/src/models/createResumeForm.schema.ts
@@ -1,12 +1,28 @@
import { z } from "zod";
+const MAX_FILE_SIZE = 5 * 1024 * 1024; // 5 MB
+
+const SUPPORTED_MIME_TYPES = [
+ "application/pdf", // PDF
+ "application/msword", // Word .doc
+ "application/vnd.openxmlformats-officedocument.wordprocessingml.document", // Word .docx
+];
+
export const CreateResumeFormSchema = z.object({
id: z.string().optional(),
createdBy: z.string().optional(),
title: z
- .string({
- required_error: "Resume title is required.",
- })
- .min(1),
+ .string()
+ .min(1, "Resume title is required.")
+ .max(100, "Title must be less than 100 characters"),
profileId: z.string().optional(),
+ file: z
+ .instanceof(File)
+ .refine((file) => SUPPORTED_MIME_TYPES.includes(file.type), {
+ message: "Only PDF and Word documents are allowed.",
+ })
+ .refine((file) => file.size <= MAX_FILE_SIZE, {
+ message: "File size must be less than 5MB",
+ })
+ .optional(),
});
diff --git a/src/models/profile.model.ts b/src/models/profile.model.ts
index 8d68517..b5b7c93 100644
--- a/src/models/profile.model.ts
+++ b/src/models/profile.model.ts
@@ -8,6 +8,16 @@ export interface Resume {
updatedAt?: Date;
ContactInfo?: ContactInfo;
ResumeSections?: ResumeSection[];
+ File?: File;
+}
+
+export interface File {
+ id?: string;
+ fileName: string;
+ filePath: string;
+ fileType: string;
+ uploadedAt?: Date;
+ Resume?: Resume;
}
export interface ContactInfo {