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(contacts): add the standing contact role, the Contacts Library tab and the Add Contact form

Khuram Niaz7ed6d8b8fd4d
diff --git a/__tests__/AddContact.spec.tsx b/__tests__/AddContact.spec.tsx
new file mode 100644
index 0000000..b499580
--- /dev/null
+++ b/__tests__/AddContact.spec.tsx
@@ -0,0 +1,169 @@
+import AddContact from "@/components/AddContact";
+import { render, screen, waitFor } from "@testing-library/react";
+import userEvent from "@testing-library/user-event";
+import { createContact, updateContact } from "@/actions/contact.actions";
+
+vi.mock("@/actions/contact.actions", () => ({
+ createContact: vi.fn(),
+ updateContact: vi.fn(),
+}));
+
+vi.mock("@/lib/toast", () => ({
+ toastSuccess: vi.fn(),
+ toastError: vi.fn(),
+ toastActionResult: vi.fn((res, opts) => res?.success && opts?.onSuccess?.()),
+}));
+
+const props = {
+ reloadContacts: vi.fn(),
+ resetEditContact: vi.fn(),
+ dialogOpen: true,
+ setDialogOpen: vi.fn(),
+ companies: [{ id: "co1", label: "Shopify", value: "shopify", createdBy: "u1" }],
+ locations: [{ id: "l1", label: "Toronto, ON", value: "toronto on", createdBy: "u1" }],
+ roles: [
+ { id: "r1", label: "Reference", value: "reference", createdBy: "u1" },
+ { id: "r2", label: "Recruiter", value: "recruiter", createdBy: "u1" },
+ ],
+} as any;
+
+// jsdom lacks scrollIntoView, which cmdk calls when selecting an item
+Element.prototype.scrollIntoView = vi.fn();
+
+describe("AddContact", () => {
+ const user = userEvent.setup({ skipHover: true });
+ beforeEach(() => vi.clearAllMocks());
+
+ it("saves a contact with just a name", async () => {
+ (createContact as any).mockResolvedValue({ success: true, data: { id: "c1" } });
+
+ render(<AddContact {...props} />);
+ 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" }),
+ ),
+ );
+ });
+
+ it("blocks a save with no name", async () => {
+ render(<AddContact {...props} />);
+ await user.click(screen.getByRole("button", { name: /save/i }));
+
+ expect(await screen.findByText(/name is required|cannot be empty/i)).toBeInTheDocument();
+ expect(createContact).not.toHaveBeenCalled();
+ });
+
+ it("prefills the name when asked", () => {
+ render(<AddContact {...props} prefillName="Priya" />);
+ expect(screen.getByLabelText(/^name$/i)).toHaveValue("Priya");
+ });
+
+ it("updates instead of creating when editing", async () => {
+ (updateContact as any).mockResolvedValue({ success: true, data: { id: "c1" } });
+
+ render(
+ <AddContact
+ {...props}
+ editContact={{ id: "c1", name: "Dave Patel" } as any}
+ />,
+ );
+ await user.click(screen.getByRole("button", { name: /save/i }));
+
+ await waitFor(() =>
+ expect(updateContact).toHaveBeenCalledWith(
+ expect.objectContaining({ id: "c1", name: "Dave Patel" }),
+ ),
+ );
+ expect(createContact).not.toHaveBeenCalled();
+ });
+
+ it("carries the standing role through to the action", async () => {
+ (updateContact as any).mockResolvedValue({ success: true, data: { id: "c1" } });
+
+ render(
+ <AddContact
+ {...props}
+ editContact={{ id: "c1", name: "Dave Patel", roleId: "r1" } as any}
+ />,
+ );
+ await user.click(screen.getByRole("button", { name: /save/i }));
+
+ await waitFor(() =>
+ expect(updateContact).toHaveBeenCalledWith(
+ expect.objectContaining({ contactRole: "r1" }),
+ ),
+ );
+ });
+
+ it("hides the shared-history fields until the role is Reference", () => {
+ render(<AddContact {...props} />);
+
+ expect(screen.queryByText(/how you know them/i)).not.toBeInTheDocument();
+ expect(screen.queryByLabelText(/relationship/i)).not.toBeInTheDocument();
+ expect(screen.queryByText(/worked together at/i)).not.toBeInTheDocument();
+ });
+
+ it("shows the shared-history fields for a Reference contact", () => {
+ render(
+ <AddContact
+ {...props}
+ editContact={{ id: "c1", name: "Dave Patel", roleId: "r1" } as any}
+ />,
+ );
+
+ expect(screen.getByText(/how you know them/i)).toBeInTheDocument();
+ expect(screen.getByLabelText(/relationship/i)).toBeInTheDocument();
+ expect(screen.getByText(/worked together at/i)).toBeInTheDocument();
+ });
+
+ it("clears the shared history when the role moves off Reference", async () => {
+ (updateContact as any).mockResolvedValue({ success: true, data: { id: "c1" } });
+
+ render(
+ <AddContact
+ {...props}
+ editContact={
+ {
+ id: "c1",
+ name: "Dave Patel",
+ roleId: "r1",
+ relationship: "my manager",
+ } as any
+ }
+ />,
+ );
+
+ await user.click(screen.getByRole("combobox", { name: /role/i }));
+ await user.click(await screen.findByRole("option", { name: /recruiter/i }));
+
+ expect(screen.queryByLabelText(/relationship/i)).not.toBeInTheDocument();
+
+ await user.click(screen.getByRole("button", { name: /save/i }));
+
+ await waitFor(() =>
+ expect(updateContact).toHaveBeenCalledWith(
+ expect.objectContaining({ contactRole: "r2", relationship: "" }),
+ ),
+ );
+ });
+
+ it("hands the saved contact back to the caller", async () => {
+ (createContact as any).mockResolvedValue({ success: true, data: { id: "c9" } });
+ const onSaved = vi.fn();
+
+ render(<AddContact {...props} onSaved={onSaved} />);
+ await user.type(screen.getByLabelText(/^name$/i), "Priya Nair");
+ await user.click(screen.getByRole("button", { name: /save/i }));
+
+ await waitFor(() =>
+ expect(onSaved).toHaveBeenCalledWith({
+ id: "c9",
+ label: "Priya Nair",
+ value: "priya nair",
+ }),
+ );
+ });
+});
diff --git a/__tests__/AdminTabsContainer.spec.tsx b/__tests__/AdminTabsContainer.spec.tsx
index 2f15710..854e5bb 100644
--- a/__tests__/AdminTabsContainer.spec.tsx
+++ b/__tests__/AdminTabsContainer.spec.tsx
@@ -13,6 +13,8 @@ vi.mock("next/navigation", () => ({
vi.mock("@/actions/company.actions", () => ({
getCompanyList: vi.fn().mockResolvedValue({ data: [], total: 0 }),
getCompanyById: vi.fn(),
+ getAllCompanies: vi.fn().mockResolvedValue([]),
+ addCompany: vi.fn(),
}));
vi.mock("@/actions/jobtitle.actions", () => ({
@@ -21,6 +23,15 @@ vi.mock("@/actions/jobtitle.actions", () => ({
vi.mock("@/actions/jobLocation.actions", () => ({
getJobLocationsList: vi.fn().mockResolvedValue({ data: [], total: 0 }),
+ getAllJobLocations: vi.fn().mockResolvedValue([]),
+}));
+
+vi.mock("@/actions/contact.actions", () => ({
+ getContactList: vi.fn().mockResolvedValue({ data: [], total: 0 }),
+ getContactById: vi.fn(),
+ deleteContactById: vi.fn(),
+ createContact: vi.fn(),
+ updateContact: vi.fn(),
}));
vi.mock("@/actions/activity.actions", () => ({
@@ -30,6 +41,7 @@ vi.mock("@/actions/activity.actions", () => ({
vi.mock("@/actions/contactRole.actions", () => ({
getContactRoleList: vi.fn().mockResolvedValue({ data: [], total: 0 }),
+ getAllContactRoles: vi.fn().mockResolvedValue([]),
createContactRole: vi.fn(),
deleteContactRoleById: vi.fn(),
}));
@@ -54,6 +66,7 @@ describe("AdminTabsContainer", () => {
expect(
screen.getByRole("tab", { name: "Activity Types" })
).toBeInTheDocument();
+ expect(screen.getByRole("tab", { name: "Contacts" })).toBeInTheDocument();
expect(screen.getByRole("tab", { name: "Roles" })).toBeInTheDocument();
});
diff --git a/__tests__/ContactsContainer.spec.tsx b/__tests__/ContactsContainer.spec.tsx
new file mode 100644
index 0000000..70802c1
--- /dev/null
+++ b/__tests__/ContactsContainer.spec.tsx
@@ -0,0 +1,140 @@
+import ContactsContainer from "@/components/admin/ContactsContainer";
+import { render, screen, waitFor } from "@testing-library/react";
+import userEvent from "@testing-library/user-event";
+import { getContactList, deleteContactById } from "@/actions/contact.actions";
+
+vi.mock("@/actions/contact.actions", () => ({
+ getContactList: vi.fn(),
+ deleteContactById: vi.fn(),
+ createContact: vi.fn(),
+ updateContact: vi.fn(),
+ getContactById: vi.fn(),
+}));
+
+vi.mock("@/actions/contactRole.actions", () => ({
+ getAllContactRoles: vi.fn().mockResolvedValue([
+ { id: "r1", label: "Recruiter", value: "recruiter", createdBy: "u1" },
+ ]),
+ createContactRole: vi.fn(),
+}));
+
+vi.mock("@/actions/company.actions", () => ({
+ getAllCompanies: vi.fn().mockResolvedValue([]),
+ addCompany: vi.fn(),
+}));
+
+vi.mock("@/actions/jobLocation.actions", () => ({
+ getAllJobLocations: vi.fn().mockResolvedValue([]),
+}));
+
+vi.mock("@/lib/toast", () => ({
+ toastSuccess: vi.fn(),
+ toastError: vi.fn(),
+ toastActionResult: vi.fn(),
+}));
+
+let intersectionCallback: IntersectionObserverCallback | undefined;
+global.IntersectionObserver = class {
+ constructor(cb: IntersectionObserverCallback) { intersectionCallback = cb; }
+ observe() {}
+ unobserve() {}
+ disconnect() {}
+} as any;
+
+const contacts = [
+ {
+ id: "c1",
+ name: "Dave Patel",
+ title: "Engineering Manager",
+ email: "[email protected]",
+ phone: null,
+ linkedinUrl: null,
+ companyId: "co1",
+ Company: { id: "co1", label: "Shopify" },
+ locationId: null,
+ Location: null,
+ relationship: "my manager",
+ workedAtCompanyId: "co1",
+ WorkedAtCompany: { id: "co1", label: "Shopify" },
+ roleId: null,
+ Role: null,
+ workedFrom: new Date("2019-01-01"),
+ workedTo: new Date("2021-06-01"),
+ notes: "Happy to be a reference.",
+ lastContactedAt: new Date("2026-08-01"),
+ createdAt: new Date(),
+ updatedAt: new Date(),
+ createdBy: "u1",
+ jobLinks: [
+ {
+ id: "jc1",
+ jobId: "j1",
+ contactId: "c1",
+ roleId: "r1",
+ createdAt: new Date(),
+ Role: { id: "r1", label: "Reference", value: "reference", createdBy: "u1" },
+ Job: { id: "j1", JobTitle: { label: "Staff Engineer" }, Company: { label: "Datadog" } },
+ },
+ ],
+ _count: { jobLinks: 1 },
+ },
+];
+
+// The established shim for driving Radix Select in jsdom — see TaskForm.spec.
+beforeAll(() => {
+ window.HTMLElement.prototype.scrollIntoView = vi.fn();
+ window.HTMLElement.prototype.hasPointerCapture = vi.fn();
+});
+
+describe("ContactsContainer", () => {
+ const user = userEvent.setup({ skipHover: true });
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+ (getContactList as any).mockResolvedValue({ data: contacts, total: 1 });
+ });
+
+ it("renders the six summary columns", async () => {
+ render(<ContactsContainer />);
+ await waitFor(() => expect(screen.getByText("Dave Patel")).toBeInTheDocument());
+ expect(screen.getByText("Engineering Manager")).toBeInTheDocument();
+ expect(screen.getByText("Shopify")).toBeInTheDocument();
+ expect(screen.getByText("Reference")).toBeInTheDocument();
+ });
+
+ it("keeps the rest of the record in the expanded row until it is opened", async () => {
+ render(<ContactsContainer />);
+ await waitFor(() => expect(screen.getByText("Dave Patel")).toBeInTheDocument());
+
+ expect(screen.queryByText("[email protected]")).not.toBeInTheDocument();
+
+ await user.click(screen.getByRole("button", { name: /expand dave patel/i }));
+
+ expect(await screen.findByText("[email protected]")).toBeInTheDocument();
+ expect(screen.getByText(/Happy to be a reference/)).toBeInTheDocument();
+ expect(screen.getByText(/Staff Engineer/)).toBeInTheDocument();
+ });
+
+ it("refetches with the selected role when the filter changes", async () => {
+ render(<ContactsContainer />);
+ await waitFor(() => expect(getContactList).toHaveBeenCalled());
+
+ await user.click(screen.getByRole("combobox", { name: /filter by role/i }));
+ await user.click(await screen.findByText("Recruiter"));
+
+ await waitFor(() =>
+ expect(getContactList).toHaveBeenLastCalledWith(1, expect.any(Number), undefined, "r1"),
+ );
+ });
+
+ it("names the linked-job count in the delete confirmation", async () => {
+ render(<ContactsContainer />);
+ await waitFor(() => expect(screen.getByText("Dave Patel")).toBeInTheDocument());
+
+ await user.click(screen.getByRole("button", { name: /toggle menu/i }));
+ await user.click(await screen.findByText("Delete"));
+
+ expect(await screen.findByText(/1 job/i)).toBeInTheDocument();
+ expect(deleteContactById).not.toHaveBeenCalled();
+ });
+});
diff --git a/__tests__/backupOrdering.spec.ts b/__tests__/backupOrdering.spec.ts
index 59f92af..6c5a3ce 100644
--- a/__tests__/backupOrdering.spec.ts
+++ b/__tests__/backupOrdering.spec.ts
@@ -70,6 +70,7 @@ describe("backup ordering", () => {
companyId: "Company",
locationId: "Location",
workedAtCompanyId: "Company",
+ roleId: "ContactRole",
});
});
diff --git a/__tests__/contact.actions.spec.ts b/__tests__/contact.actions.spec.ts
index e6a22e9..4f73072 100644
--- a/__tests__/contact.actions.spec.ts
+++ b/__tests__/contact.actions.spec.ts
@@ -51,11 +51,16 @@ describe("contact actions", () => {
]);
});
- it("filters on a role held through any job link", async () => {
+ it("filters on the standing role or one held through any job link", async () => {
await getContactList(1, 10, undefined, "role-1");
- expect(db.contact.findMany.mock.calls[0][0].where.jobLinks).toEqual({
- some: { roleId: "role-1" },
- });
+ expect(db.contact.findMany.mock.calls[0][0].where.AND).toEqual([
+ {
+ OR: [
+ { roleId: "role-1" },
+ { jobLinks: { some: { roleId: "role-1" } } },
+ ],
+ },
+ ]);
});
it("pages with skip and take", async () => {
diff --git a/__tests__/contactRole.actions.spec.ts b/__tests__/contactRole.actions.spec.ts
index 0b3655d..bdbec93 100644
--- a/__tests__/contactRole.actions.spec.ts
+++ b/__tests__/contactRole.actions.spec.ts
@@ -16,6 +16,7 @@ vi.mock("@/lib/db", () => ({
delete: vi.fn(),
},
jobContact: { count: vi.fn() },
+ contact: { count: vi.fn() },
},
}));
@@ -42,7 +43,7 @@ describe("contactRole actions", () => {
where: { createdBy: user.id },
skip: 0,
take: 10,
- include: { _count: { select: { jobContacts: true } } },
+ include: { _count: { select: { jobContacts: true, contacts: true } } },
orderBy: [{ label: "asc" }],
}),
);
@@ -89,6 +90,7 @@ describe("contactRole actions", () => {
it("counts only links on this user's jobs when guarding a delete", async () => {
db.jobContact.count.mockResolvedValue(0);
+ db.contact.count.mockResolvedValue(0);
db.contactRole.delete.mockResolvedValue({ id: "r1" });
await deleteContactRoleById("r1");
@@ -101,6 +103,20 @@ describe("contactRole actions", () => {
});
});
+ it("refuses to delete a role that contacts hold as their standing role", async () => {
+ db.jobContact.count.mockResolvedValue(0);
+ db.contact.count.mockResolvedValue(2);
+
+ const res = await deleteContactRoleById("r1");
+
+ expect(res.success).toBe(false);
+ expect(res.message).toContain("2");
+ expect(db.contact.count).toHaveBeenCalledWith({
+ where: { roleId: "r1", createdBy: user.id },
+ });
+ expect(db.contactRole.delete).not.toHaveBeenCalled();
+ });
+
it("returns all roles for the picker, scoped to the user", async () => {
db.contactRole.findMany.mockResolvedValue([]);
diff --git a/prisma/migrations/20260912170952_contact_default_role/migration.sql b/prisma/migrations/20260912170952_contact_default_role/migration.sql
new file mode 100644
index 0000000..b9d1900
--- /dev/null
+++ b/prisma/migrations/20260912170952_contact_default_role/migration.sql
@@ -0,0 +1,39 @@
+-- RedefineTables
+PRAGMA defer_foreign_keys=ON;
+PRAGMA foreign_keys=OFF;
+CREATE TABLE "new_Contact" (
+ "id" TEXT NOT NULL PRIMARY KEY,
+ "name" TEXT NOT NULL,
+ "title" TEXT,
+ "email" TEXT,
+ "phone" TEXT,
+ "linkedinUrl" TEXT,
+ "companyId" TEXT,
+ "locationId" TEXT,
+ "relationship" TEXT,
+ "workedAtCompanyId" TEXT,
+ "workedFrom" DATETIME,
+ "workedTo" DATETIME,
+ "roleId" TEXT,
+ "notes" TEXT,
+ "lastContactedAt" DATETIME,
+ "createdAt" DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
+ "updatedAt" DATETIME NOT NULL,
+ "createdBy" TEXT NOT NULL,
+ "interviewId" TEXT,
+ CONSTRAINT "Contact_companyId_fkey" FOREIGN KEY ("companyId") REFERENCES "Company" ("id") ON DELETE SET NULL ON UPDATE CASCADE,
+ CONSTRAINT "Contact_locationId_fkey" FOREIGN KEY ("locationId") REFERENCES "Location" ("id") ON DELETE SET NULL ON UPDATE CASCADE,
+ CONSTRAINT "Contact_workedAtCompanyId_fkey" FOREIGN KEY ("workedAtCompanyId") REFERENCES "Company" ("id") ON DELETE SET NULL ON UPDATE CASCADE,
+ CONSTRAINT "Contact_roleId_fkey" FOREIGN KEY ("roleId") REFERENCES "ContactRole" ("id") ON DELETE SET NULL ON UPDATE CASCADE,
+ CONSTRAINT "Contact_createdBy_fkey" FOREIGN KEY ("createdBy") REFERENCES "User" ("id") ON DELETE RESTRICT ON UPDATE CASCADE,
+ CONSTRAINT "Contact_interviewId_fkey" FOREIGN KEY ("interviewId") REFERENCES "Interview" ("id") ON DELETE SET NULL ON UPDATE CASCADE
+);
+INSERT INTO "new_Contact" ("companyId", "createdAt", "createdBy", "email", "id", "interviewId", "lastContactedAt", "linkedinUrl", "locationId", "name", "notes", "phone", "relationship", "title", "updatedAt", "workedAtCompanyId", "workedFrom", "workedTo") SELECT "companyId", "createdAt", "createdBy", "email", "id", "interviewId", "lastContactedAt", "linkedinUrl", "locationId", "name", "notes", "phone", "relationship", "title", "updatedAt", "workedAtCompanyId", "workedFrom", "workedTo" FROM "Contact";
+DROP TABLE "Contact";
+ALTER TABLE "new_Contact" RENAME TO "Contact";
+CREATE INDEX "Contact_createdBy_idx" ON "Contact"("createdBy");
+CREATE INDEX "Contact_companyId_idx" ON "Contact"("companyId");
+CREATE INDEX "Contact_workedAtCompanyId_idx" ON "Contact"("workedAtCompanyId");
+CREATE INDEX "Contact_roleId_idx" ON "Contact"("roleId");
+PRAGMA foreign_keys=ON;
+PRAGMA defer_foreign_keys=OFF;
diff --git a/prisma/schema.prisma b/prisma/schema.prisma
index d2d8198..17c4466 100644
--- a/prisma/schema.prisma
+++ b/prisma/schema.prisma
@@ -228,6 +228,11 @@ model Contact {
workedFrom DateTime?
workedTo DateTime?
+ // What this person generally is to you. The per-job role on JobContact wins
+ // for a specific job; this is the standing answer and the Phase 5 prefill.
+ roleId String?
+ Role ContactRole? @relation(fields: [roleId], references: [id])
+
notes String?
lastContactedAt DateTime?
@@ -244,6 +249,7 @@ model Contact {
@@index([createdBy])
@@index([companyId])
@@index([workedAtCompanyId])
+ @@index([roleId])
}
model ContactRole {
@@ -253,6 +259,7 @@ model ContactRole {
createdBy String // userId
user User @relation(fields: [createdBy], references: [id])
jobContacts JobContact[]
+ contacts Contact[]
@@unique([value, createdBy])
}
diff --git a/src/actions/contact/mutations.ts b/src/actions/contact/mutations.ts
index 06e18a2..6226654 100644
--- a/src/actions/contact/mutations.ts
+++ b/src/actions/contact/mutations.ts
@@ -21,6 +21,7 @@ const toContactData = (values: ContactFormValues) => ({
workedAtCompanyId: nullable(values.workedAtCompany),
workedFrom: values.workedFrom ?? null,
workedTo: values.workedTo ?? null,
+ roleId: nullable(values.contactRole),
notes: nullable(values.notes),
lastContactedAt: values.lastContactedAt ?? null,
});
diff --git a/src/actions/contact/queries.ts b/src/actions/contact/queries.ts
index fe006e8..e8ddbac 100644
--- a/src/actions/contact/queries.ts
+++ b/src/actions/contact/queries.ts
@@ -7,6 +7,7 @@ import { APP_CONSTANTS } from "@/lib/constants";
// Narrowed to what the table row and the expanded row render. Not shared: only
// this module reads it.
const CONTACT_LIST_INCLUDE = {
+ Role: true,
Company: { select: { id: true, label: true } },
Location: { select: { id: true, label: true } },
WorkedAtCompany: { select: { id: true, label: true } },
@@ -46,8 +47,11 @@ export const getContactList = async (
{ title: { contains: search } },
];
}
+ // Either the standing role on the person or a role they hold on some job,
+ // so a reference never linked to a job still answers the filter. Nested in
+ // AND because the search above already owns the top-level OR.
if (roleId) {
- where.jobLinks = { some: { roleId } };
+ where.AND = [{ OR: [{ roleId }, { jobLinks: { some: { roleId } } }] }];
}
const [data, total] = await Promise.all([
diff --git a/src/actions/contactRole.actions.ts b/src/actions/contactRole.actions.ts
index 1aee6ee..73b722e 100644
--- a/src/actions/contactRole.actions.ts
+++ b/src/actions/contactRole.actions.ts
@@ -36,7 +36,7 @@ export const getContactRoleList = async (
where: whereClause,
skip: (page - 1) * limit,
take: limit,
- include: { _count: { select: { jobContacts: true } } },
+ include: { _count: { select: { jobContacts: true, contacts: true } } },
orderBy: [{ label: "asc" }],
}),
prisma.contactRole.count({ where: whereClause }),
@@ -77,6 +77,17 @@ export const deleteContactRoleById = async (
);
}
+ // Contact.roleId is SetNull, so without this guard deleting a role would
+ // silently clear it on every contact that holds it.
+ const holders = await prisma.contact.count({
+ where: { roleId, createdBy: user.id },
+ });
+ if (holders > 0) {
+ throw new Error(
+ `Role cannot be deleted due to ${holders} contact${holders === 1 ? "" : "s"} having it as their role! `,
+ );
+ }
+
const res = await prisma.contactRole.delete({
where: { id: roleId, createdBy: user.id },
});
diff --git a/src/components/AddContact.tsx b/src/components/AddContact.tsx
new file mode 100644
index 0000000..b342c7a
--- /dev/null
+++ b/src/components/AddContact.tsx
@@ -0,0 +1,466 @@
+"use client";
+import { useEffect, useTransition } from "react";
+import { useForm } from "react-hook-form";
+import { zodResolver } from "@hookform/resolvers/zod";
+import { PlusCircle } from "lucide-react";
+import { Button } from "./ui/button";
+import {
+ Dialog,
+ DialogContent,
+ DialogHeader,
+ DialogTitle,
+} from "./ui/dialog";
+import {
+ Form,
+ FormControl,
+ FormField,
+ FormItem,
+ FormLabel,
+ FormMessage,
+} from "./ui/form";
+import { Input } from "./ui/input";
+import { Textarea } from "./ui/textarea";
+import { Combobox } from "./ComboBox";
+import { DatePicker } from "./DatePicker";
+import { FormDialogFooter } from "./FormDialogFooter";
+import { toastActionResult } from "@/lib/toast";
+import { createContact, updateContact } from "@/actions/contact.actions";
+import {
+ AddContactFormSchema,
+ type ContactFormValues,
+} from "@/models/addContactForm.schema";
+import type { Contact, ContactRef, ContactRole } from "@/models/contact.model";
+import type { Company, JobLocation } from "@/models/job.model";
+
+type AddContactProps = {
+ reloadContacts: () => void;
+ editContact?: Contact | null;
+ resetEditContact: () => void;
+ dialogOpen: boolean;
+ setDialogOpen: (open: boolean) => void;
+ companies: Company[];
+ locations: JobLocation[];
+ roles: ContactRole[];
+ prefillName?: string;
+ hideTrigger?: boolean;
+ onSaved?: (contact: ContactRef) => void;
+};
+
+const REFERENCE_ROLE_VALUE = "reference";
+
+const EMPTY_CONTACT: ContactFormValues = {
+ name: "",
+ title: "",
+ email: "",
+ phone: "",
+ linkedinUrl: "",
+ company: "",
+ location: "",
+ relationship: "",
+ workedAtCompany: "",
+ contactRole: "",
+ workedFrom: null,
+ workedTo: null,
+ notes: "",
+ lastContactedAt: null,
+};
+
+// A labelled rule between field groups; spans both columns of the form grid
+function SectionHeading({ children }: { children: React.ReactNode }) {
+ return (
+ <div className="md:col-span-2 flex items-center gap-3 pt-2">
+ <span className="text-xs font-medium uppercase tracking-wide text-muted-foreground">
+ {children}
+ </span>
+ <span className="h-px flex-1 bg-border" />
+ </div>
+ );
+}
+
+function AddContact({
+ reloadContacts,
+ editContact,
+ resetEditContact,
+ dialogOpen,
+ setDialogOpen,
+ companies,
+ locations,
+ roles,
+ prefillName,
+ hideTrigger,
+ onSaved,
+}: AddContactProps) {
+ const [isPending, startTransition] = useTransition();
+
+ const pageTitle = editContact ? "Edit Contact" : "Add Contact";
+
+ const form = useForm<ContactFormValues>({
+ resolver: zodResolver(AddContactFormSchema),
+ defaultValues: prefillName
+ ? { ...EMPTY_CONTACT, name: prefillName }
+ : EMPTY_CONTACT,
+ });
+
+ const { reset } = form;
+
+ // The shared-history fields only make sense for a reference
+ const roleId = form.watch("contactRole");
+ const isReference = roles.some(
+ (role) => role.id === roleId && role.value === REFERENCE_ROLE_VALUE,
+ );
+
+ // Clear on an explicit role change only — an effect would also wipe the
+ // history a non-reference contact was saved with the moment you open it
+ const onRoleChange = (
+ field: { onChange: (value: string) => void },
+ value: string,
+ ) => {
+ field.onChange(value);
+ const stillReference = roles.some(
+ (role) => role.id === value && role.value === REFERENCE_ROLE_VALUE,
+ );
+ if (stillReference) return;
+ form.setValue("relationship", "");
+ form.setValue("workedAtCompany", "");
+ form.setValue("workedFrom", null);
+ form.setValue("workedTo", null);
+ };
+
+ useEffect(() => {
+ if (editContact) {
+ reset(
+ {
+ id: editContact.id,
+ name: editContact.name ?? "",
+ title: editContact.title ?? "",
+ email: editContact.email ?? "",
+ phone: editContact.phone ?? "",
+ linkedinUrl: editContact.linkedinUrl ?? "",
+ company: editContact.companyId ?? "",
+ location: editContact.locationId ?? "",
+ relationship: editContact.relationship ?? "",
+ workedAtCompany: editContact.workedAtCompanyId ?? "",
+ contactRole: editContact.roleId ?? "",
+ workedFrom: editContact.workedFrom ?? null,
+ workedTo: editContact.workedTo ?? null,
+ notes: editContact.notes ?? "",
+ lastContactedAt: editContact.lastContactedAt ?? null,
+ },
+ { keepDefaultValues: true },
+ );
+ } else if (prefillName) {
+ reset({ ...EMPTY_CONTACT, name: prefillName }, { keepDefaultValues: true });
+ }
+ }, [editContact, prefillName, reset]);
+
+ const openDialog = () => {
+ if (!editContact) {
+ reset();
+ resetEditContact();
+ }
+ setDialogOpen(true);
+ };
+
+ const closeDialog = () => setDialogOpen(false);
+
+ const onSubmit = (values: ContactFormValues) => {
+ startTransition(async () => {
+ const res = editContact
+ ? await updateContact({ ...values, id: editContact.id })
+ : await createContact(values);
+ const name = values.name.trim();
+ toastActionResult(res, {
+ success: `Contact has been ${editContact ? "updated" : "created"} successfully`,
+ onSuccess: () => {
+ onSaved?.({ id: res.data.id, label: name, value: name.toLowerCase() });
+ reset();
+ setDialogOpen(false);
+ resetEditContact();
+ reloadContacts();
+ },
+ });
+ });
+ };
+
+ return (
+ <>
+ {!hideTrigger && (
+ <Button
+ size="sm"
+ variant="outline"
+ className="h-8 gap-1"
+ onClick={openDialog}
+ data-testid="add-contact-btn"
+ >
+ <PlusCircle className="h-3.5 w-3.5" />
+ <span className="sr-only sm:not-sr-only sm:whitespace-nowrap">
+ New Contact
+ </span>
+ </Button>
+ )}
+ <Dialog open={dialogOpen} onOpenChange={setDialogOpen}>
+ <DialogContent className="sm:max-w-2xl max-h-[85vh] overflow-y-auto">
+ <DialogHeader>
+ <DialogTitle>{pageTitle}</DialogTitle>
+ </DialogHeader>
+ <Form {...form}>
+ <form
+ onSubmit={form.handleSubmit(onSubmit)}
+ className="grid grid-cols-1 md:grid-cols-2 gap-4 p-2"
+ >
+ <FormField
+ control={form.control}
+ name="name"
+ render={({ field }) => (
+ <FormItem>
+ <FormLabel>Name</FormLabel>
+ <FormControl>
+ <Input placeholder="e.g. Dana Whitfield" {...field} />
+ </FormControl>
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+
+ <FormField
+ control={form.control}
+ name="title"
+ render={({ field }) => (
+ <FormItem>
+ <FormLabel>Title</FormLabel>
+ <FormControl>
+ <Input placeholder="e.g. Engineering Manager" {...field} />
+ </FormControl>
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+
+ <FormField
+ control={form.control}
+ name="email"
+ render={({ field }) => (
+ <FormItem>
+ <FormLabel>Email</FormLabel>
+ <FormControl>
+ <Input
+ type="email"
+ placeholder="[email protected]"
+ {...field}
+ />
+ </FormControl>
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+
+ <FormField
+ control={form.control}
+ name="phone"
+ render={({ field }) => (
+ <FormItem>
+ <FormLabel>Phone</FormLabel>
+ <FormControl>
+ <Input placeholder="e.g. +1 416 555 0134" {...field} />
+ </FormControl>
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+
+ <div className="md:col-span-2">
+ <FormField
+ control={form.control}
+ name="linkedinUrl"
+ render={({ field }) => (
+ <FormItem>
+ <FormLabel>LinkedIn URL</FormLabel>
+ <FormControl>
+ <Input
+ placeholder="https://www.linkedin.com/in/..."
+ {...field}
+ />
+ </FormControl>
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+ </div>
+
+ <SectionHeading>Where they work</SectionHeading>
+
+ <FormField
+ control={form.control}
+ name="company"
+ render={({ field }) => (
+ <FormItem className="flex flex-col">
+ <FormLabel>Company</FormLabel>
+ <Combobox options={companies} field={field} creatable fullWidth />
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+
+ <FormField
+ control={form.control}
+ name="location"
+ render={({ field }) => (
+ <FormItem className="flex flex-col">
+ <FormLabel>Location</FormLabel>
+ <Combobox options={locations} field={field} creatable fullWidth />
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+
+ <FormField
+ control={form.control}
+ name="contactRole"
+ render={({ field }) => (
+ <FormItem className="flex flex-col">
+ <FormLabel>Role</FormLabel>
+ <Combobox
+ options={roles}
+ field={{
+ ...field,
+ onChange: (value: string) => onRoleChange(field, value),
+ }}
+ creatable
+ fullWidth
+ label="role"
+ />
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+
+ {isReference && (
+ <>
+ <SectionHeading>How you know them</SectionHeading>
+
+ <FormField
+ control={form.control}
+ name="relationship"
+ render={({ field }) => (
+ <FormItem>
+ <FormLabel>Relationship</FormLabel>
+ <FormControl>
+ <Input placeholder="e.g. my manager, peer" {...field} />
+ </FormControl>
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+
+ <FormField
+ control={form.control}
+ name="workedAtCompany"
+ render={({ field }) => (
+ <FormItem className="flex flex-col">
+ <FormLabel>Worked together at</FormLabel>
+ <Combobox
+ options={companies}
+ field={field}
+ creatable
+ fullWidth
+ label="company"
+ />
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+
+ {/* captionLayout gives the year dropdown: a 2019 start date is
+ otherwise a lot of clicking */}
+ <FormField
+ control={form.control}
+ name="workedFrom"
+ render={({ field }) => (
+ <FormItem className="flex flex-col">
+ <FormLabel>From</FormLabel>
+ <DatePicker
+ field={field}
+ presets={false}
+ isEnabled
+ captionLayout
+ fullWidth
+ />
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+
+ <FormField
+ control={form.control}
+ name="workedTo"
+ render={({ field }) => (
+ <FormItem className="flex flex-col">
+ <FormLabel>To</FormLabel>
+ <DatePicker
+ field={field}
+ presets={false}
+ isEnabled
+ captionLayout
+ fullWidth
+ />
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+ </>
+ )}
+
+ <SectionHeading>Follow-up</SectionHeading>
+
+ <FormField
+ control={form.control}
+ name="lastContactedAt"
+ render={({ field }) => (
+ <FormItem className="flex flex-col">
+ <FormLabel>Last contacted</FormLabel>
+ <DatePicker
+ field={field}
+ presets={false}
+ isEnabled
+ captionLayout
+ fullWidth
+ />
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+
+ <div className="md:col-span-2">
+ <FormField
+ control={form.control}
+ name="notes"
+ render={({ field }) => (
+ <FormItem>
+ <FormLabel>Notes</FormLabel>
+ <FormControl>
+ <Textarea
+ className="min-h-24"
+ placeholder="How you met, what to follow up on..."
+ {...field}
+ />
+ </FormControl>
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+ </div>
+
+ <FormDialogFooter
+ onCancel={closeDialog}
+ isPending={isPending}
+ saveDisabled={isPending}
+ />
+ </form>
+ </Form>
+ </DialogContent>
+ </Dialog>
+ </>
+ );
+}
+
+export default AddContact;
diff --git a/src/components/ComboBox.tsx b/src/components/ComboBox.tsx
index f3b86bf..7406d5f 100644
--- a/src/components/ComboBox.tsx
+++ b/src/components/ComboBox.tsx
@@ -37,6 +37,8 @@ interface ComboboxProps {
freeText?: boolean;
label?: string;
onSearchChange?: (search: string) => void;
+ // Opt out of the default fixed trigger width when the field sits in a grid
+ fullWidth?: boolean;
}
export function Combobox({
@@ -46,6 +48,7 @@ export function Combobox({
freeText,
label,
onSearchChange,
+ fullWidth,
}: ComboboxProps) {
// Placeholder text only; the accessible name comes from FormLabel/FormControl
const displayName = label ?? field.name;
@@ -140,7 +143,8 @@ export function Combobox({
variant="outline"
role="combobox"
className={cn(
- "md:w-[240px] lg:w-[280px] justify-between",
+ "justify-between",
+ fullWidth ? "w-full" : "md:w-[240px] lg:w-[280px]",
!field.value && "text-muted-foreground"
)}
>
@@ -159,7 +163,14 @@ export function Combobox({
</Button>
</FormControl>
</PopoverTrigger>
- <PopoverContent className="md:w-[240px] lg:w-[280px] p-0">
+ <PopoverContent
+ className={cn(
+ "p-0",
+ fullWidth
+ ? "w-(--radix-popover-trigger-width)"
+ : "md:w-[240px] lg:w-[280px]"
+ )}
+ >
<Command
filter={(value, search) =>
value.toLowerCase().includes(search.toLowerCase()) ? 1 : 0
diff --git a/src/components/DatePicker.tsx b/src/components/DatePicker.tsx
index 20bd58e..8693717 100644
--- a/src/components/DatePicker.tsx
+++ b/src/components/DatePicker.tsx
@@ -28,6 +28,8 @@ interface DatePickerProps {
presets: boolean;
isEnabled: boolean;
captionLayout?: boolean;
+ // Opt out of the default fixed trigger width when the field sits in a grid
+ fullWidth?: boolean;
}
export function DatePicker({
@@ -35,6 +37,7 @@ export function DatePicker({
presets,
isEnabled,
captionLayout,
+ fullWidth,
}: DatePickerProps) {
const [isPopoverOpen, setIsPopoverOpen] = useState<boolean>(false);
@@ -45,7 +48,8 @@ export function DatePicker({
<Button
variant={"outline"}
className={cn(
- "md:w-[240px] lg:w-[280px] justify-start text-left font-normal",
+ "justify-start text-left font-normal",
+ fullWidth ? "w-full" : "md:w-[240px] lg:w-[280px]",
!field.value && "text-muted-foreground"
)}
disabled={!isEnabled}
diff --git a/src/components/admin/AdminTabsContainer.tsx b/src/components/admin/AdminTabsContainer.tsx
index 88c7714..3a7ec32 100644
--- a/src/components/admin/AdminTabsContainer.tsx
+++ b/src/components/admin/AdminTabsContainer.tsx
@@ -2,6 +2,7 @@
import ActivityTypesContainer from "@/components/admin/ActivityTypesContainer";
import CompaniesContainer from "@/components/admin/CompaniesContainer";
import ContactRolesContainer from "@/components/admin/ContactRolesContainer";
+import ContactsContainer from "@/components/admin/ContactsContainer";
import JobLocationsContainer from "@/components/admin/JobLocationsContainer";
import JobSourcesContainer from "@/components/admin/JobSourcesContainer";
import JobTitlesContainer from "@/components/admin/JobTitlesContainer";
@@ -40,6 +41,7 @@ function AdminTabsContainer() {
<TabsTrigger value="sources">Sources</TabsTrigger>
<TabsTrigger value="skills">Skills</TabsTrigger>
<TabsTrigger value="activity-types">Activity Types</TabsTrigger>
+ <TabsTrigger value="contacts">Contacts</TabsTrigger>
<TabsTrigger value="roles">Roles</TabsTrigger>
</TabsList>
<TabsContent value="companies">
@@ -60,6 +62,9 @@ function AdminTabsContainer() {
<TabsContent value="activity-types">
<ActivityTypesContainer />
</TabsContent>
+ <TabsContent value="contacts">
+ <ContactsContainer />
+ </TabsContent>
<TabsContent value="roles">
<ContactRolesContainer />
</TabsContent>
diff --git a/src/components/admin/ContactRolesTable.tsx b/src/components/admin/ContactRolesTable.tsx
index f13454b..f3a2f76 100644
--- a/src/components/admin/ContactRolesTable.tsx
+++ b/src/components/admin/ContactRolesTable.tsx
@@ -37,13 +37,18 @@ function ContactRolesTable({ roles, reloadRoles }: ContactRolesTableProps) {
const onDeleteRole = (role: ContactRole) => {
const links = role._count?.jobContacts ?? 0;
- if (links > 0) {
+ const holders = role._count?.contacts ?? 0;
+ if (links > 0 || holders > 0) {
setAlert({
openState: true,
title: "Associated contacts exist!",
- description: `This role is used by ${links} contact link${
- links === 1 ? "" : "s"
- }. Remove those links before deleting the role.`,
+ description: links
+ ? `This role is used by ${links} contact link${
+ links === 1 ? "" : "s"
+ }. Remove those links before deleting the role.`
+ : `This role is set on ${holders} contact${
+ holders === 1 ? "" : "s"
+ }. Change their role before deleting it.`,
deleteAction: false,
});
} else {
diff --git a/src/components/admin/ContactRow.tsx b/src/components/admin/ContactRow.tsx
new file mode 100644
index 0000000..cff9f5a
--- /dev/null
+++ b/src/components/admin/ContactRow.tsx
@@ -0,0 +1,202 @@
+"use client";
+import Link from "next/link";
+import { format } from "date-fns";
+import {
+ ChevronDown,
+ ChevronRight,
+ MoreVertical,
+ Pencil,
+ Trash,
+} from "lucide-react";
+import { Badge } from "../ui/badge";
+import { Button } from "../ui/button";
+import {
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuLabel,
+ DropdownMenuTrigger,
+} from "../ui/dropdown-menu";
+import { TableCell, TableRow } from "../ui/table";
+import type { Contact } from "@/models/contact.model";
+
+type ContactRowProps = {
+ contact: Contact;
+ expanded: boolean;
+ onToggle: () => void;
+ onEdit: () => void;
+ onDelete: () => void;
+};
+
+function overlapLabel(contact: Contact) {
+ if (!contact.workedFrom) return null;
+ const to = contact.workedTo ? format(contact.workedTo, "MMM yyyy") : "present";
+ return `${format(contact.workedFrom, "MMM yyyy")} – ${to}`;
+}
+
+function ContactRow({
+ contact,
+ expanded,
+ onToggle,
+ onEdit,
+ onDelete,
+}: ContactRowProps) {
+ const links = contact.jobLinks ?? [];
+ // The standing role first, then any per-job role it does not already cover
+ const roles = Array.from(
+ new Map([
+ ...(contact.Role ? [[contact.Role.id, contact.Role.label]] : []),
+ ...links.map((link) => [link.Role.id, link.Role.label]),
+ ] as [string, string][]).entries(),
+ );
+ const overlap = overlapLabel(contact);
+ const hasContactBlock =
+ contact.email || contact.phone || contact.linkedinUrl || contact.Location;
+ const hasHistoryBlock =
+ contact.relationship || contact.WorkedAtCompany || overlap;
+
+ return (
+ <>
+ <TableRow>
+ <TableCell className="w-8">
+ <Button
+ variant="ghost"
+ size="icon"
+ onClick={onToggle}
+ aria-label={`${expanded ? "Collapse" : "Expand"} ${contact.name}`}
+ >
+ {expanded ? (
+ <ChevronDown className="h-4 w-4" />
+ ) : (
+ <ChevronRight className="h-4 w-4" />
+ )}
+ </Button>
+ </TableCell>
+ <TableCell className="font-medium">{contact.name}</TableCell>
+ <TableCell className="hidden sm:table-cell">
+ {contact.title ?? "—"}
+ </TableCell>
+ <TableCell>{contact.Company?.label ?? "—"}</TableCell>
+ <TableCell>
+ {roles.length > 0 ? (
+ <span className="flex flex-wrap gap-1">
+ {roles.map(([id, label]) => (
+ <Badge
+ key={id}
+ variant={
+ id === contact.roleId ? "default" : "secondary"
+ }
+ >
+ {label}
+ </Badge>
+ ))}
+ </span>
+ ) : (
+ "—"
+ )}
+ </TableCell>
+ <TableCell>{contact._count?.jobLinks ?? 0}</TableCell>
+ <TableCell>
+ {contact.lastContactedAt ? format(contact.lastContactedAt, "PP") : "—"}
+ </TableCell>
+ <TableCell>
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <Button aria-haspopup="true" size="icon" variant="ghost">
+ <MoreVertical className="h-4 w-4" />
+ <span className="sr-only">Toggle menu</span>
+ </Button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="end">
+ <DropdownMenuLabel>Actions</DropdownMenuLabel>
+ <DropdownMenuItem className="cursor-pointer" onClick={onEdit}>
+ <Pencil className="mr-2 h-4 w-4" />
+ Edit Contact
+ </DropdownMenuItem>
+ <DropdownMenuItem
+ className="text-red-600 cursor-pointer"
+ onClick={onDelete}
+ >
+ <Trash className="mr-2 h-4 w-4" />
+ Delete
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ </TableCell>
+ </TableRow>
+ {expanded && (
+ <TableRow>
+ <TableCell colSpan={8} className="bg-muted/40">
+ <div className="grid gap-4 sm:grid-cols-2 text-sm">
+ {hasContactBlock && (
+ <div className="space-y-1">
+ {contact.email && (
+ <div>
+ <a
+ href={`mailto:${contact.email}`}
+ className="text-primary underline-offset-4 hover:underline"
+ >
+ {contact.email}
+ </a>
+ </div>
+ )}
+ {contact.phone && <div>{contact.phone}</div>}
+ {contact.linkedinUrl && (
+ <div>
+ <a
+ href={contact.linkedinUrl}
+ target="_blank"
+ rel="noopener noreferrer"
+ className="text-primary underline-offset-4 hover:underline"
+ >
+ LinkedIn
+ </a>
+ </div>
+ )}
+ {contact.Location && <div>{contact.Location.label}</div>}
+ </div>
+ )}
+ {hasHistoryBlock && (
+ <div className="space-y-1">
+ <div className="font-medium text-muted-foreground">
+ How you know them
+ </div>
+ {contact.relationship && <div>{contact.relationship}</div>}
+ {contact.WorkedAtCompany && (
+ <div>{contact.WorkedAtCompany.label}</div>
+ )}
+ {overlap && (
+ <div className="text-muted-foreground">{overlap}</div>
+ )}
+ </div>
+ )}
+ {contact.notes && (
+ <p className="sm:col-span-2 whitespace-pre-wrap">
+ {contact.notes}
+ </p>
+ )}
+ {links.length > 0 && (
+ <ul className="sm:col-span-2 space-y-1">
+ {links.map((link) => (
+ <li key={link.id}>
+ <Link
+ href={`/dashboard/myjobs/${link.Job?.id}`}
+ className="text-primary underline-offset-4 hover:underline"
+ >
+ {link.Job?.JobTitle.label} at {link.Job?.Company.label}
+ </Link>
+ {" — "}
+ {link.Role.label}
+ </li>
+ ))}
+ </ul>
+ )}
+ </div>
+ </TableCell>
+ </TableRow>
+ )}
+ </>
+ );
+}
+
+export default ContactRow;
diff --git a/src/components/admin/ContactsContainer.tsx b/src/components/admin/ContactsContainer.tsx
new file mode 100644
index 0000000..72bba4c
--- /dev/null
+++ b/src/components/admin/ContactsContainer.tsx
@@ -0,0 +1,106 @@
+"use client";
+import { useEffect, useState } from "react";
+import { Loader } from "lucide-react";
+import { Card, CardContent, CardTitle } from "../ui/card";
+import { ResponsiveCardHeader } from "../ResponsiveCardHeader";
+import Loading from "../Loading";
+import { RecordsCount } from "../RecordsCount";
+import { SearchInput } from "../SearchInput";
+import AddContact from "../AddContact";
+import ContactsTable from "./ContactsTable";
+import { ContactRoleFilter } from "./contacts-container/ContactRoleFilter";
+import { useContactsList } from "./contacts-container/useContactsList";
+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";
+
+function ContactsContainer() {
+ const [searchTerm, setSearchTerm] = useState("");
+ const [roleId, setRoleId] = useState<string | undefined>(undefined);
+ 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 list = useContactsList(searchTerm, roleId);
+
+ // The tab is a client component with no server parent to pass these down,
+ // and the Library's other tabs should not pay for this one's pickers.
+ useEffect(() => {
+ 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);
+ });
+ }, []);
+
+ const onEditContact = async (contactId: string) => {
+ const contact = await getContactById(contactId);
+ setEditContact(contact);
+ setDialogOpen(true);
+ };
+
+ return (
+ <div className="col-span-3">
+ <Card x-chunk="dashboard-06-chunk-0">
+ <ResponsiveCardHeader>
+ <div className="flex items-baseline gap-2">
+ <CardTitle>Contacts</CardTitle>
+ {!list.initialLoading && list.total > 0 && (
+ <RecordsCount
+ count={list.contacts.length}
+ total={list.total}
+ label="contacts"
+ />
+ )}
+ </div>
+ <div className="flex flex-wrap items-center justify-end gap-2 sm:ml-auto">
+ <ContactRoleFilter roleId={roleId} onRoleChange={setRoleId} />
+ <SearchInput
+ value={searchTerm}
+ onChange={setSearchTerm}
+ placeholder="Search contacts..."
+ />
+ <AddContact
+ editContact={editContact}
+ reloadContacts={list.reload}
+ resetEditContact={() => setEditContact(null)}
+ dialogOpen={dialogOpen}
+ setDialogOpen={setDialogOpen}
+ companies={companies}
+ locations={locations}
+ roles={roles}
+ />
+ </div>
+ </ResponsiveCardHeader>
+ <CardContent>
+ {list.initialLoading && <Loading />}
+ {list.contacts.length > 0 && (
+ <ContactsTable
+ contacts={list.contacts}
+ reloadContacts={list.reload}
+ editContact={onEditContact}
+ />
+ )}
+ {list.hasMore && (
+ <div ref={list.sentinelRef} className="flex justify-center p-4">
+ {list.loadingMore && (
+ <Loader className="h-5 w-5 animate-spin text-blue-500" />
+ )}
+ </div>
+ )}
+ </CardContent>
+ </Card>
+ </div>
+ );
+}
+
+export default ContactsContainer;
diff --git a/src/components/admin/ContactsTable.tsx b/src/components/admin/ContactsTable.tsx
new file mode 100644
index 0000000..77b81bd
--- /dev/null
+++ b/src/components/admin/ContactsTable.tsx
@@ -0,0 +1,111 @@
+"use client";
+import { useState } from "react";
+import {
+ Table,
+ TableBody,
+ TableHead,
+ TableHeader,
+ TableRow,
+} from "../ui/table";
+import ContactRow from "./ContactRow";
+import { DeleteAlertDialog } from "../DeleteAlertDialog";
+import { deleteContactById } from "@/actions/contact.actions";
+import { toastSuccess, toastError } from "@/lib/toast";
+import { AlertDialog } from "@/models/alertDialog.model";
+import type { Contact } from "@/models/contact.model";
+
+type ContactsTableProps = {
+ contacts: Contact[];
+ reloadContacts: () => void;
+ editContact: (id: string) => void;
+};
+
+function ContactsTable({
+ contacts,
+ reloadContacts,
+ editContact,
+}: ContactsTableProps) {
+ const [expandedId, setExpandedId] = useState<string | null>(null);
+ const [alert, setAlert] = useState<AlertDialog>({
+ openState: false,
+ deleteAction: false,
+ });
+
+ // A link is meaningless without the person and JobContact cascades from
+ // contactId, so the dialog warns about the links rather than blocking.
+ const onDeleteContact = (contact: Contact) => {
+ const jobs = contact._count?.jobLinks ?? 0;
+ setAlert({
+ openState: true,
+ deleteAction: true,
+ itemId: contact.id,
+ title: jobs > 0 ? "Delete this contact?" : undefined,
+ description:
+ jobs > 0
+ ? `${contact.name} is linked to ${jobs} job${jobs === 1 ? "" : "s"}. Deleting the contact removes those links. This cannot be undone.`
+ : undefined,
+ });
+ };
+
+ const deleteContact = async (contactId: string | undefined) => {
+ if (contactId) {
+ const { success, message } = await deleteContactById(contactId);
+ if (success) {
+ toastSuccess("Contact has been deleted successfully");
+ reloadContacts();
+ } else {
+ toastError(message);
+ }
+ }
+ };
+
+ return (
+ <>
+ <Table>
+ <TableHeader>
+ <TableRow>
+ <TableHead className="w-8">
+ <span className="sr-only">Expand</span>
+ </TableHead>
+ <TableHead>Name</TableHead>
+ <TableHead className="hidden sm:table-cell">Title</TableHead>
+ <TableHead>Company</TableHead>
+ <TableHead>Roles</TableHead>
+ <TableHead>Jobs</TableHead>
+ <TableHead>Last contacted</TableHead>
+ <TableHead>
+ <span className="sr-only">Actions</span>
+ </TableHead>
+ </TableRow>
+ </TableHeader>
+ <TableBody>
+ {contacts.map((contact: Contact) => (
+ <ContactRow
+ key={contact.id}
+ contact={contact}
+ expanded={expandedId === contact.id}
+ onToggle={() =>
+ setExpandedId((prev) =>
+ prev === contact.id ? null : contact.id,
+ )
+ }
+ onEdit={() => editContact(contact.id)}
+ onDelete={() => onDeleteContact(contact)}
+ />
+ ))}
+ </TableBody>
+ </Table>
+ <DeleteAlertDialog
+ pageTitle="contact"
+ open={alert.openState}
+ onOpenChange={() => setAlert({ openState: false, deleteAction: false })}
+ onDelete={() => deleteContact(alert.itemId)}
+ alertTitle={alert.title}
+ alertDescription={alert.description}
+ deleteAction={alert.deleteAction}
+ />
+ </>
+ );
+}
+
+export default ContactsTable;
diff --git a/src/components/admin/contacts-container/ContactRoleFilter.tsx b/src/components/admin/contacts-container/ContactRoleFilter.tsx
new file mode 100644
index 0000000..5724db3
--- /dev/null
+++ b/src/components/admin/contacts-container/ContactRoleFilter.tsx
@@ -0,0 +1,47 @@
+"use client";
+
+import { useEffect, useState } from "react";
+import {
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue,
+} from "@/components/ui/select";
+import { getAllContactRoles } from "@/actions/contactRole.actions";
+import type { ContactRole } from "@/models/contact.model";
+
+// Select cannot hold an empty-string value, so all-roles gets a sentinel
+const ALL = "all";
+
+type Props = {
+ roleId?: string;
+ onRoleChange: (roleId?: string) => void;
+};
+
+export function ContactRoleFilter({ roleId, onRoleChange }: Props) {
+ const [roles, setRoles] = useState<ContactRole[]>([]);
+
+ useEffect(() => {
+ getAllContactRoles().then((res) => Array.isArray(res) && setRoles(res));
+ }, []);
+
+ return (
+ <Select
+ value={roleId ?? ALL}
+ onValueChange={(v) => onRoleChange(v === ALL ? undefined : v)}
+ >
+ <SelectTrigger aria-label="Filter by role" className="h-8 w-[160px]">
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ <SelectItem value={ALL}>All roles</SelectItem>
+ {roles.map((role) => (
+ <SelectItem key={role.id} value={role.id}>
+ {role.label}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ );
+}
diff --git a/src/components/admin/contacts-container/useContactsList.ts b/src/components/admin/contacts-container/useContactsList.ts
new file mode 100644
index 0000000..f980a3b
--- /dev/null
+++ b/src/components/admin/contacts-container/useContactsList.ts
@@ -0,0 +1,75 @@
+"use client";
+
+import { useCallback, useEffect, useRef, useState } from "react";
+import { getContactList } from "@/actions/contact.actions";
+import { APP_CONSTANTS } from "@/lib/constants";
+import { useInfiniteScroll } from "@/hooks/useInfiniteScroll";
+import type { Contact } from "@/models/contact.model";
+
+export function useContactsList(searchTerm: string, roleId?: string) {
+ const [contacts, setContacts] = useState<Contact[]>([]);
+ const [total, setTotal] = useState<number>(0);
+ const [page, setPage] = useState<number>(1);
+ const [initialLoading, setInitialLoading] = useState<boolean>(false);
+ const [loadingMore, setLoadingMore] = useState<boolean>(false);
+ const requestIdRef = useRef(0);
+
+ const load = useCallback(
+ async (nextPage: number, search?: string) => {
+ const requestId = ++requestIdRef.current;
+ if (nextPage === 1) setInitialLoading(true);
+ else setLoadingMore(true);
+ const { data, total: t } = await getContactList(
+ nextPage,
+ APP_CONSTANTS.RECORDS_PER_PAGE,
+ search,
+ roleId,
+ );
+ // A slow unfiltered response must not overwrite a fast filtered one
+ if (requestId !== requestIdRef.current) return;
+ if (data) {
+ setContacts((prev) => (nextPage === 1 ? data : [...prev, ...data]));
+ setTotal(t);
+ setPage(nextPage);
+ }
+ setInitialLoading(false);
+ setLoadingMore(false);
+ },
+ [roleId],
+ );
+
+ const reload = useCallback(
+ async () => load(1, searchTerm || undefined),
+ [load, searchTerm],
+ );
+
+ // One effect for role changes and debounced search: both reset to page 1
+ // and replace the list, so a separate mount effect would double-fetch.
+ useEffect(() => {
+ const timer = setTimeout(
+ () => load(1, searchTerm || undefined),
+ searchTerm ? 300 : 0,
+ );
+ return () => clearTimeout(timer);
+ }, [searchTerm, load]);
+
+ const hasMore = contacts.length < total;
+ const sentinelRef = useInfiniteScroll(
+ hasMore,
+ initialLoading || loadingMore,
+ useCallback(
+ () => load(page + 1, searchTerm || undefined),
+ [load, page, searchTerm],
+ ),
+ );
+
+ return {
+ contacts,
+ total,
+ initialLoading,
+ loadingMore,
+ hasMore,
+ sentinelRef,
+ reload,
+ };
+}
diff --git a/src/lib/backup/ordering.ts b/src/lib/backup/ordering.ts
index 0823af8..8710083 100644
--- a/src/lib/backup/ordering.ts
+++ b/src/lib/backup/ordering.ts
@@ -148,6 +148,7 @@ export const MODEL_SPECS: Record<BackupModel, ModelSpec> = {
companyId: "Company",
locationId: "Location",
workedAtCompanyId: "Company",
+ roleId: "ContactRole",
},
scope: byCreatedBy,
},
diff --git a/src/lib/backup/schema.ts b/src/lib/backup/schema.ts
index dcd7937..fa6bb14 100644
--- a/src/lib/backup/schema.ts
+++ b/src/lib/backup/schema.ts
@@ -243,6 +243,7 @@ const Contact = z.object({
workedAtCompanyId: optId.optional(),
workedFrom: optDt.optional(),
workedTo: optDt.optional(),
+ roleId: optId.optional(),
notes: optStr.optional(),
lastContactedAt: optDt.optional(),
updatedAt: dt.optional(),
diff --git a/src/models/addContactForm.schema.ts b/src/models/addContactForm.schema.ts
index ba4ea2d..a332135 100644
--- a/src/models/addContactForm.schema.ts
+++ b/src/models/addContactForm.schema.ts
@@ -41,6 +41,8 @@ export const AddContactFormSchema = z
workedAtCompany: z.string().optional(),
workedFrom: z.date().nullable().optional(),
workedTo: z.date().nullable().optional(),
+ // Named for ComboBox's `case "contactRole"` create path, not for the column
+ contactRole: z.string().optional(),
notes: optionalText(2000),
lastContactedAt: z.date().nullable().optional(),
})
diff --git a/src/models/contact.model.ts b/src/models/contact.model.ts
index 55579cd..6aff542 100644
--- a/src/models/contact.model.ts
+++ b/src/models/contact.model.ts
@@ -6,7 +6,7 @@ export interface ContactRole {
label: string;
value: string;
createdBy: string;
- _count?: { jobContacts: number };
+ _count?: { jobContacts: number; contacts: number };
}
export interface EntityRef {
@@ -57,6 +57,8 @@ export interface Contact {
WorkedAtCompany: EntityRef | null;
workedFrom: Date | null;
workedTo: Date | null;
+ roleId: string | null;
+ Role: ContactRole | null;
notes: string | null;
lastContactedAt: Date | null;
createdAt: Date;