feat(ui): migrate discovery search and recovery
This commit is contained in:
@@ -1,4 +1,4 @@
|
||||
import { FormEvent, useEffect, useMemo, useState } from "react";
|
||||
import { FormEvent, useEffect, useMemo, useRef, useState } from "react";
|
||||
import { Alert, Box, Button, Card, CardActions, CardContent, Chip, CircularProgress, FormControlLabel, MenuItem, Stack, Switch, TextField, Typography } from "@mui/material";
|
||||
import SearchIcon from "@mui/icons-material/Search";
|
||||
import AddIcon from "@mui/icons-material/Add";
|
||||
@@ -9,6 +9,9 @@ import { useNavigate } from "react-router-dom";
|
||||
import { api } from "../api";
|
||||
import { useI18n } from "../i18n/I18nProvider";
|
||||
import { useDialogActions } from "../dialogs";
|
||||
import type { TranslationKey } from "../i18n/translations";
|
||||
import { PageHeader } from "../layout/PageLayout";
|
||||
import ViewStateNotice from "../components/ViewStateNotice";
|
||||
|
||||
type DiscoveredJob = {
|
||||
id: string;
|
||||
@@ -39,9 +42,9 @@ export default function JobDiscoveryPage() {
|
||||
const [location, setLocation] = useState("");
|
||||
const [jobs, setJobs] = useState<DiscoveredJob[]>([]);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [error, setError] = useState("");
|
||||
const [error, setError] = useState<TranslationKey | null>(null);
|
||||
const [hasSearched, setHasSearched] = useState(false);
|
||||
const [lastSearch, setLastSearch] = useState({ query: "", location: "" });
|
||||
const [lastSearch, setLastSearch] = useState<{ query: string; location: string; saved?: SavedSearch }>({ query: "", location: "" });
|
||||
const [sortOrder, setSortOrder] = useState<SortOrder>("updated");
|
||||
const [savedSearches, setSavedSearches] = useState<SavedSearch[]>([]);
|
||||
const [savedSearchState, setSavedSearchState] = useState<"loading" | "loaded" | "error">("loading");
|
||||
@@ -50,6 +53,17 @@ export default function JobDiscoveryPage() {
|
||||
const [savingSearch, setSavingSearch] = useState(false);
|
||||
const [activeSavedSearchId, setActiveSavedSearchId] = useState<number | null>(null);
|
||||
const [updatingSavedSearchId, setUpdatingSavedSearchId] = useState<number | null>(null);
|
||||
const [mutating, setMutating] = useState(false);
|
||||
const pending = useRef(false);
|
||||
const resultsRef = useRef<HTMLDivElement>(null);
|
||||
const removedControlRef = useRef<Element | null>(null);
|
||||
const busy = loading || savingSearch || updatingSavedSearchId !== null || mutating;
|
||||
|
||||
useEffect(() => {
|
||||
const control = removedControlRef.current;
|
||||
removedControlRef.current = null;
|
||||
if (control && !control.isConnected && document.activeElement === document.body) resultsRef.current?.focus();
|
||||
}, [jobs, savedSearches]);
|
||||
|
||||
useEffect(() => {
|
||||
let active = true;
|
||||
@@ -71,12 +85,14 @@ export default function JobDiscoveryPage() {
|
||||
}, [savedSearchLoad]);
|
||||
|
||||
const runSearch = async (nextQuery: string, nextLocation: string) => {
|
||||
setLoading(true); setError(""); setJobs([]); setHasSearched(true); setLastSearch({ query: nextQuery, location: nextLocation });
|
||||
if (pending.current) return;
|
||||
pending.current = true;
|
||||
setLoading(true); setError(null); setJobs([]); setActiveSavedSearchId(null); setHasSearched(true); setLastSearch({ query: nextQuery, location: nextLocation });
|
||||
try {
|
||||
const response = await api.get<DiscoveredJob[]>("/job-discovery/search", { params: { q: nextQuery || undefined, location: nextLocation || undefined } });
|
||||
setJobs(response.data ?? []);
|
||||
} catch { setError(t("jobDiscoveryUnavailable")); }
|
||||
finally { setLoading(false); }
|
||||
} catch { setError("jobDiscoveryUnavailable"); }
|
||||
finally { pending.current = false; setLoading(false); }
|
||||
};
|
||||
|
||||
const search = (event: FormEvent) => {
|
||||
@@ -85,53 +101,72 @@ export default function JobDiscoveryPage() {
|
||||
};
|
||||
|
||||
const saveSearch = async () => {
|
||||
if (pending.current || savedSearchState !== "loaded") return;
|
||||
pending.current = true;
|
||||
const name = savedName.trim() || query.trim() || location.trim() || t("jobDiscoverySavedDefaultName");
|
||||
setSavingSearch(true); setError("");
|
||||
setSavingSearch(true); setError(null);
|
||||
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); }
|
||||
} catch { setError("jobDiscoverySaveSearchFailed"); }
|
||||
finally { pending.current = false; 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 });
|
||||
const runSavedSearch = async (saved: SavedSearch, applyFilters = true) => {
|
||||
if (pending.current) return;
|
||||
pending.current = true;
|
||||
setLoading(true); setError(null); setJobs([]); setHasSearched(true); setActiveSavedSearchId(saved.id);
|
||||
if (applyFilters) { setQuery(saved.query); setLocation(saved.location); }
|
||||
setLastSearch({ query: saved.query, location: saved.location, saved });
|
||||
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); }
|
||||
} catch { setError("jobDiscoveryUnavailable"); }
|
||||
finally { pending.current = false; setLoading(false); }
|
||||
};
|
||||
|
||||
const deleteSavedSearch = async (saved: SavedSearch) => {
|
||||
if (!(await confirmAction(t("jobDiscoveryDeleteSavedConfirm", { name: saved.name }), { title: t("jobDiscoveryDeleteSavedTitle"), confirmLabel: t("adminUsersDelete"), destructive: true }))) return;
|
||||
if (pending.current) return;
|
||||
pending.current = true;
|
||||
const control = document.activeElement;
|
||||
try {
|
||||
if (!(await confirmAction(t("jobDiscoveryDeleteSavedConfirm", { name: saved.name }), { title: t("jobDiscoveryDeleteSavedTitle"), confirmLabel: t("adminUsersDelete"), destructive: true }))) return;
|
||||
setMutating(true);
|
||||
setError(null);
|
||||
await api.delete(`/job-discovery/saved-searches/${saved.id}`);
|
||||
removedControlRef.current = control;
|
||||
setSavedSearches((current) => current.filter((item) => item.id !== saved.id));
|
||||
if (activeSavedSearchId === saved.id) setActiveSavedSearchId(null);
|
||||
} catch { setError(t("jobDiscoveryDeleteSavedFailed")); }
|
||||
} catch { setError("jobDiscoveryDeleteSavedFailed"); }
|
||||
finally { pending.current = false; setMutating(false); }
|
||||
};
|
||||
|
||||
const toggleSavedSearchAlerts = async (saved: SavedSearch) => {
|
||||
setUpdatingSavedSearchId(saved.id); setError("");
|
||||
if (pending.current) return;
|
||||
pending.current = true;
|
||||
setUpdatingSavedSearchId(saved.id); setError(null);
|
||||
try {
|
||||
const response = await api.patch<SavedSearch>(`/job-discovery/saved-searches/${saved.id}`, { isActive: !saved.isActive });
|
||||
setSavedSearches((current) => current.map((item) => item.id === saved.id ? response.data : item));
|
||||
} catch { setError(t("jobDiscoveryUpdateAlertsFailed")); }
|
||||
finally { setUpdatingSavedSearchId(null); }
|
||||
} catch { setError("jobDiscoveryUpdateAlertsFailed"); }
|
||||
finally { pending.current = false; setUpdatingSavedSearchId(null); }
|
||||
};
|
||||
|
||||
const dismissJob = async (jobId: string) => {
|
||||
if (activeSavedSearchId === null) return;
|
||||
if (activeSavedSearchId === null || pending.current) return;
|
||||
pending.current = true;
|
||||
const control = document.activeElement;
|
||||
setMutating(true); setError(null);
|
||||
try {
|
||||
await api.patch(`/job-discovery/saved-searches/${activeSavedSearchId}/results/${encodeURIComponent(jobId)}/dismiss`, { isDismissed: true });
|
||||
removedControlRef.current = control;
|
||||
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")); }
|
||||
} catch { setError("jobDiscoveryDismissFailed"); }
|
||||
finally { pending.current = false; setMutating(false); }
|
||||
};
|
||||
|
||||
const sortedJobs = useMemo(() => [...jobs].sort((left, right) => {
|
||||
@@ -146,42 +181,42 @@ export default function JobDiscoveryPage() {
|
||||
const formatDate = (value?: string) => value ? new Date(value).toLocaleDateString(language === "nb" ? "nb-NO" : "en") : null;
|
||||
|
||||
return (
|
||||
<Stack spacing={3}>
|
||||
<Stack spacing={3} sx={{ minWidth: 0 }}>
|
||||
<Box component="form" onSubmit={search} sx={{ display: "grid", gridTemplateColumns: { xs: "1fr", md: "2fr 1fr auto" }, gap: 1.5 }}>
|
||||
<TextField label={t("jobDiscoveryRoleCompany")} value={query} onChange={(event) => setQuery(event.target.value)} />
|
||||
<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>
|
||||
<TextField label={t("jobDiscoveryRoleCompany")} value={query} disabled={busy} onChange={(event) => setQuery(event.target.value)} />
|
||||
<TextField label={t("jobDiscoveryMunicipality")} value={location} disabled={busy} onChange={(event) => setLocation(event.target.value)} />
|
||||
<Button type="submit" variant="contained" startIcon={loading ? <CircularProgress aria-hidden="true" size={18} color="inherit" /> : <SearchIcon />} disabled={busy}>{t("jobDiscoverySearchNav")}</Button>
|
||||
</Box>
|
||||
<Card variant="outlined" aria-busy={savedSearchState === "loading"}>
|
||||
<CardContent sx={{ display: "grid", gap: 1.5 }}>
|
||||
<CardContent sx={{ display: "grid", gap: 1.5, p: "var(--app-card-padding)", "&:last-child": { pb: "var(--app-card-padding)" } }}>
|
||||
<Box>
|
||||
<Typography component="h2" variant="h6" sx={{ fontWeight: 800 }}>{t("jobDiscoverySavedSearches")}</Typography>
|
||||
<Typography component="h2" variant="sectionTitle">{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 || savedSearchState !== "loaded"}>{t("jobDiscoverySaveSearch")}</Button>
|
||||
<TextField size="small" label={t("jobDiscoverySavedName")} value={savedName} disabled={busy} onChange={(event) => setSavedName(event.target.value)} />
|
||||
<Button variant="outlined" startIcon={<BookmarkAddOutlinedIcon />} onClick={() => void saveSearch()} disabled={busy || savedSearchState !== "loaded"}>{t("jobDiscoverySaveSearch")}</Button>
|
||||
</Box>
|
||||
{savedSearchState === "loading" ? <Typography role="status" aria-label={t("jobDiscoverySavedLoading")} variant="body2" color="text.secondary">{t("jobDiscoverySavedLoading")}</Typography> : savedSearchState === "error" ? (
|
||||
<Alert severity="error" variant="outlined" action={<Button color="inherit" onClick={() => setSavedSearchLoad((current) => current + 1)}>{t("retry")}</Button>}>
|
||||
<Alert severity="error" variant="outlined" action={<Button color="inherit" disabled={busy} onClick={() => setSavedSearchLoad((current) => current + 1)}>{t("retry")}</Button>}>
|
||||
{t("jobDiscoverySavedLoadFailed")}
|
||||
</Alert>
|
||||
) : 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 key={saved.id} role="group" aria-label={saved.name} sx={{ display: "flex", flexWrap: "wrap", alignItems: "center", gap: 1, p: 1.5, border: 1, borderColor: activeSavedSearchId === saved.id ? "primary.main" : "divider", borderRadius: 1, minWidth: 0 }}>
|
||||
<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>
|
||||
<Typography sx={{ fontWeight: 700, overflowWrap: "anywhere" }}>{saved.name}</Typography>
|
||||
<Typography variant="caption" color="text.secondary" sx={{ overflowWrap: "anywhere" }}>{[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 })} />
|
||||
<FormControlLabel
|
||||
sx={{ m: 0 }}
|
||||
control={<Switch size="small" checked={saved.isActive} disabled={updatingSavedSearchId === saved.id} onChange={() => void toggleSavedSearchAlerts(saved)} />}
|
||||
control={<Switch size="small" checked={saved.isActive} disabled={busy} onChange={() => void toggleSavedSearchAlerts(saved)} />}
|
||||
label={<Typography variant="body2">{t("jobDiscoveryAutomaticAlerts")}</Typography>}
|
||||
/>
|
||||
<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>
|
||||
<Button size="small" startIcon={<RefreshIcon />} onClick={() => void runSavedSearch(saved)} disabled={busy}>{t("jobDiscoveryRunSaved")}</Button>
|
||||
<Button size="small" color="error" startIcon={<DeleteOutlineIcon />} onClick={() => void deleteSavedSearch(saved)} disabled={busy}>{t("adminUsersDelete")}</Button>
|
||||
</Box>
|
||||
))}
|
||||
</Stack>
|
||||
@@ -189,10 +224,17 @@ export default function JobDiscoveryPage() {
|
||||
</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}
|
||||
<Box role="region" aria-label={t("jobDiscoveryResults")} tabIndex={-1} ref={resultsRef} aria-busy={loading} sx={{ display: "grid", gap: 2, minWidth: 0 }}>
|
||||
{hasSearched ? <PageHeader level="h2" title={t("jobDiscoveryResults")} /> : null}
|
||||
<ViewStateNotice compact loading={loading} title={t(error ?? "jobDiscoveryUnavailable")}
|
||||
error={error ? { kind: "unavailable", message: t(error), retryable: error === "jobDiscoveryUnavailable" } : null}
|
||||
onRetry={() => {
|
||||
if (pending.current) return;
|
||||
resultsRef.current?.focus();
|
||||
void (lastSearch.saved ? runSavedSearch(lastSearch.saved, false) : runSearch(lastSearch.query, lastSearch.location));
|
||||
}} />
|
||||
{!loading && !hasSearched ? <Typography color="text.secondary">{t("jobDiscoveryGuidance")}</Typography> : null}
|
||||
{!loading && hasSearched && !error && jobs.length === 0 ? <Alert severity="info" variant="outlined" sx={{ color: "text.primary" }}>{t("jobDiscoveryNoResults")}</Alert> : null}
|
||||
{loading ? <Typography role="status" color="text.secondary">{t("jobDiscoverySearching")}</Typography> : null}
|
||||
{jobs.length > 0 ? (
|
||||
<Box sx={{ display: "flex", gap: 2, alignItems: { xs: "stretch", sm: "center" }, justifyContent: "space-between", flexDirection: { xs: "column", sm: "row" } }}>
|
||||
<Typography role="status">{t(jobs.length === 1 ? "jobDiscoveryResultOne" : "jobDiscoveryResultMany", { count: jobs.length })}</Typography>
|
||||
@@ -205,14 +247,14 @@ export default function JobDiscoveryPage() {
|
||||
) : null}
|
||||
<Box sx={{ display: "grid", gridTemplateColumns: { xs: "1fr", lg: "repeat(2, minmax(0, 1fr))" }, gap: 2 }}>
|
||||
{sortedJobs.map((job) => (
|
||||
<Card key={job.id} variant="outlined" sx={{ display: "flex", flexDirection: "column" }}>
|
||||
<CardContent>
|
||||
<Stack direction="row" spacing={1} sx={{ mb: 1 }}>
|
||||
<Card key={job.id} component="article" aria-label={job.title} variant="outlined" sx={{ display: "flex", flexDirection: "column", minWidth: 0 }}>
|
||||
<CardContent sx={{ p: "var(--app-card-padding)" }}>
|
||||
<Box sx={{ display: "flex", flexWrap: "wrap", gap: 1, 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>
|
||||
</Box>
|
||||
<Typography component="h3" variant="sectionTitle" sx={{ overflowWrap: "anywhere" }}>{job.title}</Typography>
|
||||
<Typography color="text.secondary" sx={{ overflowWrap: "anywhere" }}>{[job.company, job.location || t("jobDiscoveryLocationMissing")].filter(Boolean).join(" · ")}</Typography>
|
||||
<Stack spacing={0.25} sx={{ mt: 1 }}>
|
||||
<Typography variant="caption" color="text.secondary">
|
||||
{job.acquisitionType === "searched" ? t("jobDiscoverySearchedListing") : t("jobDiscoverySourceTypeMissing")}
|
||||
@@ -223,14 +265,15 @@ export default function JobDiscoveryPage() {
|
||||
<Typography variant="caption" color="text.secondary">{t("jobDiscoveryWorkArrangementMissing")}</Typography>
|
||||
</Stack>
|
||||
</CardContent>
|
||||
<CardActions sx={{ mt: "auto" }}>
|
||||
<CardActions sx={{ mt: "auto", p: "var(--app-card-padding)", pt: 0, flexWrap: "wrap", gap: 1, "& .MuiButton-root": { ml: 0, whiteSpace: "normal", maxWidth: "100%" } }}>
|
||||
<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}
|
||||
{activeSavedSearchId !== null ? <Button color="inherit" disabled={busy} onClick={() => void dismissJob(job.id)}>{t("jobDiscoveryDismiss")}</Button> : null}
|
||||
</CardActions>
|
||||
</Card>
|
||||
))}
|
||||
</Box>
|
||||
</Box>
|
||||
</Stack>
|
||||
);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user