All files / components/JobPanel SavedTab.tsx

98.51% Statements 399/405
92.47% Branches 86/93
91.3% Functions 21/23
98.51% Lines 399/405

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 4061x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 173x 173x 173x 173x 173x 173x 173x 173x 173x 173x 173x 173x 173x 173x 173x 173x 173x 173x 173x 173x 40x 40x 40x 40x 40x 38x 2x 2x 2x 2x 40x 40x 40x 40x 40x 40x 1x 1x 173x 173x 173x 32x 173x 173x 173x 173x 173x 173x 173x 173x 173x 62x 62x 62x 31x 31x 31x 31x 31x 31x 31x     31x 31x 31x 31x 31x 31x 173x 173x 173x 30x 30x 30x     30x 173x 173x 173x 1x 1x 1x 1x 1x   1x 1x 1x 1x 173x 173x 173x 173x 7x 7x 6x 7x 1x 1x 7x 173x 173x 2x 2x 2x 2x 173x 173x 1x 1x 1x 1x 173x 173x 2x 2x 2x 2x 173x 173x 2x 2x 1x 1x 1x 1x 1x 1x 1x 2x 173x 173x 2x 2x 2x 2x 2x 2x 173x 173x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 1x 1x 1x 1x 1x 1x   1x 1x 2x 2x 2x 2x 2x 173x 173x 173x 173x 1x 171x 2x 169x 1x 168x 173x 173x 173x 173x 173x 173x 173x 173x 173x 173x 173x 173x 173x 173x 173x 688x 688x 688x 173x 173x 173x 173x 173x 173x 173x 173x 173x 173x 173x 173x 173x 173x 1032x 1032x 1032x 173x 173x 173x 173x 173x 173x 173x 173x 173x 173x 173x 173x 173x 173x 860x 860x 860x 173x 173x 173x 173x 173x 173x 173x 173x 173x 173x 173x 173x 173x 688x 688x 688x 173x 173x 173x 173x 173x 173x 173x 173x 173x 173x 2x 2x 2x 2x 2x 173x 173x 173x 173x 173x 173x 173x 173x 173x 173x 173x 173x 173x 173x 173x 173x 173x 3x 3x 3x 3x 3x 3x 173x 173x 173x 4x 4x 4x 4x 4x 4x 173x 173x 173x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 173x 173x 173x 173x 55x 55x 55x 55x 55x 55x 173x 173x 173x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 173x 173x 173x 114x 13x 13x 13x 13x 13x 13x 13x 13x 101x 101x 101x 1375x 1375x 1375x 1375x 1375x 1375x 1375x 1375x 101x 101x 173x 173x 173x 173x 173x  
import { useCallback, useEffect, useRef, useState } from "react";
import { importFromJson } from "../../services/importService";
import { jobStorage } from "../../services/jobStorage";
import { fetchAccount, startCheckout, SAVED_JOBS_CAP } from "../../services/accountService";
import type { Arrangement, JobStatus, SavedJob } from "../../types/job";
import { ARRANGEMENTS, JOB_STATUSES } from "../../types/job";
import { SavedJobRow } from "./SavedJobRow";
import { useLiveFingerprint } from "./useFreshness";
import { filterByVerdict, sortByFit, verdictLabel, type Verdict } from "../../../shared/fitView";
import { getCachedFingerprint, getProfile } from "../../services/profileStorage";
 
type SortOrder = "newest" | "oldest" | "fit-highest" | "fit-lowest";
 
const SORT_OPTIONS: { value: SortOrder; label: string }[] = [
  { value: "newest", label: "Saved (newest)" },
  { value: "oldest", label: "Saved (oldest)" },
  { value: "fit-highest", label: "Fit (highest)" },
  { value: "fit-lowest", label: "Fit (lowest)" },
];
 
const VERDICT_OPTIONS: Exclude<Verdict, "unrated">[] = [
  "strong",
  "worth-a-shot",
  "stretch",
  "long-shot",
  "dealbreaker",
];
 
type LoadState = "loading" | "ready" | "error";
 
