fix(app): harden account and workflow state

This commit is contained in:
cesnimda
2026-08-24 20:21:09 +02:00
parent e7cacad7d6
commit dca5daa1a2
32 changed files with 811 additions and 86 deletions
@@ -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>
);
}
+8 -9
View File
@@ -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]);
+34 -44
View File
@@ -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>