feat(discovery): add saved job searches

This commit is contained in:
cesnimda
2026-08-31 17:17:48 +02:00
parent 78ad0c66f9
commit c2181afaea
13 changed files with 461 additions and 80 deletions
+34
View File
@@ -274,6 +274,23 @@ export const translations = {
jobDiscoveryWorkArrangementMissing: "Work arrangement not provided by this source",
jobDiscoveryViewListing: "View listing",
jobDiscoverySaveTracker: "Save to tracker",
jobDiscoverySavedSearches: "Saved searches",
jobDiscoverySavedSearchesHelp: "Run a saved NAV search to see which vacancies are genuinely new since your last check.",
jobDiscoverySavedName: "Search name",
jobDiscoverySavedDefaultName: "Recent vacancies",
jobDiscoverySaveSearch: "Save search",
jobDiscoveryNoSavedSearches: "No saved searches yet.",
jobDiscoverySaveSearchFailed: "The search could not be saved.",
jobDiscoveryDeleteSavedTitle: "Delete saved search?",
jobDiscoveryDeleteSavedConfirm: "Delete “{name}” and its seen/dismissed history?",
jobDiscoveryDeleteSavedFailed: "The saved search could not be deleted.",
jobDiscoveryDismissFailed: "The vacancy could not be dismissed.",
jobDiscoveryAllRecent: "All recent vacancies",
jobDiscoveryLastRun: "Last checked {date}",
jobDiscoveryTrackedCount: "{count} tracked",
jobDiscoveryRunSaved: "Check for new jobs",
jobDiscoveryNewResult: "New",
jobDiscoveryDismiss: "Dismiss",
jobDetails: "Job details",
jobDetailsWorkspaceSubtitle: "Manage this application, its documents, timeline, and correspondence.",
operations: "Operations",
@@ -2632,6 +2649,23 @@ export const translations = {
jobDiscoveryWorkArrangementMissing: "Arbeidsform er ikke oppgitt av kilden",
jobDiscoveryViewListing: "Vis stilling",
jobDiscoverySaveTracker: "Lagre i oversikten",
jobDiscoverySavedSearches: "Lagrede søk",
jobDiscoverySavedSearchesHelp: "Kjør et lagret NAV-søk for å se hvilke stillinger som faktisk er nye siden sist.",
jobDiscoverySavedName: "Navn på søket",
jobDiscoverySavedDefaultName: "Nylige stillinger",
jobDiscoverySaveSearch: "Lagre søk",
jobDiscoveryNoSavedSearches: "Ingen lagrede søk ennå.",
jobDiscoverySaveSearchFailed: "Søket kunne ikke lagres.",
jobDiscoveryDeleteSavedTitle: "Slette lagret søk?",
jobDiscoveryDeleteSavedConfirm: "Slette «{name}» og historikken over viste og avviste stillinger?",
jobDiscoveryDeleteSavedFailed: "Det lagrede søket kunne ikke slettes.",
jobDiscoveryDismissFailed: "Stillingen kunne ikke avvises.",
jobDiscoveryAllRecent: "Alle nylige stillinger",
jobDiscoveryLastRun: "Sist sjekket {date}",
jobDiscoveryTrackedCount: "{count} fulgt",
jobDiscoveryRunSaved: "Se etter nye stillinger",
jobDiscoveryNewResult: "Ny",
jobDiscoveryDismiss: "Avvis",
jobDetails: "Jobbdetaljer",
jobDetailsWorkspaceSubtitle: "Administrer søknaden, dokumentene, tidslinjen og korrespondansen.",
operations: "Operasjoner",
+34 -21
View File
@@ -3,26 +3,30 @@ import "@testing-library/jest-dom";
import { fireEvent, render, screen, waitFor } from "@testing-library/react";
import { MemoryRouter } from "react-router-dom";
import { api } from "./api";
import { ConfirmProvider } from "./confirm";
import { PromptProvider } from "./prompt";
import { I18nProvider } from "./i18n/I18nProvider";
import JobDiscoveryPage from "./views/JobDiscoveryPage";
jest.mock("./api", () => ({ api: { get: jest.fn() } }));
jest.mock("./api", () => ({ api: { get: jest.fn(), post: jest.fn(), patch: jest.fn(), delete: jest.fn() } }));
const mockedApi = api as jest.Mocked<typeof api>;
function renderPage() {
return render(<I18nProvider><MemoryRouter><JobDiscoveryPage /></MemoryRouter></I18nProvider>);
return render(<I18nProvider><ConfirmProvider><PromptProvider><MemoryRouter><JobDiscoveryPage /></MemoryRouter></PromptProvider></ConfirmProvider></I18nProvider>);
}
beforeEach(() => window.localStorage.clear());
function searchResponse(data: any[]) {
mockedApi.get.mockImplementation((url) => Promise.resolve({ data: String(url).endsWith("saved-searches") ? [] : data } as any));
}
beforeEach(() => { window.localStorage.clear(); searchResponse([]); });
afterEach(() => jest.clearAllMocks());
test("shows honest source metadata and offers the existing reviewed save flow", async () => {
mockedApi.get.mockResolvedValue({ data: [{ id: "abc", title: "Backend Developer", company: "Acme", location: "OSLO", modifiedAt: "2026-08-01T10:00:00Z", deadline: "2026-08-15T23:59:59Z", url: "https://arbeidsplassen.nav.no/stillinger/stilling/abc", source: "nav", sourceName: "NAV Arbeidsplassen", acquisitionType: "searched", retrievedAt: "2026-08-10T10:00:00Z", countryCode: "NO" }] } as any);
searchResponse([{ id: "abc", title: "Backend Developer", company: "Acme", location: "OSLO", modifiedAt: "2026-08-01T10:00:00Z", deadline: "2026-08-15T23:59:59Z", url: "https://arbeidsplassen.nav.no/stillinger/stilling/abc", source: "nav", sourceName: "NAV Arbeidsplassen", acquisitionType: "searched", retrievedAt: "2026-08-10T10:00:00Z", countryCode: "NO" }]);
renderPage();
fireEvent.change(screen.getByLabelText("Role or company"), { target: { value: "backend" } });
fireEvent.click(screen.getByRole("button", { name: "Search NAV" }));
expect(await screen.findByText("Backend Developer")).toBeInTheDocument();
expect(screen.getByText("NAV Arbeidsplassen")).toBeInTheDocument();
expect(screen.getByText(/Searched listing · Retrieved/)).toBeInTheDocument();
@@ -32,51 +36,60 @@ test("shows honest source metadata and offers the existing reviewed save flow",
});
test("distinguishes the initial guidance from a completed empty search", async () => {
mockedApi.get.mockResolvedValue({ data: [] } as any);
renderPage();
expect(screen.getByText("Search recent active vacancies by role, company, or municipality.")).toBeInTheDocument();
fireEvent.click(screen.getByRole("button", { name: "Search NAV" }));
expect(await screen.findByText(/No active vacancies matched this search/)).toBeInTheDocument();
expect(screen.queryByText("Search recent active vacancies by role, company, or municipality.")).not.toBeInTheDocument();
});
test("retries the last submitted search after an error", async () => {
mockedApi.get.mockRejectedValueOnce(new Error("offline")).mockResolvedValueOnce({ data: [] } as any);
let searchAttempts = 0;
mockedApi.get.mockImplementation((url) => {
if (String(url).endsWith("saved-searches")) return Promise.resolve({ data: [] } as any);
searchAttempts += 1;
return searchAttempts === 1 ? Promise.reject(new Error("offline")) : Promise.resolve({ data: [] } as any);
});
renderPage();
fireEvent.change(screen.getByLabelText("Role or company"), { target: { value: " utvikler " } });
fireEvent.change(screen.getByLabelText("Municipality"), { target: { value: " Oslo " } });
fireEvent.click(screen.getByRole("button", { name: "Search NAV" }));
fireEvent.click(await screen.findByRole("button", { name: "Retry" }));
await waitFor(() => expect(mockedApi.get).toHaveBeenCalledTimes(2));
await waitFor(() => expect(searchAttempts).toBe(2));
expect(mockedApi.get).toHaveBeenLastCalledWith("/job-discovery/search", { params: { q: "utvikler", location: "Oslo" } });
});
test("sorts returned vacancies by title", async () => {
mockedApi.get.mockResolvedValue({ data: [
searchResponse([
{ id: "2", title: "Zoologist", url: "https://arbeidsplassen.nav.no/2", source: "nav", countryCode: "NO" },
{ id: "1", title: "Analyst", url: "https://arbeidsplassen.nav.no/1", source: "nav", countryCode: "NO" },
] } as any);
]);
renderPage();
fireEvent.click(screen.getByRole("button", { name: "Search NAV" }));
await screen.findByText("2 vacancies found");
fireEvent.mouseDown(screen.getByRole("combobox", { name: "Sort results" }));
fireEvent.click(await screen.findByRole("option", { name: "Title AZ" }));
const titles = screen.getAllByRole("heading", { level: 6 }).map((element) => element.textContent);
expect(titles).toEqual(["Analyst", "Zoologist"]);
expect(screen.getAllByRole("heading", { level: 6 }).map((element) => element.textContent)).toEqual(["Analyst", "Zoologist"]);
});
test("renders the discovery workflow in Norwegian Bokmål", async () => {
window.localStorage.setItem("uiLanguage", "nb");
mockedApi.get.mockResolvedValue({ data: [] } as any);
renderPage();
expect(screen.getByLabelText("Rolle eller bedrift")).toBeInTheDocument();
fireEvent.click(screen.getByRole("button", { name: "Søk i NAV" }));
expect(await screen.findByText(/Ingen aktive stillinger samsvarte/)).toBeInTheDocument();
});
test("runs a saved search, marks unseen vacancies, and dismisses them", async () => {
const saved = { id: 7, name: "Backend Oslo", query: "backend", location: "Oslo", resultCount: 0, dismissedCount: 0 };
mockedApi.get.mockResolvedValue({ data: [saved] } as any);
mockedApi.post.mockResolvedValue({ data: { search: { ...saved, resultCount: 1 }, jobs: [{ job: { id: "new-1", title: "Platform Engineer", url: "https://example.test/new-1", source: "nav", countryCode: "NO" }, isNew: true, isDismissed: false }] } } as any);
mockedApi.patch.mockResolvedValue({ data: null } as any);
renderPage();
fireEvent.click(await screen.findByRole("button", { name: "Check for new jobs" }));
expect(await screen.findByText("Platform Engineer")).toBeInTheDocument();
expect(screen.getByText("New")).toBeInTheDocument();
fireEvent.click(screen.getByRole("button", { name: "Dismiss" }));
await waitFor(() => expect(screen.queryByText("Platform Engineer")).not.toBeInTheDocument());
expect(mockedApi.patch).toHaveBeenCalledWith("/job-discovery/saved-searches/7/results/new-1/dismiss", { isDismissed: true });
});
+95 -2
View File
@@ -1,10 +1,14 @@
import { FormEvent, useMemo, useState } from "react";
import { FormEvent, useEffect, useMemo, useState } from "react";
import { Alert, Box, Button, Card, CardActions, CardContent, Chip, CircularProgress, MenuItem, Stack, TextField, Typography } from "@mui/material";
import SearchIcon from "@mui/icons-material/Search";
import AddIcon from "@mui/icons-material/Add";
import BookmarkAddOutlinedIcon from "@mui/icons-material/BookmarkAddOutlined";
import DeleteOutlineIcon from "@mui/icons-material/DeleteOutline";
import RefreshIcon from "@mui/icons-material/Refresh";
import { useNavigate } from "react-router-dom";
import { api } from "../api";
import { useI18n } from "../i18n/I18nProvider";
import { useDialogActions } from "../dialogs";
type DiscoveredJob = {
id: string;
@@ -19,13 +23,18 @@ type DiscoveredJob = {
acquisitionType?: string;
retrievedAt?: string;
countryCode: string;
isNew?: boolean;
};
type SavedSearch = { id: number; name: string; query: string; location: string; lastRunAtUtc?: string; resultCount: number; dismissedCount: number };
type SavedSearchRun = { search: SavedSearch; jobs: Array<{ job: DiscoveredJob; isNew: boolean; isDismissed: boolean }> };
type SortOrder = "updated" | "deadline" | "title";
export default function JobDiscoveryPage() {
const navigate = useNavigate();
const { language, t } = useI18n();
const { confirmAction } = useDialogActions();
const [query, setQuery] = useState("");
const [location, setLocation] = useState("");
const [jobs, setJobs] = useState<DiscoveredJob[]>([]);
@@ -34,6 +43,18 @@ export default function JobDiscoveryPage() {
const [hasSearched, setHasSearched] = useState(false);
const [lastSearch, setLastSearch] = useState({ query: "", location: "" });
const [sortOrder, setSortOrder] = useState<SortOrder>("updated");
const [savedSearches, setSavedSearches] = useState<SavedSearch[]>([]);
const [savedName, setSavedName] = useState("");
const [savingSearch, setSavingSearch] = useState(false);
const [activeSavedSearchId, setActiveSavedSearchId] = useState<number | null>(null);
useEffect(() => {
let active = true;
api.get<SavedSearch[]>("/job-discovery/saved-searches")
.then((response) => { if (active) setSavedSearches(Array.isArray(response.data) ? response.data : []); })
.catch(() => { /* One-off discovery remains usable if saved-search storage is unavailable. */ });
return () => { active = false; };
}, []);
const runSearch = async (nextQuery: string, nextLocation: string) => {
setLoading(true); setError(""); setJobs([]); setHasSearched(true); setLastSearch({ query: nextQuery, location: nextLocation });
@@ -49,6 +70,47 @@ export default function JobDiscoveryPage() {
void runSearch(query.trim(), location.trim());
};
const saveSearch = async () => {
const name = savedName.trim() || query.trim() || location.trim() || t("jobDiscoverySavedDefaultName");
setSavingSearch(true); setError("");
try {
const response = await api.post<SavedSearch>("/job-discovery/saved-searches", { name, query: query.trim(), location: location.trim() });
setSavedSearches((current) => [response.data, ...current]);
setSavedName("");
} catch { setError(t("jobDiscoverySaveSearchFailed")); }
finally { setSavingSearch(false); }
};
const runSavedSearch = async (saved: SavedSearch) => {
setLoading(true); setError(""); setHasSearched(true); setActiveSavedSearchId(saved.id);
setQuery(saved.query); setLocation(saved.location); setLastSearch({ query: saved.query, location: saved.location });
try {
const response = await api.post<SavedSearchRun>(`/job-discovery/saved-searches/${saved.id}/run`);
const visible = response.data.jobs.filter((item) => !item.isDismissed).map((item) => ({ ...item.job, isNew: item.isNew }));
setJobs(visible);
setSavedSearches((current) => current.map((item) => item.id === saved.id ? response.data.search : item));
} catch { setError(t("jobDiscoveryUnavailable")); }
finally { setLoading(false); }
};
const deleteSavedSearch = async (saved: SavedSearch) => {
if (!(await confirmAction(t("jobDiscoveryDeleteSavedConfirm", { name: saved.name }), { title: t("jobDiscoveryDeleteSavedTitle"), confirmLabel: t("adminUsersDelete"), destructive: true }))) return;
try {
await api.delete(`/job-discovery/saved-searches/${saved.id}`);
setSavedSearches((current) => current.filter((item) => item.id !== saved.id));
if (activeSavedSearchId === saved.id) setActiveSavedSearchId(null);
} catch { setError(t("jobDiscoveryDeleteSavedFailed")); }
};
const dismissJob = async (jobId: string) => {
if (activeSavedSearchId === null) return;
try {
await api.patch(`/job-discovery/saved-searches/${activeSavedSearchId}/results/${encodeURIComponent(jobId)}/dismiss`, { isDismissed: true });
setJobs((current) => current.filter((item) => item.id !== jobId));
setSavedSearches((current) => current.map((item) => item.id === activeSavedSearchId ? { ...item, dismissedCount: item.dismissedCount + 1 } : item));
} catch { setError(t("jobDiscoveryDismissFailed")); }
};
const sortedJobs = useMemo(() => [...jobs].sort((left, right) => {
if (sortOrder === "title") return left.title.localeCompare(right.title);
if (sortOrder === "deadline") {
@@ -67,6 +129,33 @@ export default function JobDiscoveryPage() {
<TextField label={t("jobDiscoveryMunicipality")} value={location} onChange={(event) => setLocation(event.target.value)} />
<Button type="submit" variant="contained" startIcon={loading ? <CircularProgress size={18} color="inherit" /> : <SearchIcon />} disabled={loading}>{t("jobDiscoverySearchNav")}</Button>
</Box>
<Card variant="outlined">
<CardContent sx={{ display: "grid", gap: 1.5 }}>
<Box>
<Typography component="h2" variant="h6" sx={{ fontWeight: 800 }}>{t("jobDiscoverySavedSearches")}</Typography>
<Typography variant="body2" color="text.secondary">{t("jobDiscoverySavedSearchesHelp")}</Typography>
</Box>
<Box sx={{ display: "grid", gridTemplateColumns: { xs: "1fr", sm: "minmax(0, 1fr) auto" }, gap: 1 }}>
<TextField size="small" label={t("jobDiscoverySavedName")} value={savedName} onChange={(event) => setSavedName(event.target.value)} />
<Button variant="outlined" startIcon={<BookmarkAddOutlinedIcon />} onClick={() => void saveSearch()} disabled={savingSearch}>{t("jobDiscoverySaveSearch")}</Button>
</Box>
{savedSearches.length === 0 ? <Typography variant="body2" color="text.secondary">{t("jobDiscoveryNoSavedSearches")}</Typography> : (
<Stack spacing={1}>
{savedSearches.map((saved) => (
<Box key={saved.id} sx={{ display: "flex", flexWrap: "wrap", alignItems: "center", gap: 1, p: 1.25, border: 1, borderColor: activeSavedSearchId === saved.id ? "primary.main" : "divider", borderRadius: 2 }}>
<Box sx={{ flex: "1 1 220px", minWidth: 0 }}>
<Typography sx={{ fontWeight: 700 }}>{saved.name}</Typography>
<Typography variant="caption" color="text.secondary">{[saved.query, saved.location].filter(Boolean).join(" · ") || t("jobDiscoveryAllRecent")}{saved.lastRunAtUtc ? ` · ${t("jobDiscoveryLastRun", { date: formatDate(saved.lastRunAtUtc) ?? "" })}` : ""}</Typography>
</Box>
<Chip size="small" label={t("jobDiscoveryTrackedCount", { count: saved.resultCount })} />
<Button size="small" startIcon={<RefreshIcon />} onClick={() => void runSavedSearch(saved)} disabled={loading}>{t("jobDiscoveryRunSaved")}</Button>
<Button size="small" color="error" startIcon={<DeleteOutlineIcon />} onClick={() => void deleteSavedSearch(saved)}>{t("adminUsersDelete")}</Button>
</Box>
))}
</Stack>
)}
</CardContent>
</Card>
<Alert severity="info" variant="outlined" sx={{ color: "text.primary", "& .MuiAlert-icon": { color: "info.main" } }}>{t("jobDiscoverySourceHelp")}</Alert>
{error ? <Alert severity="error" variant="outlined" sx={{ color: "text.primary" }} action={<Button color="inherit" onClick={() => void runSearch(lastSearch.query, lastSearch.location)} disabled={loading}>{t("retry")}</Button>}>{error}</Alert> : null}
{!loading && !hasSearched ? <Typography color="text.secondary">{t("jobDiscoveryGuidance")}</Typography> : null}
@@ -86,7 +175,10 @@ export default function JobDiscoveryPage() {
{sortedJobs.map((job) => (
<Card key={job.id} variant="outlined" sx={{ display: "flex", flexDirection: "column" }}>
<CardContent>
<Chip label={job.sourceName || job.source.toUpperCase()} size="small" color="primary" variant="outlined" sx={{ mb: 1 }} />
<Stack direction="row" spacing={1} sx={{ mb: 1 }}>
<Chip label={job.sourceName || job.source.toUpperCase()} size="small" color="primary" variant="outlined" />
{job.isNew ? <Chip label={t("jobDiscoveryNewResult")} size="small" color="success" /> : null}
</Stack>
<Typography variant="h6" sx={{ fontWeight: 800 }}>{job.title}</Typography>
<Typography color="text.secondary">{[job.company, job.location || t("jobDiscoveryLocationMissing")].filter(Boolean).join(" · ")}</Typography>
<Stack spacing={0.25} sx={{ mt: 1 }}>
@@ -102,6 +194,7 @@ export default function JobDiscoveryPage() {
<CardActions sx={{ mt: "auto" }}>
<Button href={job.url} target="_blank" rel="noreferrer">{t("jobDiscoveryViewListing")}</Button>
<Button startIcon={<AddIcon />} onClick={() => navigate("/jobs?add=" + encodeURIComponent(job.url))}>{t("jobDiscoverySaveTracker")}</Button>
{activeSavedSearchId !== null ? <Button color="inherit" onClick={() => void dismissJob(job.id)}>{t("jobDiscoveryDismiss")}</Button> : null}
</CardActions>
</Card>
))}