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 Contacts tab; AddContact company prefill and ContactsTable hideCompanyColumn

Khuram Niaz312048da1e28
diff --git a/__tests__/AddContact.spec.tsx b/__tests__/AddContact.spec.tsx
index b499580..5bf836c 100644
--- a/__tests__/AddContact.spec.tsx
+++ b/__tests__/AddContact.spec.tsx
@@ -61,6 +61,55 @@ describe("AddContact", () => {
expect(screen.getByLabelText(/^name$/i)).toHaveValue("Priya");
});
+ it("prefills the company when asked", () => {
+ render(<AddContact {...props} prefillCompanyId="co1" />);
+ expect(
+ screen.getByRole("combobox", { name: /^company$/i }),
+ ).toHaveTextContent("Shopify");
+ });
+
+ it("saves the prefilled company with the new contact", async () => {
+ (createContact as any).mockResolvedValue({ success: true, data: { id: "c1" } });
+
+ render(<AddContact {...props} prefillCompanyId="co1" />);
+ await user.type(screen.getByLabelText(/^name$/i), "Dave Patel");
+ await user.click(screen.getByRole("button", { name: /save/i }));
+
+ await waitFor(() =>
+ expect(createContact).toHaveBeenCalledWith(
+ expect.objectContaining({ name: "Dave Patel", company: "co1" }),
+ ),
+ );
+ });
+
+ it("ignores the company prefill when editing", () => {
+ render(
+ <AddContact
+ {...props}
+ prefillCompanyId="co1"
+ editContact={{ id: "c1", name: "Dave Patel", companyId: null } as any}
+ />,
+ );
+ expect(
+ screen.getByRole("combobox", { name: /^company$/i }),
+ ).toHaveTextContent(/select company/i);
+ });
+
+ it("starts from the prefill again each time the dialog reopens", async () => {
+ const { rerender } = render(
+ <AddContact {...props} hideTrigger prefillCompanyId="co1" />,
+ );
+ await user.type(screen.getByLabelText(/^name$/i), "Half typed");
+
+ rerender(<AddContact {...props} hideTrigger prefillCompanyId="co1" dialogOpen={false} />);
+ rerender(<AddContact {...props} hideTrigger prefillCompanyId="co1" dialogOpen />);
+
+ expect(screen.getByLabelText(/^name$/i)).toHaveValue("");
+ expect(
+ screen.getByRole("combobox", { name: /^company$/i }),
+ ).toHaveTextContent("Shopify");
+ });
+
it("updates instead of creating when editing", async () => {
(updateContact as any).mockResolvedValue({ success: true, data: { id: "c1" } });
diff --git a/__tests__/CompanyDetails.spec.tsx b/__tests__/CompanyDetails.spec.tsx
index a2c458b..c43baac 100644
--- a/__tests__/CompanyDetails.spec.tsx
+++ b/__tests__/CompanyDetails.spec.tsx
@@ -4,7 +4,9 @@ import userEvent from "@testing-library/user-event";
import {
deleteCompanyById,
setCompanyWatched,
+ getAllCompanies,
} from "@/actions/company.actions";
+import { deleteContactById, getContactById } from "@/actions/contact.actions";
import { toastError } from "@/lib/toast";
const router = { push: vi.fn(), replace: vi.fn(), refresh: vi.fn(), back: vi.fn() };
@@ -36,6 +38,25 @@ vi.mock("@/components/CircularScore", () => ({
),
}));
+vi.mock("@/actions/contact.actions", () => ({
+ getContactById: vi.fn(),
+ deleteContactById: vi.fn(),
+ createContact: vi.fn(),
+ updateContact: vi.fn(),
+}));
+
+vi.mock("@/actions/contactRole.actions", () => ({
+ getAllContactRoles: vi.fn().mockResolvedValue([]),
+ createContactRole: vi.fn(),
+}));
+
+vi.mock("@/actions/jobLocation.actions", () => ({
+ getAllJobLocations: vi.fn().mockResolvedValue([]),
+}));
+
+// jsdom lacks scrollIntoView, which cmdk calls when selecting an item
+Element.prototype.scrollIntoView = vi.fn();
+
const makeDetails = (overrides: Record<string, unknown> = {}) =>
({
id: "co1",
@@ -380,3 +401,116 @@ describe("CompanyDetails – Jobs tab", () => {
expect(screen.getByRole("tab", { name: /jobs/i })).toHaveTextContent(/^Jobs$/);
});
});
+
+describe("CompanyDetails – Contacts tab", () => {
+ const user = userEvent.setup({ skipHover: true });
+
+ const person = (id: string, name: string, overrides: Record<string, unknown> = {}) => ({
+ id,
+ name,
+ title: null,
+ email: null,
+ phone: null,
+ linkedinUrl: null,
+ companyId: null,
+ Company: null,
+ locationId: null,
+ Location: null,
+ relationship: null,
+ workedAtCompanyId: null,
+ WorkedAtCompany: null,
+ workedFrom: null,
+ workedTo: null,
+ roleId: null,
+ Role: null,
+ notes: null,
+ lastContactedAt: null,
+ createdAt: new Date(),
+ updatedAt: new Date(),
+ createdBy: "u1",
+ jobLinks: [],
+ _count: { jobLinks: 0 },
+ ...overrides,
+ });
+
+ const dave = person("c1", "Dave Patel", { companyId: "co1", Company: { id: "co1", label: "Stripe" } });
+ const priya = person("c2", "Priya Nair", { workedAtCompanyId: "co1", WorkedAtCompany: { id: "co1", label: "Stripe" } });
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+ searchParams = new URLSearchParams("tab=contacts");
+ (getAllCompanies as any).mockResolvedValue([
+ { id: "co1", label: "Stripe", value: "stripe", createdBy: "u1" },
+ ]);
+ });
+
+ it("shows only the sections that have people", () => {
+ render(<CompanyDetails details={makeDetails({ currentContacts: [dave] })} />);
+
+ expect(screen.getByRole("heading", { name: "Works here" })).toBeInTheDocument();
+ expect(screen.queryByRole("heading", { name: "Worked with you here" })).not.toBeInTheDocument();
+ });
+
+ it("drops the Company column only in Works here", () => {
+ render(
+ <CompanyDetails
+ details={makeDetails({ currentContacts: [dave], formerContacts: [priya] })}
+ />,
+ );
+
+ expect(screen.getAllByRole("columnheader", { name: "Company" })).toHaveLength(1);
+ });
+
+ it("lists someone in both groups twice but counts them once", () => {
+ render(
+ <CompanyDetails
+ details={makeDetails({ currentContacts: [dave], formerContacts: [dave] })}
+ />,
+ );
+
+ expect(screen.getAllByText("Dave Patel")).toHaveLength(2);
+ expect(screen.getByRole("tab", { name: /contacts/i })).toHaveTextContent("1");
+ expect(fact("Contacts")).toHaveTextContent("1");
+ });
+
+ it("offers Add Contact from the empty state and loads the pickers once", async () => {
+ render(<CompanyDetails details={makeDetails()} />);
+
+ const panel = screen.getByRole("tabpanel");
+ expect(within(panel).getByText("No contacts at this company yet")).toBeInTheDocument();
+
+ await user.click(within(panel).getByRole("button", { name: "Add Contact" }));
+ expect(
+ await screen.findByRole("combobox", { name: /^company$/i }),
+ ).toHaveTextContent("Stripe");
+
+ await user.keyboard("{Escape}");
+ await user.click(within(panel).getByRole("button", { name: "Add Contact" }));
+ await screen.findByRole("combobox", { name: /^company$/i });
+
+ expect(getAllCompanies).toHaveBeenCalledTimes(1);
+ });
+
+ it("opens the dialog in edit mode from a row", async () => {
+ (getContactById as any).mockResolvedValue(dave);
+ render(<CompanyDetails details={makeDetails({ currentContacts: [dave] })} />);
+
+ await user.click(screen.getByRole("button", { name: /toggle menu/i }));
+ await user.click(await screen.findByRole("menuitem", { name: /edit contact/i }));
+
+ expect(getContactById).toHaveBeenCalledWith("c1");
+ expect(await screen.findByRole("heading", { name: "Edit Contact" })).toBeInTheDocument();
+ });
+
+ it("refreshes the page after deleting a contact", async () => {
+ (deleteContactById as any).mockResolvedValue({ success: true });
+ render(<CompanyDetails details={makeDetails({ currentContacts: [dave] })} />);
+
+ await user.click(screen.getByRole("button", { name: /toggle menu/i }));
+ await user.click(await screen.findByRole("menuitem", { name: /delete/i }));
+ const dialog = await screen.findByRole("alertdialog");
+ await user.click(within(dialog).getByRole("button", { name: /delete/i }));
+
+ await waitFor(() => expect(router.refresh).toHaveBeenCalled());
+ });
+});
diff --git a/__tests__/ContactsTable.spec.tsx b/__tests__/ContactsTable.spec.tsx
new file mode 100644
index 0000000..2483d79
--- /dev/null
+++ b/__tests__/ContactsTable.spec.tsx
@@ -0,0 +1,70 @@
+import ContactsTable from "@/components/admin/ContactsTable";
+import { render, screen } from "@testing-library/react";
+import userEvent from "@testing-library/user-event";
+
+vi.mock("@/actions/contact.actions", () => ({
+ deleteContactById: vi.fn(),
+}));
+
+vi.mock("@/lib/toast", () => ({
+ toastSuccess: vi.fn(),
+ toastError: vi.fn(),
+}));
+
+const contact = {
+ id: "c1",
+ name: "Dave Patel",
+ title: null,
+ email: null,
+ phone: null,
+ linkedinUrl: null,
+ companyId: "co1",
+ Company: { id: "co1", label: "Shopify" },
+ locationId: null,
+ Location: null,
+ relationship: null,
+ workedAtCompanyId: null,
+ WorkedAtCompany: null,
+ workedFrom: null,
+ workedTo: null,
+ roleId: null,
+ Role: null,
+ notes: "Met at a meetup",
+ lastContactedAt: null,
+ createdAt: new Date(),
+ updatedAt: new Date(),
+ createdBy: "u1",
+ jobLinks: [],
+ _count: { jobLinks: 0 },
+} as any;
+
+describe("ContactsTable", () => {
+ const user = userEvent.setup({ skipHover: true });
+
+ it("shows the Company column by default", () => {
+ render(
+ <ContactsTable contacts={[contact]} reloadContacts={vi.fn()} editContact={vi.fn()} />,
+ );
+
+ expect(screen.getByRole("columnheader", { name: "Company" })).toBeInTheDocument();
+ expect(screen.getByText("Shopify")).toBeInTheDocument();
+ });
+
+ it("drops the Company column and narrows the expanded row when asked", async () => {
+ render(
+ <ContactsTable
+ contacts={[contact]}
+ reloadContacts={vi.fn()}
+ editContact={vi.fn()}
+ hideCompanyColumn
+ />,
+ );
+
+ expect(screen.queryByRole("columnheader", { name: "Company" })).not.toBeInTheDocument();
+ expect(screen.queryByText("Shopify")).not.toBeInTheDocument();
+
+ await user.click(screen.getByRole("button", { name: /expand dave patel/i }));
+
+ expect(screen.getByText("Met at a meetup").closest("td")).toHaveAttribute("colspan", "7");
+ });
+});
diff --git a/src/components/AddContact.tsx b/src/components/AddContact.tsx
index 6c97189..2066c4e 100644
--- a/src/components/AddContact.tsx
+++ b/src/components/AddContact.tsx
@@ -43,6 +43,7 @@ type AddContactProps = {
locations: JobLocation[];
roles: ContactRole[];
prefillName?: string;
+ prefillCompanyId?: string;
hideTrigger?: boolean;
pickersLoading?: boolean;
onSaved?: (contact: ContactRef) => void;
@@ -89,6 +90,7 @@ function AddContact({
locations,
roles,
prefillName,
+ prefillCompanyId,
hideTrigger,
pickersLoading,
onSaved,
@@ -97,11 +99,15 @@ function AddContact({
const pageTitle = editContact ? "Edit Contact" : "Add Contact";
+ const prefilled: ContactFormValues = {
+ ...EMPTY_CONTACT,
+ ...(prefillName ? { name: prefillName } : {}),
+ ...(prefillCompanyId ? { company: prefillCompanyId } : {}),
+ };
+
const form = useForm<ContactFormValues>({
resolver: zodResolver(AddContactFormSchema),
- defaultValues: prefillName
- ? { ...EMPTY_CONTACT, name: prefillName }
- : EMPTY_CONTACT,
+ defaultValues: prefilled,
});
const { reset } = form;
@@ -151,10 +157,17 @@ function AddContact({
},
{ keepDefaultValues: true },
);
- } else if (prefillName) {
- reset({ ...EMPTY_CONTACT, name: prefillName }, { keepDefaultValues: true });
+ } else if (dialogOpen && (prefillName || prefillCompanyId)) {
+ reset(
+ {
+ ...EMPTY_CONTACT,
+ ...(prefillName ? { name: prefillName } : {}),
+ ...(prefillCompanyId ? { company: prefillCompanyId } : {}),
+ },
+ { keepDefaultValues: true },
+ );
}
- }, [editContact, prefillName, reset]);
+ }, [editContact, prefillName, prefillCompanyId, dialogOpen, reset]);
const openDialog = () => {
if (!editContact) {
diff --git a/src/components/admin/CompanyDetails.tsx b/src/components/admin/CompanyDetails.tsx
index 92c85e9..70d4673 100644
--- a/src/components/admin/CompanyDetails.tsx
+++ b/src/components/admin/CompanyDetails.tsx
@@ -18,9 +18,10 @@ import { Card } from "../ui/card";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "../ui/tabs";
import { useTabQueryParam } from "@/hooks/useTabQueryParam";
import { CompanyJobsTab } from "./company-details/CompanyJobsTab";
+import { CompanyContactsTab } from "./company-details/CompanyContactsTab";
const LIBRARY_COMPANIES = "/dashboard/admin?tab=companies";
-const COMPANY_DETAIL_TABS = ["jobs"] as const;
+const COMPANY_DETAIL_TABS = ["jobs", "contacts"] as const;
type CompanyDetailsProps = {
details: CompanyDetailsData;
@@ -134,12 +135,29 @@ function CompanyDetails({ details }: CompanyDetailsProps) {
</Badge>
)}
</TabsTrigger>
+ <TabsTrigger value="contacts">
+ Contacts
+ {contactsCount > 0 && (
+ <Badge variant="secondary" className="ml-2">
+ {contactsCount}
+ </Badge>
+ )}
+ </TabsTrigger>
</TabsList>
<TabsContent value="jobs" className="mt-4">
<Card className="p-6">
<CompanyJobsTab jobs={jobs} />
</Card>
</TabsContent>
+ <TabsContent value="contacts" className="mt-4">
+ <Card className="p-6">
+ <CompanyContactsTab
+ companyId={details.id}
+ currentContacts={currentContacts}
+ formerContacts={formerContacts}
+ />
+ </Card>
+ </TabsContent>
</Tabs>
</div>
<AddCompany
diff --git a/src/components/admin/ContactRow.tsx b/src/components/admin/ContactRow.tsx
index cff9f5a..93a9aed 100644
--- a/src/components/admin/ContactRow.tsx
+++ b/src/components/admin/ContactRow.tsx
@@ -26,6 +26,7 @@ type ContactRowProps = {
onToggle: () => void;
onEdit: () => void;
onDelete: () => void;
+ hideCompanyColumn?: boolean;
};
function overlapLabel(contact: Contact) {
@@ -40,6 +41,7 @@ function ContactRow({
onToggle,
onEdit,
onDelete,
+ hideCompanyColumn,
}: ContactRowProps) {
const links = contact.jobLinks ?? [];
// The standing role first, then any per-job role it does not already cover
@@ -76,7 +78,9 @@ function ContactRow({
<TableCell className="hidden sm:table-cell">
{contact.title ?? "—"}
</TableCell>
- <TableCell>{contact.Company?.label ?? "—"}</TableCell>
+ {!hideCompanyColumn && (
+ <TableCell>{contact.Company?.label ?? "—"}</TableCell>
+ )}
<TableCell>
{roles.length > 0 ? (
<span className="flex flex-wrap gap-1">
@@ -126,7 +130,7 @@ function ContactRow({
</TableRow>
{expanded && (
<TableRow>
- <TableCell colSpan={8} className="bg-muted/40">
+ <TableCell colSpan={hideCompanyColumn ? 7 : 8} className="bg-muted/40">
<div className="grid gap-4 sm:grid-cols-2 text-sm">
{hasContactBlock && (
<div className="space-y-1">
diff --git a/src/components/admin/ContactsTable.tsx b/src/components/admin/ContactsTable.tsx
index 77b81bd..99e8d5a 100644
--- a/src/components/admin/ContactsTable.tsx
+++ b/src/components/admin/ContactsTable.tsx
@@ -18,12 +18,14 @@ type ContactsTableProps = {
contacts: Contact[];
reloadContacts: () => void;
editContact: (id: string) => void;
+ hideCompanyColumn?: boolean;
};
function ContactsTable({
contacts,
reloadContacts,
editContact,
+ hideCompanyColumn,
}: ContactsTableProps) {
const [expandedId, setExpandedId] = useState<string | null>(null);
const [alert, setAlert] = useState<AlertDialog>({
@@ -69,7 +71,7 @@ function ContactsTable({
</TableHead>
<TableHead>Name</TableHead>
<TableHead className="hidden sm:table-cell">Title</TableHead>
- <TableHead>Company</TableHead>
+ {!hideCompanyColumn && <TableHead>Company</TableHead>}
<TableHead>Roles</TableHead>
<TableHead>Jobs</TableHead>
<TableHead>Last contacted</TableHead>
@@ -91,6 +93,7 @@ function ContactsTable({
}
onEdit={() => editContact(contact.id)}
onDelete={() => onDeleteContact(contact)}
+ hideCompanyColumn={hideCompanyColumn}
/>
))}
</TableBody>
diff --git a/src/components/admin/company-details/CompanyContactsTab.tsx b/src/components/admin/company-details/CompanyContactsTab.tsx
new file mode 100644
index 0000000..ade1030
--- /dev/null
+++ b/src/components/admin/company-details/CompanyContactsTab.tsx
@@ -0,0 +1,128 @@
+"use client";
+
+import { useCallback, useRef, useState } from "react";
+import { useRouter } from "next/navigation";
+import { PlusCircle, Users } from "lucide-react";
+import { Button } from "@/components/ui/button";
+import AddContact from "@/components/AddContact";
+import ContactsTable from "@/components/admin/ContactsTable";
+import { JobTabEmptyState } from "@/components/myjobs/job-details/JobTabEmptyState";
+import { getContactById } from "@/actions/contact.actions";
+import { getAllCompanies } from "@/actions/company.actions";
+import { getAllJobLocations } from "@/actions/jobLocation.actions";
+import { getAllContactRoles } from "@/actions/contactRole.actions";
+import type { Contact, ContactRole } from "@/models/contact.model";
+import type { Company, JobLocation } from "@/models/job.model";
+
+type CompanyContactsTabProps = {
+ companyId: string;
+ currentContacts: Contact[];
+ formerContacts: Contact[];
+};
+
+export function CompanyContactsTab({
+ companyId,
+ currentContacts,
+ formerContacts,
+}: CompanyContactsTabProps) {
+ const router = useRouter();
+ const [dialogOpen, setDialogOpen] = useState(false);
+ const [editContact, setEditContact] = useState<Contact | null>(null);
+ const [companies, setCompanies] = useState<Company[]>([]);
+ const [locations, setLocations] = useState<JobLocation[]>([]);
+ const [roles, setRoles] = useState<ContactRole[]>([]);
+ const [pickersLoading, setPickersLoading] = useState(false);
+ const pickersRequested = useRef(false);
+
+ const reload = () => router.refresh();
+
+ // Most visits never open the dialog, so its three option lists wait for it
+ const openDialog = useCallback((open: boolean) => {
+ setDialogOpen(open);
+ if (!open || pickersRequested.current) return;
+ pickersRequested.current = true;
+ setPickersLoading(true);
+ Promise.all([getAllCompanies(), getAllJobLocations(), getAllContactRoles()])
+ .then(([companyList, locationList, roleList]) => {
+ if (Array.isArray(companyList)) setCompanies(companyList);
+ if (Array.isArray(locationList)) setLocations(locationList);
+ if (Array.isArray(roleList)) setRoles(roleList);
+ })
+ .finally(() => setPickersLoading(false));
+ }, []);
+
+ const onAdd = () => {
+ setEditContact(null);
+ openDialog(true);
+ };
+
+ const onEdit = async (contactId: string) => {
+ const contact = await getContactById(contactId);
+ setEditContact(contact);
+ openDialog(true);
+ };
+
+ const hasAny = currentContacts.length > 0 || formerContacts.length > 0;
+
+ return (
+ <div className="space-y-6">
+ {hasAny && (
+ <div className="flex justify-end">
+ <Button variant="outline" size="sm" className="h-7 gap-1" onClick={onAdd}>
+ <PlusCircle className="h-3.5 w-3.5" />
+ Add Contact
+ </Button>
+ </div>
+ )}
+
+ {currentContacts.length > 0 && (
+ <section className="space-y-2">
+ <h3 className="text-sm font-medium text-muted-foreground">Works here</h3>
+ <ContactsTable
+ contacts={currentContacts}
+ reloadContacts={reload}
+ editContact={onEdit}
+ hideCompanyColumn
+ />
+ </section>
+ )}
+
+ {formerContacts.length > 0 && (
+ <section className="space-y-2">
+ <h3 className="text-sm font-medium text-muted-foreground">
+ Worked with you here
+ </h3>
+ <ContactsTable
+ contacts={formerContacts}
+ reloadContacts={reload}
+ editContact={onEdit}
+ />
+ </section>
+ )}
+
+ {!hasAny && (
+ <JobTabEmptyState
+ icon={Users}
+ title="No contacts at this company yet"
+ description="Add the recruiters, hiring managers and colleagues you know here."
+ actionLabel="Add Contact"
+ onAction={onAdd}
+ />
+ )}
+
+ <AddContact
+ hideTrigger
+ prefillCompanyId={companyId}
+ editContact={editContact}
+ resetEditContact={() => setEditContact(null)}
+ reloadContacts={reload}
+ dialogOpen={dialogOpen}
+ setDialogOpen={openDialog}
+ pickersLoading={pickersLoading}
+ companies={companies}
+ locations={locations}
+ roles={roles}
+ />
+ </div>
+ );
+}