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.

Use db for settings

Khuram Niazc797d559780a
diff --git a/prisma/migrations/20260131063928_add_user_settings/migration.sql b/prisma/migrations/20260131063928_add_user_settings/migration.sql
new file mode 100644
index 0000000..7aa5a25
--- /dev/null
+++ b/prisma/migrations/20260131063928_add_user_settings/migration.sql
@@ -0,0 +1,12 @@
+-- CreateTable
+CREATE TABLE "UserSettings" (
+ "id" TEXT NOT NULL PRIMARY KEY,
+ "userId" TEXT NOT NULL,
+ "settings" TEXT NOT NULL DEFAULT '{}',
+ "createdAt" DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
+ "updatedAt" DATETIME NOT NULL,
+ CONSTRAINT "UserSettings_userId_fkey" FOREIGN KEY ("userId") REFERENCES "User" ("id") ON DELETE RESTRICT ON UPDATE CASCADE
+);
+
+-- CreateIndex
+CREATE UNIQUE INDEX "UserSettings_userId_key" ON "UserSettings"("userId");
diff --git a/prisma/schema.prisma b/prisma/schema.prisma
index ede617b..9743017 100644
--- a/prisma/schema.prisma
+++ b/prisma/schema.prisma
@@ -28,6 +28,16 @@ model User {
ActivityType ActivityType[]
Task Task[]
Automation Automation[]
+ Settings UserSettings?
+}
+
+model UserSettings {
+ id String @id @default(uuid())
+ userId String @unique
+ user User @relation(fields: [userId], references: [id])
+ settings String @default("{}")
+ createdAt DateTime @default(now())
+ updatedAt DateTime @updatedAt
}
model Profile {
diff --git a/src/actions/userSettings.actions.ts b/src/actions/userSettings.actions.ts
new file mode 100644
index 0000000..57d8438
--- /dev/null
+++ b/src/actions/userSettings.actions.ts
@@ -0,0 +1,132 @@
+"use server";
+import prisma from "@/lib/db";
+import { handleError } from "@/lib/utils";
+import { getCurrentUser } from "@/utils/user.utils";
+import {
+ UserSettingsData,
+ defaultUserSettings,
+ AiSettings,
+ DisplaySettings,
+} from "@/models/userSettings.model";
+
+export const getUserSettings = async (): Promise<any | undefined> => {
+ try {
+ const user = await getCurrentUser();
+
+ if (!user) {
+ throw new Error("Not authenticated");
+ }
+
+ const userSettings = await prisma.userSettings.findUnique({
+ where: { userId: user.id },
+ });
+
+ if (!userSettings) {
+ return {
+ success: true,
+ data: {
+ userId: user.id,
+ settings: defaultUserSettings,
+ },
+ };
+ }
+
+ const settings: UserSettingsData = JSON.parse(userSettings.settings);
+
+ return {
+ success: true,
+ data: {
+ userId: user.id,
+ settings: {
+ ...defaultUserSettings,
+ ...settings,
+ },
+ },
+ };
+ } catch (error) {
+ const msg = "Failed to fetch user settings.";
+ return handleError(error, msg);
+ }
+};
+
+export const updateUserSettings = async (
+ settings: Partial<UserSettingsData>
+): Promise<any | undefined> => {
+ try {
+ const user = await getCurrentUser();
+
+ if (!user) {
+ throw new Error("Not authenticated");
+ }
+
+ const existingSettings = await prisma.userSettings.findUnique({
+ where: { userId: user.id },
+ });
+
+ let mergedSettings: UserSettingsData;
+
+ if (existingSettings) {
+ const currentSettings: UserSettingsData = JSON.parse(
+ existingSettings.settings
+ );
+ mergedSettings = {
+ ...defaultUserSettings,
+ ...currentSettings,
+ ...settings,
+ ai: {
+ ...defaultUserSettings.ai,
+ ...currentSettings.ai,
+ ...settings.ai,
+ },
+ display: {
+ ...defaultUserSettings.display,
+ ...currentSettings.display,
+ ...settings.display,
+ },
+ };
+ } else {
+ mergedSettings = {
+ ...defaultUserSettings,
+ ...settings,
+ ai: { ...defaultUserSettings.ai, ...settings.ai },
+ display: { ...defaultUserSettings.display, ...settings.display },
+ };
+ }
+
+ const userSettings = await prisma.userSettings.upsert({
+ where: { userId: user.id },
+ update: {
+ settings: JSON.stringify(mergedSettings),
+ },
+ create: {
+ userId: user.id,
+ settings: JSON.stringify(mergedSettings),
+ },
+ });
+
+ const parsedSettings: UserSettingsData = JSON.parse(userSettings.settings);
+
+ return {
+ success: true,
+ data: {
+ userId: user.id,
+ settings: parsedSettings,
+ },
+ };
+ } catch (error) {
+ const msg = "Failed to update user settings.";
+ return handleError(error, msg);
+ }
+};
+
+export const updateAiSettings = async (
+ aiSettings: AiSettings
+): Promise<any | undefined> => {
+ return updateUserSettings({ ai: aiSettings });
+};
+
+export const updateDisplaySettings = async (
+ displaySettings: DisplaySettings
+): Promise<any | undefined> => {
+ return updateUserSettings({ display: displaySettings });
+};
diff --git a/src/components/profile/AiJobMatchSection.tsx b/src/components/profile/AiJobMatchSection.tsx
index 8d2fba3..ffeeaa7 100644
--- a/src/components/profile/AiJobMatchSection.tsx
+++ b/src/components/profile/AiJobMatchSection.tsx
@@ -23,7 +23,6 @@ import {
import Loading from "../Loading";
import { AiModel, defaultModel } from "@/models/ai.model";
import { AiJobMatchResponseContent } from "./AiJobMatchResponseContent";
-import { getFromLocalStorage } from "@/utils/localstorage.utils";
import {
Tooltip,
TooltipContent,
@@ -33,6 +32,7 @@ import {
import { Info, CheckCircle, XCircle } from "lucide-react";
import { checkIfModelIsRunning } from "@/utils/ai.utils";
import { JobMatchSchema } from "@/models/ai.schemas";
+import { getUserSettings } from "@/actions/userSettings.actions";
interface AiSectionProps {
aISectionOpen: boolean;
@@ -48,14 +48,30 @@ export const AiJobMatchSection = ({
const [selectedResumeId, setSelectedResumeId] = useState<string>();
const [runningModelName, setRunningModelName] = useState<string>("");
const [runningModelError, setRunningModelError] = useState<string>("");
-
- const selectedModel: AiModel = getFromLocalStorage(
- "aiSettings",
-
- defaultModel,
- );
+ const [selectedModel, setSelectedModel] = useState<AiModel>(defaultModel);
+ const [isLoadingSettings, setIsLoadingSettings] = useState(true);
const resumesRef = useRef<Resume[]>([]);
+ useEffect(() => {
+ const fetchSettings = async () => {
+ try {
+ const result = await getUserSettings();
+ if (result.success && result.data?.settings?.ai) {
+ const aiSettings = result.data.settings.ai;
+ setSelectedModel({
+ provider: aiSettings.provider || defaultModel.provider,
+ model: aiSettings.model,
+ });
+ }
+ } catch (error) {
+ console.error("Error fetching AI settings:", error);
+ } finally {
+ setIsLoadingSettings(false);
+ }
+ };
+ fetchSettings();
+ }, []);
+
// Standard single-agent mode
const { object, submit, isLoading, stop } = useObject({
api: "/api/ai/resume/match",
@@ -186,6 +202,7 @@ export const AiJobMatchSection = ({
onValueChange={onSelectResume}
disabled={
isLoading ||
+ isLoadingSettings ||
(selectedModel.provider === "ollama" && !runningModelName)
}
>
diff --git a/src/components/profile/AiResumeReviewSection.tsx b/src/components/profile/AiResumeReviewSection.tsx
index c254380..c3972d9 100644
--- a/src/components/profile/AiResumeReviewSection.tsx
+++ b/src/components/profile/AiResumeReviewSection.tsx
@@ -12,12 +12,11 @@ import {
SheetTrigger,
} from "../ui/sheet";
import Loading from "../Loading";
-import { useState } from "react";
+import { useState, useEffect } from "react";
import { toast } from "../ui/use-toast";
import { Resume } from "@/models/profile.model";
-import { AiModel, defaultModel, ResumeReviewResponse } from "@/models/ai.model";
+import { AiModel, defaultModel } from "@/models/ai.model";
import { AiResumeReviewResponseContent } from "./AiResumeReviewResponseContent";
-import { getFromLocalStorage } from "@/utils/localstorage.utils";
import {
Tooltip,
TooltipContent,
@@ -26,6 +25,7 @@ import {
} from "../ui/tooltip";
import { checkIfModelIsRunning } from "@/utils/ai.utils";
import { ResumeReviewSchema } from "@/models/ai.schemas";
+import { getUserSettings } from "@/actions/userSettings.actions";
interface AiSectionProps {
resume: Resume;
@@ -35,11 +35,28 @@ const AiResumeReviewSection = ({ resume }: AiSectionProps) => {
const [aISectionOpen, setAiSectionOpen] = useState(false);
const [runningModelName, setRunningModelName] = useState<string>("");
const [runningModelError, setRunningModelError] = useState<string>("");
+ const [selectedModel, setSelectedModel] = useState<AiModel>(defaultModel);
+ const [isLoadingSettings, setIsLoadingSettings] = useState(true);
- const selectedModel: AiModel = getFromLocalStorage(
- "aiSettings",
- defaultModel
- );
+ useEffect(() => {
+ const fetchSettings = async () => {
+ try {
+ const result = await getUserSettings();
+ if (result.success && result.data?.settings?.ai) {
+ const aiSettings = result.data.settings.ai;
+ setSelectedModel({
+ provider: aiSettings.provider || defaultModel.provider,
+ model: aiSettings.model,
+ });
+ }
+ } catch (error) {
+ console.error("Error fetching AI settings:", error);
+ } finally {
+ setIsLoadingSettings(false);
+ }
+ };
+ fetchSettings();
+ }, []);
// Standard single-agent mode
const { object, submit, isLoading, stop } = useObject({
@@ -102,7 +119,7 @@ const AiResumeReviewSection = ({ resume }: AiSectionProps) => {
variant="outline"
className="h-8 gap-1 cursor-pointer"
onClick={() => triggerSheetChange(true)}
- disabled={isLoading || resume.ResumeSections?.length! < 2}
+ disabled={isLoading || isLoadingSettings || resume.ResumeSections?.length! < 2}
>
<Sparkles className="h-3.5 w-3.5" />
<span className="sr-only sm:not-sr-only sm:whitespace-nowrap">
diff --git a/src/components/settings/AiSettings.tsx b/src/components/settings/AiSettings.tsx
index bca1e23..0bb59d7 100644
--- a/src/components/settings/AiSettings.tsx
+++ b/src/components/settings/AiSettings.tsx
@@ -18,13 +18,10 @@ import {
} from "../ui/select";
import { Label } from "../ui/label";
import { Button } from "../ui/button";
-import {
- getFromLocalStorage,
- saveToLocalStorage,
-} from "@/utils/localstorage.utils";
import { toast } from "../ui/use-toast";
-import { XCircle, CheckCircle } from "lucide-react";
+import { XCircle, CheckCircle, Loader2 } from "lucide-react";
import { checkIfModelIsRunning } from "@/utils/ai.utils";
+import { getUserSettings, updateAiSettings } from "@/actions/userSettings.actions";
interface OllamaModelResponse {
models: {
@@ -54,6 +51,8 @@ function AiSettings() {
const [ollamaModels, setOllamaModels] = useState<string[]>([]);
const [deepseekModels, setDeepseekModels] = useState<string[]>([]);
const [isLoadingModels, setIsLoadingModels] = useState(false);
+ const [isLoadingSettings, setIsLoadingSettings] = useState(true);
+ const [isSaving, setIsSaving] = useState(false);
const [isInitialized, setIsInitialized] = useState(false);
const [fetchError, setFetchError] = useState<string>("");
const [runningModelError, setRunningModelError] = useState<string>("");
@@ -84,10 +83,25 @@ function AiSettings() {
};
useEffect(() => {
- const savedSettings = getFromLocalStorage("aiSettings", selectedModel);
- setSelectedModel(savedSettings);
- setIsInitialized(true);
- // eslint-disable-next-line react-hooks/exhaustive-deps
+ const fetchSettings = async () => {
+ setIsLoadingSettings(true);
+ try {
+ const result = await getUserSettings();
+ if (result.success && result.data?.settings?.ai) {
+ const aiSettings = result.data.settings.ai;
+ setSelectedModel({
+ provider: aiSettings.provider || defaultModel.provider,
+ model: aiSettings.model,
+ });
+ }
+ } catch (error) {
+ console.error("Error fetching user settings:", error);
+ } finally {
+ setIsLoadingSettings(false);
+ setIsInitialized(true);
+ }
+ };
+ fetchSettings();
}, []);
useEffect(() => {
@@ -237,7 +251,7 @@ function AiSettings() {
return [];
}
};
- const saveModelSettings = () => {
+ const saveModelSettings = async () => {
if (!selectedModel.model) {
toast({
variant: "destructive",
@@ -246,13 +260,52 @@ function AiSettings() {
});
return;
}
- saveToLocalStorage("aiSettings", selectedModel);
- toast({
- variant: "success",
- title: "Saved!",
- description: "AI Settings saved successfully.",
- });
+ setIsSaving(true);
+ try {
+ const result = await updateAiSettings({
+ provider: selectedModel.provider,
+ model: selectedModel.model,
+ });
+ if (result.success) {
+ toast({
+ variant: "success",
+ title: "Saved!",
+ description: "AI Settings saved successfully.",
+ });
+ } else {
+ toast({
+ variant: "destructive",
+ title: "Error",
+ description: result.message || "Failed to save AI settings.",
+ });
+ }
+ } catch (error) {
+ console.error("Error saving AI settings:", error);
+ toast({
+ variant: "destructive",
+ title: "Error",
+ description: "Failed to save AI settings.",
+ });
+ } finally {
+ setIsSaving(false);
+ }
};
+ if (isLoadingSettings) {
+ return (
+ <Card>
+ <CardHeader>
+ <CardTitle>AI Settings</CardTitle>
+ </CardHeader>
+ <CardContent className="ml-4">
+ <div className="flex items-center gap-2">
+ <Loader2 className="h-4 w-4 animate-spin" />
+ <span>Loading settings...</span>
+ </div>
+ </CardContent>
+ </Card>
+ );
+ }
+
return (
<Card>
<CardHeader>
@@ -343,9 +396,11 @@ function AiSettings() {
!selectedModel.model ||
(selectedModel.provider === AiProvider.OLLAMA &&
!runningModelName) ||
- isLoadingModels
+ isLoadingModels ||
+ isSaving
}
>
+ {isSaving && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
Save
</Button>
</CardContent>
diff --git a/src/components/settings/DisplaySettings.tsx b/src/components/settings/DisplaySettings.tsx
index e93ffc1..3298919 100644
--- a/src/components/settings/DisplaySettings.tsx
+++ b/src/components/settings/DisplaySettings.tsx
@@ -1,4 +1,5 @@
"use client";
+import { useEffect, useState } from "react";
import { z } from "zod";
import { Card, CardContent, CardHeader, CardTitle } from "../ui/card";
import {
@@ -16,6 +17,8 @@ import { zodResolver } from "@hookform/resolvers/zod";
import { toast } from "../ui/use-toast";
import { Button } from "../ui/button";
import { useTheme } from "next-themes";
+import { Loader2 } from "lucide-react";
+import { getUserSettings, updateDisplaySettings } from "@/actions/userSettings.actions";
const appearanceFormSchema = z.object({
theme: z.enum(["light", "dark", "system"], {
@@ -25,30 +28,88 @@ const appearanceFormSchema = z.object({
type AppearanceFormValues = z.infer<typeof appearanceFormSchema>;
-const currentTheme =
- typeof window !== "undefined"
- ? (localStorage.getItem("theme") as "light" | "dark" | "system" | undefined)
- : "system";
-
-// This can come from your database or API.
-const defaultValues: Partial<AppearanceFormValues> = {
- theme: currentTheme || "system",
-};
-
function DisplaySettings() {
- const { setTheme, systemTheme } = useTheme();
+ const { setTheme, theme, systemTheme } = useTheme();
+ const [isLoading, setIsLoading] = useState(true);
+ const [isSaving, setIsSaving] = useState(false);
+
const form = useForm<AppearanceFormValues>({
resolver: zodResolver(appearanceFormSchema),
- defaultValues,
+ defaultValues: {
+ theme: "system",
+ },
});
- function onSubmit(data: AppearanceFormValues) {
- setTheme(data.theme);
- toast({
- variant: "success",
- title: `Your selected theme has been saved.`,
- });
+ useEffect(() => {
+ const fetchSettings = async () => {
+ setIsLoading(true);
+ try {
+ const result = await getUserSettings();
+ if (result.success && result.data?.settings?.display?.theme) {
+ const savedTheme = result.data.settings.display.theme;
+ form.reset({ theme: savedTheme });
+ setTheme(savedTheme);
+ } else if (theme) {
+ form.reset({ theme: theme as "light" | "dark" | "system" });
+ }
+ } catch (error) {
+ console.error("Error fetching display settings:", error);
+ if (theme) {
+ form.reset({ theme: theme as "light" | "dark" | "system" });
+ }
+ } finally {
+ setIsLoading(false);
+ }
+ };
+ fetchSettings();
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, []);
+
+ async function onSubmit(data: AppearanceFormValues) {
+ setIsSaving(true);
+ try {
+ const result = await updateDisplaySettings({ theme: data.theme });
+ if (result.success) {
+ setTheme(data.theme);
+ toast({
+ variant: "success",
+ title: "Your selected theme has been saved.",
+ });
+ } else {
+ toast({
+ variant: "destructive",
+ title: "Error",
+ description: result.message || "Failed to save display settings.",
+ });
+ }
+ } catch (error) {
+ console.error("Error saving display settings:", error);
+ toast({
+ variant: "destructive",
+ title: "Error",
+ description: "Failed to save display settings.",
+ });
+ } finally {
+ setIsSaving(false);
+ }
}
+
+ if (isLoading) {
+ return (
+ <Card>
+ <CardHeader>
+ <CardTitle>Appearance</CardTitle>
+ </CardHeader>
+ <CardContent className="ml-4">
+ <div className="flex items-center gap-2">
+ <Loader2 className="h-4 w-4 animate-spin" />
+ <span>Loading settings...</span>
+ </div>
+ </CardContent>
+ </Card>
+ );
+ }
+
return (
<Card>
<CardHeader>
@@ -70,7 +131,7 @@ function DisplaySettings() {
<FormMessage />
<RadioGroup
onValueChange={field.onChange}
- defaultValue={field.value}
+ value={field.value}
className="grid max-w-lg md:grid-cols-3 gap-8 pt-2"
>
<FormItem>
@@ -118,7 +179,10 @@ function DisplaySettings() {
)}
/>
- <Button type="submit">Update preferences</Button>
+ <Button type="submit" disabled={isSaving}>
+ {isSaving && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
+ Update preferences
+ </Button>
</form>
</Form>
</div>
diff --git a/src/models/userSettings.model.ts b/src/models/userSettings.model.ts
new file mode 100644
index 0000000..73726a6
--- /dev/null
+++ b/src/models/userSettings.model.ts
@@ -0,0 +1,30 @@
+import { AiProvider } from "./ai.model";
+
+export interface AiSettings {
+ provider: AiProvider;
+ model: string | undefined;
+}
+
+export interface DisplaySettings {
+ theme: "light" | "dark" | "system";
+}
+
+export interface UserSettingsData {
+ ai: AiSettings;
+ display: DisplaySettings;
+}
+
+export interface UserSettings {
+ userId: string;
+ settings: UserSettingsData;
+}
+
+export const defaultUserSettings: UserSettingsData = {
+ ai: {
+ provider: AiProvider.OLLAMA,
+ model: undefined,
+ },
+ display: {
+ theme: "system",
+ },
+};