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.

refactor(actions): consolidate company/jobtitle/location/source list queries into getReferenceEntityList

Khuram Niaz97b2f501f4f4
diff --git a/__tests__/jobLocation.actions.spec.ts b/__tests__/jobLocation.actions.spec.ts
index 1b3267e..fc2ed76 100644
--- a/__tests__/jobLocation.actions.spec.ts
+++ b/__tests__/jobLocation.actions.spec.ts
@@ -173,6 +173,41 @@ describe("Job Location Actions", () => {
expect(result).toEqual({ success: false, message: "Database error" });
});
+
+ it("should filter locations by label when search is provided", async () => {
+ (getCurrentUser as any).mockResolvedValue(mockUser);
+ const mockData = [{ id: "loc-1", label: "New York", value: "new york" }];
+ (prisma.location.findMany as any).mockResolvedValue(mockData);
+ (prisma.location.count as any).mockResolvedValue(1);
+
+ const result = await getJobLocationsList(1, 10, undefined, "New");
+
+ expect(result).toEqual({ data: mockData, total: 1 });
+ expect(prisma.location.findMany).toHaveBeenCalledWith({
+ where: { createdBy: mockUser.id, label: { contains: "New" } },
+ skip: 0,
+ take: 10,
+ orderBy: { jobsApplied: { _count: "desc" } },
+ });
+ expect(prisma.location.count).toHaveBeenCalledWith({
+ where: { createdBy: mockUser.id, label: { contains: "New" } },
+ });
+ });
+
+ it("should not apply a label filter when search is empty", async () => {
+ (getCurrentUser as any).mockResolvedValue(mockUser);
+ (prisma.location.findMany as any).mockResolvedValue([]);
+ (prisma.location.count as any).mockResolvedValue(0);
+
+ await getJobLocationsList(1, 10, undefined, "");
+
+ expect(prisma.location.findMany).toHaveBeenCalledWith({
+ where: { createdBy: mockUser.id },
+ skip: 0,
+ take: 10,
+ orderBy: { jobsApplied: { _count: "desc" } },
+ });
+ });
});
describe("deleteJobLocationById", () => {
diff --git a/__tests__/jobSource.actions.spec.ts b/__tests__/jobSource.actions.spec.ts
new file mode 100644
index 0000000..c8742cc
--- /dev/null
+++ b/__tests__/jobSource.actions.spec.ts
@@ -0,0 +1,200 @@
+// Covers the paginated list in jobSource.actions.ts — not the same-named
+// bare-array getJobSourceList in job/references.ts (see job.actions.spec.ts).
+import {
+ getJobSourceList,
+ deleteJobSourceById,
+} from "@/actions/jobSource.actions";
+import { getCurrentUser } from "@/utils/user.utils";
+import { PrismaClient } from "@prisma/client";
+
+const prisma = new PrismaClient();
+
+vi.mock("@prisma/client", () => {
+ const mPrismaClient = {
+ jobSource: {
+ findMany: vi.fn(),
+ count: vi.fn(),
+ delete: vi.fn(),
+ },
+ job: {
+ count: vi.fn(),
+ groupBy: vi.fn(),
+ },
+ };
+ return {
+ PrismaClient: vi.fn(function () {
+ return mPrismaClient;
+ }),
+ };
+});
+
+vi.mock("@/utils/user.utils", () => ({
+ getCurrentUser: vi.fn(),
+}));
+
+vi.mock("next/cache", () => ({
+ revalidatePath: vi.fn(),
+}));
+
+describe("Job Source Actions", () => {
+ const mockUser = { id: "user-id" };
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+ });
+
+ describe("getJobSourceList", () => {
+ it("should return paginated job source list", async () => {
+ (getCurrentUser as any).mockResolvedValue(mockUser);
+ const mockData = [{ id: "src-1", label: "LinkedIn", value: "linkedin" }];
+ (prisma.jobSource.findMany as any).mockResolvedValue(mockData);
+ (prisma.jobSource.count as any).mockResolvedValue(1);
+
+ const result = await getJobSourceList(1, 10);
+
+ expect(result).toEqual({ data: mockData, total: 1 });
+ expect(prisma.jobSource.findMany).toHaveBeenCalledWith({
+ where: { createdBy: mockUser.id },
+ skip: 0,
+ take: 10,
+ orderBy: { jobsApplied: { _count: "desc" } },
+ });
+ expect(prisma.jobSource.count).toHaveBeenCalledWith({
+ where: { createdBy: mockUser.id },
+ });
+ });
+
+ it("should select applied counts and splice jobsTotal when countBy is provided", async () => {
+ (getCurrentUser as any).mockResolvedValue(mockUser);
+ const mockData = [{ id: "src-1", label: "LinkedIn", value: "linkedin" }];
+ (prisma.jobSource.findMany as any).mockResolvedValue(mockData);
+ (prisma.jobSource.count as any).mockResolvedValue(1);
+ (prisma.job.groupBy as any).mockResolvedValue([
+ { jobSourceId: "src-1", _count: { id: 4 } },
+ ]);
+
+ const result = await getJobSourceList(1, 10, "applied");
+
+ expect(result).toEqual({
+ data: [{ ...mockData[0], _count: { jobsTotal: 4 } }],
+ total: 1,
+ });
+ expect(prisma.jobSource.findMany).toHaveBeenCalledWith({
+ where: { createdBy: mockUser.id },
+ skip: 0,
+ take: 10,
+ select: {
+ id: true,
+ label: true,
+ value: true,
+ _count: {
+ select: {
+ jobsApplied: {
+ where: { applied: true },
+ },
+ },
+ },
+ },
+ orderBy: { jobsApplied: { _count: "desc" } },
+ });
+ expect(prisma.job.groupBy).toHaveBeenCalledWith({
+ by: ["jobSourceId"],
+ where: { userId: mockUser.id },
+ _count: { id: true },
+ });
+ });
+
+ it("should calculate skip correctly for page 3", async () => {
+ (getCurrentUser as any).mockResolvedValue(mockUser);
+ (prisma.jobSource.findMany as any).mockResolvedValue([]);
+ (prisma.jobSource.count as any).mockResolvedValue(0);
+
+ await getJobSourceList(3, 5);
+
+ expect(prisma.jobSource.findMany).toHaveBeenCalledWith(
+ expect.objectContaining({ skip: 10, take: 5 })
+ );
+ });
+
+ it("should return error for unauthenticated user", async () => {
+ (getCurrentUser as any).mockResolvedValue(null);
+
+ const result = await getJobSourceList(1, 10);
+
+ expect(result).toEqual({ success: false, message: "Not authenticated" });
+ expect(prisma.jobSource.findMany).not.toHaveBeenCalled();
+ });
+
+ it("should handle errors", async () => {
+ (getCurrentUser as any).mockRejectedValue(new Error("Database error"));
+
+ const result = await getJobSourceList(1, 10);
+
+ expect(result).toEqual({ success: false, message: "Database error" });
+ });
+
+ it("should filter job sources by label when search is provided", async () => {
+ (getCurrentUser as any).mockResolvedValue(mockUser);
+ const mockData = [{ id: "src-1", label: "LinkedIn", value: "linkedin" }];
+ (prisma.jobSource.findMany as any).mockResolvedValue(mockData);
+ (prisma.jobSource.count as any).mockResolvedValue(1);
+
+ const result = await getJobSourceList(1, 10, undefined, "Link");
+
+ expect(result).toEqual({ data: mockData, total: 1 });
+ expect(prisma.jobSource.findMany).toHaveBeenCalledWith({
+ where: { createdBy: mockUser.id, label: { contains: "Link" } },
+ skip: 0,
+ take: 10,
+ orderBy: { jobsApplied: { _count: "desc" } },
+ });
+ expect(prisma.jobSource.count).toHaveBeenCalledWith({
+ where: { createdBy: mockUser.id, label: { contains: "Link" } },
+ });
+ });
+
+ it("should not apply a label filter when search is empty", async () => {
+ (getCurrentUser as any).mockResolvedValue(mockUser);
+ (prisma.jobSource.findMany as any).mockResolvedValue([]);
+ (prisma.jobSource.count as any).mockResolvedValue(0);
+
+ await getJobSourceList(1, 10, undefined, "");
+
+ expect(prisma.jobSource.findMany).toHaveBeenCalledWith({
+ where: { createdBy: mockUser.id },
+ skip: 0,
+ take: 10,
+ orderBy: { jobsApplied: { _count: "desc" } },
+ });
+ });
+ });
+
+ describe("deleteJobSourceById", () => {
+ it("should delete a job source with no linked jobs", async () => {
+ (getCurrentUser as any).mockResolvedValue(mockUser);
+ (prisma.job.count as any).mockResolvedValue(0);
+ (prisma.jobSource.delete as any).mockResolvedValue({ id: "src-1" });
+
+ const result = await deleteJobSourceById("src-1");
+
+ expect(result).toEqual({ res: { id: "src-1" }, success: true });
+ expect(prisma.jobSource.delete).toHaveBeenCalledWith({
+ where: { id: "src-1", createdBy: mockUser.id },
+ });
+ });
+
+ it("should refuse to delete a job source that has linked jobs", async () => {
+ (getCurrentUser as any).mockResolvedValue(mockUser);
+ (prisma.job.count as any).mockResolvedValue(2);
+
+ const result = await deleteJobSourceById("src-1");
+
+ expect(result).toEqual({
+ success: false,
+ message:
+ "Job source cannot be deleted due to 2 number of associated jobs! ",
+ });
+ expect(prisma.jobSource.delete).not.toHaveBeenCalled();
+ });
+ });
+});
diff --git a/__tests__/referenceList.spec.ts b/__tests__/referenceList.spec.ts
new file mode 100644
index 0000000..751bde2
--- /dev/null
+++ b/__tests__/referenceList.spec.ts
@@ -0,0 +1,283 @@
+import { getReferenceEntityList } from "@/actions/referenceList";
+import { PrismaClient } from "@prisma/client";
+
+const prisma = new PrismaClient();
+
+vi.mock("@prisma/client", () => {
+ const mPrismaClient = {
+ job: {
+ groupBy: vi.fn(),
+ },
+ };
+ return {
+ PrismaClient: vi.fn(function () {
+ return mPrismaClient;
+ }),
+ };
+});
+
+describe("getReferenceEntityList", () => {
+ const userId = "user-id";
+
+ const makeModel = (data: any[] = [], total = 0) => ({
+ findMany: vi.fn().mockResolvedValue(data),
+ count: vi.fn().mockResolvedValue(total),
+ });
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+ });
+
+ it("queries without a select and issues no groupBy when countBy is absent", async () => {
+ const data = [{ id: "a", label: "A", value: "a" }];
+ const model = makeModel(data, 1);
+
+ const result = await getReferenceEntityList({
+ model,
+ userId,
+ fkField: "locationId",
+ appliedRelation: "jobsApplied",
+ page: 1,
+ limit: 10,
+ });
+
+ expect(result).toEqual({ data, total: 1 });
+ expect(model.findMany).toHaveBeenCalledWith({
+ where: { createdBy: userId },
+ skip: 0,
+ take: 10,
+ orderBy: { jobsApplied: { _count: "desc" } },
+ });
+ expect(model.count).toHaveBeenCalledWith({ where: { createdBy: userId } });
+ expect(prisma.job.groupBy).not.toHaveBeenCalled();
+ });
+
+ it("uses the supplied relation name in both select and orderBy", async () => {
+ const model = makeModel([{ id: "a", label: "A", value: "a" }], 1);
+ (prisma.job.groupBy as any).mockResolvedValue([]);
+
+ await getReferenceEntityList({
+ model,
+ userId,
+ fkField: "jobTitleId",
+ appliedRelation: "jobs",
+ page: 1,
+ limit: 10,
+ countBy: "applied",
+ });
+
+ expect(model.findMany).toHaveBeenCalledWith({
+ where: { createdBy: userId },
+ skip: 0,
+ take: 10,
+ select: {
+ id: true,
+ label: true,
+ value: true,
+ _count: {
+ select: {
+ jobs: { where: { applied: true } },
+ },
+ },
+ },
+ orderBy: { jobs: { _count: "desc" } },
+ });
+ });
+
+ it("merges extraSelect fields into the select", async () => {
+ const model = makeModel([{ id: "a", label: "A", value: "a" }], 1);
+ (prisma.job.groupBy as any).mockResolvedValue([]);
+
+ await getReferenceEntityList({
+ model,
+ userId,
+ fkField: "companyId",
+ appliedRelation: "jobsApplied",
+ extraSelect: { logoUrl: true },
+ page: 1,
+ limit: 10,
+ countBy: "applied",
+ });
+
+ expect(model.findMany).toHaveBeenCalledWith(
+ expect.objectContaining({
+ select: {
+ id: true,
+ label: true,
+ value: true,
+ logoUrl: true,
+ _count: {
+ select: {
+ jobsApplied: { where: { applied: true } },
+ },
+ },
+ },
+ })
+ );
+ });
+
+ it("splices jobsTotal onto each row from the base groupBy", async () => {
+ const model = makeModel(
+ [
+ { id: "a", label: "A", value: "a", _count: { jobsApplied: 2 } },
+ { id: "b", label: "B", value: "b", _count: { jobsApplied: 0 } },
+ ],
+ 2
+ );
+ (prisma.job.groupBy as any).mockResolvedValue([
+ { locationId: "a", _count: { id: 7 } },
+ ]);
+
+ const result = await getReferenceEntityList({
+ model,
+ userId,
+ fkField: "locationId",
+ appliedRelation: "jobsApplied",
+ page: 1,
+ limit: 10,
+ countBy: "applied",
+ });
+
+ expect(prisma.job.groupBy).toHaveBeenCalledWith({
+ by: ["locationId"],
+ where: { userId },
+ _count: { id: true },
+ });
+ expect(result.data).toEqual([
+ { id: "a", label: "A", value: "a", _count: { jobsApplied: 2, jobsTotal: 7 } },
+ { id: "b", label: "B", value: "b", _count: { jobsApplied: 0, jobsTotal: 0 } },
+ ]);
+ });
+
+ it("splices each extraCount under its own key with its own filter", async () => {
+ const model = makeModel(
+ [{ id: "a", label: "A", value: "a", _count: { jobsApplied: 2 } }],
+ 1
+ );
+ (prisma.job.groupBy as any)
+ .mockResolvedValueOnce([{ companyId: "a", _count: { id: 3 } }])
+ .mockResolvedValueOnce([{ companyId: "a", _count: { id: 9 } }]);
+
+ const result = await getReferenceEntityList({
+ model,
+ userId,
+ fkField: "companyId",
+ appliedRelation: "jobsApplied",
+ extraCounts: [
+ { key: "jobsRejected", where: { Status: { value: "rejected" } } },
+ ],
+ page: 1,
+ limit: 10,
+ countBy: "applied",
+ });
+
+ expect(prisma.job.groupBy).toHaveBeenNthCalledWith(1, {
+ by: ["companyId"],
+ where: { userId, Status: { value: "rejected" } },
+ _count: { id: true },
+ });
+ expect(prisma.job.groupBy).toHaveBeenNthCalledWith(2, {
+ by: ["companyId"],
+ where: { userId },
+ _count: { id: true },
+ });
+ expect(result.data).toEqual([
+ {
+ id: "a",
+ label: "A",
+ value: "a",
+ _count: { jobsApplied: 2, jobsRejected: 3, jobsTotal: 9 },
+ },
+ ]);
+ });
+
+ it("applies a label filter to findMany and count when search is provided", async () => {
+ const model = makeModel([], 0);
+
+ await getReferenceEntityList({
+ model,
+ userId,
+ fkField: "companyId",
+ appliedRelation: "jobsApplied",
+ page: 1,
+ limit: 10,
+ search: "Ama",
+ });
+
+ expect(model.findMany).toHaveBeenCalledWith(
+ expect.objectContaining({
+ where: { createdBy: userId, label: { contains: "Ama" } },
+ })
+ );
+ expect(model.count).toHaveBeenCalledWith({
+ where: { createdBy: userId, label: { contains: "Ama" } },
+ });
+ });
+
+ it("does not apply a label filter when search is an empty string", async () => {
+ const model = makeModel([], 0);
+
+ await getReferenceEntityList({
+ model,
+ userId,
+ fkField: "companyId",
+ appliedRelation: "jobsApplied",
+ page: 1,
+ limit: 10,
+ search: "",
+ });
+
+ expect(model.findMany).toHaveBeenCalledWith(
+ expect.objectContaining({ where: { createdBy: userId } })
+ );
+ });
+
+ it("computes skip from page and limit", async () => {
+ const model = makeModel([], 0);
+
+ await getReferenceEntityList({
+ model,
+ userId,
+ fkField: "locationId",
+ appliedRelation: "jobsApplied",
+ page: 3,
+ limit: 5,
+ });
+
+ expect(model.findMany).toHaveBeenCalledWith(
+ expect.objectContaining({ skip: 10, take: 5 })
+ );
+ });
+
+ it("returns rows untouched when countBy is absent even if groupBy data exists", async () => {
+ const data = [{ id: "a", label: "A", value: "a" }];
+ const model = makeModel(data, 1);
+
+ const result = await getReferenceEntityList({
+ model,
+ userId,
+ fkField: "locationId",
+ appliedRelation: "jobsApplied",
+ page: 1,
+ limit: 10,
+ });
+
+ expect(result.data).toBe(data);
+ });
+
+ it("propagates a delegate rejection to the caller", async () => {
+ const model = makeModel();
+ model.findMany.mockRejectedValue(new Error("Database error"));
+
+ await expect(
+ getReferenceEntityList({
+ model,
+ userId,
+ fkField: "locationId",
+ appliedRelation: "jobsApplied",
+ page: 1,
+ limit: 10,
+ })
+ ).rejects.toThrow("Database error");
+ });
+});
diff --git a/src/actions/company/queries.ts b/src/actions/company/queries.ts
index c6c85ff..2870c4b 100644
--- a/src/actions/company/queries.ts
+++ b/src/actions/company/queries.ts
@@ -3,47 +3,7 @@ import prisma from "@/lib/db";
import { handleError } from "@/lib/utils";
import { APP_CONSTANTS } from "@/lib/constants";
import { requireUser } from "../shared";
-
-type JobCountGroup = { companyId: string; _count: { id: number } };
-
-const COMPANY_WITH_APPLIED_COUNT_SELECT = {
- id: true,
- label: true,
- value: true,
- logoUrl: true,
- _count: {
- select: {
- jobsApplied: {
- where: {
- applied: true,
- },
- },
- },
- },
-};
-
-// Prisma can only count the `applied` relation inline, so the rejected and
-// total tallies come from separate groupBy queries and are spliced on here.
-const attachJobCounts = (
- data: any[],
- rejectedCounts: JobCountGroup[],
- totalCounts: JobCountGroup[],
-) => {
- const rejectedMap = new Map(
- rejectedCounts.map((r) => [r.companyId, r._count.id]),
- );
-
- const totalMap = new Map(totalCounts.map((r) => [r.companyId, r._count.id]));
-
- return data.map((company) => ({
- ...company,
- _count: {
- ...(company._count ?? {}),
- jobsRejected: rejectedMap.get(company.id) ?? 0,
- jobsTotal: totalMap.get(company.id) ?? 0,
- },
- }));
-};
+import { getReferenceEntityList } from "../referenceList";
export const getCompanyList = async (
page: number = 1,
@@ -53,61 +13,21 @@ export const getCompanyList = async (
): Promise<any | undefined> => {
try {
const user = await requireUser();
- const skip = (page - 1) * limit;
-
- const whereClause: any = {
- createdBy: user.id,
- };
-
- if (search) {
- whereClause.label = { contains: search };
- }
- const [data, total, rejectedCounts, totalCounts] = await Promise.all([
- prisma.company.findMany({
- where: whereClause,
- skip,
- take: limit,
- ...(countBy ? { select: COMPANY_WITH_APPLIED_COUNT_SELECT } : {}),
- orderBy: {
- jobsApplied: {
- _count: "desc",
- },
- },
- }),
- prisma.company.count({
- where: whereClause,
- }),
- countBy
- ? prisma.job.groupBy({
- by: ["companyId"],
- where: {
- userId: user.id,
- Status: { value: "rejected" },
- },
- _count: { id: true },
- })
- : Promise.resolve([]),
- countBy
- ? prisma.job.groupBy({
- by: ["companyId"],
- where: {
- userId: user.id,
- },
- _count: { id: true },
- })
- : Promise.resolve([]),
- ]);
-
- const dataWithRejected = countBy
- ? attachJobCounts(
- data as any[],
- rejectedCounts as JobCountGroup[],
- totalCounts as JobCountGroup[],
- )
- : data;
-
- return { data: dataWithRejected, total };
+ return await getReferenceEntityList({
+ model: prisma.company,
+ userId: user.id,
+ fkField: "companyId",
+ appliedRelation: "jobsApplied",
+ extraSelect: { logoUrl: true },
+ extraCounts: [
+ { key: "jobsRejected", where: { Status: { value: "rejected" } } },
+ ],
+ page,
+ limit,
+ countBy,
+ search,
+ });
} catch (error) {
const msg = "Failed to fetch company list. ";
return handleError(error, msg);
diff --git a/src/actions/jobLocation.actions.ts b/src/actions/jobLocation.actions.ts
index 656a8fe..78ae5b4 100644
--- a/src/actions/jobLocation.actions.ts
+++ b/src/actions/jobLocation.actions.ts
@@ -3,6 +3,7 @@ import prisma from "@/lib/db";
import { handleError } from "@/lib/utils";
import { getCurrentUser } from "@/utils/user.utils";
import { APP_CONSTANTS } from "@/lib/constants";
+import { getReferenceEntityList } from "./referenceList";
export const getAllJobLocations = async (): Promise<any | undefined> => {
try {
@@ -25,7 +26,8 @@ export const getAllJobLocations = async (): Promise<any | undefined> => {
export const getJobLocationsList = async (
page: number = 1,
limit: number = APP_CONSTANTS.RECORDS_PER_PAGE,
- countBy?: string
+ countBy?: string,
+ search?: string,
): Promise<any | undefined> => {
try {
const user = await getCurrentUser();
@@ -33,72 +35,17 @@ export const getJobLocationsList = async (
if (!user) {
throw new Error("Not authenticated");
}
- const skip = (page - 1) * limit;
- const [data, total, totalCounts] = await Promise.all([
- prisma.location.findMany({
- where: {
- createdBy: user.id,
- },
- skip,
- take: limit,
- ...(countBy
- ? {
- select: {
- id: true,
- label: true,
- value: true,
- _count: {
- select: {
- jobsApplied: {
- where: {
- applied: true,
- },
- },
- },
- },
- },
- }
- : {}),
- orderBy: {
- jobsApplied: {
- _count: "desc",
- },
- },
- }),
- prisma.location.count({
- where: {
- createdBy: user.id,
- },
- }),
- countBy
- ? prisma.job.groupBy({
- by: ["locationId"],
- where: {
- userId: user.id,
- },
- _count: { id: true },
- })
- : Promise.resolve([]),
- ]);
-
- const totalMap = new Map(
- (totalCounts as { locationId: string; _count: { id: number } }[]).map(
- (r) => [r.locationId, r._count.id],
- ),
- );
-
- const dataWithTotal = countBy
- ? (data as any[]).map((location) => ({
- ...location,
- _count: {
- ...(location._count ?? {}),
- jobsTotal: totalMap.get(location.id) ?? 0,
- },
- }))
- : data;
-
- return { data: dataWithTotal, total };
+ return await getReferenceEntityList({
+ model: prisma.location,
+ userId: user.id,
+ fkField: "locationId",
+ appliedRelation: "jobsApplied",
+ page,
+ limit,
+ countBy,
+ search,
+ });
} catch (error) {
const msg = "Failed to fetch job location list. ";
return handleError(error, msg);
diff --git a/src/actions/jobSource.actions.ts b/src/actions/jobSource.actions.ts
index 732d44d..e28be35 100644
--- a/src/actions/jobSource.actions.ts
+++ b/src/actions/jobSource.actions.ts
@@ -3,11 +3,13 @@ import prisma from "@/lib/db";
import { handleError } from "@/lib/utils";
import { getCurrentUser } from "@/utils/user.utils";
import { APP_CONSTANTS } from "@/lib/constants";
+import { getReferenceEntityList } from "./referenceList";
export const getJobSourceList = async (
page: number = 1,
limit: number = APP_CONSTANTS.RECORDS_PER_PAGE,
- countBy?: string
+ countBy?: string,
+ search?: string,
): Promise<any | undefined> => {
try {
const user = await getCurrentUser();
@@ -15,72 +17,17 @@ export const getJobSourceList = async (
if (!user) {
throw new Error("Not authenticated");
}
- const skip = (page - 1) * limit;
- const [data, total, totalCounts] = await Promise.all([
- prisma.jobSource.findMany({
- where: {
- createdBy: user.id,
- },
- skip,
- take: limit,
- ...(countBy
- ? {
- select: {
- id: true,
- label: true,
- value: true,
- _count: {
- select: {
- jobsApplied: {
- where: {
- applied: true,
- },
- },
- },
- },
- },
- }
- : {}),
- orderBy: {
- jobsApplied: {
- _count: "desc",
- },
- },
- }),
- prisma.jobSource.count({
- where: {
- createdBy: user.id,
- },
- }),
- countBy
- ? prisma.job.groupBy({
- by: ["jobSourceId"],
- where: {
- userId: user.id,
- },
- _count: { id: true },
- })
- : Promise.resolve([]),
- ]);
-
- const totalMap = new Map(
- (totalCounts as { jobSourceId: string; _count: { id: number } }[]).map(
- (r) => [r.jobSourceId, r._count.id],
- ),
- );
-
- const dataWithTotal = countBy
- ? (data as any[]).map((source) => ({
- ...source,
- _count: {
- ...(source._count ?? {}),
- jobsTotal: totalMap.get(source.id) ?? 0,
- },
- }))
- : data;
-
- return { data: dataWithTotal, total };
+ return await getReferenceEntityList({
+ model: prisma.jobSource,
+ userId: user.id,
+ fkField: "jobSourceId",
+ appliedRelation: "jobsApplied",
+ page,
+ limit,
+ countBy,
+ search,
+ });
} catch (error) {
const msg = "Failed to fetch job source list. ";
return handleError(error, msg);
diff --git a/src/actions/jobtitle.actions.ts b/src/actions/jobtitle.actions.ts
index 947edd8..a0b2f8e 100644
--- a/src/actions/jobtitle.actions.ts
+++ b/src/actions/jobtitle.actions.ts
@@ -4,6 +4,7 @@ import { handleError } from "@/lib/utils";
import { getCurrentUser } from "@/utils/user.utils";
import { APP_CONSTANTS } from "@/lib/constants";
import { canonicalizeEntityValue } from "@/lib/jobs/canonicalize";
+import { getReferenceEntityList } from "./referenceList";
export const getAllJobTitles = async (): Promise<any | undefined> => {
try {
@@ -35,76 +36,17 @@ export const getJobTitleList = async (
if (!user) {
throw new Error("Not authenticated");
}
- const skip = (page - 1) * limit;
- const whereClause: any = {
- createdBy: user.id,
- };
-
- if (search) {
- whereClause.label = { contains: search };
- }
-
- const [data, total, totalCounts] = await Promise.all([
- prisma.jobTitle.findMany({
- where: whereClause,
- skip,
- take: limit,
- ...(countBy
- ? {
- select: {
- id: true,
- label: true,
- value: true,
- _count: {
- select: {
- jobs: {
- where: {
- applied: true,
- },
- },
- },
- },
- },
- }
- : {}),
- orderBy: {
- jobs: {
- _count: "desc",
- },
- },
- }),
- prisma.jobTitle.count({
- where: whereClause,
- }),
- countBy
- ? prisma.job.groupBy({
- by: ["jobTitleId"],
- where: {
- userId: user.id,
- },
- _count: { id: true },
- })
- : Promise.resolve([]),
- ]);
-
- const totalMap = new Map(
- (totalCounts as { jobTitleId: string; _count: { id: number } }[]).map(
- (r) => [r.jobTitleId, r._count.id],
- ),
- );
-
- const dataWithTotal = countBy
- ? (data as any[]).map((title) => ({
- ...title,
- _count: {
- ...(title._count ?? {}),
- jobsTotal: totalMap.get(title.id) ?? 0,
- },
- }))
- : data;
-
- return { data: dataWithTotal, total };
+ return await getReferenceEntityList({
+ model: prisma.jobTitle,
+ userId: user.id,
+ fkField: "jobTitleId",
+ appliedRelation: "jobs",
+ page,
+ limit,
+ countBy,
+ search,
+ });
} catch (error) {
const msg = "Failed to fetch job title list. ";
return handleError(error, msg);
diff --git a/src/actions/referenceList.ts b/src/actions/referenceList.ts
new file mode 100644
index 0000000..65023e0
--- /dev/null
+++ b/src/actions/referenceList.ts
@@ -0,0 +1,128 @@
+import prisma from "@/lib/db";
+
+// Not a "use server" module: it takes a Prisma delegate as an argument, so it
+// must never become a callable server-action endpoint.
+
+export type ReferenceListDelegate = {
+ findMany: (args: any) => Promise<any>;
+ count: (args: any) => Promise<any>;
+};
+
+export type ReferenceExtraCount = {
+ key: string;
+ where: Record<string, any>;
+};
+
+export type ReferenceListParams = {
+ model: ReferenceListDelegate;
+ userId: string;
+ fkField: string;
+ appliedRelation: string;
+ extraSelect?: Record<string, true>;
+ extraCounts?: ReferenceExtraCount[];
+ page: number;
+ limit: number;
+ countBy?: string;
+ search?: string;
+};
+
+export const getReferenceEntityList = async ({
+ model,
+ userId,
+ fkField,
+ appliedRelation,
+ extraSelect,
+ extraCounts,
+ page,
+ limit,
+ countBy,
+ search,
+}: ReferenceListParams): Promise<{ data: any; total: number }> => {
+ const skip = (page - 1) * limit;
+
+ const whereClause: any = {
+ createdBy: userId,
+ };
+
+ if (search) {
+ whereClause.label = { contains: search };
+ }
+
+ // Prisma can only count the applied relation inline, so every other tally
+ // comes from its own groupBy and is spliced on below.
+ const countSpecs = countBy
+ ? [
+ ...(extraCounts ?? []).map((extra) => ({
+ key: extra.key,
+ where: { userId, ...extra.where },
+ })),
+ { key: "jobsTotal", where: { userId } },
+ ]
+ : [];
+
+ const [data, total, ...groups] = await Promise.all([
+ model.findMany({
+ where: whereClause,
+ skip,
+ take: limit,
+ ...(countBy
+ ? {
+ select: {
+ id: true,
+ label: true,
+ value: true,
+ ...extraSelect,
+ _count: {
+ select: {
+ [appliedRelation]: {
+ where: {
+ applied: true,
+ },
+ },
+ },
+ },
+ },
+ }
+ : {}),
+ orderBy: {
+ [appliedRelation]: {
+ _count: "desc",
+ },
+ },
+ }),
+ model.count({
+ where: whereClause,
+ }),
+ // Prisma's groupBy generics need a literal `by` tuple; ours is dynamic.
+ ...countSpecs.map((spec) =>
+ (prisma.job.groupBy as any)({
+ by: [fkField],
+ where: spec.where,
+ _count: { id: true },
+ })
+ ),
+ ]);
+
+ if (!countBy) {
+ return { data, total };
+ }
+
+ const maps = countSpecs.map((spec, index) => ({
+ key: spec.key,
+ counts: new Map(
+ (groups[index] ?? []).map((row: any) => [row[fkField], row._count.id])
+ ),
+ }));
+
+ const dataWithCounts = (data as any[]).map((entity) => ({
+ ...entity,
+ _count: {
+ ...(entity._count ?? {}),
+ ...Object.fromEntries(
+ maps.map(({ key, counts }) => [key, counts.get(entity.id) ?? 0])
+ ),
+ },
+ }));
+
+ return { data: dataWithCounts, total };
+};