export function SavedTab() {
  const [jobs, setJobs] = useState<SavedJob[]>([]);
  const [arrangement, setArrangement] = useState<Arrangement | "all">("all");
  const [status, setStatus] = useState<JobStatus | "all">("all");
  const [sortOrder, setSortOrder] = useState<SortOrder>("newest");
  const [verdict, setVerdict] = useState<Exclude<Verdict, "unrated"> | "all">("all");
  // The library is server-backed: a failed load must show as a failure with
  // Retry, never as an empty library (FR-015).
  const [loadState, setLoadState] = useState<LoadState>("loading");
  const [actionError, setActionError] = useState<string | null>(null);
  const [importSummary, setImportSummary] = useState<string | null>(null);
  const [importing, setImporting] = useState(false);
  const fileInputRef = useRef<HTMLInputElement>(null);
  // Downgrade over-cap banner (FR-021/022): the true, unfiltered library
  // size vs. the tier cap — independent of the arrangement/status filters
  // applied to `jobs` above.
  const [totalCount, setTotalCount] = useState<number | null>(null);
  const [tier, setTier] = useState<"free" | "premium" | null>(null);
  const [upgradeBusy, setUpgradeBusy] = useState(false);
 
  const reload = useCallback(async () => {
    setLoadState((prev) => (prev === "ready" ? prev : "loading"));
    try {
      const noFilter = arrangement === "all" && status === "all";
      const [filtered, all] = await Promise.all([
        noFilter
          ? Promise.resolve(undefined)
          : jobStorage.list({
              ...(arrangement !== "all" ? { arrangement } : {}),
              ...(status !== "all" ? { status } : {}),
            }),
        jobStorage.list({}),
      ]);
      setJobs(filtered ?? all);
      setTotalCount(all.length);
      setLoadState("ready");
    } catch {
      setLoadState("error");
    }
  }, [arrangement, status]);
 
  useEffect(() => {
    void reload();
  }, [reload]);
 
  // The current profile fingerprint for the out-of-date markers: the session
  // cache first, then one profile fetch (which fills the cache for next time).
  const [reportedFingerprint, setReportedFingerprint] = useState<
    string | null | undefined
  >(undefined);
  const currentFingerprint = useLiveFingerprint(reportedFingerprint);
  useEffect(() => {
    // After the list settles, so this extra request can't be the one that
    // meets a transient failure meant for the library load.
    if (loadState === "loading") return;
    let cancelled = false;
    void (async () => {
      let value = await getCachedFingerprint();
      if (value === undefined) {
        try {
          value = (await getProfile())?.fingerprint ?? null;
        } catch {
          value = undefined; // unknown: no markers rather than wrong ones
        }
      }
      if (!cancelled) setReportedFingerprint(value);
    })();
    return () => {
      cancelled = true;
    };
  }, [loadState]);
 
  useEffect(() => {
    fetchAccount()
      .then((account) => setTier(account.tier))
      .catch(() => {
        // The AccountBar surfaces this failure; the over-cap banner just
        // stays hidden without a known tier.
      });
  }, []);
 
  const handleUpgrade = async () => {
    setUpgradeBusy(true);
    try {
      const { checkoutUrl } = await startCheckout();
      window.open(checkoutUrl, "_blank", "noopener,noreferrer");
    } catch {
      // AccountBar (options page) surfaces the specific failure.
    } finally {
      setUpgradeBusy(false);
    }
  };
 
  const overCap = tier !== null && totalCount !== null && totalCount > SAVED_JOBS_CAP[tier];
 
  const runAction = async (action: () => Promise<unknown>, failureMessage: string) => {
    try {
      await action();
      setActionError(null);
    } catch (err) {
      setActionError(err instanceof Error ? err.message : failureMessage);
    }
  };
 
  const handleStatusChange = (canonicalUrl: string, newStatus: JobStatus) =>
    runAction(async () => {
      await jobStorage.update(canonicalUrl, { status: newStatus });
      await reload();
    }, "The status change could not be saved. Try again.");
 
  const handleNotesChange = (canonicalUrl: string, notes: string) =>
    runAction(async () => {
      await jobStorage.update(canonicalUrl, { notes });
      await reload();
    }, "The notes could not be saved. Try again.");
 
  const handleDelete = (canonicalUrl: string) =>
    runAction(async () => {
      await jobStorage.remove(canonicalUrl);
      await reload();
    }, "The posting could not be deleted. Try again.");
 
  const handleExport = () =>
    runAction(async () => {
      const json = await jobStorage.exportAll();
      const blob = new Blob([json], { type: "application/json" });
      const url = URL.createObjectURL(blob);
      const anchor = document.createElement("a");
      anchor.href = url;
      anchor.download = `saved-jobs-${new Date().toISOString().slice(0, 10)}.json`;
      anchor.click();
      URL.revokeObjectURL(url);
    }, "The export could not be downloaded. Try again.");
 
  const readFileText = (file: File) =>
    new Promise<string>((resolve, reject) => {
      const reader = new FileReader();
      reader.onload = () => resolve(reader.result as string);
      reader.onerror = () => reject(reader.error);
      reader.readAsText(file);
    });
 
  const handleImportFile = async (file: File) => {
    setImporting(true);
    setImportSummary(null);
    setActionError(null);
    try {
      const result = await importFromJson(await readFileText(file));
      const counts = `Imported ${result.importedJobs} posting${
        result.importedJobs === 1 ? "" : "s"
      }, skipped ${result.skippedDuplicates} duplicate${
        result.skippedDuplicates === 1 ? "" : "s"
      }${result.invalidEntries > 0 ? ` (${result.invalidEntries} unreadable entries ignored)` : ""}.`;
      if (result.status === "completed") {
        setImportSummary(counts);
      } else {
        // Partial imports are safe to retry: existing records are skipped.
        setActionError(
          result.status === "invalid-file"
            ? (result.errorMessage ?? "This file could not be imported.")
            : `${result.errorMessage ?? "The import could not finish."} ${counts}`
        );
      }
      await reload();
    } finally {
      setImporting(false);
    }
  };
 
  const verdictFiltered = verdict === "all" ? jobs : filterByVerdict(jobs, verdict);
  const displayed =
    sortOrder === "fit-highest"
      ? sortByFit(verdictFiltered, "highest")
      : sortOrder === "fit-lowest"
        ? sortByFit(verdictFiltered, "lowest")
        : sortOrder === "oldest"
          ? [...verdictFiltered].sort((a, b) => Date.parse(a.savedAt) - Date.parse(b.savedAt))
          : verdictFiltered;
 
  return (
    <div className="flex h-full flex-col">
      <div className="flex shrink-0 flex-wrap items-center gap-2 border-b border-gray-200/70 bg-white px-3 py-2 dark:border-gray-800 dark:bg-gray-900">
        <label className="sr-only" htmlFor="filter-arrangement">
          Filter by arrangement
        </label>
        <select
          id="filter-arrangement"
          value={arrangement}
          onChange={(e) => setArrangement(e.target.value as Arrangement | "all")}
          className="rounded-md border border-gray-200 bg-white px-1.5 py-0.5 text-xs text-gray-700 dark:border-gray-700 dark:bg-gray-800 dark:text-gray-200"
        >
          <option value="all">All arrangements</option>
          {ARRANGEMENTS.map((a) => (
            <option key={a} value={a}>
              {a}
            </option>
          ))}
        </select>
 
        <label className="sr-only" htmlFor="filter-status">
          Filter by status
        </label>
        <select
          id="filter-status"
          value={status}
          onChange={(e) => setStatus(e.target.value as JobStatus | "all")}
          className="rounded-md border border-gray-200 bg-white px-1.5 py-0.5 text-xs text-gray-700 dark:border-gray-700 dark:bg-gray-800 dark:text-gray-200"
        >
          <option value="all">All statuses</option>
          {JOB_STATUSES.map((s) => (
            <option key={s} value={s}>
              {s}
            </option>
          ))}
        </select>
 
        <label className="sr-only" htmlFor="filter-verdict">
          Filter by verdict
        </label>
        <select
          id="filter-verdict"
          value={verdict}
          onChange={(e) => setVerdict(e.target.value as Exclude<Verdict, "unrated"> | "all")}
          className="rounded-md border border-gray-200 bg-white px-1.5 py-0.5 text-xs text-gray-700 dark:border-gray-700 dark:bg-gray-800 dark:text-gray-200"
        >
          <option value="all">All verdicts</option>
          {VERDICT_OPTIONS.map((v) => (
            <option key={v} value={v}>
              {verdictLabel(v)}
            </option>
          ))}
        </select>
 
        <label className="sr-only" htmlFor="sort-order">
          Sort by
        </label>
        <select
          id="sort-order"
          value={sortOrder}
          onChange={(e) => setSortOrder(e.target.value as SortOrder)}
          className="rounded-md border border-gray-200 bg-white px-1.5 py-0.5 text-xs text-gray-700 dark:border-gray-700 dark:bg-gray-800 dark:text-gray-200"
        >
          {SORT_OPTIONS.map((o) => (
            <option key={o.value} value={o.value}>
              {o.label}
            </option>
          ))}
        </select>
 
        <input
          ref={fileInputRef}
          type="file"
          accept="application/json,.json"
          className="hidden"
          aria-label="Import saved postings file"
          onChange={(e) => {
            const file = e.target.files?.[0];
            // Allow re-selecting the same file after a failed attempt.
            e.target.value = "";
            if (file) void handleImportFile(file);
          }}
        />
        <button
          onClick={() => fileInputRef.current?.click()}
          disabled={importing}
          className="ml-auto rounded-md px-2 py-0.5 text-xs font-medium text-blue-700 hover:bg-blue-50 disabled:opacity-50 dark:text-blue-400 dark:hover:bg-blue-950/40"
        >
          {importing ? "Importing…" : "Import"}
        </button>
        <button
          onClick={() => void handleExport()}
          className="rounded-md px-2 py-0.5 text-xs font-medium text-blue-700 hover:bg-blue-50 dark:text-blue-400 dark:hover:bg-blue-950/40"
        >
          Export
        </button>
      </div>
 
      {importSummary && (
        <div
          role="status"
          className="shrink-0 border-b border-green-200 bg-green-50 px-3 py-2 text-xs text-green-700 dark:border-green-900/60 dark:bg-green-950/40 dark:text-green-300"
        >
          {importSummary}
        </div>
      )}
 
      {actionError && (
        <div
          role="alert"
          className="shrink-0 border-b border-red-200 bg-red-50 px-3 py-2 text-xs text-red-700 dark:border-red-900/60 dark:bg-red-950/40 dark:text-red-300"
        >
          {actionError}
        </div>
      )}
 
      {overCap && tier && totalCount !== null && (
        <div
          role="status"
          className="shrink-0 border-b border-amber-200 bg-amber-50 px-3 py-2 text-xs text-amber-800 dark:border-amber-900/60 dark:bg-amber-950/40 dark:text-amber-300"
        >
          Your library has {totalCount} postings, over the{" "}
          {SAVED_JOBS_CAP[tier].toLocaleString()}-posting {tier} limit. Existing
          postings are safe — view, edit, and delete still work; new postings
          can&rsquo;t be saved until you free up space.
          {tier === "free" && (
            <button
              onClick={() => void handleUpgrade()}
              disabled={upgradeBusy}
              aria-label="Upgrade to Premium"
              className="ml-2 font-semibold underline hover:no-underline disabled:opacity-60"
            >
              Upgrade
            </button>
          )}
        </div>
      )}
 
      <div className="min-h-0 flex-1 overflow-y-auto p-3">
        {loadState === "loading" && (
          <div
            role="status"
            className="flex items-center justify-center px-6 py-16 text-sm text-gray-400 dark:text-gray-500"
          >
            Loading saved postings…
          </div>
        )}
 
        {loadState === "error" && (
          <div
            role="alert"
            className="mx-auto mt-8 max-w-xs rounded-lg border border-red-200 bg-red-50 p-4 text-center dark:border-red-900/60 dark:bg-red-950/40"
          >
            <p className="text-sm font-medium text-red-700 dark:text-red-300">
              Your saved postings could not be loaded.
            </p>
            <p className="mt-1 text-xs text-red-600/80 dark:text-red-400/80">
              Check your connection — nothing has been lost.
            </p>
            <button
              onClick={() => void reload()}
              className="mt-3 rounded-md bg-red-600 px-3 py-1 text-xs font-semibold text-white hover:bg-red-700"
            >
              Retry
            </button>
          </div>
        )}
 
        {loadState === "ready" &&
          (displayed.length === 0 ? (
            <div className="flex flex-col items-center justify-center px-6 py-16 text-center">
              <p className="text-sm font-medium text-gray-600 dark:text-gray-400">
                No saved postings{arrangement !== "all" || status !== "all" || verdict !== "all" ? " match these filters" : " yet"}
              </p>
              <p className="mt-1 text-xs text-gray-400 dark:text-gray-600">
                Analyzed postings you save will appear here.
              </p>
            </div>
          ) : (
            <ul aria-label="Saved postings" className="space-y-2">
              {displayed.map((job) => (
                <SavedJobRow
                  key={job.canonicalUrl}
                  job={job}
                  currentFingerprint={currentFingerprint}
                  onStatusChange={(url, s) => void handleStatusChange(url, s)}
                  onNotesChange={(url, notes) => void handleNotesChange(url, notes)}
                  onDelete={(url) => void handleDelete(url)}
                />
              ))}
            </ul>
          ))}
      </div>
    </div>
  );
}