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 getCompanyDetails and share the contact include and score helper

Khuram Niazebe9ad5cc67f
diff --git a/__tests__/companyDetails.actions.spec.ts b/__tests__/companyDetails.actions.spec.ts
new file mode 100644
index 0000000..38d0ac9
--- /dev/null
+++ b/__tests__/companyDetails.actions.spec.ts
@@ -0,0 +1,151 @@
+import { getCompanyDetails } from "@/actions/company.actions";
+import { getCurrentUser } from "@/utils/user.utils";
+import prisma from "@/lib/db";
+
+vi.mock("@/lib/db", () => ({
+ default: {
+ company: { findFirst: vi.fn() },
+ job: { findMany: vi.fn(), count: vi.fn() },
+ contact: { findMany: vi.fn() },
+ },
+}));
+
+vi.mock("@/utils/user.utils", () => ({ getCurrentUser: vi.fn() }));
+
+vi.mock("next/cache", () => ({ revalidatePath: vi.fn() }));
+
+const db = prisma as any;
+const user = { id: "user-1" };
+const company = {
+ id: "co1",
+ label: "Stripe",
+ value: "stripe",
+ createdBy: user.id,
+};
+
+describe("getCompanyDetails", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ (getCurrentUser as any).mockResolvedValue(user);
+ db.company.findFirst.mockResolvedValue(company);
+ db.job.findMany.mockResolvedValue([]);
+ db.job.count.mockResolvedValue(0);
+ db.contact.findMany.mockResolvedValue([]);
+ });
+
+ it("returns null for a company the user does not own, reading nothing else", async () => {
+ db.company.findFirst.mockResolvedValue(null);
+
+ await expect(getCompanyDetails("co-other")).resolves.toBeNull();
+ expect(db.company.findFirst).toHaveBeenCalledWith({
+ where: { id: "co-other", createdBy: user.id },
+ });
+ expect(db.job.findMany).not.toHaveBeenCalled();
+ expect(db.contact.findMany).not.toHaveBeenCalled();
+ });
+
+ it("scopes every job and contact query to the session user", async () => {
+ await getCompanyDetails("co1");
+
+ expect(db.job.findMany.mock.calls[0][0].where).toMatchObject({
+ companyId: "co1",
+ userId: user.id,
+ });
+ expect(db.job.count.mock.calls[0][0].where).toMatchObject({
+ companyId: "co1",
+ userId: user.id,
+ });
+ expect(db.contact.findMany.mock.calls.map((c: any) => c[0].where)).toEqual([
+ { companyId: "co1", createdBy: user.id },
+ { workedAtCompanyId: "co1", createdBy: user.id },
+ ]);
+ });
+
+ it("lists jobs newest first and leaves dismissed jobs out", async () => {
+ await getCompanyDetails("co1");
+
+ const args = db.job.findMany.mock.calls[0][0];
+ expect(args.orderBy).toEqual({ createdAt: "desc" });
+ expect(args.where.OR).toEqual([
+ { discoveryStatus: null },
+ { discoveryStatus: { not: "dismissed" } },
+ ]);
+ });
+
+ it("counts dismissed jobs separately so the delete check still sees them", async () => {
+ db.job.count.mockResolvedValue(3);
+
+ const result = await getCompanyDetails("co1");
+
+ expect(db.job.count.mock.calls[0][0].where).toEqual({
+ companyId: "co1",
+ userId: user.id,
+ discoveryStatus: "dismissed",
+ });
+ expect(result.dismissedJobsCount).toBe(3);
+ });
+
+ it("derives appliedCount from the applied flag", async () => {
+ db.job.findMany.mockResolvedValue([
+ { id: "j1", applied: true, matchScore: null, matchData: null },
+ { id: "j2", applied: false, matchScore: null, matchData: null },
+ { id: "j3", applied: true, matchScore: null, matchData: null },
+ ]);
+
+ const result = await getCompanyDetails("co1");
+
+ expect(result.appliedCount).toBe(2);
+ expect(result.jobs).toHaveLength(3);
+ });
+
+ it("hides the pre-rank score of an un-analyzed job and drops matchData", async () => {
+ db.job.findMany.mockResolvedValue([
+ {
+ id: "j1",
+ applied: false,
+ matchScore: 29,
+ matchData: JSON.stringify({ analyzed: false }),
+ },
+ {
+ id: "j2",
+ applied: false,
+ matchScore: 71,
+ matchData: JSON.stringify({ matchScore: 71 }),
+ },
+ ]);
+
+ const result = await getCompanyDetails("co1");
+
+ expect(result.jobs).toEqual([
+ { id: "j1", applied: false, matchScore: null },
+ { id: "j2", applied: false, matchScore: 71 },
+ ]);
+ });
+
+ it("returns the company with its two contact groups", async () => {
+ const dave = { id: "c1", name: "Dave" };
+ const priya = { id: "c2", name: "Priya" };
+ db.contact.findMany
+ .mockResolvedValueOnce([dave])
+ .mockResolvedValueOnce([priya]);
+
+ const result = await getCompanyDetails("co1");
+
+ expect(result).toMatchObject({
+ id: "co1",
+ label: "Stripe",
+ currentContacts: [dave],
+ formerContacts: [priya],
+ });
+ });
+
+ it("fails cleanly when not authenticated", async () => {
+ (getCurrentUser as any).mockResolvedValue(null);
+
+ await expect(getCompanyDetails("co1")).resolves.toEqual({
+ success: false,
+ message: "Not authenticated",
+ });
+ expect(db.company.findFirst).not.toHaveBeenCalled();
+ });
+});
diff --git a/src/actions/company.actions.ts b/src/actions/company.actions.ts
index 34b31a5..805d24b 100644
--- a/src/actions/company.actions.ts
+++ b/src/actions/company.actions.ts
@@ -6,6 +6,7 @@ export {
getCompanyList,
getAllCompanies,
getCompanyById,
+ getCompanyDetails,
} from "./company/queries";
export {
diff --git a/src/actions/company/queries.ts b/src/actions/company/queries.ts
index 316190f..b71c652 100644
--- a/src/actions/company/queries.ts
+++ b/src/actions/company/queries.ts
@@ -4,6 +4,8 @@ import { handleError } from "@/lib/utils";
import { APP_CONSTANTS } from "@/lib/constants";
import { requireUser } from "../shared";
import { getReferenceEntityList } from "../referenceList";
+import { CONTACT_LIST_INCLUDE } from "../contact/shared";
+import { hideUnanalyzedScore } from "../job/shared";
export const getCompanyList = async (
page: number = 1,
@@ -96,3 +98,74 @@ export const getCompanyById = async (
}
}
};
+
+const COMPANY_JOB_SELECT = {
+ id: true,
+ createdAt: true,
+ applied: true,
+ appliedDate: true,
+ matchScore: true,
+ matchData: true,
+ JobTitle: { select: { label: true } },
+ Status: { select: { label: true, value: true } },
+ Location: { select: { label: true } },
+ JobSource: { select: { label: true } },
+};
+
+// null covers both a missing id and another user's company, so the page's 404
+// never reveals which. Dismissed jobs are hidden like on the Jobs page, but
+// counted, because deleteCompanyById's job guard still sees them.
+export const getCompanyDetails = async (
+ companyId: string,
+): Promise<any | undefined> => {
+ try {
+ const user = await requireUser();
+
+ const company = await prisma.company.findFirst({
+ where: { id: companyId, createdBy: user.id },
+ });
+ if (!company) return null;
+
+ const [jobs, dismissedJobsCount, currentContacts, formerContacts] =
+ await Promise.all([
+ prisma.job.findMany({
+ where: {
+ companyId,
+ userId: user.id,
+ OR: [
+ { discoveryStatus: null },
+ { discoveryStatus: { not: "dismissed" } },
+ ],
+ },
+ select: COMPANY_JOB_SELECT,
+ orderBy: { createdAt: "desc" },
+ }),
+ prisma.job.count({
+ where: { companyId, userId: user.id, discoveryStatus: "dismissed" },
+ }),
+ prisma.contact.findMany({
+ where: { companyId, createdBy: user.id },
+ include: CONTACT_LIST_INCLUDE,
+ orderBy: [{ name: "asc" }],
+ }),
+ prisma.contact.findMany({
+ where: { workedAtCompanyId: companyId, createdBy: user.id },
+ include: CONTACT_LIST_INCLUDE,
+ orderBy: [{ name: "asc" }],
+ }),
+ ]);
+
+ const visibleJobs = jobs.map(hideUnanalyzedScore);
+
+ return {
+ ...company,
+ jobs: visibleJobs,
+ appliedCount: visibleJobs.filter((job) => job.applied).length,
+ dismissedJobsCount,
+ currentContacts,
+ formerContacts,
+ };
+ } catch (error) {
+ return handleError(error, "Failed to fetch company details. ");
+ }
+};
diff --git a/src/actions/contact/queries.ts b/src/actions/contact/queries.ts
index e8ddbac..4631449 100644
--- a/src/actions/contact/queries.ts
+++ b/src/actions/contact/queries.ts
@@ -3,29 +3,7 @@ import prisma from "@/lib/db";
import { handleError } from "@/lib/utils";
import { requireUser } from "../shared";
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 } },
- jobLinks: {
- include: {
- Role: true,
- Job: {
- select: {
- id: true,
- JobTitle: { select: { label: true } },
- Company: { select: { label: true } },
- },
- },
- },
- orderBy: { createdAt: "asc" as const },
- },
- _count: { select: { jobLinks: true } },
-};
+import { CONTACT_LIST_INCLUDE } from "./shared";
// Contacts get their own query rather than getReferenceEntityList: that helper
// counts jobs grouped by an FK on Job, and a contact reaches Job only through
diff --git a/src/actions/contact/shared.ts b/src/actions/contact/shared.ts
new file mode 100644
index 0000000..961da9a
--- /dev/null
+++ b/src/actions/contact/shared.ts
@@ -0,0 +1,22 @@
+// Not a "use server" module: contact/queries.ts and company/queries.ts both
+// read contacts in the shape ContactsTable and ContactRow render.
+export const CONTACT_LIST_INCLUDE = {
+ Role: true,
+ Company: { select: { id: true, label: true } },
+ Location: { select: { id: true, label: true } },
+ WorkedAtCompany: { select: { id: true, label: true } },
+ jobLinks: {
+ include: {
+ Role: true,
+ Job: {
+ select: {
+ id: true,
+ JobTitle: { select: { label: true } },
+ Company: { select: { label: true } },
+ },
+ },
+ },
+ orderBy: { createdAt: "asc" as const },
+ },
+ _count: { select: { jobLinks: true } },
+};
diff --git a/src/actions/job/queries.ts b/src/actions/job/queries.ts
index 004b69b..d0ada89 100644
--- a/src/actions/job/queries.ts
+++ b/src/actions/job/queries.ts
@@ -4,6 +4,7 @@ import { handleError } from "@/lib/utils";
import { JOB_TYPES } from "@/models/job.model";
import { APP_CONSTANTS } from "@/lib/constants";
import { requireUser } from "../shared";
+import { hideUnanalyzedScore } from "./shared";
const JOB_LIST_SELECT = {
id: true,
@@ -25,19 +26,6 @@ const JOB_LIST_SELECT = {
_count: { select: { Notes: true } },
};
-// An automation job saved without LLM analysis carries only its keyword
-// pre-rank in matchScore, which the list must not show as an AI match. The
-// matchData body is dropped so the list payload stays small.
-function hideUnanalyzedScore<
- T extends { matchScore: number | null; matchData: string | null },
->({ matchData, ...job }: T) {
- let analyzed = true;
- try {
- analyzed = JSON.parse(matchData ?? "{}").analyzed !== false;
- } catch {}
- return analyzed ? job : { ...job, matchScore: null };
-}
-
const JOB_EXPORT_SELECT = {
id: true,
createdAt: true,
diff --git a/src/actions/job/shared.ts b/src/actions/job/shared.ts
new file mode 100644
index 0000000..90fc294
--- /dev/null
+++ b/src/actions/job/shared.ts
@@ -0,0 +1,15 @@
+// Not a "use server" module: job/queries.ts and company/queries.ts both map
+// job rows through this, and exporting it from either would make it an action.
+
+// An automation job saved without LLM analysis carries only its keyword
+// pre-rank in matchScore, which the list must not show as an AI match. The
+// matchData body is dropped so the list payload stays small.
+export function hideUnanalyzedScore<
+ T extends { matchScore: number | null; matchData: string | null },
+>({ matchData, ...job }: T) {
+ let analyzed = true;
+ try {
+ analyzed = JSON.parse(matchData ?? "{}").analyzed !== false;
+ } catch {}
+ return analyzed ? job : { ...job, matchScore: null };
+}
diff --git a/src/models/companyDetails.model.ts b/src/models/companyDetails.model.ts
new file mode 100644
index 0000000..833f6fd
--- /dev/null
+++ b/src/models/companyDetails.model.ts
@@ -0,0 +1,24 @@
+import type { Contact } from "./contact.model";
+import type { Company } from "./job.model";
+
+// What getCompanyDetails returns: the job rows are narrowed to the Jobs tab's
+// columns, and matchData is already folded into matchScore server-side.
+export interface CompanyJobRow {
+ id: string;
+ createdAt: Date;
+ applied: boolean;
+ appliedDate: Date | null;
+ matchScore: number | null;
+ JobTitle: { label: string };
+ Status: { label: string; value: string };
+ Location: { label: string } | null;
+ JobSource: { label: string } | null;
+}
+
+export interface CompanyDetails extends Company {
+ jobs: CompanyJobRow[];
+ appliedCount: number;
+ dismissedJobsCount: number;
+ currentContacts: Contact[];
+ formerContacts: Contact[];
+}