fix(app): harden account and workflow state
This commit is contained in:
@@ -15,6 +15,7 @@ import ShieldIcon from "@mui/icons-material/Shield";
|
||||
import SearchIcon from "@mui/icons-material/Search";
|
||||
import MemoryIcon from "@mui/icons-material/Memory";
|
||||
import DescriptionOutlinedIcon from "@mui/icons-material/DescriptionOutlined";
|
||||
import MailOutlineIcon from "@mui/icons-material/MailOutline";
|
||||
|
||||
import { Navigate, Route, Routes, useLocation, useNavigate, useParams, createBrowserRouter, RouterProvider } from "react-router-dom";
|
||||
|
||||
@@ -94,11 +95,11 @@ function breadcrumbsFor(path: string, t: (k: any) => string): string[] {
|
||||
if (path.startsWith("/correspondence/review")) return [t("home"), "Gmail review queue"];
|
||||
if (path.startsWith("/correspondence")) return [t("home"), "Correspondence inbox"];
|
||||
if (path.startsWith("/trash")) return [t("home"), t("trash")];
|
||||
if (path.startsWith("/settings/connected-accounts")) return [t("home"), t("settings"), "Connected accounts"];
|
||||
if (path.startsWith("/settings")) return [t("home"), t("settings")];
|
||||
if (path.startsWith("/profile")) return [t("home"), t("account"), t("profile")];
|
||||
if (path.startsWith("/career/builder")) return [t("home"), "Career Workspace", "CV Builder"];
|
||||
if (path.startsWith("/career")) return [t("home"), "Career Workspace"];
|
||||
if (path.startsWith("/settings/connected-accounts")) return [t("home"), t("settings"), "Connected accounts"];
|
||||
if (path.startsWith("/admin/audit")) return [t("home"), t("admin"), t("auditLog")];
|
||||
if (path.startsWith("/admin/users")) return [t("home"), t("admin"), t("users")];
|
||||
if (path.startsWith("/admin/system")) return [t("home"), t("admin"), t("system")];
|
||||
@@ -117,11 +118,11 @@ function titleFor(path: string, t: (k: any) => string): string {
|
||||
if (path.startsWith("/correspondence/review")) return "Gmail review queue";
|
||||
if (path.startsWith("/correspondence")) return "Correspondence inbox";
|
||||
if (path.startsWith("/trash")) return t("trash");
|
||||
if (path.startsWith("/settings/connected-accounts")) return "Connected accounts";
|
||||
if (path.startsWith("/settings")) return t("settings");
|
||||
if (path.startsWith("/profile")) return t("profile");
|
||||
if (path.startsWith("/career/builder")) return "CV Builder";
|
||||
if (path.startsWith("/career")) return "Career Workspace";
|
||||
if (path.startsWith("/settings/connected-accounts")) return "Connected accounts";
|
||||
if (path.startsWith("/admin/audit")) return t("auditLog");
|
||||
if (path.startsWith("/admin/users")) return t("users");
|
||||
if (path.startsWith("/admin/system")) return t("systemStatus");
|
||||
@@ -282,6 +283,7 @@ function Shell({ jobPageSize, setJobPageSize, jobColumns, setJobColumns, themeMo
|
||||
{ to: "/reminders", label: t("reminders"), icon: <AlarmIcon fontSize="small" />, badgeCount: reminderCount, section: t("manage") },
|
||||
{ to: "/kanban", label: t("kanbanBoard"), icon: <ViewKanbanIcon fontSize="small" />, section: t("manage") },
|
||||
{ to: "/companies", label: t("companies"), icon: <BusinessIcon fontSize="small" />, section: t("manage") },
|
||||
{ to: "/correspondence", label: t("correspondenceInbox"), icon: <MailOutlineIcon fontSize="small" />, section: t("manage") },
|
||||
{ to: "/career", label: "Career Workspace", icon: <DescriptionOutlinedIcon fontSize="small" />, section: t("manage") },
|
||||
{ to: "/career/builder", label: "CV Builder", icon: <DescriptionOutlinedIcon fontSize="small" />, section: t("manage") },
|
||||
{ to: "/trash", label: t("trash"), icon: <DeleteOutlineIcon fontSize="small" />, section: t("manage") },
|
||||
|
||||
@@ -0,0 +1,62 @@
|
||||
import React from "react";
|
||||
import "@testing-library/jest-dom";
|
||||
import { fireEvent, render, screen, waitFor } from "@testing-library/react";
|
||||
|
||||
import { api } from "./api";
|
||||
import { setAuthUserKey } from "./auth";
|
||||
import SavedViewsMenu from "./components/SavedViewsMenu";
|
||||
import { useCompanies } from "./hooks/useCompanies";
|
||||
import { I18nProvider } from "./i18n/I18nProvider";
|
||||
|
||||
const mockedApi = api as jest.Mocked<typeof api>;
|
||||
|
||||
function CompaniesProbe() {
|
||||
const { companies } = useCompanies();
|
||||
return <div>{companies.map((company) => company.name).join(", ") || "No companies"}</div>;
|
||||
}
|
||||
|
||||
describe("account-scoped browser state", () => {
|
||||
beforeEach(() => {
|
||||
window.localStorage.clear();
|
||||
jest.clearAllMocks();
|
||||
});
|
||||
|
||||
it("keeps saved views private to the account that created them", async () => {
|
||||
setAuthUserKey("user-a", false);
|
||||
const first = render(
|
||||
<I18nProvider>
|
||||
<SavedViewsMenu current={{ status: "Interview" }} onApply={jest.fn()} />
|
||||
</I18nProvider>,
|
||||
);
|
||||
|
||||
fireEvent.click(screen.getByRole("button", { name: "Saved views" }));
|
||||
fireEvent.change(screen.getByLabelText("Name"), { target: { value: "User A interviews" } });
|
||||
fireEvent.click(screen.getByRole("button", { name: "Save current" }));
|
||||
expect(screen.getByText("User A interviews")).toBeInTheDocument();
|
||||
first.unmount();
|
||||
|
||||
setAuthUserKey("user-b", false);
|
||||
render(
|
||||
<I18nProvider>
|
||||
<SavedViewsMenu current={{}} onApply={jest.fn()} />
|
||||
</I18nProvider>,
|
||||
);
|
||||
fireEvent.click(screen.getByRole("button", { name: "Saved views" }));
|
||||
|
||||
expect(screen.queryByText("User A interviews")).not.toBeInTheDocument();
|
||||
expect(screen.getByText("No saved views yet.")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("does not show a previous account's cached companies after account switching", async () => {
|
||||
setAuthUserKey("user-a", false);
|
||||
mockedApi.get.mockResolvedValueOnce({ data: [{ id: 1, name: "User A Company" }] } as any);
|
||||
render(<CompaniesProbe />);
|
||||
expect(await screen.findByText("User A Company")).toBeInTheDocument();
|
||||
|
||||
mockedApi.get.mockResolvedValueOnce({ data: [{ id: 2, name: "User B Company" }] } as any);
|
||||
setAuthUserKey("user-b", false);
|
||||
|
||||
await waitFor(() => expect(screen.getByText("User B Company")).toBeInTheDocument());
|
||||
expect(screen.queryByText("User A Company")).not.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,57 @@
|
||||
import React from 'react';
|
||||
import '@testing-library/jest-dom';
|
||||
import { fireEvent, render, screen, waitFor } from '@testing-library/react';
|
||||
|
||||
import { api } from './api';
|
||||
import { AccountPlanProvider } from './accountPlan';
|
||||
import { ApplicationStatusSuggestion, ApplicationStrategySnapshot } from './components/ApplicationWorkflowAssist';
|
||||
import { I18nProvider } from './i18n/I18nProvider';
|
||||
import { ToastProvider } from './toast';
|
||||
|
||||
jest.mock('./api', () => ({
|
||||
api: { get: jest.fn(), post: jest.fn(), patch: jest.fn() },
|
||||
getApiErrorMessage: (_error: unknown, fallback?: string) => fallback || 'Request failed.',
|
||||
}));
|
||||
|
||||
const mockedApi = api as jest.Mocked<typeof api>;
|
||||
|
||||
beforeEach(() => jest.clearAllMocks());
|
||||
|
||||
test('recruiter status suggestions require an explicit apply action', async () => {
|
||||
const applied = jest.fn();
|
||||
mockedApi.get.mockResolvedValue({ data: { hasSuggestion: true, currentStatus: 'Applied', suggestedStatus: 'Interview' } } as any);
|
||||
mockedApi.patch.mockResolvedValue({ data: {} } as any);
|
||||
render(<ToastProvider><ApplicationStatusSuggestion jobId={42} onApplied={applied} /></ToastProvider>);
|
||||
|
||||
const button = await screen.findByRole('button', { name: 'Apply Interview' });
|
||||
expect(mockedApi.patch).not.toHaveBeenCalled();
|
||||
fireEvent.click(button);
|
||||
await waitFor(() => expect(mockedApi.patch).toHaveBeenCalledWith('/jobapplications/42/status', { status: 'Interview' }));
|
||||
expect(applied).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
test('strategy snapshot shows saved output and queues regeneration only on request', async () => {
|
||||
mockedApi.get.mockImplementation((url: string) => {
|
||||
if (url.endsWith('/focus-plan')) return Promise.resolve({ data: {
|
||||
strategicSummary: 'Lead with delivery evidence.',
|
||||
immediatePriorities: ['Tailor the summary'],
|
||||
proofPointsToLeadWith: ['Reduced lead time'],
|
||||
cvBulletIdeas: ['Quantify the migration'],
|
||||
coverLetterAngles: ['Public-service impact'],
|
||||
followUpApproach: ['Follow up after five days'],
|
||||
} } as any);
|
||||
return Promise.reject(new Error('no operation'));
|
||||
});
|
||||
mockedApi.post.mockResolvedValue({ data: {
|
||||
created: true,
|
||||
statusUrl: '/operations/op-1',
|
||||
operation: { id: 'op-1', taskType: 'focus-plan', status: 'queued', createdAtUtc: '', canCancel: true, canRetry: false },
|
||||
} } as any);
|
||||
|
||||
render(<I18nProvider><ToastProvider><AccountPlanProvider value={{ plan: 'pro', canUseAi: true, canUseProThemes: true }}><ApplicationStrategySnapshot jobId={42} /></AccountPlanProvider></ToastProvider></I18nProvider>);
|
||||
expect(await screen.findByText('Lead with delivery evidence.')).toBeInTheDocument();
|
||||
expect(mockedApi.post).not.toHaveBeenCalled();
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Regenerate' }));
|
||||
await waitFor(() => expect(mockedApi.post).toHaveBeenCalledWith('/jobapplications/42/focus-plan/operations', { attachmentIds: null }));
|
||||
expect(await screen.findByText('queued')).toBeInTheDocument();
|
||||
});
|
||||
@@ -72,6 +72,11 @@ export function getAuthUserKey(): string {
|
||||
return safeGet(window.localStorage, AUTH_USER_KEY) ?? "anon";
|
||||
}
|
||||
|
||||
export function getUserScopedStorageKey(baseKey: string, userKey = getAuthUserKey()): string {
|
||||
const normalizedUser = userKey.trim() || "anon";
|
||||
return `${baseKey}:${encodeURIComponent(normalizedUser)}`;
|
||||
}
|
||||
|
||||
export function setAuthUserKey(value: string | null | undefined, emit = true) {
|
||||
const previous = getAuthUserKey();
|
||||
const next = typeof value === "string" ? value.trim() : "";
|
||||
|
||||
@@ -12,6 +12,7 @@ import { getApiErrorMessage } from "../api";
|
||||
import {
|
||||
ApplicationCv, CoverLetter, TailoringPlan, applicationAssetsApi,
|
||||
} from "../applicationWorkspace";
|
||||
import { cvBuilderApi } from "../cvBuilder";
|
||||
|
||||
// Phase 5.4 — Application Assets sections for the workspace.
|
||||
//
|
||||
@@ -100,6 +101,20 @@ export function ApplicationCvSection({ jobId }: { jobId: number }) {
|
||||
|
||||
const attached = data?.attachedVariantId ?? "";
|
||||
|
||||
const duplicateForJob = async () => {
|
||||
if (!data?.attachedVariantId) return;
|
||||
setBusy(true);
|
||||
try {
|
||||
const copy = await cvBuilderApi.duplicate(data.attachedVariantId, `${data.attachedVariantName || "CV"} — tailored copy`);
|
||||
setData(await applicationAssetsApi.attachVariant(jobId, copy.id));
|
||||
window.location.assign(`/career/builder/${copy.id}`);
|
||||
} catch (err) {
|
||||
setError(getApiErrorMessage(err, "Could not create a tailored CV copy."));
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Stack spacing={2}>
|
||||
<Shell
|
||||
@@ -155,6 +170,9 @@ export function ApplicationCvSection({ jobId }: { jobId: number }) {
|
||||
>
|
||||
Edit, preview and export
|
||||
</Button>
|
||||
<Button size="small" variant="contained" disabled={busy} onClick={() => void duplicateForJob()}>
|
||||
Duplicate for this job
|
||||
</Button>
|
||||
</Stack>
|
||||
</Stack>
|
||||
</Paper>
|
||||
|
||||
@@ -0,0 +1,158 @@
|
||||
import React, { useCallback, useEffect, useRef, useState } from "react";
|
||||
|
||||
import { Alert, Box, Button, CircularProgress, Paper, Stack, Typography } from "@mui/material";
|
||||
|
||||
import { api, getApiErrorMessage } from "../api";
|
||||
import { useAccountPlan } from "../accountPlan";
|
||||
import type { FocusPlanResponse, StatusSuggestion, StrategySnapshotOperationResponse, UserOperation } from "../types";
|
||||
import { useToast } from "../toast";
|
||||
import { DraftCard, ListCard, TwoColumnSection } from "./JobDetailsPanels";
|
||||
|
||||
const terminal = (status: UserOperation["status"]) => ["succeeded", "failed", "cancelled"].includes(status);
|
||||
|
||||
export function ApplicationStatusSuggestion({ jobId, onApplied }: { jobId: number; onApplied: () => void }) {
|
||||
const [suggestion, setSuggestion] = useState<StatusSuggestion | null>(null);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const { toast } = useToast();
|
||||
|
||||
useEffect(() => {
|
||||
let active = true;
|
||||
api.get<StatusSuggestion>(`/jobapplications/${jobId}/status-suggestion`)
|
||||
.then(({ data }) => { if (active) setSuggestion(data.hasSuggestion ? data : null); })
|
||||
.catch(() => { if (active) setSuggestion(null); });
|
||||
return () => { active = false; };
|
||||
}, [jobId]);
|
||||
|
||||
if (!suggestion?.suggestedStatus) return null;
|
||||
|
||||
const apply = async () => {
|
||||
setBusy(true);
|
||||
try {
|
||||
await api.patch(`/jobapplications/${jobId}/status`, { status: suggestion.suggestedStatus });
|
||||
setSuggestion(null);
|
||||
onApplied();
|
||||
toast("Application status updated from the latest message.", "success");
|
||||
} catch (error) {
|
||||
toast(getApiErrorMessage(error, "Could not apply the suggested status."), "error");
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Alert
|
||||
severity="info"
|
||||
action={<Button color="inherit" size="small" disabled={busy} onClick={() => void apply()}>Apply {suggestion.suggestedStatus}</Button>}
|
||||
>
|
||||
A recent recruiter message suggests moving this application from {suggestion.currentStatus || "its current stage"} to {suggestion.suggestedStatus}.
|
||||
</Alert>
|
||||
);
|
||||
}
|
||||
|
||||
export function ApplicationStrategySnapshot({ jobId }: { jobId: number }) {
|
||||
const { canUseAi } = useAccountPlan();
|
||||
const { toast } = useToast();
|
||||
const [plan, setPlan] = useState<FocusPlanResponse | null>(null);
|
||||
const [operation, setOperation] = useState<UserOperation | null>(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const announced = useRef<string | null>(null);
|
||||
|
||||
const loadPlan = useCallback(async () => {
|
||||
try {
|
||||
const { data } = await api.get<FocusPlanResponse>(`/jobapplications/${jobId}/focus-plan`);
|
||||
setPlan(data);
|
||||
} catch {
|
||||
setPlan(null);
|
||||
}
|
||||
}, [jobId]);
|
||||
|
||||
useEffect(() => {
|
||||
let active = true;
|
||||
setLoading(true);
|
||||
Promise.all([
|
||||
loadPlan(),
|
||||
api.get<UserOperation>(`/jobapplications/${jobId}/focus-plan/operation`)
|
||||
.then(({ data }) => { if (active) setOperation(data); })
|
||||
.catch(() => { if (active) setOperation(null); }),
|
||||
]).finally(() => { if (active) setLoading(false); });
|
||||
return () => { active = false; };
|
||||
}, [jobId, loadPlan]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!operation || terminal(operation.status)) return;
|
||||
const timer = window.setTimeout(() => {
|
||||
api.get<UserOperation>(`/operations/${operation.id}`)
|
||||
.then(({ data }) => setOperation(data))
|
||||
.catch(() => undefined);
|
||||
}, 1000);
|
||||
return () => window.clearTimeout(timer);
|
||||
}, [operation]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!operation || !terminal(operation.status)) return;
|
||||
const key = `${operation.id}:${operation.status}`;
|
||||
if (announced.current === key) return;
|
||||
announced.current = key;
|
||||
if (operation.status === "succeeded") {
|
||||
void loadPlan();
|
||||
toast("Strategy snapshot completed.", "success");
|
||||
} else if (operation.status === "failed") toast("Strategy snapshot failed. You can retry safely.", "error");
|
||||
else toast("Strategy snapshot cancelled.", "info");
|
||||
}, [loadPlan, operation, toast]);
|
||||
|
||||
const generate = async () => {
|
||||
setLoading(true);
|
||||
try {
|
||||
const { data } = await api.post<StrategySnapshotOperationResponse>(`/jobapplications/${jobId}/focus-plan/operations`, { attachmentIds: null });
|
||||
announced.current = null;
|
||||
setOperation(data.operation);
|
||||
toast(data.created ? "Strategy snapshot queued." : "Strategy snapshot is already queued.", "info");
|
||||
} catch (error) {
|
||||
toast(getApiErrorMessage(error, "Could not queue the strategy snapshot."), "error");
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const mutateOperation = async (action: "cancel" | "retry") => {
|
||||
if (!operation) return;
|
||||
try {
|
||||
announced.current = null;
|
||||
const { data } = await api.post<UserOperation>(`/operations/${operation.id}/${action}`);
|
||||
setOperation(data);
|
||||
} catch (error) {
|
||||
toast(getApiErrorMessage(error, `Could not ${action} the strategy snapshot.`), "error");
|
||||
}
|
||||
};
|
||||
|
||||
const working = !!operation && !terminal(operation.status);
|
||||
return (
|
||||
<Paper sx={{ p: { xs: 2, sm: 2.5 }, borderRadius: 3 }}>
|
||||
<Stack direction="row" justifyContent="space-between" alignItems="center" gap={1} sx={{ mb: 2 }}>
|
||||
<Box>
|
||||
<Typography variant="subtitle2" sx={{ fontWeight: 800 }}>Strategy snapshot</Typography>
|
||||
<Typography variant="caption" color="text.secondary">An on-demand plan grounded in this advert and your saved career data.</Typography>
|
||||
</Box>
|
||||
<Button variant="outlined" size="small" disabled={!canUseAi || loading || working} onClick={() => void generate()}>
|
||||
{!canUseAi ? "Pro required" : plan ? "Regenerate" : "Generate"}
|
||||
</Button>
|
||||
</Stack>
|
||||
{operation && operation.status !== "succeeded" ? (
|
||||
<Alert severity={operation.status === "failed" ? "error" : operation.status === "cancelled" ? "warning" : "info"} sx={{ mb: 2 }} action={<>
|
||||
{operation.canCancel ? <Button size="small" color="inherit" onClick={() => void mutateOperation("cancel")}>Cancel</Button> : null}
|
||||
{operation.canRetry ? <Button size="small" color="inherit" onClick={() => void mutateOperation("retry")}>Retry</Button> : null}
|
||||
</>}>
|
||||
{operation.progressStage || operation.status.replaceAll("_", " ")}{operation.progressPercent != null ? ` · ${operation.progressPercent}%` : ""}
|
||||
</Alert>
|
||||
) : null}
|
||||
{loading && !plan ? <Box sx={{ py: 4, display: "flex", justifyContent: "center" }}><CircularProgress size={28} /></Box> : plan ? (
|
||||
<Stack spacing={2}>
|
||||
<DraftCard title="Strategic summary" content={plan.strategicSummary} />
|
||||
<TwoColumnSection leftTitle="Immediate priorities" leftItems={plan.immediatePriorities} rightTitle="Proof points" rightItems={plan.proofPointsToLeadWith} />
|
||||
<TwoColumnSection leftTitle="CV bullet ideas" leftItems={plan.cvBulletIdeas} rightTitle="Cover letter angles" rightItems={plan.coverLetterAngles} />
|
||||
<ListCard title="Follow-up approach" items={plan.followUpApproach} />
|
||||
</Stack>
|
||||
) : <Typography color="text.secondary">No strategy snapshot yet. Generate one when you want AI-assisted planning.</Typography>}
|
||||
</Paper>
|
||||
);
|
||||
}
|
||||
@@ -50,7 +50,7 @@ import { useDialogActions } from "../dialogs";
|
||||
import { useI18n } from "../i18n/I18nProvider";
|
||||
import { JobApplication } from "../types";
|
||||
import { useViewResource } from "../hooks/useViewResource";
|
||||
import { getWorkflowAction, needsInterviewPrep, needsWorkflowWork } from "../jobWorkflowSignals";
|
||||
import { getWorkflowAction } from "../jobWorkflowSignals";
|
||||
|
||||
interface PagedResult<T> {
|
||||
items: T[];
|
||||
@@ -276,6 +276,7 @@ export default function JobTable({ refreshToken, pageSize, onPageSizeChange, col
|
||||
setCompanyFilterId(nextCompany);
|
||||
setLocationFilter(view.location ?? "");
|
||||
setNeedsFollowUpOnly(Boolean(view.needsFollowUp));
|
||||
setReadinessFilter(view.readiness ?? "all");
|
||||
setPage(0);
|
||||
updateListRoute({
|
||||
q: view.q || null,
|
||||
@@ -283,6 +284,7 @@ export default function JobTable({ refreshToken, pageSize, onPageSizeChange, col
|
||||
companyId: nextCompany === "All" ? null : String(nextCompany),
|
||||
location: view.location || null,
|
||||
needsFollowUp: view.needsFollowUp ? "1" : null,
|
||||
readiness: view.readiness ?? null,
|
||||
page: null,
|
||||
});
|
||||
};
|
||||
@@ -303,7 +305,8 @@ export default function JobTable({ refreshToken, pageSize, onPageSizeChange, col
|
||||
sortBy,
|
||||
sortDir,
|
||||
needsFollowUp: needsFollowUpOnly ? true : undefined,
|
||||
}), [page, pageSize, debouncedSearch, statusFilter, companyFilterId, debouncedLocation, includeDeleted, mode, sortBy, sortDir, needsFollowUpOnly]);
|
||||
readiness: readinessFilter === "all" ? undefined : readinessFilter,
|
||||
}), [page, pageSize, debouncedSearch, statusFilter, companyFilterId, debouncedLocation, includeDeleted, mode, sortBy, sortDir, needsFollowUpOnly, readinessFilter]);
|
||||
|
||||
const jobsResource = useViewResource(
|
||||
async () => {
|
||||
@@ -333,11 +336,7 @@ export default function JobTable({ refreshToken, pageSize, onPageSizeChange, col
|
||||
updateListRoute({ sortBy: key === "dateApplied" ? null : key, sortDir: key === "dateApplied" && nextDirection === "desc" ? null : nextDirection, page: null });
|
||||
};
|
||||
|
||||
const filteredJobs = useMemo(() => {
|
||||
if (readinessFilter === "all") return jobs;
|
||||
if (readinessFilter === "interview") return jobs.filter((job) => needsInterviewPrep(job));
|
||||
return jobs.filter((job) => needsWorkflowWork(job));
|
||||
}, [jobs, readinessFilter]);
|
||||
const filteredJobs = jobs;
|
||||
|
||||
useEffect(() => {
|
||||
const focusJobId = (location.state as { focusJobId?: unknown } | null)?.focusJobId;
|
||||
@@ -532,7 +531,7 @@ export default function JobTable({ refreshToken, pageSize, onPageSizeChange, col
|
||||
|
||||
<Box sx={{ display: "grid", gridTemplateColumns: "minmax(0, 1fr) auto", gap: 0.75, alignItems: "center", pt: 0.25 }}>
|
||||
<Box sx={{ minWidth: 0 }}>
|
||||
<SavedViewsMenu current={{ q: search.trim() || undefined, status: statusFilter !== "All" ? statusFilter : undefined, companyId: companyFilterId === "All" ? undefined : (companyFilterId as number), location: locationFilter.trim() || undefined, needsFollowUp: needsFollowUpOnly ? true : undefined }} onApply={applySavedView} />
|
||||
<SavedViewsMenu current={{ q: search.trim() || undefined, status: statusFilter !== "All" ? statusFilter : undefined, companyId: companyFilterId === "All" ? undefined : (companyFilterId as number), location: locationFilter.trim() || undefined, needsFollowUp: needsFollowUpOnly ? true : undefined, readiness: readinessFilter === "all" ? undefined : readinessFilter }} onApply={applySavedView} />
|
||||
</Box>
|
||||
<Button variant="text" size="small" startIcon={<ViewColumnIcon />} onClick={(e) => setColumnsAnchor(e.currentTarget)} sx={{ justifySelf: "end", minHeight: 40, px: 1 }}>
|
||||
{t("jobTableColumns")}
|
||||
@@ -588,7 +587,7 @@ export default function JobTable({ refreshToken, pageSize, onPageSizeChange, col
|
||||
</FormControl>
|
||||
) : null}
|
||||
{mode === "jobs" ? <FormControlLabel control={<Checkbox checked={includeDeleted} onChange={(e) => changeIncludeDeleted(e.target.checked)} />} label={t("jobTableShowDeleted")} sx={{ mr: 0 }} /> : null}
|
||||
<SavedViewsMenu current={{ q: search.trim() || undefined, status: statusFilter !== "All" ? statusFilter : undefined, companyId: companyFilterId === "All" ? undefined : (companyFilterId as number), location: locationFilter.trim() || undefined, needsFollowUp: needsFollowUpOnly ? true : undefined }} onApply={applySavedView} />
|
||||
<SavedViewsMenu current={{ q: search.trim() || undefined, status: statusFilter !== "All" ? statusFilter : undefined, companyId: companyFilterId === "All" ? undefined : (companyFilterId as number), location: locationFilter.trim() || undefined, needsFollowUp: needsFollowUpOnly ? true : undefined, readiness: readinessFilter === "all" ? undefined : readinessFilter }} onApply={applySavedView} />
|
||||
{!isMobile ? <Tooltip title={t("jobTableColumns")}><IconButton aria-label={t("jobTableColumns")} onClick={(e) => setColumnsAnchor(e.currentTarget)}><ViewColumnIcon /></IconButton></Tooltip> : null}
|
||||
</Box>
|
||||
</Box>
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import React, { useMemo, useState } from "react";
|
||||
import React, { useEffect, useMemo, useState } from "react";
|
||||
|
||||
import {
|
||||
Button,
|
||||
@@ -15,6 +15,7 @@ import BookmarkBorderIcon from "@mui/icons-material/BookmarkBorder";
|
||||
import DeleteOutlineIcon from "@mui/icons-material/DeleteOutline";
|
||||
|
||||
import { useI18n } from "../i18n/I18nProvider";
|
||||
import { AUTH_USER_CHANGED_EVENT, getUserScopedStorageKey } from "../auth";
|
||||
|
||||
export type SavedViewParams = {
|
||||
q?: string;
|
||||
@@ -22,6 +23,7 @@ export type SavedViewParams = {
|
||||
companyId?: number;
|
||||
location?: string;
|
||||
needsFollowUp?: boolean;
|
||||
readiness?: "needs-work" | "interview";
|
||||
};
|
||||
|
||||
type SavedView = {
|
||||
@@ -35,7 +37,7 @@ const KEY = "jt_saved_views_v1";
|
||||
|
||||
function loadViews(): SavedView[] {
|
||||
try {
|
||||
const raw = window.localStorage.getItem(KEY);
|
||||
const raw = window.localStorage.getItem(getUserScopedStorageKey(KEY));
|
||||
if (!raw) return [];
|
||||
const v = JSON.parse(raw);
|
||||
if (!Array.isArray(v)) return [];
|
||||
@@ -46,7 +48,7 @@ function loadViews(): SavedView[] {
|
||||
}
|
||||
|
||||
function saveViews(views: SavedView[]) {
|
||||
window.localStorage.setItem(KEY, JSON.stringify(views));
|
||||
window.localStorage.setItem(getUserScopedStorageKey(KEY), JSON.stringify(views));
|
||||
}
|
||||
|
||||
export default function SavedViewsMenu({
|
||||
@@ -61,6 +63,16 @@ export default function SavedViewsMenu({
|
||||
const [name, setName] = useState("");
|
||||
const [views, setViews] = useState<SavedView[]>(() => loadViews());
|
||||
|
||||
useEffect(() => {
|
||||
const reloadForAccount = () => {
|
||||
setViews(loadViews());
|
||||
setName("");
|
||||
setAnchor(null);
|
||||
};
|
||||
window.addEventListener(AUTH_USER_CHANGED_EVENT, reloadForAccount);
|
||||
return () => window.removeEventListener(AUTH_USER_CHANGED_EVENT, reloadForAccount);
|
||||
}, []);
|
||||
|
||||
const hasAny = views.length > 0;
|
||||
|
||||
const canSave = useMemo(() => name.trim().length > 0, [name]);
|
||||
|
||||
@@ -2,6 +2,7 @@ import React, { useEffect, useState } from "react";
|
||||
|
||||
import {
|
||||
Box,
|
||||
Alert,
|
||||
Button,
|
||||
Checkbox,
|
||||
FormControl,
|
||||
@@ -10,6 +11,7 @@ import {
|
||||
MenuItem,
|
||||
Paper,
|
||||
Select,
|
||||
Skeleton,
|
||||
Tab,
|
||||
Tabs,
|
||||
Typography,
|
||||
@@ -26,6 +28,8 @@ import AiUsageCard from "./AiUsageCard";
|
||||
import AiPrivacySettingsCard from "./AiPrivacySettingsCard";
|
||||
import { ThemeModePref } from "../themePrefs";
|
||||
import { useI18n } from "../i18n/I18nProvider";
|
||||
import { api, getApiErrorMessage } from "../api";
|
||||
import { useToast } from "../toast";
|
||||
|
||||
interface Props {
|
||||
pageSize: 15 | 20 | 25;
|
||||
@@ -51,39 +55,10 @@ function SectionCard({ title, subtitle, children }: { title: string; subtitle?:
|
||||
);
|
||||
}
|
||||
|
||||
const NOTIFICATION_PREFS_KEY = "settings.notificationPrefs";
|
||||
|
||||
type NotificationPrefs = {
|
||||
emailFollowUpReminders: boolean;
|
||||
emailGhostedJobAlerts: boolean;
|
||||
inAppReminderHighlights: boolean;
|
||||
emailFollowUpRemindersEnabled: boolean;
|
||||
};
|
||||
|
||||
function loadNotificationPrefs(): NotificationPrefs {
|
||||
try {
|
||||
const raw = window.localStorage.getItem(NOTIFICATION_PREFS_KEY);
|
||||
if (!raw) {
|
||||
return {
|
||||
emailFollowUpReminders: true,
|
||||
emailGhostedJobAlerts: true,
|
||||
inAppReminderHighlights: true,
|
||||
};
|
||||
}
|
||||
return {
|
||||
emailFollowUpReminders: true,
|
||||
emailGhostedJobAlerts: true,
|
||||
inAppReminderHighlights: true,
|
||||
...JSON.parse(raw),
|
||||
};
|
||||
} catch {
|
||||
return {
|
||||
emailFollowUpReminders: true,
|
||||
emailGhostedJobAlerts: true,
|
||||
inAppReminderHighlights: true,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
export default function SettingsView({
|
||||
pageSize,
|
||||
onPageSizeChange,
|
||||
@@ -95,11 +70,31 @@ export default function SettingsView({
|
||||
const navigate = useNavigate();
|
||||
const [tab, setTab] = useState(0);
|
||||
const { language, setLanguage, t } = useI18n();
|
||||
const [notificationPrefs, setNotificationPrefs] = useState<NotificationPrefs>(() => loadNotificationPrefs());
|
||||
const { toast } = useToast();
|
||||
const [notificationPrefs, setNotificationPrefs] = useState<NotificationPrefs | null>(null);
|
||||
const [notificationError, setNotificationError] = useState<string | null>(null);
|
||||
const [savingNotifications, setSavingNotifications] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
window.localStorage.setItem(NOTIFICATION_PREFS_KEY, JSON.stringify(notificationPrefs));
|
||||
}, [notificationPrefs]);
|
||||
let active = true;
|
||||
api.get<NotificationPrefs>("/notification-settings")
|
||||
.then(({ data }) => { if (active) setNotificationPrefs(data); })
|
||||
.catch((error) => { if (active) setNotificationError(getApiErrorMessage(error, "Notification settings could not be loaded.")); });
|
||||
return () => { active = false; };
|
||||
}, []);
|
||||
|
||||
const saveNotifications = async () => {
|
||||
if (!notificationPrefs) return;
|
||||
setSavingNotifications(true);
|
||||
setNotificationError(null);
|
||||
try {
|
||||
const { data } = await api.put<NotificationPrefs>("/notification-settings", notificationPrefs);
|
||||
setNotificationPrefs(data);
|
||||
toast("Notification settings saved.", "success");
|
||||
} catch (error) {
|
||||
setNotificationError(getApiErrorMessage(error, "Notification settings could not be saved."));
|
||||
} finally { setSavingNotifications(false); }
|
||||
};
|
||||
|
||||
return (
|
||||
<Paper sx={{ mt: 0, p: 2.5, borderRadius: 4, border: "none", boxShadow: "0px 1px 2px 0px rgba(15,23,42,0.04), 0px 8px 24px -12px rgba(15,23,42,0.12)" }}>
|
||||
@@ -214,20 +209,15 @@ export default function SettingsView({
|
||||
|
||||
<TabPanel value={tab} index={2}>
|
||||
<SectionCard title={t("settingsNotificationsTitle")} subtitle={t("settingsNotificationsBody")}>
|
||||
<Box sx={{ display: "grid", gap: 1 }}>
|
||||
{notificationError ? <Alert severity="error" sx={{ mb: 1.5 }}>{notificationError}</Alert> : null}
|
||||
{!notificationPrefs ? <Skeleton variant="rounded" height={70} /> : <Box sx={{ display: "grid", gap: 1 }}>
|
||||
<FormControlLabel
|
||||
control={<Checkbox checked={notificationPrefs.emailFollowUpReminders} onChange={(e) => setNotificationPrefs((prev) => ({ ...prev, emailFollowUpReminders: e.target.checked }))} />}
|
||||
control={<Checkbox checked={notificationPrefs.emailFollowUpRemindersEnabled} onChange={(e) => setNotificationPrefs({ emailFollowUpRemindersEnabled: e.target.checked })} />}
|
||||
label={t("settingsNotificationsFollowUpReminders")}
|
||||
/>
|
||||
<FormControlLabel
|
||||
control={<Checkbox checked={notificationPrefs.emailGhostedJobAlerts} onChange={(e) => setNotificationPrefs((prev) => ({ ...prev, emailGhostedJobAlerts: e.target.checked }))} />}
|
||||
label={t("settingsNotificationsGhostedJobs")}
|
||||
/>
|
||||
<FormControlLabel
|
||||
control={<Checkbox checked={notificationPrefs.inAppReminderHighlights} onChange={(e) => setNotificationPrefs((prev) => ({ ...prev, inAppReminderHighlights: e.target.checked }))} />}
|
||||
label={t("settingsNotificationsInAppReminders")}
|
||||
/>
|
||||
</Box>
|
||||
<Typography variant="caption" color="text.secondary">Disabling this prevents the background reminder worker from sending follow-up email to your account. In-app reminders remain available.</Typography>
|
||||
<Box><Button variant="contained" disabled={savingNotifications} onClick={() => void saveNotifications()}>{savingNotifications ? "Saving…" : "Save notification settings"}</Button></Box>
|
||||
</Box>}
|
||||
<Typography variant="caption" sx={{ color: "text.secondary", display: "block", mt: 1.5 }}>
|
||||
{t("settingsNotificationsDelivery")}
|
||||
</Typography>
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import React, { createContext, useCallback, useContext, useMemo, useState } from "react";
|
||||
import React, { createContext, useCallback, useContext, useMemo, useRef, useState } from "react";
|
||||
import { Alert, Button, Dialog, DialogActions, DialogContent, DialogTitle, Typography } from "@mui/material";
|
||||
|
||||
type ConfirmOptions = {
|
||||
@@ -15,12 +15,12 @@ type ConfirmContextValue = {
|
||||
|
||||
type ConfirmState = ConfirmOptions & {
|
||||
open: boolean;
|
||||
resolver?: (value: boolean) => void;
|
||||
};
|
||||
|
||||
const ConfirmContext = createContext<ConfirmContextValue | null>(null);
|
||||
|
||||
export function ConfirmProvider({ children }: { children: React.ReactNode }) {
|
||||
const resolverRef = useRef<((value: boolean) => void) | null>(null);
|
||||
const [state, setState] = useState<ConfirmState>({
|
||||
open: false,
|
||||
message: "",
|
||||
@@ -31,14 +31,15 @@ export function ConfirmProvider({ children }: { children: React.ReactNode }) {
|
||||
});
|
||||
|
||||
const closeWith = useCallback((value: boolean) => {
|
||||
setState((prev) => {
|
||||
prev.resolver?.(value);
|
||||
return { ...prev, open: false, resolver: undefined };
|
||||
});
|
||||
const resolve = resolverRef.current;
|
||||
resolverRef.current = null;
|
||||
setState((prev) => ({ ...prev, open: false }));
|
||||
resolve?.(value);
|
||||
}, []);
|
||||
|
||||
const confirm = useCallback((options: ConfirmOptions) => {
|
||||
return new Promise<boolean>((resolve) => {
|
||||
resolverRef.current = resolve;
|
||||
setState({
|
||||
open: true,
|
||||
title: options.title ?? "Confirm action",
|
||||
@@ -46,7 +47,6 @@ export function ConfirmProvider({ children }: { children: React.ReactNode }) {
|
||||
confirmLabel: options.confirmLabel ?? "Confirm",
|
||||
cancelLabel: options.cancelLabel ?? "Cancel",
|
||||
destructive: options.destructive ?? false,
|
||||
resolver: resolve,
|
||||
});
|
||||
});
|
||||
}, []);
|
||||
|
||||
@@ -1,31 +1,50 @@
|
||||
import { useEffect, useState } from "react";
|
||||
|
||||
import { api } from "../api";
|
||||
import { AUTH_USER_CHANGED_EVENT, getAuthUserKey } from "../auth";
|
||||
import { Company } from "../types";
|
||||
import { useViewResource, ViewResourceError } from "./useViewResource";
|
||||
|
||||
let cachedCompanies: Company[] | null = null;
|
||||
let inflight: Promise<Company[]> | null = null;
|
||||
let cacheOwner = "";
|
||||
|
||||
function resetForOwner(owner: string) {
|
||||
if (cacheOwner === owner) return;
|
||||
cacheOwner = owner;
|
||||
cachedCompanies = null;
|
||||
inflight = null;
|
||||
}
|
||||
|
||||
function cachedForCurrentOwner() {
|
||||
const owner = getAuthUserKey();
|
||||
resetForOwner(owner);
|
||||
return cachedCompanies;
|
||||
}
|
||||
|
||||
async function fetchCompanies(): Promise<Company[]> {
|
||||
const owner = getAuthUserKey();
|
||||
resetForOwner(owner);
|
||||
if (cachedCompanies) return cachedCompanies;
|
||||
if (inflight) return inflight;
|
||||
|
||||
inflight = api
|
||||
const request = api
|
||||
.get<Company[]>('/companies')
|
||||
.then((r) => {
|
||||
cachedCompanies = r.data;
|
||||
if (cacheOwner === owner && getAuthUserKey() === owner) cachedCompanies = r.data;
|
||||
return r.data;
|
||||
})
|
||||
.finally(() => {
|
||||
inflight = null;
|
||||
if (inflight === request) inflight = null;
|
||||
});
|
||||
inflight = request;
|
||||
|
||||
return inflight;
|
||||
}
|
||||
|
||||
export function invalidateCompaniesCache() {
|
||||
cachedCompanies = null;
|
||||
inflight = null;
|
||||
}
|
||||
|
||||
export function useCompanies(): {
|
||||
@@ -37,7 +56,7 @@ export function useCompanies(): {
|
||||
} {
|
||||
const [cacheBust, setCacheBust] = useState(0);
|
||||
const resource = useViewResource(fetchCompanies, {
|
||||
initialData: cachedCompanies ?? [],
|
||||
initialData: cachedForCurrentOwner() ?? [],
|
||||
errorMessage: 'Unable to load companies right now.',
|
||||
deps: [cacheBust],
|
||||
});
|
||||
@@ -48,6 +67,15 @@ export function useCompanies(): {
|
||||
}
|
||||
}, [resource.data, resource.error]);
|
||||
|
||||
useEffect(() => {
|
||||
const reloadForAccount = () => {
|
||||
resetForOwner(getAuthUserKey());
|
||||
setCacheBust((value) => value + 1);
|
||||
};
|
||||
window.addEventListener(AUTH_USER_CHANGED_EVENT, reloadForAccount);
|
||||
return () => window.removeEventListener(AUTH_USER_CHANGED_EVENT, reloadForAccount);
|
||||
}, []);
|
||||
|
||||
return {
|
||||
companies: resource.data,
|
||||
loading: resource.loading,
|
||||
|
||||
@@ -66,6 +66,7 @@ export function useViewResource<T>(
|
||||
const [error, setError] = useState<ViewResourceError | null>(null);
|
||||
const hasLoadedRef = useRef(hasLoaded);
|
||||
const loadRef = useRef(load);
|
||||
const requestSequence = useRef(0);
|
||||
|
||||
useEffect(() => {
|
||||
hasLoadedRef.current = hasLoaded;
|
||||
@@ -78,18 +79,22 @@ export function useViewResource<T>(
|
||||
const reload = useCallback(async () => {
|
||||
if (!enabled) return;
|
||||
|
||||
const requestId = ++requestSequence.current;
|
||||
const alreadyLoaded = hasLoadedRef.current;
|
||||
setLoading(!alreadyLoaded);
|
||||
setRefreshing(alreadyLoaded);
|
||||
try {
|
||||
const next = await loadRef.current();
|
||||
if (requestId !== requestSequence.current) return;
|
||||
setData(next);
|
||||
setError(null);
|
||||
setHasLoaded(true);
|
||||
} catch (err: any) {
|
||||
if (requestId !== requestSequence.current) return;
|
||||
setError(normalizeError(err, errorMessage));
|
||||
setHasLoaded(true);
|
||||
} finally {
|
||||
if (requestId !== requestSequence.current) return;
|
||||
setLoading(false);
|
||||
setRefreshing(false);
|
||||
}
|
||||
@@ -97,6 +102,7 @@ export function useViewResource<T>(
|
||||
|
||||
useEffect(() => {
|
||||
if (!enabled) {
|
||||
requestSequence.current += 1;
|
||||
setLoading(false);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -27,7 +27,7 @@ const mockedApi = api as jest.Mocked<typeof api>;
|
||||
|
||||
function renderView() {
|
||||
return render(
|
||||
<MemoryRouter future={{ v7_startTransition: true, v7_relativeSplatPath: true }}>
|
||||
<MemoryRouter>
|
||||
<ToastProvider>
|
||||
<I18nProvider>
|
||||
<SettingsView
|
||||
@@ -83,6 +83,7 @@ beforeEach(() => {
|
||||
},
|
||||
} as any);
|
||||
}
|
||||
if (url === '/notification-settings') return Promise.resolve({ data: { emailFollowUpRemindersEnabled: true } } as any);
|
||||
return Promise.resolve({ data: {} } as any);
|
||||
});
|
||||
window.localStorage.clear();
|
||||
@@ -110,11 +111,14 @@ test('settings view has no accent picker and uses one follow-up section, one not
|
||||
expect(screen.queryAllByText(/open reminders/i)).toHaveLength(0);
|
||||
|
||||
fireEvent.click(screen.getByRole('tab', { name: /notifications/i }));
|
||||
expect(screen.getByText(/notification settings/i)).toBeInTheDocument();
|
||||
expect(screen.getByText(/^notification settings$/i)).toBeInTheDocument();
|
||||
// SMTP status now lives under Admin → System → Settings (the old "check system status" link was removed).
|
||||
expect(screen.getAllByText(/smtp delivery and test mail live under/i).length).toBe(1);
|
||||
expect(screen.getByLabelText(/email reminders for follow-ups/i)).toBeInTheDocument();
|
||||
expect(screen.getByLabelText(/email alerts for ghosted jobs/i)).toBeInTheDocument();
|
||||
expect(screen.queryByLabelText(/email alerts for ghosted jobs/i)).not.toBeInTheDocument();
|
||||
fireEvent.click(screen.getByLabelText(/email reminders for follow-ups/i));
|
||||
fireEvent.click(screen.getByRole('button', { name: /save notification settings/i }));
|
||||
expect(mockedApi.put).toHaveBeenCalledWith('/notification-settings', { emailFollowUpRemindersEnabled: false });
|
||||
});
|
||||
|
||||
test('AI privacy settings are server-backed and external processing is local-only by default', async () => {
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
import React from "react";
|
||||
import "@testing-library/jest-dom";
|
||||
import { act, render, screen } from "@testing-library/react";
|
||||
|
||||
import { useViewResource } from "./hooks/useViewResource";
|
||||
|
||||
function deferred<T>() {
|
||||
let resolve!: (value: T) => void;
|
||||
const promise = new Promise<T>((next) => { resolve = next; });
|
||||
return { promise, resolve };
|
||||
}
|
||||
|
||||
it("ignores an older request that completes after a newer dependency load", async () => {
|
||||
const first = deferred<string>();
|
||||
const second = deferred<string>();
|
||||
const load = jest.fn((key: string) => key === "first" ? first.promise : second.promise);
|
||||
|
||||
function Probe({ query }: { query: string }) {
|
||||
const resource = useViewResource(() => load(query), {
|
||||
initialData: "empty",
|
||||
errorMessage: "Unable to load.",
|
||||
deps: [query],
|
||||
});
|
||||
return <div>{resource.data}</div>;
|
||||
}
|
||||
|
||||
const view = render(<Probe query="first" />);
|
||||
view.rerender(<Probe query="second" />);
|
||||
|
||||
await act(async () => { second.resolve("new result"); });
|
||||
expect(screen.getByText("new result")).toBeInTheDocument();
|
||||
|
||||
await act(async () => { first.resolve("stale result"); });
|
||||
expect(screen.getByText("new result")).toBeInTheDocument();
|
||||
expect(screen.queryByText("stale result")).not.toBeInTheDocument();
|
||||
});
|
||||
@@ -30,6 +30,7 @@ import {
|
||||
} from "../components/ApplicationAssets";
|
||||
import { ApplicationInterviewPrep } from "../components/InterviewPrep";
|
||||
import EditJobDialog from "../components/EditJobDialog";
|
||||
import { ApplicationStatusSuggestion, ApplicationStrategySnapshot } from "../components/ApplicationWorkflowAssist";
|
||||
import { useConfirm } from "../confirm";
|
||||
import {
|
||||
WORKSPACE_SECTIONS, WorkspaceOverview, WorkspaceSectionKey, applicationWorkspaceApi, workspaceSection,
|
||||
@@ -189,10 +190,12 @@ export function ApplicationWorkspace({
|
||||
|
||||
<Box sx={{ display: "grid", gap: 2 }}>
|
||||
<WorkspaceHeader overview={overview} onEdit={() => setEditOpen(true)} />
|
||||
{section === "overview" && jobId > 0 && <ApplicationStatusSuggestion jobId={jobId} onApplied={load} />}
|
||||
{section === "overview" && <OverviewSection overview={overview} onGo={go} onReload={load} />}
|
||||
{section === "job-details" && <JobDetailsSection overview={overview} onEdit={() => setEditOpen(true)} />}
|
||||
{/* Deterministic answer first, then the AI panel below it — the page never generates on load. */}
|
||||
{section === "analysis" && jobId > 0 && <ApplicationAnalysis jobId={jobId} />}
|
||||
{section === "analysis" && jobId > 0 && <ApplicationStrategySnapshot jobId={jobId} />}
|
||||
{section === "match" && jobId > 0 && <ApplicationMatch jobId={jobId} />}
|
||||
{section === "timeline" && jobId > 0 && <ApplicationTimeline jobId={jobId} />}
|
||||
{section === "interview" && jobId > 0 && <ApplicationInterviewPrep jobId={jobId} />}
|
||||
|
||||
@@ -27,6 +27,7 @@ import {
|
||||
StructuredCvProfile,
|
||||
} from "../profileCv";
|
||||
import { JobApplication } from "../types";
|
||||
import { getUserScopedStorageKey } from "../auth";
|
||||
|
||||
|
||||
type CvSectionOption = "" | "Professional Summary" | "Core Skills" | "Experience Highlights" | "Selected Achievements" | "Projects";
|
||||
@@ -273,7 +274,9 @@ export default function ProfilePage() {
|
||||
setLastName(r.data?.lastName ?? "");
|
||||
setDisplayName(r.data?.displayName ?? "");
|
||||
setProfileCvText(r.data?.profileCvText ?? "");
|
||||
setHeadline(window.localStorage.getItem("profileHeadline") ?? "");
|
||||
const persistedHeadline = parseStructuredCvJson(r.data?.profileCvStructureJson).contact.headline;
|
||||
const userKey = r.data?.id || r.data?.email || r.data?.userName || "anon";
|
||||
setHeadline(persistedHeadline ?? window.localStorage.getItem(getUserScopedStorageKey("profileHeadline", userKey)) ?? "");
|
||||
if (r.data?.provider === "local") {
|
||||
const pending = await api.get<PendingEmailChange>("/auth/email-change");
|
||||
setPendingEmail(pending.data?.pendingEmail ?? null);
|
||||
@@ -489,7 +492,8 @@ export default function ProfilePage() {
|
||||
// /profile saves identity only. The backend does partial updates, so omitting the
|
||||
// master-profile fields leaves them untouched (they are owned by /career).
|
||||
await api.put("/auth/profile", { userName, firstName, lastName, displayName });
|
||||
window.localStorage.setItem("profileHeadline", headline.trim());
|
||||
const userKey = me?.id || me?.email || me?.userName;
|
||||
if (userKey) window.localStorage.setItem(getUserScopedStorageKey("profileHeadline", userKey), headline.trim());
|
||||
await loadProfile();
|
||||
toast(t("profileUpdated"), "success");
|
||||
} catch (e: any) {
|
||||
|
||||
@@ -70,10 +70,18 @@ function buildJob(overrides: Partial<JobApplication>): JobApplication {
|
||||
}
|
||||
|
||||
function setupApiMocks({ reminders, jobs }: { reminders?: JobApplication[]; jobs?: JobApplication[] }) {
|
||||
mockedApi.get.mockImplementation((url: string) => {
|
||||
mockedApi.get.mockImplementation((url: string, config?: any) => {
|
||||
if (url === '/companies') return Promise.resolve({ data: [{ id: 1, name: 'Acme' }, { id: 2, name: 'Beta' }] } as any);
|
||||
if (url === '/jobapplications/reminders') return Promise.resolve({ data: reminders ?? [] } as any);
|
||||
if (url === '/jobapplications') return Promise.resolve({ data: { items: jobs ?? [], total: jobs?.length ?? 0, page: 1, pageSize: 15 } } as any);
|
||||
if (url === '/jobapplications') {
|
||||
const readiness = config?.params?.readiness;
|
||||
const filtered = (jobs ?? []).filter((job) => readiness === 'interview'
|
||||
? job.workflowSignal?.needsInterviewPrep
|
||||
: readiness === 'needs-work'
|
||||
? job.workflowSignal?.hasPackageGap || job.workflowSignal?.needsInterviewPrep
|
||||
: true);
|
||||
return Promise.resolve({ data: { items: filtered, total: filtered.length, page: 1, pageSize: 15 } } as any);
|
||||
}
|
||||
if (url === '/jobapplications/stats') return Promise.resolve({ data: { total: reminders?.length ?? 0, active: reminders?.length ?? 0, deleted: 0, byStatus: {}, appliedLast30Days: reminders?.length ?? 0, averageDaysSinceApplied: 7 } } as any);
|
||||
if (url === '/jobapplications/analytics-overview') return Promise.resolve({ data: { funnel: [], responseRateBySource: [], topCompanies: [], totalResponses: 1, totalActive: reminders?.length ?? 0 } } as any);
|
||||
if (url === '/jobapplications/analytics' || url === '/jobapplications/tags') return Promise.resolve({ data: [] } as any);
|
||||
@@ -270,5 +278,8 @@ test('job table readiness filter follows workflow signals instead of raw notes o
|
||||
fireEvent.click(await screen.findByRole('option', { name: /needs work/i }));
|
||||
|
||||
expect(await screen.findByText(/application engineer/i)).toBeInTheDocument();
|
||||
expect(screen.queryByText(/operations analyst/i)).not.toBeInTheDocument();
|
||||
await waitFor(() => expect(screen.queryByText(/operations analyst/i)).not.toBeInTheDocument());
|
||||
expect(mockedApi.get).toHaveBeenCalledWith('/jobapplications', expect.objectContaining({
|
||||
params: expect.objectContaining({ readiness: 'needs-work' }),
|
||||
}));
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user