Skip to content

Job application tracker and AI-powered job search assistant. Helps job seekers manage their search journey with AI resume review, job matching, task logging, and application analytics, all while keeping your data private.

feat(companies): add the company details page with header, summary card and Jobs tab; extract BoardCell, make the empty-state action optional and keep query params in useTabQueryParam

Khuram Niaza5a21004ad4b
diff --git a/__tests__/AddCompany.spec.tsx b/__tests__/AddCompany.spec.tsx
index 57f89cb..a50fb3a 100644
--- a/__tests__/AddCompany.spec.tsx
+++ b/__tests__/AddCompany.spec.tsx
@@ -30,6 +30,21 @@ describe("AddCompany Component", () => {
).toBeInTheDocument();
});
+ it("renders no New Company button when the trigger is hidden", () => {
+ render(
+ <AddCompany
+ reloadCompanies={mockReloadCompanies}
+ resetEditCompany={mockResetEditCompany}
+ dialogOpen={false}
+ setDialogOpen={mockSetDialogOpen}
+ hideTrigger
+ />,
+ );
+ expect(
+ screen.queryByRole("button", { name: /new company/i }),
+ ).not.toBeInTheDocument();
+ });
+
it("should open dialog when Add Company button is clicked", async () => {
render(
<AddCompany
diff --git a/__tests__/CompanyDetails.spec.tsx b/__tests__/CompanyDetails.spec.tsx
new file mode 100644
index 0000000..a2c458b
--- /dev/null
+++ b/__tests__/CompanyDetails.spec.tsx
@@ -0,0 +1,382 @@
+import CompanyDetails from "@/components/admin/CompanyDetails";
+import { render, screen, waitFor, within } from "@testing-library/react";
+import userEvent from "@testing-library/user-event";
+import {
+ deleteCompanyById,
+ setCompanyWatched,
+} from "@/actions/company.actions";
+import { toastError } from "@/lib/toast";
+
+const router = { push: vi.fn(), replace: vi.fn(), refresh: vi.fn(), back: vi.fn() };
+let searchParams = new URLSearchParams();
+
+vi.mock("next/navigation", () => ({
+ useRouter: () => router,
+ useSearchParams: () => searchParams,
+ usePathname: () => "/dashboard/admin/companies/co1",
+}));
+
+vi.mock("@/actions/company.actions", () => ({
+ deleteCompanyById: vi.fn(),
+ setCompanyWatched: vi.fn(),
+ addCompany: vi.fn(),
+ updateCompany: vi.fn(),
+ getAllCompanies: vi.fn().mockResolvedValue([]),
+}));
+
+vi.mock("@/lib/toast", () => ({
+ toastSuccess: vi.fn(),
+ toastError: vi.fn(),
+ toastActionResult: vi.fn(),
+}));
+
+vi.mock("@/components/CircularScore", () => ({
+ CircularScore: ({ score }: { score: number }) => (
+ <div data-testid="circular-score">{score}%</div>
+ ),
+}));
+
+const makeDetails = (overrides: Record<string, unknown> = {}) =>
+ ({
+ id: "co1",
+ label: "Stripe",
+ value: "stripe",
+ createdBy: "u1",
+ watched: false,
+ watchedAt: null,
+ atsProvider: null,
+ atsToken: null,
+ atsHost: null,
+ websiteUrl: null,
+ careersUrl: null,
+ industry: null,
+ jobs: [],
+ appliedCount: 0,
+ dismissedJobsCount: 0,
+ currentContacts: [],
+ formerContacts: [],
+ ...overrides,
+ }) as any;
+
+const fact = (label: string) =>
+ within(screen.getByTestId("company-summary")).getByText(label)
+ .nextElementSibling as HTMLElement;
+
+describe("CompanyDetails – header", () => {
+ const user = userEvent.setup({ skipHover: true });
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+ searchParams = new URLSearchParams();
+ });
+
+ it("shows the company name with its industry and website host", () => {
+ render(
+ <CompanyDetails
+ details={makeDetails({
+ industry: "Payments",
+ websiteUrl: "https://stripe.com/about",
+ })}
+ />,
+ );
+
+ expect(screen.getByRole("heading", { name: "Stripe" })).toBeInTheDocument();
+ expect(screen.getByText("Payments · stripe.com")).toBeInTheDocument();
+ });
+
+ it("drops the subtitle line when there is neither industry nor website", () => {
+ render(<CompanyDetails details={makeDetails()} />);
+
+ expect(screen.getByRole("heading", { name: "Stripe" }).nextElementSibling).toBeNull();
+ });
+
+ it("goes back to the Library companies tab", () => {
+ render(<CompanyDetails details={makeDetails()} />);
+
+ expect(
+ screen.getByRole("link", { name: /back to companies/i }),
+ ).toHaveAttribute("href", "/dashboard/admin?tab=companies");
+ });
+
+ it("returns to the watchlist scope it was opened from", () => {
+ searchParams = new URLSearchParams("scope=watchlist");
+ render(<CompanyDetails details={makeDetails()} />);
+
+ expect(
+ screen.getByRole("link", { name: /back to companies/i }),
+ ).toHaveAttribute("href", "/dashboard/admin?tab=companies&scope=watchlist");
+ });
+
+ it("watches the company and refreshes the page", async () => {
+ (setCompanyWatched as any).mockResolvedValue({ success: true });
+ render(<CompanyDetails details={makeDetails()} />);
+
+ await user.click(screen.getByRole("button", { name: /^watch$/i }));
+
+ expect(setCompanyWatched).toHaveBeenCalledWith("co1", true);
+ await waitFor(() => expect(router.refresh).toHaveBeenCalled());
+ });
+
+ it("offers Unwatch for a watched company", () => {
+ render(<CompanyDetails details={makeDetails({ watched: true })} />);
+
+ expect(screen.getByRole("button", { name: /unwatch/i })).toBeInTheDocument();
+ });
+
+ it("opens the edit dialog", async () => {
+ render(<CompanyDetails details={makeDetails()} />);
+
+ await user.click(screen.getByRole("button", { name: /^edit$/i }));
+
+ expect(
+ await screen.findByRole("heading", { name: "Edit Company" }),
+ ).toBeInTheDocument();
+ });
+
+ it("reopens Edit with the saved values after an abandoned change", async () => {
+ render(<CompanyDetails details={makeDetails({ industry: "Payments" })} />);
+
+ await user.click(screen.getByRole("button", { name: /^edit$/i }));
+ const industry = await screen.findByLabelText("Industry");
+ await user.clear(industry);
+ await user.type(industry, "Half typed");
+ await user.keyboard("{Escape}");
+
+ await user.click(screen.getByRole("button", { name: /^edit$/i }));
+
+ expect(await screen.findByLabelText("Industry")).toHaveValue("Payments");
+ });
+
+ it("lists only the external links the company has", async () => {
+ render(
+ <CompanyDetails
+ details={makeDetails({ websiteUrl: "https://stripe.com" })}
+ />,
+ );
+
+ await user.click(screen.getByRole("button", { name: /more links/i }));
+
+ expect(
+ screen.getByRole("menuitem", { name: /open website/i }),
+ ).toHaveAttribute("href", "https://stripe.com");
+ expect(
+ screen.queryByRole("menuitem", { name: /open careers page/i }),
+ ).not.toBeInTheDocument();
+ expect(
+ screen.queryByRole("menuitem", { name: /open job board/i }),
+ ).not.toBeInTheDocument();
+ });
+
+ it("builds the job board link from the board coordinates", async () => {
+ render(
+ <CompanyDetails
+ details={makeDetails({ atsProvider: "greenhouse", atsToken: "stripe" })}
+ />,
+ );
+
+ await user.click(screen.getByRole("button", { name: /more links/i }));
+
+ expect(
+ screen.getByRole("menuitem", { name: /open job board/i }).getAttribute("href"),
+ ).toMatch(/\/stripe$/);
+ });
+
+ it("hides the links menu when there is nothing to open", () => {
+ render(<CompanyDetails details={makeDetails()} />);
+
+ expect(
+ screen.queryByRole("button", { name: /more links/i }),
+ ).not.toBeInTheDocument();
+ });
+});
+
+describe("CompanyDetails – summary card", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ searchParams = new URLSearchParams();
+ });
+
+ it("shows the watch state", () => {
+ render(
+ <CompanyDetails
+ details={makeDetails({ watched: true, watchedAt: new Date() })}
+ />,
+ );
+
+ expect(fact("Watchlist")).toHaveTextContent(/^Watched/);
+ });
+
+ it("shows Not watched and em dashes for missing attributes", () => {
+ render(<CompanyDetails details={makeDetails()} />);
+
+ expect(fact("Watchlist")).toHaveTextContent("Not watched");
+ expect(fact("Board")).toHaveTextContent("—");
+ expect(fact("Industry")).toHaveTextContent("—");
+ expect(fact("Website")).toHaveTextContent("—");
+ expect(fact("Careers page")).toHaveTextContent("—");
+ });
+
+ it("counts jobs, applied jobs and distinct contacts", () => {
+ const dave = { id: "c1", name: "Dave Patel", _count: { jobLinks: 0 } };
+ const priya = { id: "c2", name: "Priya Nair", _count: { jobLinks: 0 } };
+ render(
+ <CompanyDetails
+ details={makeDetails({
+ jobs: [
+ { id: "j1", applied: true, JobTitle: { label: "A" }, Status: { label: "Applied", value: "applied" }, Location: null, JobSource: null, appliedDate: null, matchScore: null, createdAt: new Date() },
+ { id: "j2", applied: false, JobTitle: { label: "B" }, Status: { label: "Draft", value: "draft" }, Location: null, JobSource: null, appliedDate: null, matchScore: null, createdAt: new Date() },
+ ],
+ appliedCount: 1,
+ currentContacts: [dave, priya],
+ formerContacts: [dave],
+ })}
+ />,
+ );
+
+ expect(fact("Jobs")).toHaveTextContent("2");
+ expect(fact("Applied")).toHaveTextContent("1");
+ expect(fact("Contacts")).toHaveTextContent("2");
+ });
+});
+
+describe("CompanyDetails – delete", () => {
+ const user = userEvent.setup({ skipHover: true });
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+ searchParams = new URLSearchParams();
+ });
+
+ const job = {
+ id: "j1",
+ applied: false,
+ appliedDate: null,
+ matchScore: null,
+ createdAt: new Date(),
+ JobTitle: { label: "Backend Engineer" },
+ Status: { label: "Draft", value: "draft" },
+ Location: null,
+ JobSource: null,
+ };
+
+ it("explains instead of confirming when the company has jobs", async () => {
+ render(<CompanyDetails details={makeDetails({ jobs: [job] })} />);
+
+ await user.click(screen.getByRole("button", { name: /^delete$/i }));
+
+ expect(await screen.findByText("Associated jobs exist!")).toBeInTheDocument();
+ expect(deleteCompanyById).not.toHaveBeenCalled();
+ });
+
+ it("still blocks when every job was dismissed, and says so", async () => {
+ render(<CompanyDetails details={makeDetails({ dismissedJobsCount: 3 })} />);
+
+ await user.click(screen.getByRole("button", { name: /^delete$/i }));
+
+ expect(await screen.findByText("Associated jobs exist!")).toBeInTheDocument();
+ expect(screen.getByText(/3 of them were dismissed by automations/)).toBeInTheDocument();
+ });
+
+ it("deletes a company with no jobs and returns to the Library", async () => {
+ (deleteCompanyById as any).mockResolvedValue({ success: true });
+ searchParams = new URLSearchParams("scope=watchlist");
+ render(<CompanyDetails details={makeDetails()} />);
+
+ await user.click(screen.getByRole("button", { name: /^delete$/i }));
+ const dialog = await screen.findByRole("alertdialog");
+ await user.click(within(dialog).getByRole("button", { name: /delete/i }));
+
+ await waitFor(() => expect(deleteCompanyById).toHaveBeenCalledWith("co1"));
+ expect(router.push).toHaveBeenCalledWith(
+ "/dashboard/admin?tab=companies&scope=watchlist",
+ );
+ });
+
+ it("surfaces the server's reason when the delete is refused", async () => {
+ (deleteCompanyById as any).mockResolvedValue({
+ success: false,
+ message: "Company cannot be deleted due to 2 associated contacts! ",
+ });
+ render(<CompanyDetails details={makeDetails()} />);
+
+ await user.click(screen.getByRole("button", { name: /^delete$/i }));
+ const dialog = await screen.findByRole("alertdialog");
+ await user.click(within(dialog).getByRole("button", { name: /delete/i }));
+
+ await waitFor(() =>
+ expect(toastError).toHaveBeenCalledWith(
+ "Company cannot be deleted due to 2 associated contacts! ",
+ ),
+ );
+ expect(router.push).not.toHaveBeenCalled();
+ });
+});
+
+describe("CompanyDetails – Jobs tab", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ searchParams = new URLSearchParams();
+ });
+
+ const job = (overrides: Record<string, unknown> = {}) => ({
+ id: "j1",
+ createdAt: new Date("2026-09-01"),
+ applied: true,
+ appliedDate: new Date("2026-09-02"),
+ matchScore: 82,
+ JobTitle: { label: "Backend Engineer" },
+ Status: { label: "Applied", value: "applied" },
+ Location: { label: "Remote" },
+ JobSource: { label: "LinkedIn" },
+ ...overrides,
+ });
+
+ it("opens on the Jobs tab with a count badge", () => {
+ render(<CompanyDetails details={makeDetails({ jobs: [job(), job({ id: "j2" })] })} />);
+
+ const tab = screen.getByRole("tab", { name: /jobs/i });
+ expect(tab).toHaveAttribute("data-state", "active");
+ expect(tab).toHaveTextContent("2");
+ });
+
+ it("links each job title to the job's details page", () => {
+ render(<CompanyDetails details={makeDetails({ jobs: [job()] })} />);
+
+ expect(
+ screen.getByRole("link", { name: "Backend Engineer" }),
+ ).toHaveAttribute("href", "/dashboard/myjobs/j1");
+ });
+
+ it("shows status, location, source and the match score", () => {
+ render(<CompanyDetails details={makeDetails({ jobs: [job()] })} />);
+
+ const row = screen.getByRole("row", { name: /backend engineer/i });
+ expect(within(row).getByText("Applied")).toBeInTheDocument();
+ expect(within(row).getByText("Remote")).toBeInTheDocument();
+ expect(within(row).getByText("LinkedIn")).toBeInTheDocument();
+ expect(within(row).getByTestId("circular-score")).toHaveTextContent("82%");
+ });
+
+ it("shows Not applied and a dash for an unapplied, unmatched job", () => {
+ render(
+ <CompanyDetails
+ details={makeDetails({
+ jobs: [job({ appliedDate: null, matchScore: null, JobSource: null })],
+ })}
+ />,
+ );
+
+ const row = screen.getByRole("row", { name: /backend engineer/i });
+ expect(within(row).getByText("Not applied")).toBeInTheDocument();
+ expect(within(row).queryByTestId("circular-score")).not.toBeInTheDocument();
+ });
+
+ it("shows an empty state with no action when there are no jobs", () => {
+ render(<CompanyDetails details={makeDetails()} />);
+
+ const panel = screen.getByRole("tabpanel");
+ expect(within(panel).getByText("No jobs at this company yet")).toBeInTheDocument();
+ expect(within(panel).queryByRole("button")).not.toBeInTheDocument();
+ expect(screen.getByRole("tab", { name: /jobs/i })).toHaveTextContent(/^Jobs$/);
+ });
+});
diff --git a/__tests__/CompanyDetailsPage.spec.tsx b/__tests__/CompanyDetailsPage.spec.tsx
new file mode 100644
index 0000000..45657e4
--- /dev/null
+++ b/__tests__/CompanyDetailsPage.spec.tsx
@@ -0,0 +1,54 @@
+import { render, screen } from "@testing-library/react";
+import CompanyDetailsPage from "@/app/dashboard/admin/companies/[id]/page";
+
+const notFound = vi.fn(() => {
+ throw new Error("NEXT_NOT_FOUND");
+});
+
+vi.mock("next/navigation", () => ({
+ notFound: () => notFound(),
+}));
+
+const getCompanyDetails = vi.fn();
+
+vi.mock("@/actions/company.actions", () => ({
+ getCompanyDetails: (id: string) => getCompanyDetails(id),
+}));
+
+vi.mock("@/components/admin/CompanyDetails", () => ({
+ default: () => <div data-testid="company-details" />,
+}));
+
+describe("CompanyDetailsPage", () => {
+ beforeEach(() => {
+ notFound.mockClear();
+ });
+
+ // A foreign id resolves to null too, so it 404s exactly like a missing one.
+ it("renders not found when the company does not resolve for the user", async () => {
+ getCompanyDetails.mockResolvedValue(null);
+
+ await expect(
+ CompanyDetailsPage({ params: Promise.resolve({ id: "missing" }) }),
+ ).rejects.toThrow("NEXT_NOT_FOUND");
+ expect(notFound).toHaveBeenCalled();
+ });
+
+ it("renders not found when the fetch failed", async () => {
+ getCompanyDetails.mockResolvedValue({ success: false, message: "boom" });
+
+ await expect(
+ CompanyDetailsPage({ params: Promise.resolve({ id: "any" }) }),
+ ).rejects.toThrow("NEXT_NOT_FOUND");
+ });
+
+ it("renders the details for a company the user owns", async () => {
+ getCompanyDetails.mockResolvedValue({ id: "co1", label: "Stripe" });
+
+ render(await CompanyDetailsPage({ params: Promise.resolve({ id: "co1" }) }));
+
+ expect(getCompanyDetails).toHaveBeenCalledWith("co1");
+ expect(screen.getByTestId("company-details")).toBeInTheDocument();
+ expect(notFound).not.toHaveBeenCalled();
+ });
+});
diff --git a/__tests__/JobTabEmptyState.spec.tsx b/__tests__/JobTabEmptyState.spec.tsx
new file mode 100644
index 0000000..22e5a86
--- /dev/null
+++ b/__tests__/JobTabEmptyState.spec.tsx
@@ -0,0 +1,30 @@
+import { render, screen } from "@testing-library/react";
+import { Briefcase } from "lucide-react";
+import { JobTabEmptyState } from "@/components/myjobs/job-details/JobTabEmptyState";
+
+describe("JobTabEmptyState", () => {
+ it("renders the action when given a label and a handler", () => {
+ render(
+ <JobTabEmptyState
+ icon={Briefcase}
+ title="Nothing here"
+ description="Add one."
+ actionLabel="Add"
+ onAction={vi.fn()}
+ />,
+ );
+ expect(screen.getByRole("button", { name: "Add" })).toBeInTheDocument();
+ });
+
+ it("renders no button without an action", () => {
+ render(
+ <JobTabEmptyState
+ icon={Briefcase}
+ title="Nothing here"
+ description="Nothing to do."
+ />,
+ );
+ expect(screen.getByText("Nothing here")).toBeInTheDocument();
+ expect(screen.queryByRole("button")).not.toBeInTheDocument();
+ });
+});
diff --git a/__tests__/useTabQueryParam.spec.tsx b/__tests__/useTabQueryParam.spec.tsx
new file mode 100644
index 0000000..2e49426
--- /dev/null
+++ b/__tests__/useTabQueryParam.spec.tsx
@@ -0,0 +1,43 @@
+import { renderHook } from "@testing-library/react";
+import { useTabQueryParam } from "@/hooks/useTabQueryParam";
+
+const router = { replace: vi.fn() };
+let searchParams = new URLSearchParams();
+
+vi.mock("next/navigation", () => ({
+ useRouter: () => router,
+ useSearchParams: () => searchParams,
+}));
+
+describe("useTabQueryParam", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ searchParams = new URLSearchParams();
+ });
+
+ it("keeps the other query params when switching tabs", () => {
+ searchParams = new URLSearchParams("scope=watchlist&tab=jobs");
+ const { result } = renderHook(() =>
+ useTabQueryParam(["jobs", "contacts"], "jobs"),
+ );
+
+ result.current[1]("contacts");
+
+ expect(router.replace).toHaveBeenCalledWith(
+ "?scope=watchlist&tab=contacts",
+ { scroll: false },
+ );
+ });
+
+ it("writes just the tab when there is nothing else in the URL", () => {
+ const { result } = renderHook(() =>
+ useTabQueryParam(["jobs", "contacts"], "jobs"),
+ );
+
+ result.current[1]("contacts");
+
+ expect(router.replace).toHaveBeenCalledWith("?tab=contacts", {
+ scroll: false,
+ });
+ });
+});
diff --git a/src/app/dashboard/admin/companies/[id]/page.tsx b/src/app/dashboard/admin/companies/[id]/page.tsx
new file mode 100644
index 0000000..8c062b2
--- /dev/null
+++ b/src/app/dashboard/admin/companies/[id]/page.tsx
@@ -0,0 +1,23 @@
+import { notFound } from "next/navigation";
+import { getCompanyDetails } from "@/actions/company.actions";
+import CompanyDetails from "@/components/admin/CompanyDetails";
+
+async function CompanyDetailsPage({
+ params,
+}: {
+ params: Promise<{ id: string }>;
+}) {
+ const { id } = await params;
+ const details = await getCompanyDetails(id);
+
+ // null (missing or not yours) and a failed read both land here
+ if (!details?.id) notFound();
+
+ return (
+ <div className="col-span-3">
+ <CompanyDetails details={details} />
+ </div>
+ );
+}
+
+export default CompanyDetailsPage;
diff --git a/src/components/admin/AddCompany.tsx b/src/components/admin/AddCompany.tsx
index fe995fe..fc173e4 100644
--- a/src/components/admin/AddCompany.tsx
+++ b/src/components/admin/AddCompany.tsx
@@ -33,6 +33,7 @@ type AddCompanyProps = {
resetEditCompany: () => void;
dialogOpen: boolean;
setDialogOpen: (e: boolean) => void;
+ hideTrigger?: boolean;
};
function AddCompany({
@@ -41,6 +42,7 @@ function AddCompany({
resetEditCompany,
dialogOpen,
setDialogOpen,
+ hideTrigger,
}: AddCompanyProps) {
const [isPending, startTransition] = useTransition();
@@ -106,18 +108,20 @@ function AddCompany({
return (
<>
- <Button
- size="sm"
- variant="outline"
- className="h-8 gap-1"
- onClick={addCompanyForm}
- data-testid="add-company-btn"
- >
- <PlusCircle className="h-3.5 w-3.5" />
- <span className="sr-only sm:not-sr-only sm:whitespace-nowrap">
- New Company
- </span>
- </Button>
+ {!hideTrigger && (
+ <Button
+ size="sm"
+ variant="outline"
+ className="h-8 gap-1"
+ onClick={addCompanyForm}
+ data-testid="add-company-btn"
+ >
+ <PlusCircle className="h-3.5 w-3.5" />
+ <span className="sr-only sm:not-sr-only sm:whitespace-nowrap">
+ New Company
+ </span>
+ </Button>
+ )}
<Dialog open={dialogOpen} onOpenChange={setDialogOpen}>
<DialogContent className="lg:max-h-screen overflow-y-scroll">
<DialogHeader>
diff --git a/src/components/admin/BoardCell.tsx b/src/components/admin/BoardCell.tsx
new file mode 100644
index 0000000..ade1ae3
--- /dev/null
+++ b/src/components/admin/BoardCell.tsx
@@ -0,0 +1,34 @@
+import { ExternalLink } from "lucide-react";
+import { companyBoardUrl } from "@/lib/atsBoardUrl";
+import { PROVIDER_META } from "@/components/automations/ats-search-step/types";
+import type { Company } from "@/models/job.model";
+import type { JobBoard, LeverHost } from "@/models/automation.model";
+
+// A watched row may have no board (a company watched from the Library), so the
+// cell degrades to an em dash rather than building a URL from a null token.
+export function BoardCell({ company }: { company: Company }) {
+ if (!company.atsToken || !company.atsProvider) {
+ return <span className="text-muted-foreground">—</span>;
+ }
+ const provider = company.atsProvider as JobBoard;
+ return (
+ <span className="flex items-center gap-1.5">
+ <span className="text-muted-foreground">
+ {PROVIDER_META[provider].label} {company.atsToken}
+ </span>
+ <a
+ href={companyBoardUrl(provider, {
+ token: company.atsToken,
+ host: (company.atsHost as LeverHost) ?? undefined,
+ })}
+ target="_blank"
+ rel="noopener noreferrer"
+ aria-label={`Open ${company.label} job board`}
+ title="Open job board"
+ className="text-muted-foreground hover:text-foreground"
+ >
+ <ExternalLink className="h-3.5 w-3.5" />
+ </a>
+ </span>
+ );
+}
diff --git a/src/components/admin/CompaniesTable.tsx b/src/components/admin/CompaniesTable.tsx
index 98c5fb8..6a865de 100644
--- a/src/components/admin/CompaniesTable.tsx
+++ b/src/components/admin/CompaniesTable.tsx
@@ -18,7 +18,6 @@ import {
import { Company } from "@/models/job.model";
import {
Briefcase,
- ExternalLink,
Eye,
EyeOff,
MoreVertical,
@@ -29,12 +28,10 @@ import { useState } from "react";
import Link from "next/link";
import { formatDistanceToNow } from "date-fns";
import { deleteCompanyById, setCompanyWatched } from "@/actions/company.actions";
-import { companyBoardUrl } from "@/lib/atsBoardUrl";
-import { PROVIDER_META } from "@/components/automations/ats-search-step/types";
import { toastSuccess, toastError } from "@/lib/toast";
import { DeleteAlertDialog } from "../DeleteAlertDialog";
import { AlertDialog } from "@/models/alertDialog.model";
-import type { JobBoard, LeverHost } from "@/models/automation.model";
+import { BoardCell } from "./BoardCell";
type CompaniesTableProps = {
companies: Company[];
@@ -43,35 +40,6 @@ type CompaniesTableProps = {
scope?: "mine" | "watchlist";
};
-// A watched row may have no board (a company watched from the Library), so the
-// cell degrades to an em dash rather than building a URL from a null token.
-function BoardCell({ company }: { company: Company }) {
- if (!company.atsToken || !company.atsProvider) {
- return <span className="text-muted-foreground">—</span>;
- }
- const provider = company.atsProvider as JobBoard;
- return (
- <span className="flex items-center gap-1.5">
- <span className="text-muted-foreground">
- {PROVIDER_META[provider].label} {company.atsToken}
- </span>
- <a
- href={companyBoardUrl(provider, {
- token: company.atsToken,
- host: (company.atsHost as LeverHost) ?? undefined,
- })}
- target="_blank"
- rel="noopener noreferrer"
- aria-label={`Open ${company.label} job board`}
- title="Open job board"
- className="text-muted-foreground hover:text-foreground"
- >
- <ExternalLink className="h-3.5 w-3.5" />
- </a>
- </span>
- );
-}
-
function CompaniesTable({
companies,
reloadCompanies,
diff --git a/src/components/admin/CompanyDetails.tsx b/src/components/admin/CompanyDetails.tsx
new file mode 100644
index 0000000..92c85e9
--- /dev/null
+++ b/src/components/admin/CompanyDetails.tsx
@@ -0,0 +1,166 @@
+"use client";
+import { useState } from "react";
+import { useRouter, useSearchParams } from "next/navigation";
+import { DeleteAlertDialog } from "../DeleteAlertDialog";
+import AddCompany from "./AddCompany";
+import {
+ deleteCompanyById,
+ setCompanyWatched,
+} from "@/actions/company.actions";
+import { toastError, toastSuccess } from "@/lib/toast";
+import { AlertDialog } from "@/models/alertDialog.model";
+import type { CompanyDetails as CompanyDetailsData } from "@/models/companyDetails.model";
+import type { Company } from "@/models/job.model";
+import { CompanyDetailsHeader } from "./company-details/CompanyDetailsHeader";
+import { CompanySummaryCard } from "./company-details/CompanySummaryCard";
+import { Badge } from "../ui/badge";
+import { Card } from "../ui/card";
+import { Tabs, TabsContent, TabsList, TabsTrigger } from "../ui/tabs";
+import { useTabQueryParam } from "@/hooks/useTabQueryParam";
+import { CompanyJobsTab } from "./company-details/CompanyJobsTab";
+
+const LIBRARY_COMPANIES = "/dashboard/admin?tab=companies";
+const COMPANY_DETAIL_TABS = ["jobs"] as const;
+
+type CompanyDetailsProps = {
+ details: CompanyDetailsData;
+};
+
+function blockedDescription(total: number, dismissed: number) {
+ const jobs = `This company has ${total} associated job${total === 1 ? "" : "s"} (applied or not).`;
+ const hidden =
+ dismissed > 0
+ ? ` ${dismissed} of them ${dismissed === 1 ? "was" : "were"} dismissed by automations; pick Dismissed (discovered) on the Jobs page to see them.`
+ : "";
+ return `${jobs}${hidden} Remove or reassign them before deleting this company.`;
+}
+
+function CompanyDetails({ details }: CompanyDetailsProps) {
+ const router = useRouter();
+ const searchParams = useSearchParams();
+ const backHref =
+ searchParams.get("scope") === "watchlist"
+ ? `${LIBRARY_COMPANIES}&scope=watchlist`
+ : LIBRARY_COMPANIES;
+ const [activeTab, handleTabChange] = useTabQueryParam(
+ COMPANY_DETAIL_TABS,
+ "jobs",
+ );
+ const [editOpen, setEditOpen] = useState(false);
+ const [editTarget, setEditTarget] = useState<Company | null>(null);
+ const [alert, setAlert] = useState<AlertDialog>({
+ openState: false,
+ deleteAction: false,
+ });
+
+ const { jobs, dismissedJobsCount, currentContacts, formerContacts } = details;
+ const contactsCount = new Set(
+ [...currentContacts, ...formerContacts].map((contact) => contact.id),
+ ).size;
+
+ const toggleWatch = async () => {
+ const next = !details.watched;
+ const res = await setCompanyWatched(details.id, next);
+ if (res.success) {
+ toastSuccess(
+ next
+ ? `${details.label} added to your watchlist`
+ : `${details.label} removed from your watchlist. It stays in your Library.`,
+ );
+ router.refresh();
+ } else {
+ toastError(res.message);
+ }
+ };
+
+ // AddCompany refills its form only when editCompany changes identity, so
+ // a fresh copy per open discards an abandoned edit
+ const openEdit = () => {
+ setEditTarget({ ...details });
+ setEditOpen(true);
+ };
+
+ // Jobs block up front, dismissed ones included, because the server guard
+ // counts them; contacts and resume entries are left to the server message.
+ const onDelete = () => {
+ const total = jobs.length + dismissedJobsCount;
+ if (total > 0) {
+ setAlert({
+ openState: true,
+ deleteAction: false,
+ title: "Associated jobs exist!",
+ description: blockedDescription(total, dismissedJobsCount),
+ });
+ } else {
+ setAlert({ openState: true, deleteAction: true, itemId: details.id });
+ }
+ };
+
+ const deleteCompany = async () => {
+ const { success, message } = await deleteCompanyById(details.id);
+ if (success) {
+ toastSuccess("Company has been deleted successfully");
+ router.push(backHref);
+ } else {
+ toastError(message);
+ }
+ };
+
+ return (
+ <>
+ <div className="py-6 space-y-6">
+ <CompanyDetailsHeader
+ company={details}
+ backHref={backHref}
+ onToggleWatch={toggleWatch}
+ onEdit={openEdit}
+ onDelete={onDelete}
+ />
+
+ <CompanySummaryCard
+ company={details}
+ jobsCount={jobs.length}
+ appliedCount={details.appliedCount}
+ contactsCount={contactsCount}
+ />
+
+ <Tabs value={activeTab} onValueChange={handleTabChange}>
+ <TabsList>
+ <TabsTrigger value="jobs">
+ Jobs
+ {jobs.length > 0 && (
+ <Badge variant="secondary" className="ml-2">
+ {jobs.length}
+ </Badge>
+ )}
+ </TabsTrigger>
+ </TabsList>
+ <TabsContent value="jobs" className="mt-4">
+ <Card className="p-6">
+ <CompanyJobsTab jobs={jobs} />
+ </Card>
+ </TabsContent>
+ </Tabs>
+ </div>
+ <AddCompany
+ hideTrigger
+ editCompany={editTarget}
+ reloadCompanies={() => router.refresh()}
+ resetEditCompany={() => {}}
+ dialogOpen={editOpen}
+ setDialogOpen={setEditOpen}
+ />
+ <DeleteAlertDialog
+ pageTitle="company"
+ open={alert.openState}
+ onOpenChange={() => setAlert({ openState: false, deleteAction: false })}
+ onDelete={deleteCompany}
+ alertTitle={alert.title}
+ alertDescription={alert.description}
+ deleteAction={alert.deleteAction}
+ />
+ </>
+ );
+}
+
+export default CompanyDetails;
diff --git a/src/components/admin/company-details/CompanyDetailsHeader.tsx b/src/components/admin/company-details/CompanyDetailsHeader.tsx
new file mode 100644
index 0000000..e8299e1
--- /dev/null
+++ b/src/components/admin/company-details/CompanyDetailsHeader.tsx
@@ -0,0 +1,128 @@
+"use client";
+
+import Link from "next/link";
+import {
+ ArrowLeft,
+ ExternalLink,
+ Eye,
+ EyeOff,
+ MoreVertical,
+ Pencil,
+ Trash2,
+} from "lucide-react";
+import { Button } from "@/components/ui/button";
+import {
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuLabel,
+ DropdownMenuTrigger,
+} from "@/components/ui/dropdown-menu";
+import { CompanyLogo } from "@/components/myjobs/CompanyLogo";
+import { companyBoardUrl } from "@/lib/atsBoardUrl";
+import { formatUrl } from "@/lib/utils";
+import type { Company } from "@/models/job.model";
+import type { LeverHost } from "@/models/automation.model";
+import { hostnameOf } from "./hostname";
+
+type CompanyDetailsHeaderProps = {
+ company: Company;
+ backHref: string;
+ onToggleWatch: () => void;
+ onEdit: () => void;
+ onDelete: () => void;
+};
+
+export function CompanyDetailsHeader({
+ company,
+ backHref,
+ onToggleWatch,
+ onEdit,
+ onDelete,
+}: CompanyDetailsHeaderProps) {
+ const subtitle = [company.industry, hostnameOf(company.websiteUrl)]
+ .filter(Boolean)
+ .join(" · ");
+
+ const boardUrl =
+ company.atsProvider && company.atsToken
+ ? companyBoardUrl(company.atsProvider, {
+ token: company.atsToken,
+ host: (company.atsHost as LeverHost) ?? undefined,
+ })
+ : null;
+ const links = [
+ { label: "Open website", href: company.websiteUrl ? formatUrl(company.websiteUrl) : null },
+ { label: "Open careers page", href: company.careersUrl ? formatUrl(company.careersUrl) : null },
+ { label: "Open job board", href: boardUrl },
+ ].filter((link): link is { label: string; href: string } => !!link.href);
+
+ return (
+ <div className="flex flex-col gap-4 @5xl/main:flex-row @5xl/main:items-center">
+ <div className="flex flex-1 min-w-0 items-center gap-4">
+ <Button variant="ghost" size="icon" title="Go Back" asChild>
+ <Link href={backHref} aria-label="Back to Companies">
+ <ArrowLeft className="h-4 w-4" />
+ </Link>
+ </Button>
+ <CompanyLogo
+ logoUrl={company.logoUrl}
+ className="h-10 w-10 min-w-10"
+ />
+ <div className="flex-1 min-w-0">
+ <h1 className="text-2xl font-bold">{company.label}</h1>
+ {subtitle && <p className="text-muted-foreground">{subtitle}</p>}
+ </div>
+ </div>
+ <div className="flex flex-wrap justify-end gap-2">
+ <Button variant="outline" className="cursor-pointer" onClick={onToggleWatch}>
+ {company.watched ? (
+ <EyeOff className="h-4 w-4 sm:mr-2" />
+ ) : (
+ <Eye className="h-4 w-4 sm:mr-2" />
+ )}
+ <span className="sr-only sm:not-sr-only sm:whitespace-nowrap">
+ {company.watched ? "Unwatch" : "Watch"}
+ </span>
+ </Button>
+ <Button variant="outline" className="cursor-pointer" onClick={onEdit}>
+ <Pencil className="h-4 w-4 sm:mr-2" />
+ <span className="sr-only sm:not-sr-only sm:whitespace-nowrap">
+ Edit
+ </span>
+ </Button>
+ <Button
+ variant="outline"
+ className="text-destructive hover:text-destructive cursor-pointer"
+ onClick={onDelete}
+ >
+ <Trash2 className="h-4 w-4 sm:mr-2" />
+ <span className="sr-only sm:not-sr-only sm:whitespace-nowrap">
+ Delete
+ </span>
+ </Button>
+ {links.length > 0 && (
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <Button aria-haspopup="true" size="icon" variant="ghost">
+ <MoreVertical className="h-4 w-4" />
+ <span className="sr-only">More links</span>
+ </Button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="end" className="w-[200px]">
+ <DropdownMenuLabel>Links</DropdownMenuLabel>
+ {links.map((link) => (
+ <DropdownMenuItem key={link.label} className="cursor-pointer" asChild>
+ <a href={link.href} target="_blank" rel="noopener noreferrer">
+ <ExternalLink className="mr-2 h-4 w-4" />
+ {link.label}
+ </a>
+ </DropdownMenuItem>
+ ))}
+ </DropdownMenuContent>
+ </DropdownMenu>
+ )}
+ </div>
+ </div>
+ );
+}
diff --git a/src/components/admin/company-details/CompanyJobsTab.tsx b/src/components/admin/company-details/CompanyJobsTab.tsx
new file mode 100644
index 0000000..8614251
--- /dev/null
+++ b/src/components/admin/company-details/CompanyJobsTab.tsx
@@ -0,0 +1,88 @@
+"use client";
+
+import Link from "next/link";
+import { format } from "date-fns";
+import { Briefcase } from "lucide-react";
+import {
+ Table,
+ TableBody,
+ TableCell,
+ TableHead,
+ TableHeader,
+ TableRow,
+} from "@/components/ui/table";
+import { CircularScore } from "@/components/CircularScore";
+import { StatusBadge } from "@/components/StatusBadge";
+import { JobTabEmptyState } from "@/components/myjobs/job-details/JobTabEmptyState";
+import { getJobStatusBadgeColor } from "@/lib/badge-colors";
+import type { CompanyJobRow } from "@/models/companyDetails.model";
+
+type CompanyJobsTabProps = {
+ jobs: CompanyJobRow[];
+};
+
+// Read-only on purpose: every job action already lives on the job's own page
+export function CompanyJobsTab({ jobs }: CompanyJobsTabProps) {
+ if (jobs.length === 0) {
+ return (
+ <JobTabEmptyState
+ icon={Briefcase}
+ title="No jobs at this company yet"
+ description="Jobs you add or accept from an automation for this company show up here."
+ />
+ );
+ }
+
+ return (
+ <Table>
+ <TableHeader>
+ <TableRow>
+ <TableHead>Title</TableHead>
+ <TableHead>Status</TableHead>
+ <TableHead className="hidden md:table-cell">Location</TableHead>
+ <TableHead className="hidden md:table-cell">Applied</TableHead>
+ <TableHead>Match</TableHead>
+ <TableHead className="hidden md:table-cell">Source</TableHead>
+ </TableRow>
+ </TableHeader>
+ <TableBody>
+ {jobs.map((job) => (
+ <TableRow key={job.id}>
+ <TableCell className="font-medium">
+ <Link
+ href={`/dashboard/myjobs/${job.id}`}
+ className="hover:underline underline-offset-4"
+ >
+ {job.JobTitle.label}
+ </Link>
+ </TableCell>
+ <TableCell>
+ <StatusBadge
+ label={job.Status.label}
+ color={getJobStatusBadgeColor(job.Status.value)}
+ />
+ </TableCell>
+ <TableCell className="hidden md:table-cell">
+ {job.Location?.label ?? "—"}
+ </TableCell>
+ <TableCell className="hidden md:table-cell">
+ {job.appliedDate
+ ? format(new Date(job.appliedDate), "PP")
+ : "Not applied"}
+ </TableCell>
+ <TableCell>
+ {job.matchScore != null ? (
+ <CircularScore score={job.matchScore} size="sm" />
+ ) : (
+ "—"
+ )}
+ </TableCell>
+ <TableCell className="hidden md:table-cell">
+ {job.JobSource?.label ?? "—"}
+ </TableCell>
+ </TableRow>
+ ))}
+ </TableBody>
+ </Table>
+ );
+}
diff --git a/src/components/admin/company-details/CompanySummaryCard.tsx b/src/components/admin/company-details/CompanySummaryCard.tsx
new file mode 100644
index 0000000..5e61322
--- /dev/null
+++ b/src/components/admin/company-details/CompanySummaryCard.tsx
@@ -0,0 +1,84 @@
+"use client";
+
+import { formatDistanceToNow } from "date-fns";
+import { Card, CardContent } from "@/components/ui/card";
+import { BoardCell } from "@/components/admin/BoardCell";
+import { formatUrl } from "@/lib/utils";
+import type { Company } from "@/models/job.model";
+import { hostnameOf } from "./hostname";
+
+type CompanySummaryCardProps = {
+ company: Company;
+ jobsCount: number;
+ appliedCount: number;
+ contactsCount: number;
+};
+
+function Fact({ label, children }: { label: string; children: React.ReactNode }) {
+ return (
+ <div>
+ <p className="text-sm text-muted-foreground">{label}</p>
+ <div className="mt-1 font-medium">{children}</div>
+ </div>
+ );
+}
+
+function HostLink({ url }: { url?: string | null }) {
+ const host = hostnameOf(url);
+ if (!url || !host) return <>—</>;
+ return (
+ <a
+ href={formatUrl(url)}
+ target="_blank"
+ rel="noopener noreferrer"
+ className="hover:underline underline-offset-4"
+ >
+ {host}
+ </a>
+ );
+}
+
+export function CompanySummaryCard({
+ company,
+ jobsCount,
+ appliedCount,
+ contactsCount,
+}: CompanySummaryCardProps) {
+ return (
+ <Card data-testid="company-summary">
+ <CardContent className="pt-6">
+ <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
+ <Fact label="Watchlist">
+ {company.watched ? (
+ <>
+ Watched
+ {company.watchedAt && (
+ <span className="block text-sm font-normal text-muted-foreground">
+ {formatDistanceToNow(new Date(company.watchedAt), {
+ addSuffix: true,
+ })}
+ </span>
+ )}
+ </>
+ ) : (
+ "Not watched"
+ )}
+ </Fact>
+ <Fact label="Board">
+ <BoardCell company={company} />
+ </Fact>
+ <Fact label="Industry">{company.industry || "—"}</Fact>
+ <Fact label="Website">
+ <HostLink url={company.websiteUrl} />
+ </Fact>
+ <Fact label="Careers page">
+ <HostLink url={company.careersUrl} />
+ </Fact>
+ <Fact label="Jobs">{jobsCount}</Fact>
+ <Fact label="Applied">{appliedCount}</Fact>
+ <Fact label="Contacts">{contactsCount}</Fact>
+ </div>
+ </CardContent>
+ </Card>
+ );
+}
diff --git a/src/components/admin/company-details/hostname.ts b/src/components/admin/company-details/hostname.ts
new file mode 100644
index 0000000..94916d7
--- /dev/null
+++ b/src/components/admin/company-details/hostname.ts
@@ -0,0 +1,11 @@
+import { formatUrl } from "@/lib/utils";
+
+// The subtitle and the summary card show a host, not a full URL
+export function hostnameOf(url?: string | null): string | null {
+ if (!url) return null;
+ try {
+ return new URL(formatUrl(url)).hostname;
+ } catch {
+ return null;
+ }
+}
diff --git a/src/components/myjobs/job-details/JobTabEmptyState.tsx b/src/components/myjobs/job-details/JobTabEmptyState.tsx
index 118bd2e..fbc8f44 100644
--- a/src/components/myjobs/job-details/JobTabEmptyState.tsx
+++ b/src/components/myjobs/job-details/JobTabEmptyState.tsx
@@ -7,8 +7,8 @@ type JobTabEmptyStateProps = {
icon: LucideIcon;
title: string;
description: string;
- actionLabel: string;
- onAction: () => void;
+ actionLabel?: string;
+ onAction?: () => void;
actionDisabled?: boolean;
actionTitle?: string;
};
@@ -31,15 +31,17 @@ export function JobTabEmptyState({
<p className="max-w-[40ch] text-sm text-muted-foreground">
{description}
</p>
- <Button
- className="mt-1 cursor-pointer"
- onClick={onAction}
- disabled={actionDisabled}
- title={actionTitle}
- >
- <Icon className="h-4 w-4 mr-2" />
- {actionLabel}
- </Button>
+ {actionLabel && onAction && (
+ <Button
+ className="mt-1 cursor-pointer"
+ onClick={onAction}
+ disabled={actionDisabled}
+ title={actionTitle}
+ >
+ <Icon className="h-4 w-4 mr-2" />
+ {actionLabel}
+ </Button>
+ )}
</div>
);
}
diff --git a/src/hooks/useTabQueryParam.ts b/src/hooks/useTabQueryParam.ts
index 60a466f..f3eadbe 100644
--- a/src/hooks/useTabQueryParam.ts
+++ b/src/hooks/useTabQueryParam.ts
@@ -10,7 +10,9 @@ export function useTabQueryParam(
const activeTab = raw && validTabs.includes(raw) ? raw : defaultTab;
const setTab = (tab: string) => {
- router.replace(`?tab=${tab}`, { scroll: false });
+ const params = new URLSearchParams(searchParams.toString());
+ params.set("tab", tab);
+ router.replace(`?${params.toString()}`, { scroll: false });
};
return [activeTab, setTab] as const;