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.
TypeScript ai-agentai-resume-analyzerapplication-trackerapplication-tracking-systematscareerjob-applicationjob-automationjob-huntingjob-searchjob-seeker-toolsjob-trackerjob-trackingjobsearchjobseekersmcpollamaresumeresume-reviewself-hosted
feat(company): add the watch server actions, barrel re-exports and their spec
Khuram Niazc04e0b9546ed
diff --git a/__tests__/company.watch.spec.ts b/__tests__/company.watch.spec.tsnew file mode 100644index 0000000..642eae3--- /dev/null+++ b/__tests__/company.watch.spec.ts@@ -0,0 +1,260 @@+import {+ getWatchedBoards,+ setCompanyWatched,+ watchBoardCompany,+} from "@/actions/company.actions";+import { getCurrentUser } from "@/utils/user.utils";+import { PrismaClient } from "@prisma/client";++const prisma = new PrismaClient();++vi.mock("@prisma/client", () => {+ const mPrismaClient = {+ company: {+ findFirst: vi.fn(),+ findMany: vi.fn(),+ create: vi.fn(),+ update: vi.fn(),+ },+ };+ return {+ PrismaClient: vi.fn(function () {+ return mPrismaClient;+ }),+ };+});++vi.mock("@/utils/user.utils", () => ({ getCurrentUser: vi.fn() }));++describe("watchBoardCompany", () => {+ const mockUser = { id: "user-id" };+ const board = { name: "Acme Inc.", token: "acme" };++ beforeEach(() => {+ vi.clearAllMocks();+ (getCurrentUser as any).mockResolvedValue(mockUser);+ });++ it("creates a watched company when no row matches", async () => {+ (prisma.company.findFirst as any).mockResolvedValue(null);+ (prisma.company.create as any).mockResolvedValue({ id: "new-id" });++ const res = await watchBoardCompany("greenhouse", board);++ expect(res).toEqual({+ success: true,+ data: { companyId: "new-id", merged: false },+ });+ expect(prisma.company.create).toHaveBeenCalledWith({+ data: expect.objectContaining({+ createdBy: mockUser.id,+ label: "Acme Inc.",+ value: "acme",+ watched: true,+ atsProvider: "greenhouse",+ atsToken: "acme",+ atsHost: null,+ }),+ });+ });++ it("is idempotent when the same board is already watched", async () => {+ (prisma.company.findFirst as any).mockResolvedValueOnce({+ id: "existing-id",+ label: "Acme Inc.",+ atsToken: "acme",+ });+ (prisma.company.update as any).mockResolvedValue({ id: "existing-id" });++ const res = await watchBoardCompany("greenhouse", board);++ expect(res).toEqual({+ success: true,+ data: { companyId: "existing-id", merged: false },+ });+ expect(prisma.company.create).not.toHaveBeenCalled();+ });++ it("asks for confirmation before merging onto a namesake with no board", async () => {+ (prisma.company.findFirst as any)+ .mockResolvedValueOnce(null)+ .mockResolvedValueOnce({ id: "acme-id", label: "Acme", atsToken: null });++ const res = await watchBoardCompany("greenhouse", board);++ expect(res).toEqual({+ success: false,+ needsConfirm: true,+ existing: { id: "acme-id", label: "Acme" },+ });+ expect(prisma.company.update).not.toHaveBeenCalled();+ expect(prisma.company.create).not.toHaveBeenCalled();+ });++ it("merges onto the namesake when confirmMerge is set", async () => {+ (prisma.company.findFirst as any)+ .mockResolvedValueOnce(null)+ .mockResolvedValueOnce({ id: "acme-id", label: "Acme", atsToken: null });+ (prisma.company.update as any).mockResolvedValue({ id: "acme-id" });++ const res = await watchBoardCompany("greenhouse", board, {+ confirmMerge: true,+ });++ expect(res).toEqual({+ success: true,+ data: { companyId: "acme-id", merged: true },+ });+ });++ it("rejects a second board for an already-linked company", async () => {+ (prisma.company.findFirst as any)+ .mockResolvedValueOnce(null)+ .mockResolvedValueOnce({+ id: "acme-id",+ label: "Acme",+ atsProvider: "lever",+ atsToken: "acme-lever",+ });++ const res = await watchBoardCompany("greenhouse", board);++ expect(res.success).toBe(false);+ expect((res as any).message).toContain("Acme");+ expect((res as any).message).toContain("lever");+ expect((res as any).needsConfirm).toBeUndefined();+ });++ it("resolves successfully when a concurrent writer wins the create", async () => {+ const p2002 = Object.assign(new Error("Unique constraint failed"), {+ code: "P2002",+ });+ (prisma.company.findFirst as any)+ .mockResolvedValueOnce(null) // step 2: by (provider, token)+ .mockResolvedValueOnce(null) // step 3: by value+ .mockResolvedValueOnce({ id: "raced-id", label: "Acme Inc." }); // retry+ (prisma.company.create as any).mockRejectedValue(p2002);+ (prisma.company.update as any).mockResolvedValue({ id: "raced-id" });++ const res = await watchBoardCompany("greenhouse", board);++ expect(res).toEqual({+ success: true,+ data: { companyId: "raced-id", merged: false },+ });+ });++ it("writes atsHost only for Lever", async () => {+ (prisma.company.findFirst as any).mockResolvedValue(null);+ (prisma.company.create as any).mockResolvedValue({ id: "id" });++ await watchBoardCompany("lever", { ...board, host: "eu" });+ expect(prisma.company.create).toHaveBeenCalledWith({+ data: expect.objectContaining({ atsProvider: "lever", atsHost: "eu" }),+ });++ vi.clearAllMocks();+ (getCurrentUser as any).mockResolvedValue(mockUser);+ (prisma.company.findFirst as any).mockResolvedValue(null);+ (prisma.company.create as any).mockResolvedValue({ id: "id" });++ await watchBoardCompany("lever", board);+ expect(prisma.company.create).toHaveBeenCalledWith({+ data: expect.objectContaining({ atsHost: "default" }),+ });+ });++ it("returns Not authenticated with no user", async () => {+ (getCurrentUser as any).mockResolvedValue(null);+ await expect(watchBoardCompany("greenhouse", board)).resolves.toEqual({+ success: false,+ message: "Not authenticated",+ });+ });+});++describe("setCompanyWatched", () => {+ const mockUser = { id: "user-id" };++ beforeEach(() => {+ vi.clearAllMocks();+ (getCurrentUser as any).mockResolvedValue(mockUser);+ });++ it("scopes the update by owner and does not clear board coordinates", async () => {+ (prisma.company.update as any).mockResolvedValue({ id: "c1" });++ const res = await setCompanyWatched("c1", false);++ expect(res.success).toBe(true);+ expect(prisma.company.update).toHaveBeenCalledWith({+ where: { id: "c1", createdBy: mockUser.id },+ data: { watched: false, watchedAt: null },+ });+ });++ it("stamps watchedAt when watching", async () => {+ (prisma.company.update as any).mockResolvedValue({ id: "c1" });++ await setCompanyWatched("c1", true);++ const args = (prisma.company.update as any).mock.calls[0][0];+ expect(args.data.watched).toBe(true);+ expect(args.data.watchedAt).toBeInstanceOf(Date);+ });+});++describe("getWatchedBoards", () => {+ const mockUser = { id: "user-id" };++ beforeEach(() => {+ vi.clearAllMocks();+ (getCurrentUser as any).mockResolvedValue(mockUser);+ });++ it("filters to watched board-backed rows for one provider", async () => {+ (prisma.company.findMany as any).mockResolvedValue([+ {+ id: "c1",+ label: "Acme",+ atsToken: "acme",+ atsHost: null,+ atsProvider: "greenhouse",+ },+ ]);++ const res = await getWatchedBoards("greenhouse");++ expect(prisma.company.findMany).toHaveBeenCalledWith({+ where: {+ createdBy: mockUser.id,+ watched: true,+ atsToken: { not: null },+ atsProvider: "greenhouse",+ },+ select: {+ id: true,+ label: true,+ atsToken: true,+ atsHost: true,+ atsProvider: true,+ },+ orderBy: { label: "asc" },+ });+ expect(res).toEqual([+ { id: "c1", name: "Acme", token: "acme", provider: "greenhouse" },+ ]);+ });++ it("omits the provider filter when none is given", async () => {+ (prisma.company.findMany as any).mockResolvedValue([]);+ await getWatchedBoards();+ const args = (prisma.company.findMany as any).mock.calls[0][0];+ expect(args.where.atsProvider).toBeUndefined();+ });++ it("returns an empty array with no user", async () => {+ (getCurrentUser as any).mockResolvedValue(null);+ await expect(getWatchedBoards()).resolves.toEqual([]);+ });+});diff --git a/src/actions/company.actions.ts b/src/actions/company.actions.tsindex 28dc4d5..34b31a5 100644--- a/src/actions/company.actions.ts+++ b/src/actions/company.actions.ts@@ -13,3 +13,9 @@ export {updateCompany,deleteCompanyById,} from "./company/mutations";++export {+ watchBoardCompany,+ setCompanyWatched,+ getWatchedBoards,+} from "./company/watch";diff --git a/src/actions/company/watch.ts b/src/actions/company/watch.tsnew file mode 100644index 0000000..ec7ba5c--- /dev/null+++ b/src/actions/company/watch.ts@@ -0,0 +1,201 @@+"use server";+import prisma from "@/lib/db";+import { handleError } from "@/lib/utils";+import { canonicalizeEntityValue } from "@/lib/jobs/canonicalize";+import type { JobBoard, LeverHost } from "@/models/automation.model";+import type { Company } from "@/models/job.model";+import { requireUser } from "../shared";++export type WatchBoardResult =+ | { success: true; data: { companyId: string; merged: boolean } }+ | {+ success: false;+ needsConfirm: true;+ existing: { id: string; label: string };+ }+ | { success: false; message: string };++export type WatchedBoard = {+ id: string;+ name: string;+ token: string;+ host?: LeverHost;+ provider: JobBoard;+};++const WATCHED_BOARD_SELECT = {+ id: true,+ label: true,+ atsToken: true,+ atsHost: true,+ atsProvider: true,+} as const;++// Watches a board from the seed directory. Makes no network call: the name,+// token and host all arrive from JSON the browse view already loaded.+export const watchBoardCompany = async (+ provider: JobBoard,+ board: { name: string; token: string; host?: LeverHost },+ opts?: { confirmMerge?: boolean },+): Promise<WatchBoardResult> => {+ try {+ const user = await requireUser();++ const value = canonicalizeEntityValue(board.name.trim(), {+ stripLegalSuffix: true,+ });+ const atsHost = provider === "lever" ? (board.host ?? "default") : null;+ const coords = {+ atsProvider: provider,+ atsToken: board.token,+ atsHost,+ };++ const markWatched = async (id: string, withCoords: boolean) => {+ await prisma.company.update({+ where: { id, createdBy: user.id },+ data: {+ watched: true,+ watchedAt: new Date(),+ ...(withCoords ? coords : {}),+ },+ });+ };++ const byToken = await prisma.company.findFirst({+ where: {+ createdBy: user.id,+ atsProvider: provider,+ atsToken: board.token,+ },+ });+ if (byToken) {+ await markWatched(byToken.id, false);+ return { success: true, data: { companyId: byToken.id, merged: false } };+ }++ const byValue = await prisma.company.findFirst({+ where: { value, createdBy: user.id },+ });++ if (byValue) {+ if (byValue.atsToken) {+ return {+ success: false,+ message: `${byValue.label} is already linked to its ${byValue.atsProvider} board. A company can hold one board.`,+ };+ }+ if (!opts?.confirmMerge) {+ return {+ success: false,+ needsConfirm: true,+ existing: { id: byValue.id, label: byValue.label },+ };+ }+ await markWatched(byValue.id, true);+ return { success: true, data: { companyId: byValue.id, merged: true } };+ }++ try {+ const created = await prisma.company.create({+ data: {+ createdBy: user.id,+ value,+ label: board.name,+ watched: true,+ watchedAt: new Date(),+ ...coords,+ },+ });+ return { success: true, data: { companyId: created.id, merged: false } };+ } catch (error) {+ // Steps above are check-then-act, so a second tab can reach this create+ // after winning the race. Re-run both lookups rather than reading+ // error.meta.target, whose shape differs between SQLite and Postgres.+ if ((error as { code?: string }).code !== "P2002") throw error;++ const raced = await prisma.company.findFirst({+ where: {+ createdBy: user.id,+ atsProvider: provider,+ atsToken: board.token,+ },+ });+ if (raced) {+ await markWatched(raced.id, false);+ return { success: true, data: { companyId: raced.id, merged: false } };+ }++ const namesake = await prisma.company.findFirst({+ where: { value, createdBy: user.id },+ });+ if (namesake && !namesake.atsToken) {+ if (!opts?.confirmMerge) {+ return {+ success: false,+ needsConfirm: true,+ existing: { id: namesake.id, label: namesake.label },+ };+ }+ await markWatched(namesake.id, true);+ return {+ success: true,+ data: { companyId: namesake.id, merged: true },+ };+ }+ throw error;+ }+ } catch (error) {+ const msg = "Failed to watch company.";+ return handleError(error, msg) as WatchBoardResult;+ }+};++// Toggles watch intent only. Board coordinates stay true after unwatching, so+// re-watching is one click; removing the row entirely is deleteCompanyById.+export const setCompanyWatched = async (+ companyId: string,+ watched: boolean,+): Promise<{ success: boolean; message?: string; data?: Company }> => {+ try {+ const user = await requireUser();++ const res = await prisma.company.update({+ where: { id: companyId, createdBy: user.id },+ data: { watched, watchedAt: watched ? new Date() : null },+ });+ return { success: true, data: res as unknown as Company };+ } catch (error) {+ const msg = "Failed to update watch status.";+ return handleError(error, msg);+ }+};++export const getWatchedBoards = async (+ provider?: JobBoard,+): Promise<WatchedBoard[]> => {+ try {+ const user = await requireUser();++ const rows = await prisma.company.findMany({+ where: {+ createdBy: user.id,+ watched: true,+ atsToken: { not: null },+ ...(provider ? { atsProvider: provider } : {}),+ },+ select: WATCHED_BOARD_SELECT,+ orderBy: { label: "asc" },+ });++ return rows.map((row) => ({+ id: row.id,+ name: row.label,+ token: row.atsToken as string,+ provider: row.atsProvider as JobBoard,+ ...(row.atsHost ? { host: row.atsHost as LeverHost } : {}),+ }));+ } catch {+ return [];+ }+};