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
add job search automation
Khuram Niaz677c465ffeae
diff --git a/.env.example b/.env.exampleindex 19dd7cf..589bd1a 100644--- a/.env.example+++ b/.env.example@@ -25,3 +25,5 @@ OLLAMA_BASE_URL=http://host.docker.internal:11434# AI Configuration# The system uses LLM-based semantic extraction for intelligent, context-aware skill matching# No configuration needed - semantic extraction is the default++RAPIDAPI_KEY=your-rapidapi-key-herediff --git a/package-lock.json b/package-lock.jsonindex 87c459b..7c88263 100644--- a/package-lock.json+++ b/package-lock.json@@ -48,6 +48,7 @@"next": "15.5.10","next-auth": "^5.0.0-beta.25","next-themes": "^0.4.4",+ "node-cron": "^4.2.1","ollama-ai-provider-v2": "^2.0.0","papaparse": "^5.4.1","react": "19.2.4",@@ -68,6 +69,7 @@"@types/bcrypt": "^5.0.2","@types/jest": "^30.0.0","@types/node": "^22.10.2",+ "@types/node-cron": "^3.0.11","@types/papaparse": "^5.3.15","@types/react": "19.2.10","@types/react-dom": "19.2.3",@@ -5017,6 +5019,13 @@"undici-types": "~6.21.0"}},+ "node_modules/@types/node-cron": {+ "version": "3.0.11",+ "resolved": "https://registry.npmjs.org/@types/node-cron/-/node-cron-3.0.11.tgz",+ "integrity": "sha512-0ikrnug3/IyneSHqCBeslAhlK2aBfYek1fGo4bP4QnZPmiqSGRK+Oy7ZMisLWkesffJvQ1cqAcBnJC+8+nxIAg==",+ "dev": true,+ "license": "MIT"+ },"node_modules/@types/papaparse": {"version": "5.5.1","resolved": "https://registry.npmjs.org/@types/papaparse/-/papaparse-5.5.1.tgz",@@ -10810,6 +10819,15 @@"node": "^10 || ^12 || >=14"}},+ "node_modules/node-cron": {+ "version": "4.2.1",+ "resolved": "https://registry.npmjs.org/node-cron/-/node-cron-4.2.1.tgz",+ "integrity": "sha512-lgimEHPE/QDgFlywTd8yTR61ptugX3Qer29efeyWw2rv259HtGBNn1vZVmp8lB9uo9wC0t/AT4iGqXxia+CJFg==",+ "license": "ISC",+ "engines": {+ "node": ">=6.0.0"+ }+ },"node_modules/node-fetch-native": {"version": "1.6.7","resolved": "https://registry.npmjs.org/node-fetch-native/-/node-fetch-native-1.6.7.tgz",diff --git a/package.json b/package.jsonindex 1d0856f..c14b0ad 100644--- a/package.json+++ b/package.json@@ -53,6 +53,7 @@"next": "15.5.10","next-auth": "^5.0.0-beta.25","next-themes": "^0.4.4",+ "node-cron": "^4.2.1","ollama-ai-provider-v2": "^2.0.0","papaparse": "^5.4.1","react": "19.2.4",@@ -73,6 +74,7 @@"@types/bcrypt": "^5.0.2","@types/jest": "^30.0.0","@types/node": "^22.10.2",+ "@types/node-cron": "^3.0.11","@types/papaparse": "^5.3.15","@types/react": "19.2.10","@types/react-dom": "19.2.3",diff --git a/prisma/migrations/20260130042742_add_automations/migration.sql b/prisma/migrations/20260130042742_add_automations/migration.sqlnew file mode 100644index 0000000..68fbc1c--- /dev/null+++ b/prisma/migrations/20260130042742_add_automations/migration.sql@@ -0,0 +1,90 @@+-- CreateTable+CREATE TABLE "Automation" (+ "id" TEXT NOT NULL PRIMARY KEY,+ "userId" TEXT NOT NULL,+ "name" TEXT NOT NULL,+ "jobBoard" TEXT NOT NULL,+ "keywords" TEXT NOT NULL,+ "location" TEXT NOT NULL,+ "resumeId" TEXT NOT NULL,+ "matchThreshold" INTEGER NOT NULL DEFAULT 80,+ "scheduleHour" INTEGER NOT NULL,+ "nextRunAt" DATETIME,+ "lastRunAt" DATETIME,+ "status" TEXT NOT NULL DEFAULT 'active',+ "createdAt" DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,+ "updatedAt" DATETIME NOT NULL,+ CONSTRAINT "Automation_userId_fkey" FOREIGN KEY ("userId") REFERENCES "User" ("id") ON DELETE RESTRICT ON UPDATE CASCADE,+ CONSTRAINT "Automation_resumeId_fkey" FOREIGN KEY ("resumeId") REFERENCES "Resume" ("id") ON DELETE RESTRICT ON UPDATE CASCADE+);++-- CreateTable+CREATE TABLE "AutomationRun" (+ "id" TEXT NOT NULL PRIMARY KEY,+ "automationId" TEXT NOT NULL,+ "jobsSearched" INTEGER NOT NULL DEFAULT 0,+ "jobsDeduplicated" INTEGER NOT NULL DEFAULT 0,+ "jobsProcessed" INTEGER NOT NULL DEFAULT 0,+ "jobsMatched" INTEGER NOT NULL DEFAULT 0,+ "jobsSaved" INTEGER NOT NULL DEFAULT 0,+ "status" TEXT NOT NULL DEFAULT 'running',+ "errorMessage" TEXT,+ "blockedReason" TEXT,+ "startedAt" DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,+ "completedAt" DATETIME,+ CONSTRAINT "AutomationRun_automationId_fkey" FOREIGN KEY ("automationId") REFERENCES "Automation" ("id") ON DELETE CASCADE ON UPDATE CASCADE+);++-- RedefineTables+PRAGMA defer_foreign_keys=ON;+PRAGMA foreign_keys=OFF;+CREATE TABLE "new_Job" (+ "id" TEXT NOT NULL PRIMARY KEY,+ "userId" TEXT NOT NULL,+ "jobUrl" TEXT,+ "description" TEXT NOT NULL,+ "jobType" TEXT NOT NULL,+ "createdAt" DATETIME NOT NULL,+ "applied" BOOLEAN NOT NULL DEFAULT false,+ "appliedDate" DATETIME,+ "dueDate" DATETIME,+ "statusId" TEXT NOT NULL,+ "jobTitleId" TEXT NOT NULL,+ "companyId" TEXT NOT NULL,+ "jobSourceId" TEXT,+ "salaryRange" TEXT,+ "locationId" TEXT,+ "resumeId" TEXT,+ "automationId" TEXT,+ "matchScore" INTEGER,+ "matchData" TEXT,+ "discoveryStatus" TEXT,+ "discoveredAt" DATETIME,+ CONSTRAINT "Job_userId_fkey" FOREIGN KEY ("userId") REFERENCES "User" ("id") ON DELETE RESTRICT ON UPDATE CASCADE,+ CONSTRAINT "Job_statusId_fkey" FOREIGN KEY ("statusId") REFERENCES "JobStatus" ("id") ON DELETE RESTRICT ON UPDATE CASCADE,+ CONSTRAINT "Job_jobTitleId_fkey" FOREIGN KEY ("jobTitleId") REFERENCES "JobTitle" ("id") ON DELETE RESTRICT ON UPDATE CASCADE,+ CONSTRAINT "Job_companyId_fkey" FOREIGN KEY ("companyId") REFERENCES "Company" ("id") ON DELETE RESTRICT ON UPDATE CASCADE,+ CONSTRAINT "Job_jobSourceId_fkey" FOREIGN KEY ("jobSourceId") REFERENCES "JobSource" ("id") ON DELETE SET NULL ON UPDATE CASCADE,+ CONSTRAINT "Job_locationId_fkey" FOREIGN KEY ("locationId") REFERENCES "Location" ("id") ON DELETE SET NULL ON UPDATE CASCADE,+ CONSTRAINT "Job_resumeId_fkey" FOREIGN KEY ("resumeId") REFERENCES "Resume" ("id") ON DELETE SET NULL ON UPDATE CASCADE,+ CONSTRAINT "Job_automationId_fkey" FOREIGN KEY ("automationId") REFERENCES "Automation" ("id") ON DELETE SET NULL ON UPDATE CASCADE+);+INSERT INTO "new_Job" ("applied", "appliedDate", "companyId", "createdAt", "description", "dueDate", "id", "jobSourceId", "jobTitleId", "jobType", "jobUrl", "locationId", "resumeId", "salaryRange", "statusId", "userId") SELECT "applied", "appliedDate", "companyId", "createdAt", "description", "dueDate", "id", "jobSourceId", "jobTitleId", "jobType", "jobUrl", "locationId", "resumeId", "salaryRange", "statusId", "userId" FROM "Job";+DROP TABLE "Job";+ALTER TABLE "new_Job" RENAME TO "Job";+CREATE INDEX "Job_userId_automationId_idx" ON "Job"("userId", "automationId");+CREATE INDEX "Job_userId_discoveryStatus_idx" ON "Job"("userId", "discoveryStatus");+PRAGMA foreign_keys=ON;+PRAGMA defer_foreign_keys=OFF;++-- CreateIndex+CREATE INDEX "Automation_userId_idx" ON "Automation"("userId");++-- CreateIndex+CREATE INDEX "Automation_status_nextRunAt_idx" ON "Automation"("status", "nextRunAt");++-- CreateIndex+CREATE INDEX "AutomationRun_automationId_idx" ON "AutomationRun"("automationId");++-- CreateIndex+CREATE INDEX "AutomationRun_startedAt_idx" ON "AutomationRun"("startedAt");diff --git a/prisma/schema.prisma b/prisma/schema.prismaindex 69d6f17..ede617b 100644--- a/prisma/schema.prisma+++ b/prisma/schema.prisma@@ -27,6 +27,7 @@ model User {Activity Activity[]ActivityType ActivityType[]Task Task[]+ Automation Automation[]}model Profile {@@ -48,6 +49,7 @@ model Resume {File File? @relation(fields: [FileId], references: [id])FileId String? @uniqueJob Job[]+ Automation Automation[]}model File {@@ -241,6 +243,17 @@ model Job {Interview Interview[]Resume Resume? @relation(fields: [resumeId], references: [id])resumeId String?++ // Automation discovery fields+ automationId String?+ automation Automation? @relation(fields: [automationId], references: [id], onDelete: SetNull)+ matchScore Int?+ matchData String?+ discoveryStatus String?+ discoveredAt DateTime?++ @@index([userId, automationId])+ @@index([userId, discoveryStatus])}model ActivityType {@@ -301,3 +314,54 @@ model Task {@@index([userId, activityTypeId])@@index([userId, dueDate])}++model Automation {+ id String @id @default(uuid())+ userId String+ user User @relation(fields: [userId], references: [id])++ name String+ jobBoard String+ keywords String+ location String+ resumeId String+ resume Resume @relation(fields: [resumeId], references: [id])+ matchThreshold Int @default(80)++ scheduleHour Int+ nextRunAt DateTime?+ lastRunAt DateTime?++ status String @default("active")++ createdAt DateTime @default(now())+ updatedAt DateTime @updatedAt++ runs AutomationRun[]+ discoveredJobs Job[]++ @@index([userId])+ @@index([status, nextRunAt])+}++model AutomationRun {+ id String @id @default(uuid())+ automationId String+ automation Automation @relation(fields: [automationId], references: [id], onDelete: Cascade)++ jobsSearched Int @default(0)+ jobsDeduplicated Int @default(0)+ jobsProcessed Int @default(0)+ jobsMatched Int @default(0)+ jobsSaved Int @default(0)++ status String @default("running")+ errorMessage String?+ blockedReason String?++ startedAt DateTime @default(now())+ completedAt DateTime?++ @@index([automationId])+ @@index([startedAt])+}diff --git a/src/actions/automation.actions.ts b/src/actions/automation.actions.tsnew file mode 100644index 0000000..43b0975--- /dev/null+++ b/src/actions/automation.actions.ts@@ -0,0 +1,602 @@+"use server";++import db from "@/lib/db";+import { getCurrentUser } from "@/utils/user.utils";+import { calculateNextRunAt } from "@/lib/scraper/schedule";+import {+ CreateAutomationSchema,+ UpdateAutomationSchema,+ type CreateAutomationInput,+ type UpdateAutomationInput,+} from "@/models/automation.schema";+import type {+ AutomationWithResume,+ AutomationRun,+ DiscoveredJob,+ DiscoveryStatus,+} from "@/models/automation.model";+import { APP_CONSTANTS } from "@/lib/constants";++const MAX_AUTOMATIONS_PER_USER = 10;++function formatError(error: unknown, fallback: string): { success: false; message: string } {+ console.error(error, fallback);+ if (error instanceof Error) {+ return { success: false, message: error.message || fallback };+ }+ return { success: false, message: fallback };+}++export async function getAutomationsList(+ page: number = 1,+ limit: number = APP_CONSTANTS.RECORDS_PER_PAGE+): Promise<{+ success: boolean;+ data?: AutomationWithResume[];+ total?: number;+ message?: string;+}> {+ try {+ const user = await getCurrentUser();+ if (!user) {+ return { success: false, message: "Not authenticated" };+ }++ const skip = (page - 1) * limit;++ const [automations, total] = await Promise.all([+ db.automation.findMany({+ where: { userId: user.id },+ skip,+ take: limit,+ orderBy: { createdAt: "desc" },+ include: {+ resume: {+ select: { id: true, title: true },+ },+ },+ }),+ db.automation.count({ where: { userId: user.id } }),+ ]);++ return {+ success: true,+ data: automations as unknown as AutomationWithResume[],+ total,+ };+ } catch (error) {+ return formatError(error, "Failed to get automations list");+ }+}++export async function getAutomationById(id: string): Promise<{+ success: boolean;+ data?: AutomationWithResume & { runs: AutomationRun[] };+ message?: string;+}> {+ try {+ const user = await getCurrentUser();+ if (!user) {+ return { success: false, message: "Not authenticated" };+ }++ const automation = await db.automation.findFirst({+ where: { id, userId: user.id },+ include: {+ resume: {+ select: { id: true, title: true },+ },+ runs: {+ orderBy: { startedAt: "desc" },+ take: 10,+ },+ },+ });++ if (!automation) {+ return { success: false, message: "Automation not found" };+ }++ return {+ success: true,+ data: automation as unknown as AutomationWithResume & { runs: AutomationRun[] },+ };+ } catch (error) {+ return formatError(error, "Failed to get automation");+ }+}++export async function createAutomation(+ input: CreateAutomationInput+): Promise<{+ success: boolean;+ data?: AutomationWithResume;+ message?: string;+}> {+ try {+ const user = await getCurrentUser();+ if (!user) {+ return { success: false, message: "Not authenticated" };+ }++ const validated = CreateAutomationSchema.parse(input);++ const count = await db.automation.count({ where: { userId: user.id } });+ if (count >= MAX_AUTOMATIONS_PER_USER) {+ return { success: false, message: `Maximum of ${MAX_AUTOMATIONS_PER_USER} automations allowed per user` };+ }++ const resume = await db.resume.findFirst({+ where: {+ id: validated.resumeId,+ profile: { userId: user.id },+ },+ });++ if (!resume) {+ return { success: false, message: "Resume not found or doesn't belong to you" };+ }++ const nextRunAt = calculateNextRunAt(validated.scheduleHour);++ const automation = await db.automation.create({+ data: {+ userId: user.id,+ name: validated.name,+ jobBoard: validated.jobBoard,+ keywords: validated.keywords,+ location: validated.location,+ resumeId: validated.resumeId,+ matchThreshold: validated.matchThreshold,+ scheduleHour: validated.scheduleHour,+ nextRunAt,+ status: "active",+ },+ include: {+ resume: {+ select: { id: true, title: true },+ },+ },+ });++ return {+ success: true,+ data: automation as unknown as AutomationWithResume,+ };+ } catch (error) {+ return formatError(error, "Failed to create automation");+ }+}++export async function updateAutomation(+ id: string,+ input: UpdateAutomationInput+): Promise<{+ success: boolean;+ data?: AutomationWithResume;+ message?: string;+}> {+ try {+ const user = await getCurrentUser();+ if (!user) {+ return { success: false, message: "Not authenticated" };+ }++ const validated = UpdateAutomationSchema.parse(input);++ const existing = await db.automation.findFirst({+ where: { id, userId: user.id },+ });++ if (!existing) {+ return { success: false, message: "Automation not found" };+ }++ if (validated.resumeId) {+ const resume = await db.resume.findFirst({+ where: {+ id: validated.resumeId,+ profile: { userId: user.id },+ },+ });+ if (!resume) {+ return { success: false, message: "Resume not found or doesn't belong to you" };+ }+ }++ const updateData: Record<string, unknown> = { ...validated };++ if (validated.scheduleHour !== undefined) {+ updateData.nextRunAt = calculateNextRunAt(validated.scheduleHour);+ }++ const automation = await db.automation.update({+ where: { id },+ data: updateData,+ include: {+ resume: {+ select: { id: true, title: true },+ },+ },+ });++ return {+ success: true,+ data: automation as unknown as AutomationWithResume,+ };+ } catch (error) {+ return formatError(error, "Failed to update automation");+ }+}++export async function deleteAutomation(id: string): Promise<{+ success: boolean;+ message?: string;+}> {+ try {+ const user = await getCurrentUser();+ if (!user) {+ return { success: false, message: "Not authenticated" };+ }++ const automation = await db.automation.findFirst({+ where: { id, userId: user.id },+ });++ if (!automation) {+ return { success: false, message: "Automation not found" };+ }++ await db.automation.delete({ where: { id } });++ return { success: true };+ } catch (error) {+ return formatError(error, "Failed to delete automation");+ }+}++export async function pauseAutomation(id: string): Promise<{+ success: boolean;+ data?: AutomationWithResume;+ message?: string;+}> {+ try {+ const user = await getCurrentUser();+ if (!user) {+ return { success: false, message: "Not authenticated" };+ }++ const automation = await db.automation.findFirst({+ where: { id, userId: user.id },+ });++ if (!automation) {+ return { success: false, message: "Automation not found" };+ }++ const updated = await db.automation.update({+ where: { id },+ data: {+ status: "paused",+ nextRunAt: null,+ },+ include: {+ resume: {+ select: { id: true, title: true },+ },+ },+ });++ return {+ success: true,+ data: updated as unknown as AutomationWithResume,+ };+ } catch (error) {+ return formatError(error, "Failed to pause automation");+ }+}++export async function resumeAutomation(id: string): Promise<{+ success: boolean;+ data?: AutomationWithResume;+ message?: string;+}> {+ try {+ const user = await getCurrentUser();+ if (!user) {+ return { success: false, message: "Not authenticated" };+ }++ const automation = await db.automation.findFirst({+ where: { id, userId: user.id },+ });++ if (!automation) {+ return { success: false, message: "Automation not found" };+ }++ const nextRunAt = calculateNextRunAt(automation.scheduleHour);++ const updated = await db.automation.update({+ where: { id },+ data: {+ status: "active",+ nextRunAt,+ },+ include: {+ resume: {+ select: { id: true, title: true },+ },+ },+ });++ return {+ success: true,+ data: updated as unknown as AutomationWithResume,+ };+ } catch (error) {+ return formatError(error, "Failed to resume automation");+ }+}++export async function getDiscoveredJobs(options?: {+ automationId?: string;+ discoveryStatus?: DiscoveryStatus;+ page?: number;+ limit?: number;+ sortBy?: "matchScore" | "discoveredAt";+ sortOrder?: "asc" | "desc";+}): Promise<{+ success: boolean;+ data?: DiscoveredJob[];+ total?: number;+ message?: string;+}> {+ try {+ const user = await getCurrentUser();+ if (!user) {+ return { success: false, message: "Not authenticated" };+ }++ const {+ automationId,+ discoveryStatus,+ page = 1,+ limit = APP_CONSTANTS.RECORDS_PER_PAGE,+ sortBy = "matchScore",+ sortOrder = "desc",+ } = options || {};++ const skip = (page - 1) * limit;++ const where: Record<string, unknown> = {+ userId: user.id,+ automationId: { not: null },+ };++ if (automationId) {+ where.automationId = automationId;+ }++ if (discoveryStatus) {+ where.discoveryStatus = discoveryStatus;+ }++ const [jobs, total] = await Promise.all([+ db.job.findMany({+ where,+ skip,+ take: limit,+ orderBy: { [sortBy]: sortOrder },+ include: {+ automation: {+ select: { id: true, name: true },+ },+ JobTitle: { select: { label: true } },+ Company: { select: { label: true } },+ Location: { select: { label: true } },+ },+ }),+ db.job.count({ where }),+ ]);++ return {+ success: true,+ data: jobs as unknown as DiscoveredJob[],+ total,+ };+ } catch (error) {+ return formatError(error, "Failed to get discovered jobs");+ }+}++export async function getDiscoveredJobById(id: string): Promise<{+ success: boolean;+ data?: DiscoveredJob & { parsedMatchData: object | null };+ message?: string;+}> {+ try {+ const user = await getCurrentUser();+ if (!user) {+ return { success: false, message: "Not authenticated" };+ }++ const job = await db.job.findFirst({+ where: {+ id,+ userId: user.id,+ automationId: { not: null },+ },+ include: {+ automation: {+ select: { id: true, name: true },+ },+ JobTitle: { select: { label: true } },+ Company: { select: { label: true } },+ Location: { select: { label: true } },+ },+ });++ if (!job) {+ return { success: false, message: "Discovered job not found" };+ }++ let parsedMatchData = null;+ if (job.matchData) {+ try {+ parsedMatchData = JSON.parse(job.matchData);+ } catch {+ // Ignore parse errors+ }+ }++ return {+ success: true,+ data: {+ ...(job as unknown as DiscoveredJob),+ parsedMatchData,+ },+ };+ } catch (error) {+ return formatError(error, "Failed to get discovered job");+ }+}++export async function dismissDiscoveredJob(id: string): Promise<{+ success: boolean;+ data?: DiscoveredJob;+ message?: string;+}> {+ try {+ const user = await getCurrentUser();+ if (!user) {+ return { success: false, message: "Not authenticated" };+ }++ const job = await db.job.findFirst({+ where: {+ id,+ userId: user.id,+ automationId: { not: null },+ },+ });++ if (!job) {+ return { success: false, message: "Discovered job not found" };+ }++ const updated = await db.job.update({+ where: { id },+ data: { discoveryStatus: "dismissed" },+ include: {+ automation: {+ select: { id: true, name: true },+ },+ JobTitle: { select: { label: true } },+ Company: { select: { label: true } },+ Location: { select: { label: true } },+ },+ });++ return {+ success: true,+ data: updated as unknown as DiscoveredJob,+ };+ } catch (error) {+ return formatError(error, "Failed to dismiss discovered job");+ }+}++export async function acceptDiscoveredJob(id: string): Promise<{+ success: boolean;+ data?: DiscoveredJob;+ message?: string;+}> {+ try {+ const user = await getCurrentUser();+ if (!user) {+ return { success: false, message: "Not authenticated" };+ }++ const job = await db.job.findFirst({+ where: {+ id,+ userId: user.id,+ automationId: { not: null },+ },+ });++ if (!job) {+ return { success: false, message: "Discovered job not found" };+ }++ const updated = await db.job.update({+ where: { id },+ data: { discoveryStatus: "accepted" },+ include: {+ automation: {+ select: { id: true, name: true },+ },+ JobTitle: { select: { label: true } },+ Company: { select: { label: true } },+ Location: { select: { label: true } },+ },+ });++ return {+ success: true,+ data: updated as unknown as DiscoveredJob,+ };+ } catch (error) {+ return formatError(error, "Failed to accept discovered job");+ }+}++export async function getAutomationRuns(+ automationId: string,+ options?: {+ page?: number;+ limit?: number;+ }+): Promise<{+ success: boolean;+ data?: AutomationRun[];+ total?: number;+ message?: string;+}> {+ try {+ const user = await getCurrentUser();+ if (!user) {+ return { success: false, message: "Not authenticated" };+ }++ const { page = 1, limit = 10 } = options || {};+ const skip = (page - 1) * limit;++ const automation = await db.automation.findFirst({+ where: { id: automationId, userId: user.id },+ });++ if (!automation) {+ return { success: false, message: "Automation not found" };+ }++ const [runs, total] = await Promise.all([+ db.automationRun.findMany({+ where: { automationId },+ skip,+ take: limit,+ orderBy: { startedAt: "desc" },+ }),+ db.automationRun.count({ where: { automationId } }),+ ]);++ return {+ success: true,+ data: runs as unknown as AutomationRun[],+ total,+ };+ } catch (error) {+ return formatError(error, "Failed to get automation runs");+ }+}diff --git a/src/app/api/automations/[id]/logs/clear/route.ts b/src/app/api/automations/[id]/logs/clear/route.tsnew file mode 100644index 0000000..4639ca9--- /dev/null+++ b/src/app/api/automations/[id]/logs/clear/route.ts@@ -0,0 +1,33 @@+import { NextRequest, NextResponse } from "next/server";+import { auth } from "@/auth";+import db from "@/lib/db";+import { automationLogger } from "@/lib/automation-logger";++export async function POST(+ req: NextRequest,+ { params }: { params: Promise<{ id: string }> },+) {+ const session = await auth();+ const userId = session?.accessToken?.sub;++ if (!session || !session.user || !userId) {+ return NextResponse.json({ message: "Not Authenticated" }, { status: 401 });+ }++ const { id: automationId } = await params;++ const automation = await db.automation.findFirst({+ where: {+ id: automationId,+ userId,+ },+ });++ if (!automation) {+ return NextResponse.json({ message: "Automation not found" }, { status: 404 });+ }++ automationLogger.clearLogs(automationId);++ return NextResponse.json({ success: true });+}diff --git a/src/app/api/automations/[id]/logs/route.ts b/src/app/api/automations/[id]/logs/route.tsnew file mode 100644index 0000000..9a3db0c--- /dev/null+++ b/src/app/api/automations/[id]/logs/route.ts@@ -0,0 +1,113 @@+import { NextRequest, NextResponse } from "next/server";+import { auth } from "@/auth";+import db from "@/lib/db";+import { automationLogger } from "@/lib/automation-logger";++function createSSEErrorResponse(message: string): NextResponse {+ const encoder = new TextEncoder();+ const errorData = JSON.stringify({ logs: [], isRunning: false, error: message });+ const body = encoder.encode(`data: ${errorData}\n\n`);++ return new NextResponse(body, {+ status: 200,+ headers: {+ "Content-Type": "text/event-stream",+ "Cache-Control": "no-cache",+ Connection: "keep-alive",+ },+ });+}++export async function GET(+ req: NextRequest,+ { params }: { params: Promise<{ id: string }> },+) {+ const session = await auth();+ const userId = session?.accessToken?.sub;++ if (!session || !session.user || !userId) {+ return createSSEErrorResponse("Not Authenticated");+ }++ const { id: automationId } = await params;++ // Verify ownership+ const automation = await db.automation.findFirst({+ where: {+ id: automationId,+ userId,+ },+ });++ if (!automation) {+ return createSSEErrorResponse("Automation not found");+ }++ const encoder = new TextEncoder();++ const stream = new ReadableStream({+ start(controller) {+ let isClosed = false;++ const cleanup = () => {+ if (isClosed) return;+ isClosed = true;+ clearInterval(interval);+ clearTimeout(timeout);+ controller.close();+ };++ // Send initial logs+ const store = automationLogger.getStore(automationId);+ if (store) {+ const initialData = JSON.stringify({+ logs: store.logs,+ isRunning: store.isRunning,+ startedAt: store.startedAt,+ completedAt: store.completedAt,+ });+ controller.enqueue(encoder.encode(`data: ${initialData}\n\n`));+ } else {+ controller.enqueue(+ encoder.encode(+ `data: ${JSON.stringify({ logs: [], isRunning: false })}\n\n`,+ ),+ );+ }++ // Poll for new logs every second+ const interval = setInterval(() => {+ if (isClosed) return;+ const currentStore = automationLogger.getStore(automationId);+ if (currentStore) {+ const data = JSON.stringify({+ logs: currentStore.logs,+ isRunning: currentStore.isRunning,+ startedAt: currentStore.startedAt,+ completedAt: currentStore.completedAt,+ });+ controller.enqueue(encoder.encode(`data: ${data}\n\n`));++ // Stop streaming if run is completed+ if (!currentStore.isRunning && currentStore.completedAt) {+ cleanup();+ }+ }+ }, 1000);++ // Cleanup on client disconnect+ req.signal.addEventListener("abort", cleanup);++ // Auto-close after 10 minutes+ const timeout = setTimeout(cleanup, 10 * 60 * 1000);+ },+ });++ return new NextResponse(stream, {+ headers: {+ "Content-Type": "text/event-stream",+ "Cache-Control": "no-cache",+ Connection: "keep-alive",+ },+ });+}diff --git a/src/app/api/automations/[id]/run/route.ts b/src/app/api/automations/[id]/run/route.tsnew file mode 100644index 0000000..5fea3f2--- /dev/null+++ b/src/app/api/automations/[id]/run/route.ts@@ -0,0 +1,107 @@+import "server-only";++import { NextRequest, NextResponse } from "next/server";+import { auth } from "@/auth";+import db from "@/lib/db";+import { runAutomation, type RunnerResult } from "@/lib/scraper";++const RATE_LIMIT_WINDOW_MS = 60 * 60 * 1000;+const MAX_RUNS_PER_HOUR = 5;++const recentRuns = new Map<string, number[]>();++function checkRateLimit(userId: string): boolean {+ const now = Date.now();+ const userRuns = recentRuns.get(userId) || [];++ const validRuns = userRuns.filter((timestamp) => now - timestamp < RATE_LIMIT_WINDOW_MS);+ recentRuns.set(userId, validRuns);++ if (validRuns.length >= MAX_RUNS_PER_HOUR) {+ return false;+ }++ validRuns.push(now);+ recentRuns.set(userId, validRuns);+ return true;+}++export async function POST(+ req: NextRequest,+ { params }: { params: Promise<{ id: string }> }+) {+ const session = await auth();+ const userId = session?.accessToken?.sub;++ if (!session || !session.user || !userId) {+ return NextResponse.json({ message: "Not Authenticated" }, { status: 401 });+ }++ const { id: automationId } = await params;++ if (!checkRateLimit(userId)) {+ return NextResponse.json(+ { message: `Rate limit exceeded. Maximum ${MAX_RUNS_PER_HOUR} manual runs per hour.` },+ { status: 429 }+ );+ }++ try {+ const automation = await db.automation.findFirst({+ where: {+ id: automationId,+ userId,+ },+ include: {+ resume: true,+ },+ });++ if (!automation) {+ return NextResponse.json({ message: "Automation not found" }, { status: 404 });+ }++ if (!automation.resume) {+ return NextResponse.json(+ { message: "Resume is missing. Please edit the automation and select a resume." },+ { status: 400 }+ );+ }++ const result: RunnerResult = await runAutomation({+ id: automation.id,+ userId: automation.userId,+ name: automation.name,+ jobBoard: automation.jobBoard as "jsearch",+ keywords: automation.keywords,+ location: automation.location,+ resumeId: automation.resumeId,+ matchThreshold: automation.matchThreshold,+ scheduleHour: automation.scheduleHour,+ nextRunAt: automation.nextRunAt,+ lastRunAt: automation.lastRunAt,+ status: automation.status as "active" | "paused",+ createdAt: automation.createdAt,+ updatedAt: automation.updatedAt,+ });++ return NextResponse.json({+ success: true,+ run: {+ id: result.runId,+ status: result.status,+ jobsSearched: result.jobsSearched,+ jobsDeduplicated: result.jobsDeduplicated,+ jobsProcessed: result.jobsProcessed,+ jobsMatched: result.jobsMatched,+ jobsSaved: result.jobsSaved,+ errorMessage: result.errorMessage,+ blockedReason: result.blockedReason,+ },+ });+ } catch (error) {+ console.error("Manual run error:", error);+ const message = error instanceof Error ? error.message : "Run failed";+ return NextResponse.json({ success: false, message }, { status: 500 });+ }+}diff --git a/src/app/dashboard/automations/[id]/page.tsx b/src/app/dashboard/automations/[id]/page.tsxnew file mode 100644index 0000000..d17d147--- /dev/null+++ b/src/app/dashboard/automations/[id]/page.tsx@@ -0,0 +1,362 @@+"use client";++import { useCallback, useEffect, useState } from "react";+import { useParams, useRouter } from "next/navigation";+import Link from "next/link";+import { format } from "date-fns";+import {+ Card,+ CardContent,+ CardDescription,+ CardHeader,+ CardTitle,+} from "@/components/ui/card";+import { Button } from "@/components/ui/button";+import { Badge } from "@/components/ui/badge";+import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";+import { toast } from "@/components/ui/use-toast";+import {+ ArrowLeft,+ Pause,+ Play,+ RefreshCw,+ Loader2,+ Clock,+ FileText,+ AlertTriangle,+ PlayCircle,+} from "lucide-react";+import {+ getAutomationById,+ getDiscoveredJobs,+ getAutomationRuns,+ pauseAutomation,+ resumeAutomation,+ getDiscoveredJobById,+} from "@/actions/automation.actions";+import type {+ AutomationWithResume,+ AutomationRun,+ DiscoveredJob,+} from "@/models/automation.model";+import type { JobMatchResponse } from "@/models/ai.schemas";+import { DiscoveredJobsList } from "@/components/automations/DiscoveredJobsList";+import { DiscoveredJobDetail } from "@/components/automations/DiscoveredJobDetail";+import { RunHistoryList } from "@/components/automations/RunHistoryList";+import { LogsTab } from "@/components/automations/LogsTab";+import Loading from "@/components/Loading";++export default function AutomationDetailPage() {+ const params = useParams();+ const router = useRouter();+ const automationId = params.id as string;++ const [automation, setAutomation] = useState<AutomationWithResume | null>(+ null,+ );+ const [runs, setRuns] = useState<AutomationRun[]>([]);+ const [jobs, setJobs] = useState<DiscoveredJob[]>([]);+ const [loading, setLoading] = useState(true);+ const [actionLoading, setActionLoading] = useState(false);+ const [runNowLoading, setRunNowLoading] = useState(false);+ const [selectedJob, setSelectedJob] = useState<DiscoveredJob | null>(null);+ const [selectedJobMatchData, setSelectedJobMatchData] =+ useState<JobMatchResponse | null>(null);+ const [detailOpen, setDetailOpen] = useState(false);+ const [runKey, setRunKey] = useState(0);++ const loadData = useCallback(async () => {+ setLoading(true);+ try {+ const [automationResult, runsResult, jobsResult] = await Promise.all([+ getAutomationById(automationId),+ getAutomationRuns(automationId),+ getDiscoveredJobs({ automationId }),+ ]);++ if (automationResult.success && automationResult.data) {+ setAutomation(automationResult.data);+ setRuns(automationResult.data.runs || []);+ } else {+ toast({+ title: "Error",+ description: automationResult.message || "Automation not found",+ variant: "destructive",+ });+ router.push("/dashboard/automations");+ return;+ }++ if (runsResult.success && runsResult.data) {+ setRuns(runsResult.data);+ }++ if (jobsResult.success && jobsResult.data) {+ setJobs(jobsResult.data);+ }+ } catch (error) {+ toast({+ title: "Error",+ description: "Failed to load automation details",+ variant: "destructive",+ });+ }+ setLoading(false);+ }, [automationId, router]);++ useEffect(() => {+ loadData();+ }, [loadData]);++ const handlePauseResume = async () => {+ if (!automation) return;++ setActionLoading(true);+ const result =+ automation.status === "active"+ ? await pauseAutomation(automation.id)+ : await resumeAutomation(automation.id);+ setActionLoading(false);++ if (result.success) {+ toast({+ title:+ automation.status === "active"+ ? "Automation paused"+ : "Automation resumed",+ });+ loadData();+ } else {+ toast({+ title: "Error",+ description: result.message,+ variant: "destructive",+ });+ }+ };++ const handleRunNow = async () => {+ if (!automation) return;++ setRunNowLoading(true);+ setRunKey((prev) => prev + 1);+ try {+ const response = await fetch(`/api/automations/${automation.id}/run`, {+ method: "POST",+ });++ const data = await response.json();++ if (response.ok && data.success) {+ toast({+ title: "Automation run started",+ description: `Saved ${data.run.jobsSaved} new jobs`,+ });+ loadData();+ } else {+ toast({+ title: "Error",+ description: data.message || "Failed to run automation",+ variant: "destructive",+ });+ }+ } catch (error) {+ toast({+ title: "Error",+ description: "Failed to run automation",+ variant: "destructive",+ });+ }+ setRunNowLoading(false);+ };++ const handleViewJobDetails = async (job: DiscoveredJob) => {+ const result = await getDiscoveredJobById(job.id);+ if (result.success && result.data) {+ setSelectedJob(result.data);+ setSelectedJobMatchData(+ result.data.parsedMatchData as JobMatchResponse | null,+ );+ setDetailOpen(true);+ } else {+ setSelectedJob(job);+ setSelectedJobMatchData(null);+ setDetailOpen(true);+ }+ };++ if (loading) {+ return (+ <div className="container mx-auto py-6">+ <Loading />+ </div>+ );+ }++ if (!automation) {+ return null;+ }++ const resumeMissing = !automation.resume;+ const newJobsCount = jobs.filter((j) => j.discoveryStatus === "new").length;++ return (+ <div className="col-span-3 py-6 space-y-6">+ <div className="flex items-center gap-4">+ <Button variant="ghost" size="icon" asChild>+ <Link href="/dashboard/automations">+ <ArrowLeft className="h-4 w-4" />+ </Link>+ </Button>+ <div className="flex-1">+ <h1 className="text-2xl font-bold">{automation.name}</h1>+ <p className="text-muted-foreground">+ {automation.keywords} in {automation.location}+ </p>+ </div>+ <div className="flex gap-2">+ <Button variant="outline" size="icon" onClick={loadData}>+ <RefreshCw className="h-4 w-4" />+ </Button>+ <Button+ variant="outline"+ onClick={handlePauseResume}+ disabled={actionLoading || resumeMissing}+ >+ {actionLoading ? (+ <Loader2 className="h-4 w-4 mr-2 animate-spin" />+ ) : automation.status === "active" ? (+ <Pause className="h-4 w-4 mr-2" />+ ) : (+ <Play className="h-4 w-4 mr-2" />+ )}+ {automation.status === "active" ? "Pause" : "Resume"}+ </Button>+ <Button+ onClick={handleRunNow}+ disabled={+ runNowLoading || resumeMissing || automation.status === "paused"+ }+ >+ {runNowLoading ? (+ <Loader2 className="h-4 w-4 mr-2 animate-spin" />+ ) : (+ <PlayCircle className="h-4 w-4 mr-2" />+ )}+ Run Now+ </Button>+ </div>+ </div>++ <Card>+ <CardContent className="pt-6">+ <div className="grid grid-cols-2 md:grid-cols-4 gap-4">+ <div>+ <p className="text-sm text-muted-foreground">Status</p>+ <Badge+ variant={+ automation.status === "active" ? "default" : "secondary"+ }+ className="mt-1"+ >+ {automation.status}+ </Badge>+ </div>+ <div>+ <p className="text-sm text-muted-foreground">Job Board</p>+ <p className="font-medium capitalize">{automation.jobBoard}</p>+ </div>+ <div>+ <p className="text-sm text-muted-foreground">Match Threshold</p>+ <p className="font-medium">{automation.matchThreshold}%</p>+ </div>+ <div>+ <p className="text-sm text-muted-foreground">Schedule</p>+ <p className="font-medium flex items-center gap-1">+ <Clock className="h-4 w-4" />+ {automation.scheduleHour.toString().padStart(2, "0")}:00 daily+ </p>+ </div>+ <div>+ <p className="text-sm text-muted-foreground">Resume</p>+ {resumeMissing ? (+ <p className="text-amber-600 flex items-center gap-1 text-sm">+ <AlertTriangle className="h-4 w-4" />+ Missing+ </p>+ ) : (+ <p className="font-medium flex items-center gap-1">+ <FileText className="h-4 w-4" />+ {automation.resume.title}+ </p>+ )}+ </div>+ <div>+ <p className="text-sm text-muted-foreground">Next Run</p>+ <p className="font-medium">+ {automation.nextRunAt && automation.status === "active"+ ? format(new Date(automation.nextRunAt), "MMM d, h:mm a")+ : "-"}+ </p>+ </div>+ <div>+ <p className="text-sm text-muted-foreground">Last Run</p>+ <p className="font-medium">+ {automation.lastRunAt+ ? format(new Date(automation.lastRunAt), "MMM d, h:mm a")+ : "Never"}+ </p>+ </div>+ <div>+ <p className="text-sm text-muted-foreground">Discovered Jobs</p>+ <p className="font-medium">+ {jobs.length} total+ {newJobsCount > 0 && (+ <Badge variant="secondary" className="ml-2">+ {newJobsCount} new+ </Badge>+ )}+ </p>+ </div>+ </div>+ </CardContent>+ </Card>++ <Tabs defaultValue="logs">+ <TabsList>+ <TabsTrigger value="logs">Logs</TabsTrigger>+ <TabsTrigger value="jobs">+ Discovered Jobs+ {newJobsCount > 0 && (+ <Badge variant="secondary" className="ml-2">+ {newJobsCount}+ </Badge>+ )}+ </TabsTrigger>+ <TabsTrigger value="history">Run History</TabsTrigger>+ </TabsList>+ <TabsContent value="logs" className="mt-4">+ <LogsTab automationId={automationId} runKey={runKey} />+ </TabsContent>+ <TabsContent value="jobs" className="mt-4">+ <DiscoveredJobsList+ jobs={jobs}+ onRefresh={loadData}+ onViewDetails={handleViewJobDetails}+ />+ </TabsContent>+ <TabsContent value="history" className="mt-4">+ <RunHistoryList runs={runs} />+ </TabsContent>+ </Tabs>++ <DiscoveredJobDetail+ job={selectedJob}+ matchData={selectedJobMatchData}+ open={detailOpen}+ onOpenChange={setDetailOpen}+ onRefresh={loadData}+ />+ </div>+ );+}diff --git a/src/app/dashboard/automations/page.tsx b/src/app/dashboard/automations/page.tsxnew file mode 100644index 0000000..fdabdd5--- /dev/null+++ b/src/app/dashboard/automations/page.tsx@@ -0,0 +1,17 @@+import { getResumeList } from "@/actions/profile.actions";+import { AutomationContainer } from "@/components/automations/AutomationContainer";++export default async function AutomationsPage() {+ const resumeResult = await getResumeList(1, 100);+ const resumes =+ resumeResult?.data?.map((r: { id: string; title: string }) => ({+ id: r.id,+ title: r.title,+ })) || [];++ return (+ <div className="col-span-3 py-6">+ <AutomationContainer resumes={resumes} />+ </div>+ );+}diff --git a/src/components/automations/AutomationContainer.tsx b/src/components/automations/AutomationContainer.tsxnew file mode 100644index 0000000..c9fa8c1--- /dev/null+++ b/src/components/automations/AutomationContainer.tsx@@ -0,0 +1,109 @@+"use client";++import { useCallback, useEffect, useState } from "react";+import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";+import { Button } from "@/components/ui/button";+import { Plus, RefreshCw } from "lucide-react";+import { toast } from "@/components/ui/use-toast";+import { getAutomationsList } from "@/actions/automation.actions";+import type { AutomationWithResume } from "@/models/automation.model";+import { AutomationList } from "./AutomationList";+import { AutomationWizard } from "./AutomationWizard";+import Loading from "@/components/Loading";++interface Resume {+ id: string;+ title: string;+}++interface AutomationContainerProps {+ resumes: Resume[];+}++export function AutomationContainer({ resumes }: AutomationContainerProps) {+ const [automations, setAutomations] = useState<AutomationWithResume[]>([]);+ const [loading, setLoading] = useState(true);+ const [wizardOpen, setWizardOpen] = useState(false);+ const [editAutomation, setEditAutomation] = useState<AutomationWithResume | null>(null);++ const loadAutomations = useCallback(async () => {+ setLoading(true);+ const result = await getAutomationsList();++ if (result.success && result.data) {+ setAutomations(result.data);+ } else {+ toast({+ title: "Error",+ description: result.message || "Failed to load automations",+ variant: "destructive",+ });+ }+ setLoading(false);+ }, []);++ useEffect(() => {+ loadAutomations();+ }, [loadAutomations]);++ const handleEdit = (automation: AutomationWithResume) => {+ setEditAutomation(automation);+ setWizardOpen(true);+ };++ const handleWizardClose = (open: boolean) => {+ setWizardOpen(open);+ if (!open) {+ setEditAutomation(null);+ }+ };++ const handleSuccess = () => {+ loadAutomations();+ };++ return (+ <>+ <Card>+ <CardHeader className="flex flex-row items-center justify-between">+ <CardTitle>Job Discovery Automations</CardTitle>+ <div className="flex gap-2">+ <Button variant="outline" size="icon" onClick={loadAutomations}>+ <RefreshCw className="h-4 w-4" />+ </Button>+ <Button onClick={() => setWizardOpen(true)} disabled={resumes.length === 0}>+ <Plus className="h-4 w-4 mr-2" />+ Create Automation+ </Button>+ </div>+ </CardHeader>+ <CardContent>+ {resumes.length === 0 ? (+ <div className="text-center py-8 text-muted-foreground">+ <p>You need to create a resume before setting up automations.</p>+ <p className="text-sm mt-2">+ Go to your Profile to create a resume first.+ </p>+ </div>+ ) : loading ? (+ <Loading />+ ) : (+ <AutomationList+ automations={automations}+ onEdit={handleEdit}+ onRefresh={loadAutomations}+ />+ )}+ </CardContent>+ </Card>++ <AutomationWizard+ open={wizardOpen}+ onOpenChange={handleWizardClose}+ resumes={resumes}+ onSuccess={handleSuccess}+ editAutomation={editAutomation}+ />+ </>+ );+}diff --git a/src/components/automations/AutomationList.tsx b/src/components/automations/AutomationList.tsxnew file mode 100644index 0000000..b36dbdd--- /dev/null+++ b/src/components/automations/AutomationList.tsx@@ -0,0 +1,269 @@+"use client";++import { useState } from "react";+import { format } from "date-fns";+import { Card, CardContent } from "@/components/ui/card";+import { Button } from "@/components/ui/button";+import { Badge } from "@/components/ui/badge";+import {+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuSeparator,+ DropdownMenuTrigger,+} from "@/components/ui/dropdown-menu";+import {+ AlertDialog,+ AlertDialogAction,+ AlertDialogCancel,+ AlertDialogContent,+ AlertDialogDescription,+ AlertDialogFooter,+ AlertDialogHeader,+ AlertDialogTitle,+} from "@/components/ui/alert-dialog";+import { toast } from "@/components/ui/use-toast";+import {+ MoreHorizontal,+ Pause,+ Play,+ Pencil,+ Trash2,+ Clock,+ FileText,+ AlertTriangle,+ Zap,+} from "lucide-react";+import type { AutomationWithResume } from "@/models/automation.model";+import {+ deleteAutomation,+ pauseAutomation,+ resumeAutomation,+} from "@/actions/automation.actions";+import Link from "next/link";++interface AutomationListProps {+ automations: AutomationWithResume[];+ onEdit: (automation: AutomationWithResume) => void;+ onRefresh: () => void;+}++export function AutomationList({+ automations,+ onEdit,+ onRefresh,+}: AutomationListProps) {+ const [deleteId, setDeleteId] = useState<string | null>(null);+ const [isDeleting, setIsDeleting] = useState(false);+ const [loadingAction, setLoadingAction] = useState<string | null>(null);++ const handlePause = async (id: string) => {+ setLoadingAction(id);+ const result = await pauseAutomation(id);+ setLoadingAction(null);++ if (result.success) {+ toast({ title: "Automation paused" });+ onRefresh();+ } else {+ toast({+ title: "Error",+ description: result.message,+ variant: "destructive",+ });+ }+ };++ const handleResume = async (id: string) => {+ setLoadingAction(id);+ const result = await resumeAutomation(id);+ setLoadingAction(null);++ if (result.success) {+ toast({ title: "Automation resumed" });+ onRefresh();+ } else {+ toast({+ title: "Error",+ description: result.message,+ variant: "destructive",+ });+ }+ };++ const handleDelete = async () => {+ if (!deleteId) return;++ setIsDeleting(true);+ const result = await deleteAutomation(deleteId);+ setIsDeleting(false);+ setDeleteId(null);++ if (result.success) {+ toast({ title: "Automation deleted" });+ onRefresh();+ } else {+ toast({+ title: "Error",+ description: result.message,+ variant: "destructive",+ });+ }+ };++ if (automations.length === 0) {+ return (+ <Card>+ <CardContent className="flex flex-col items-center justify-center py-12">+ <Zap className="h-12 w-12 text-muted-foreground mb-4" />+ <h3 className="text-lg font-medium">No automations yet</h3>+ <p className="text-muted-foreground text-center mt-2">+ Create your first automation to start discovering jobs automatically.+ </p>+ </CardContent>+ </Card>+ );+ }++ return (+ <>+ <div className="space-y-4">+ {automations.map((automation) => {+ const isLoading = loadingAction === automation.id;+ const resumeMissing = !automation.resume;++ return (+ <div+ key={automation.id}+ className="flex items-start justify-between p-4 rounded-lg border bg-card"+ >+ <div className="flex-1 min-w-0 space-y-2">+ <div className="flex items-center gap-3 flex-wrap">+ <Link+ href={`/dashboard/automations/${automation.id}`}+ className="font-semibold hover:underline"+ >+ {automation.name}+ </Link>+ <Badge variant="outline" className="capitalize">+ {automation.jobBoard}+ </Badge>+ <Badge+ variant={automation.status === "active" ? "default" : "secondary"}+ >+ {automation.status}+ </Badge>+ </div>++ {resumeMissing && (+ <div className="flex items-center gap-2 text-amber-600 text-sm">+ <AlertTriangle className="h-4 w-4" />+ <span>Resume missing - select a new one</span>+ </div>+ )}++ <div className="flex flex-wrap gap-x-6 gap-y-1 text-sm text-muted-foreground">+ <span>+ <span className="font-medium text-foreground">Keywords:</span>{" "}+ {automation.keywords}+ </span>+ <span>+ <span className="font-medium text-foreground">Location:</span>{" "}+ {automation.location}+ </span>+ {automation.resume && (+ <span>+ <span className="font-medium text-foreground">Resume:</span>{" "}+ {automation.resume.title}+ </span>+ )}+ </div>++ <div className="flex flex-wrap gap-x-4 gap-y-1 text-sm text-muted-foreground">+ <div className="flex items-center gap-1">+ <Clock className="h-4 w-4" />+ <span>+ {automation.scheduleHour.toString().padStart(2, "0")}:00 daily+ </span>+ </div>+ <div className="flex items-center gap-1">+ <FileText className="h-4 w-4" />+ <span>{automation.matchThreshold}% threshold</span>+ </div>+ {automation.nextRunAt && automation.status === "active" && (+ <span className="text-xs">+ Next: {format(new Date(automation.nextRunAt), "MMM d, h:mm a")}+ </span>+ )}+ {automation.lastRunAt && (+ <span className="text-xs">+ Last: {format(new Date(automation.lastRunAt), "MMM d, h:mm a")}+ </span>+ )}+ </div>+ </div>++ <DropdownMenu>+ <DropdownMenuTrigger asChild>+ <Button variant="ghost" size="icon" disabled={isLoading}>+ <MoreHorizontal className="h-4 w-4" />+ </Button>+ </DropdownMenuTrigger>+ <DropdownMenuContent align="end">+ {automation.status === "active" ? (+ <DropdownMenuItem onClick={() => handlePause(automation.id)}>+ <Pause className="h-4 w-4 mr-2" />+ Pause+ </DropdownMenuItem>+ ) : (+ <DropdownMenuItem+ onClick={() => handleResume(automation.id)}+ disabled={resumeMissing}+ >+ <Play className="h-4 w-4 mr-2" />+ Resume+ </DropdownMenuItem>+ )}+ <DropdownMenuItem onClick={() => onEdit(automation)}>+ <Pencil className="h-4 w-4 mr-2" />+ Edit+ </DropdownMenuItem>+ <DropdownMenuSeparator />+ <DropdownMenuItem+ className="text-destructive"+ onClick={() => setDeleteId(automation.id)}+ >+ <Trash2 className="h-4 w-4 mr-2" />+ Delete+ </DropdownMenuItem>+ </DropdownMenuContent>+ </DropdownMenu>+ </div>+ );+ })}+ </div>++ <AlertDialog open={!!deleteId} onOpenChange={() => setDeleteId(null)}>+ <AlertDialogContent>+ <AlertDialogHeader>+ <AlertDialogTitle>Delete Automation</AlertDialogTitle>+ <AlertDialogDescription>+ Are you sure you want to delete this automation? This action cannot be+ undone. Discovered jobs will remain but lose their automation reference.+ </AlertDialogDescription>+ </AlertDialogHeader>+ <AlertDialogFooter>+ <AlertDialogCancel disabled={isDeleting}>Cancel</AlertDialogCancel>+ <AlertDialogAction+ onClick={handleDelete}+ disabled={isDeleting}+ className="bg-destructive text-destructive-foreground hover:bg-destructive/90"+ >+ {isDeleting ? "Deleting..." : "Delete"}+ </AlertDialogAction>+ </AlertDialogFooter>+ </AlertDialogContent>+ </AlertDialog>+ </>+ );+}diff --git a/src/components/automations/AutomationWizard.tsx b/src/components/automations/AutomationWizard.tsxnew file mode 100644index 0000000..12a79ea--- /dev/null+++ b/src/components/automations/AutomationWizard.tsx@@ -0,0 +1,463 @@+"use client";++import { useState, useEffect } from "react";+import { useForm } from "react-hook-form";+import { zodResolver } from "@hookform/resolvers/zod";+import {+ Dialog,+ DialogContent,+ DialogDescription,+ DialogFooter,+ DialogHeader,+ DialogTitle,+} from "@/components/ui/dialog";+import { Button } from "@/components/ui/button";+import { Input } from "@/components/ui/input";+import { Label } from "@/components/ui/label";+import {+ Select,+ SelectContent,+ SelectItem,+ SelectTrigger,+ SelectValue,+} from "@/components/ui/select";+import { Slider } from "@/components/ui/slider";+import {+ Form,+ FormControl,+ FormDescription,+ FormField,+ FormItem,+ FormLabel,+ FormMessage,+} from "@/components/ui/form";+import { CreateAutomationSchema, type CreateAutomationInput } from "@/models/automation.schema";+import { createAutomation, updateAutomation } from "@/actions/automation.actions";+import { toast } from "@/components/ui/use-toast";+import type { AutomationWithResume } from "@/models/automation.model";+import { ChevronLeft, ChevronRight, Loader2 } from "lucide-react";++interface Resume {+ id: string;+ title: string;+}++interface AutomationWizardProps {+ open: boolean;+ onOpenChange: (open: boolean) => void;+ resumes: Resume[];+ onSuccess: () => void;+ editAutomation?: AutomationWithResume | null;+}++const STEPS = [+ { id: "basics", title: "Basics", description: "Name your automation" },+ { id: "search", title: "Search", description: "Configure search criteria" },+ { id: "resume", title: "Resume", description: "Select resume for matching" },+ { id: "matching", title: "Matching", description: "Set match threshold" },+ { id: "schedule", title: "Schedule", description: "When to run" },+ { id: "review", title: "Review", description: "Confirm settings" },+];++const HOURS = Array.from({ length: 24 }, (_, i) => ({+ value: i,+ label: `${i.toString().padStart(2, "0")}:00`,+}));++export function AutomationWizard({+ open,+ onOpenChange,+ resumes,+ onSuccess,+ editAutomation,+}: AutomationWizardProps) {+ const [step, setStep] = useState(0);+ const [isSubmitting, setIsSubmitting] = useState(false);++ const form = useForm<CreateAutomationInput>({+ resolver: zodResolver(CreateAutomationSchema),+ mode: "onChange",+ defaultValues: {+ name: editAutomation?.name ?? "",+ jobBoard: (editAutomation?.jobBoard as "jsearch") ?? "jsearch",+ keywords: editAutomation?.keywords ?? "",+ location: editAutomation?.location ?? "",+ resumeId: editAutomation?.resumeId ?? "",+ matchThreshold: editAutomation?.matchThreshold ?? 80,+ scheduleHour: editAutomation?.scheduleHour ?? 8,+ },+ });++ useEffect(() => {+ if (open) {+ form.reset({+ name: editAutomation?.name ?? "",+ jobBoard: (editAutomation?.jobBoard as "jsearch") ?? "jsearch",+ keywords: editAutomation?.keywords ?? "",+ location: editAutomation?.location ?? "",+ resumeId: editAutomation?.resumeId ?? "",+ matchThreshold: editAutomation?.matchThreshold ?? 80,+ scheduleHour: editAutomation?.scheduleHour ?? 8,+ });+ setStep(0);+ }+ }, [open, editAutomation, form]);++ const formValues = form.watch();++ const onSubmit = async (data: CreateAutomationInput) => {+ setIsSubmitting(true);+ try {+ const result = editAutomation+ ? await updateAutomation(editAutomation.id, data)+ : await createAutomation(data);++ if (result.success) {+ toast({+ title: editAutomation ? "Automation updated" : "Automation created",+ description: editAutomation+ ? "Your automation has been updated successfully."+ : "Your automation has been created and will run at the scheduled time.",+ });+ form.reset();+ setStep(0);+ onOpenChange(false);+ onSuccess();+ } else {+ toast({+ title: "Error",+ description: result.message || "Something went wrong",+ variant: "destructive",+ });+ }+ } catch (error) {+ toast({+ title: "Error",+ description: "Failed to save automation",+ variant: "destructive",+ });+ } finally {+ setIsSubmitting(false);+ }+ };++ const canGoNext = () => {+ switch (step) {+ case 0:+ return (formValues.name?.trim().length ?? 0) > 0;+ case 1:+ return (+ (formValues.keywords?.trim().length ?? 0) > 0 &&+ (formValues.location?.trim().length ?? 0) > 0+ );+ case 2:+ return (formValues.resumeId?.length ?? 0) > 0;+ case 3:+ case 4:+ return true;+ default:+ return false;+ }+ };++ const nextStep = () => {+ if (step < STEPS.length - 1) {+ setStep(step + 1);+ }+ };++ const prevStep = () => {+ if (step > 0) {+ setStep(step - 1);+ }+ };++ const handleClose = () => {+ form.reset();+ setStep(0);+ onOpenChange(false);+ };++ const selectedResume = resumes.find((r) => r.id === formValues.resumeId);++ const renderStepContent = () => {+ return (+ <>+ {/* Step 0: Basics */}+ <div className={step === 0 ? "space-y-4" : "hidden"}>+ <FormField+ control={form.control}+ name="name"+ render={({ field }) => (+ <FormItem>+ <FormLabel>Automation Name</FormLabel>+ <FormControl>+ <Input placeholder="e.g., Full Stack Jobs Calgary" {...field} />+ </FormControl>+ <FormDescription>+ A descriptive name to identify this automation+ </FormDescription>+ <FormMessage />+ </FormItem>+ )}+ />+ <FormField+ control={form.control}+ name="jobBoard"+ render={({ field }) => (+ <FormItem>+ <FormLabel>Job Board</FormLabel>+ <Select onValueChange={field.onChange} value={field.value}>+ <FormControl>+ <SelectTrigger>+ <SelectValue placeholder="Select a job board" />+ </SelectTrigger>+ </FormControl>+ <SelectContent>+ <SelectItem value="jsearch">JSearch (Google Jobs)</SelectItem>+ </SelectContent>+ </Select>+ <FormDescription>+ The job board to search (more coming soon)+ </FormDescription>+ <FormMessage />+ </FormItem>+ )}+ />+ </div>++ {/* Step 1: Search */}+ <div className={step === 1 ? "space-y-4" : "hidden"}>+ <FormField+ control={form.control}+ name="keywords"+ render={({ field }) => (+ <FormItem>+ <FormLabel>Search Keywords</FormLabel>+ <FormControl>+ <Input placeholder="e.g., Full Stack Developer" {...field} />+ </FormControl>+ <FormDescription>+ Job titles, skills, or keywords to search for+ </FormDescription>+ <FormMessage />+ </FormItem>+ )}+ />+ <FormField+ control={form.control}+ name="location"+ render={({ field }) => (+ <FormItem>+ <FormLabel>Location</FormLabel>+ <FormControl>+ <Input placeholder="e.g., Calgary, AB" {...field} />+ </FormControl>+ <FormDescription>+ City, state/province, or region to search in+ </FormDescription>+ <FormMessage />+ </FormItem>+ )}+ />+ </div>++ {/* Step 2: Resume */}+ <div className={step === 2 ? "space-y-4" : "hidden"}>+ <FormField+ control={form.control}+ name="resumeId"+ render={({ field }) => (+ <FormItem>+ <FormLabel>Resume for Matching</FormLabel>+ <Select onValueChange={field.onChange} value={field.value}>+ <FormControl>+ <SelectTrigger>+ <SelectValue placeholder="Select a resume" />+ </SelectTrigger>+ </FormControl>+ <SelectContent>+ {resumes.map((resume) => (+ <SelectItem key={resume.id} value={resume.id}>+ {resume.title}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ <FormDescription>+ Jobs will be matched against this resume+ </FormDescription>+ <FormMessage />+ </FormItem>+ )}+ />+ {resumes.length === 0 && (+ <p className="text-sm text-muted-foreground">+ No resumes found. Please create a resume in your profile first.+ </p>+ )}+ </div>++ {/* Step 3: Matching */}+ <div className={step === 3 ? "space-y-4" : "hidden"}>+ <FormField+ control={form.control}+ name="matchThreshold"+ render={({ field }) => (+ <FormItem>+ <FormLabel>+ Match Threshold: {field.value}%+ </FormLabel>+ <FormControl>+ <Slider+ min={0}+ max={100}+ step={5}+ value={[field.value]}+ onValueChange={(value) => field.onChange(value[0])}+ />+ </FormControl>+ <FormDescription>+ Only save jobs that match your resume above this percentage.+ Higher = fewer but better matches.+ </FormDescription>+ <FormMessage />+ </FormItem>+ )}+ />+ </div>++ {/* Step 4: Schedule */}+ <div className={step === 4 ? "space-y-4" : "hidden"}>+ <FormField+ control={form.control}+ name="scheduleHour"+ render={({ field }) => (+ <FormItem>+ <FormLabel>Daily Run Time</FormLabel>+ <Select+ onValueChange={(val) => field.onChange(parseInt(val))}+ value={field.value.toString()}+ >+ <FormControl>+ <SelectTrigger>+ <SelectValue placeholder="Select time" />+ </SelectTrigger>+ </FormControl>+ <SelectContent>+ {HOURS.map((hour) => (+ <SelectItem key={hour.value} value={hour.value.toString()}>+ {hour.label}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ <FormDescription>+ The automation will run daily at this time (server timezone)+ </FormDescription>+ <FormMessage />+ </FormItem>+ )}+ />+ </div>++ {/* Step 5: Review */}+ <div className={step === 5 ? "space-y-4" : "hidden"}>+ <div className="rounded-lg border p-4 space-y-3">+ <div className="flex justify-between">+ <span className="text-muted-foreground">Name</span>+ <span className="font-medium">{formValues.name || "-"}</span>+ </div>+ <div className="flex justify-between">+ <span className="text-muted-foreground">Job Board</span>+ <span className="font-medium capitalize">{formValues.jobBoard || "-"}</span>+ </div>+ <div className="flex justify-between">+ <span className="text-muted-foreground">Keywords</span>+ <span className="font-medium">{formValues.keywords || "-"}</span>+ </div>+ <div className="flex justify-between">+ <span className="text-muted-foreground">Location</span>+ <span className="font-medium">{formValues.location || "-"}</span>+ </div>+ <div className="flex justify-between">+ <span className="text-muted-foreground">Resume</span>+ <span className="font-medium">{selectedResume?.title || "Not selected"}</span>+ </div>+ <div className="flex justify-between">+ <span className="text-muted-foreground">Match Threshold</span>+ <span className="font-medium">{formValues.matchThreshold ?? 80}%</span>+ </div>+ <div className="flex justify-between">+ <span className="text-muted-foreground">Schedule</span>+ <span className="font-medium">+ Daily at {(formValues.scheduleHour ?? 8).toString().padStart(2, "0")}:00+ </span>+ </div>+ </div>+ </div>+ </>+ );+ };++ return (+ <Dialog open={open} onOpenChange={handleClose}>+ <DialogContent className="sm:max-w-[500px]">+ <DialogHeader>+ <DialogTitle>+ {editAutomation ? "Edit Automation" : "Create Automation"}+ </DialogTitle>+ <DialogDescription>+ Step {step + 1} of {STEPS.length}: {STEPS[step].description}+ </DialogDescription>+ </DialogHeader>++ <div className="flex justify-center gap-1 mb-4">+ {STEPS.map((_, i) => (+ <div+ key={i}+ className={`h-1 w-8 rounded-full ${+ i <= step ? "bg-primary" : "bg-muted"+ }`}+ />+ ))}+ </div>++ <Form {...form}>+ <form onSubmit={form.handleSubmit(onSubmit, (errors) => {+ const firstError = Object.values(errors)[0];+ if (firstError?.message) {+ toast({+ title: "Validation Error",+ description: firstError.message as string,+ variant: "destructive",+ });+ }+ })}>+ <div className="py-4">{renderStepContent()}</div>++ <DialogFooter className="gap-2">+ {step > 0 && (+ <Button type="button" variant="outline" onClick={prevStep}>+ <ChevronLeft className="h-4 w-4 mr-1" />+ Back+ </Button>+ )}+ {step < STEPS.length - 1 ? (+ <Button type="button" onClick={nextStep} disabled={!canGoNext()}>+ Next+ <ChevronRight className="h-4 w-4 ml-1" />+ </Button>+ ) : (+ <Button type="submit" disabled={isSubmitting}>+ {isSubmitting && <Loader2 className="h-4 w-4 mr-2 animate-spin" />}+ {editAutomation ? "Update" : "Create"} Automation+ </Button>+ )}+ </DialogFooter>+ </form>+ </Form>+ </DialogContent>+ </Dialog>+ );+}diff --git a/src/components/automations/DiscoveredJobDetail.tsx b/src/components/automations/DiscoveredJobDetail.tsxnew file mode 100644index 0000000..3c535e7--- /dev/null+++ b/src/components/automations/DiscoveredJobDetail.tsx@@ -0,0 +1,294 @@+"use client";++import { useState } from "react";+import { format } from "date-fns";+import {+ Dialog,+ DialogContent,+ DialogDescription,+ DialogFooter,+ DialogHeader,+ DialogTitle,+} from "@/components/ui/dialog";+import {+ Accordion,+ AccordionContent,+ AccordionItem,+ AccordionTrigger,+} from "@/components/ui/accordion";+import { Button } from "@/components/ui/button";+import { Badge } from "@/components/ui/badge";+import { ScrollArea } from "@/components/ui/scroll-area";+import { toast } from "@/components/ui/use-toast";+import {+ Building2,+ MapPin,+ ExternalLink,+ Check,+ X,+ Loader2,+} from "lucide-react";+import type { DiscoveredJob } from "@/models/automation.model";+import type { JobMatchResponse } from "@/models/ai.schemas";+import { acceptDiscoveredJob, dismissDiscoveredJob } from "@/actions/automation.actions";++interface DiscoveredJobDetailProps {+ job: DiscoveredJob | null;+ matchData: JobMatchResponse | null;+ open: boolean;+ onOpenChange: (open: boolean) => void;+ onRefresh: () => void;+}++export function DiscoveredJobDetail({+ job,+ matchData,+ open,+ onOpenChange,+ onRefresh,+}: DiscoveredJobDetailProps) {+ const [loadingAction, setLoadingAction] = useState<"accept" | "dismiss" | null>(null);++ if (!job) return null;++ const handleAccept = async () => {+ setLoadingAction("accept");+ const result = await acceptDiscoveredJob(job.id);+ setLoadingAction(null);++ if (result.success) {+ toast({ title: "Job accepted", description: "The job has been added to your tracked jobs." });+ onOpenChange(false);+ onRefresh();+ } else {+ toast({+ title: "Error",+ description: result.message,+ variant: "destructive",+ });+ }+ };++ const handleDismiss = async () => {+ setLoadingAction("dismiss");+ const result = await dismissDiscoveredJob(job.id);+ setLoadingAction(null);++ if (result.success) {+ toast({ title: "Job dismissed" });+ onOpenChange(false);+ onRefresh();+ } else {+ toast({+ title: "Error",+ description: result.message,+ variant: "destructive",+ });+ }+ };++ return (+ <Dialog open={open} onOpenChange={onOpenChange}>+ <DialogContent className="max-w-2xl max-h-[90vh]">+ <DialogHeader>+ <DialogTitle className="flex items-center gap-2">+ {job.JobTitle.label}+ {job.jobUrl && (+ <a+ href={job.jobUrl}+ target="_blank"+ rel="noopener noreferrer"+ className="text-muted-foreground hover:text-foreground"+ >+ <ExternalLink className="h-4 w-4" />+ </a>+ )}+ </DialogTitle>+ <DialogDescription className="flex items-center gap-4">+ <span className="flex items-center gap-1">+ <Building2 className="h-4 w-4" />+ {job.Company.label}+ </span>+ <span className="flex items-center gap-1">+ <MapPin className="h-4 w-4" />+ {job.Location?.label || "N/A"}+ </span>+ </DialogDescription>+ </DialogHeader>++ <ScrollArea className="max-h-[60vh]">+ <div className="space-y-4 pr-4">+ <div className="flex items-center gap-4">+ <Badge variant="default" className="text-lg px-3 py-1">+ {job.matchScore}% Match+ </Badge>+ <Badge variant="outline">{job.discoveryStatus}</Badge>+ {job.automation && (+ <span className="text-sm text-muted-foreground">+ from {job.automation.name}+ </span>+ )}+ </div>++ <div>+ <h4 className="font-medium mb-2">Description</h4>+ <p className="text-sm text-muted-foreground whitespace-pre-wrap">+ {job.description}+ </p>+ </div>++ {matchData && (+ <Accordion type="single" collapsible className="w-full">+ <AccordionItem value="summary">+ <AccordionTrigger>Match Summary</AccordionTrigger>+ <AccordionContent>+ <p className="text-sm">{matchData.summary}</p>+ <Badge className="mt-2" variant="outline">+ {matchData.recommendation}+ </Badge>+ </AccordionContent>+ </AccordionItem>++ <AccordionItem value="skills">+ <AccordionTrigger>Skills Analysis</AccordionTrigger>+ <AccordionContent>+ <div className="space-y-3">+ {matchData.skills.matched.length > 0 && (+ <div>+ <h5 className="text-sm font-medium text-green-600">Matched Skills</h5>+ <div className="flex flex-wrap gap-1 mt-1">+ {matchData.skills.matched.map((skill, i) => (+ <Badge key={i} variant="secondary" className="text-xs">+ {skill}+ </Badge>+ ))}+ </div>+ </div>+ )}+ {matchData.skills.missing.length > 0 && (+ <div>+ <h5 className="text-sm font-medium text-amber-600">Missing Skills</h5>+ <div className="flex flex-wrap gap-1 mt-1">+ {matchData.skills.missing.map((skill, i) => (+ <Badge key={i} variant="outline" className="text-xs">+ {skill}+ </Badge>+ ))}+ </div>+ </div>+ )}+ {matchData.skills.transferable.length > 0 && (+ <div>+ <h5 className="text-sm font-medium text-blue-600">Transferable Skills</h5>+ <div className="flex flex-wrap gap-1 mt-1">+ {matchData.skills.transferable.map((skill, i) => (+ <Badge key={i} variant="outline" className="text-xs">+ {skill}+ </Badge>+ ))}+ </div>+ </div>+ )}+ </div>+ </AccordionContent>+ </AccordionItem>++ <AccordionItem value="requirements">+ <AccordionTrigger>Requirements Analysis</AccordionTrigger>+ <AccordionContent>+ <div className="space-y-3">+ {matchData.requirements.met.length > 0 && (+ <div>+ <h5 className="text-sm font-medium text-green-600">Met Requirements</h5>+ <ul className="text-sm mt-1 space-y-1">+ {matchData.requirements.met.map((req, i) => (+ <li key={i}>+ <span className="font-medium">{req.requirement}</span>:{" "}+ <span className="text-muted-foreground">{req.evidence}</span>+ </li>+ ))}+ </ul>+ </div>+ )}+ {matchData.requirements.missing.length > 0 && (+ <div>+ <h5 className="text-sm font-medium text-red-600">Missing Requirements</h5>+ <ul className="text-sm mt-1 space-y-1">+ {matchData.requirements.missing.map((req, i) => (+ <li key={i}>+ <span className="font-medium">{req.requirement}</span>{" "}+ <Badge variant="outline" className="text-xs">{req.importance}</Badge>+ </li>+ ))}+ </ul>+ </div>+ )}+ </div>+ </AccordionContent>+ </AccordionItem>++ {matchData.tailoringTips.length > 0 && (+ <AccordionItem value="tips">+ <AccordionTrigger>Tailoring Tips</AccordionTrigger>+ <AccordionContent>+ <ul className="text-sm space-y-2">+ {matchData.tailoringTips.map((tip, i) => (+ <li key={i}>+ <span className="font-medium">{tip.section}:</span>{" "}+ {tip.action}+ </li>+ ))}+ </ul>+ </AccordionContent>+ </AccordionItem>+ )}++ {matchData.dealBreakers.length > 0 && (+ <AccordionItem value="dealbreakers">+ <AccordionTrigger>Potential Deal Breakers</AccordionTrigger>+ <AccordionContent>+ <ul className="text-sm text-red-600 space-y-1">+ {matchData.dealBreakers.map((db, i) => (+ <li key={i}>{db}</li>+ ))}+ </ul>+ </AccordionContent>+ </AccordionItem>+ )}+ </Accordion>+ )}++ <p className="text-xs text-muted-foreground">+ Discovered on {format(new Date(job.discoveredAt), "MMM d, yyyy 'at' h:mm a")}+ </p>+ </div>+ </ScrollArea>++ {job.discoveryStatus === "new" && (+ <DialogFooter className="gap-2">+ <Button+ variant="outline"+ onClick={handleDismiss}+ disabled={loadingAction !== null}+ >+ {loadingAction === "dismiss" ? (+ <Loader2 className="h-4 w-4 mr-2 animate-spin" />+ ) : (+ <X className="h-4 w-4 mr-2" />+ )}+ Dismiss+ </Button>+ <Button onClick={handleAccept} disabled={loadingAction !== null}>+ {loadingAction === "accept" ? (+ <Loader2 className="h-4 w-4 mr-2 animate-spin" />+ ) : (+ <Check className="h-4 w-4 mr-2" />+ )}+ Accept+ </Button>+ </DialogFooter>+ )}+ </DialogContent>+ </Dialog>+ );+}diff --git a/src/components/automations/DiscoveredJobsList.tsx b/src/components/automations/DiscoveredJobsList.tsxnew file mode 100644index 0000000..9ec5cb7--- /dev/null+++ b/src/components/automations/DiscoveredJobsList.tsx@@ -0,0 +1,220 @@+"use client";++import { useState } from "react";+import { format } from "date-fns";+import {+ Card,+ CardContent,+ CardDescription,+ CardHeader,+ CardTitle,+} from "@/components/ui/card";+import { Button } from "@/components/ui/button";+import { Badge } from "@/components/ui/badge";+import {+ Table,+ TableBody,+ TableCell,+ TableHead,+ TableHeader,+ TableRow,+} from "@/components/ui/table";+import { toast } from "@/components/ui/use-toast";+import {+ Check,+ X,+ ExternalLink,+ Briefcase,+ Building2,+ MapPin,+ Loader2,+} from "lucide-react";+import type { DiscoveredJob } from "@/models/automation.model";+import { acceptDiscoveredJob, dismissDiscoveredJob } from "@/actions/automation.actions";++interface DiscoveredJobsListProps {+ jobs: DiscoveredJob[];+ onRefresh: () => void;+ onViewDetails?: (job: DiscoveredJob) => void;+}++export function DiscoveredJobsList({+ jobs,+ onRefresh,+ onViewDetails,+}: DiscoveredJobsListProps) {+ const [loadingAction, setLoadingAction] = useState<string | null>(null);++ const handleAccept = async (jobId: string) => {+ setLoadingAction(jobId);+ const result = await acceptDiscoveredJob(jobId);+ setLoadingAction(null);++ if (result.success) {+ toast({ title: "Job accepted", description: "The job has been added to your tracked jobs." });+ onRefresh();+ } else {+ toast({+ title: "Error",+ description: result.message,+ variant: "destructive",+ });+ }+ };++ const handleDismiss = async (jobId: string) => {+ setLoadingAction(jobId);+ const result = await dismissDiscoveredJob(jobId);+ setLoadingAction(null);++ if (result.success) {+ toast({ title: "Job dismissed" });+ onRefresh();+ } else {+ toast({+ title: "Error",+ description: result.message,+ variant: "destructive",+ });+ }+ };++ const getScoreBadgeVariant = (score: number) => {+ if (score >= 80) return "default";+ if (score >= 65) return "secondary";+ return "outline";+ };++ if (jobs.length === 0) {+ return (+ <Card>+ <CardContent className="flex flex-col items-center justify-center py-12">+ <Briefcase className="h-12 w-12 text-muted-foreground mb-4" />+ <h3 className="text-lg font-medium">No discovered jobs</h3>+ <p className="text-muted-foreground text-center mt-2">+ Jobs discovered by automations will appear here.+ </p>+ </CardContent>+ </Card>+ );+ }++ return (+ <Card>+ <CardHeader>+ <CardTitle>Discovered Jobs</CardTitle>+ <CardDescription>+ Jobs found by your automations that match your criteria+ </CardDescription>+ </CardHeader>+ <CardContent>+ <Table>+ <TableHeader>+ <TableRow>+ <TableHead>Job</TableHead>+ <TableHead>Company</TableHead>+ <TableHead>Location</TableHead>+ <TableHead className="text-center">Match</TableHead>+ <TableHead>Status</TableHead>+ <TableHead>Discovered</TableHead>+ <TableHead className="text-right">Actions</TableHead>+ </TableRow>+ </TableHeader>+ <TableBody>+ {jobs.map((job) => {+ const isLoading = loadingAction === job.id;++ return (+ <TableRow key={job.id}>+ <TableCell>+ <div className="flex items-center gap-2">+ <span+ className="font-medium hover:underline cursor-pointer"+ onClick={() => onViewDetails?.(job)}+ >+ {job.JobTitle.label}+ </span>+ {job.jobUrl && (+ <a+ href={job.jobUrl}+ target="_blank"+ rel="noopener noreferrer"+ className="text-muted-foreground hover:text-foreground"+ >+ <ExternalLink className="h-4 w-4" />+ </a>+ )}+ </div>+ </TableCell>+ <TableCell>+ <div className="flex items-center gap-2">+ <Building2 className="h-4 w-4 text-muted-foreground" />+ {job.Company.label}+ </div>+ </TableCell>+ <TableCell>+ <div className="flex items-center gap-2">+ <MapPin className="h-4 w-4 text-muted-foreground" />+ {job.Location?.label || "N/A"}+ </div>+ </TableCell>+ <TableCell className="text-center">+ <Badge variant={getScoreBadgeVariant(job.matchScore)}>+ {job.matchScore}%+ </Badge>+ </TableCell>+ <TableCell>+ <Badge+ variant={+ job.discoveryStatus === "accepted"+ ? "default"+ : job.discoveryStatus === "dismissed"+ ? "secondary"+ : "outline"+ }+ >+ {job.discoveryStatus}+ </Badge>+ </TableCell>+ <TableCell>+ {format(new Date(job.discoveredAt), "MMM d, yyyy")}+ </TableCell>+ <TableCell className="text-right">+ {job.discoveryStatus === "new" && (+ <div className="flex justify-end gap-2">+ <Button+ size="sm"+ variant="outline"+ onClick={() => handleAccept(job.id)}+ disabled={isLoading}+ >+ {isLoading ? (+ <Loader2 className="h-4 w-4 animate-spin" />+ ) : (+ <Check className="h-4 w-4" />+ )}+ </Button>+ <Button+ size="sm"+ variant="ghost"+ onClick={() => handleDismiss(job.id)}+ disabled={isLoading}+ >+ {isLoading ? (+ <Loader2 className="h-4 w-4 animate-spin" />+ ) : (+ <X className="h-4 w-4" />+ )}+ </Button>+ </div>+ )}+ </TableCell>+ </TableRow>+ );+ })}+ </TableBody>+ </Table>+ </CardContent>+ </Card>+ );+}diff --git a/src/components/automations/LogsTab.tsx b/src/components/automations/LogsTab.tsxnew file mode 100644index 0000000..4fe3430--- /dev/null+++ b/src/components/automations/LogsTab.tsx@@ -0,0 +1,260 @@+"use client";++import { useEffect, useRef, useState } from "react";+import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";+import { Badge } from "@/components/ui/badge";+import { ScrollArea } from "@/components/ui/scroll-area";+import { Button } from "@/components/ui/button";+import {+ AlertCircle,+ CheckCircle2,+ Info,+ AlertTriangle,+ Loader2,+ Trash2,+} from "lucide-react";+import { format } from "date-fns";+import type { AutomationLog, LogLevel } from "@/lib/automation-logger";++interface LogsTabProps {+ automationId: string;+ runKey?: number;+}++interface LogData {+ logs: AutomationLog[];+ isRunning: boolean;+ startedAt?: string;+ completedAt?: string;+}++export function LogsTab({ automationId, runKey }: LogsTabProps) {+ const [logData, setLogData] = useState<LogData>({+ logs: [],+ isRunning: false,+ });+ const [autoScroll, setAutoScroll] = useState(true);+ const [filter, setFilter] = useState<LogLevel | "all">("all");+ const scrollRef = useRef<HTMLDivElement>(null);++ useEffect(() => {+ const eventSource = new EventSource(+ `/api/automations/${automationId}/logs`,+ );++ eventSource.onmessage = (event) => {+ try {+ const data: LogData = JSON.parse(event.data);+ setLogData(data);+ } catch (err) {+ console.error("Failed to parse log data:", err);+ }+ };++ eventSource.onerror = () => {+ eventSource.close();+ };++ return () => {+ eventSource.close();+ };+ }, [automationId]);++ useEffect(() => {+ if (autoScroll && scrollRef.current) {+ scrollRef.current.scrollTop = scrollRef.current.scrollHeight;+ }+ }, [logData.logs, autoScroll]);++ useEffect(() => {+ if (runKey !== undefined) {+ setLogData({ logs: [], isRunning: true });+ }+ }, [runKey]);++ const handleClearLogs = async () => {+ try {+ await fetch(`/api/automations/${automationId}/logs/clear`, {+ method: "POST",+ });+ } catch (err) {+ console.error("Failed to clear server logs:", err);+ }+ setLogData({ logs: [], isRunning: false });+ };++ const filteredLogs =+ filter === "all"+ ? logData.logs+ : logData.logs.filter((log) => log.level === filter);++ const getLevelIcon = (level: LogLevel) => {+ switch (level) {+ case "info":+ return <Info className="h-4 w-4 text-blue-500" />;+ case "success":+ return <CheckCircle2 className="h-4 w-4 text-green-500" />;+ case "warning":+ return <AlertTriangle className="h-4 w-4 text-amber-500" />;+ case "error":+ return <AlertCircle className="h-4 w-4 text-red-500" />;+ }+ };++ const getLevelColor = (level: LogLevel) => {+ switch (level) {+ case "info":+ return "text-blue-600";+ case "success":+ return "text-green-600";+ case "warning":+ return "text-amber-600";+ case "error":+ return "text-red-600";+ }+ };++ const getLevelBadgeVariant = (level: LogLevel) => {+ switch (level) {+ case "info":+ return "default" as const;+ case "success":+ return "default" as const;+ case "warning":+ return "secondary" as const;+ case "error":+ return "destructive" as const;+ }+ };++ return (+ <Card>+ <CardHeader>+ <div className="flex items-center justify-between">+ <div className="flex items-center gap-2">+ <CardTitle>Automation Logs</CardTitle>+ {logData.isRunning && (+ <Badge variant="default" className="gap-1">+ <Loader2 className="h-3 w-3 animate-spin" />+ Running+ </Badge>+ )}+ </div>+ <div className="flex items-center gap-2">+ <div className="flex gap-1">+ <Button+ size="sm"+ variant={filter === "all" ? "default" : "outline"}+ onClick={() => setFilter("all")}+ >+ All+ </Button>+ <Button+ size="sm"+ variant={filter === "info" ? "default" : "outline"}+ onClick={() => setFilter("info")}+ >+ Info+ </Button>+ <Button+ size="sm"+ variant={filter === "success" ? "default" : "outline"}+ onClick={() => setFilter("success")}+ >+ Success+ </Button>+ <Button+ size="sm"+ variant={filter === "warning" ? "default" : "outline"}+ onClick={() => setFilter("warning")}+ >+ Warning+ </Button>+ <Button+ size="sm"+ variant={filter === "error" ? "default" : "outline"}+ onClick={() => setFilter("error")}+ >+ Error+ </Button>+ </div>+ <Button+ size="sm"+ variant="outline"+ onClick={() => setAutoScroll(!autoScroll)}+ >+ {autoScroll ? "Auto-scroll: On" : "Auto-scroll: Off"}+ </Button>+ <Button+ size="sm"+ variant="outline"+ onClick={handleClearLogs}+ disabled={logData.logs.length === 0}+ >+ <Trash2 className="h-4 w-4" />+ </Button>+ </div>+ </div>+ {logData.startedAt && (+ <p className="text-sm text-muted-foreground">+ Started: {format(new Date(logData.startedAt), "MMM d, h:mm:ss a")}+ {logData.completedAt && (+ <>+ {" "}+ • Completed:{" "}+ {format(new Date(logData.completedAt), "MMM d, h:mm:ss a")}+ </>+ )}+ </p>+ )}+ </CardHeader>+ <CardContent>+ <ScrollArea className="h-[600px] w-full" ref={scrollRef}>+ {filteredLogs.length === 0 ? (+ <div className="flex items-center justify-center h-full text-muted-foreground">+ <p>+ {logData.logs.length === 0+ ? "No logs yet. Run the automation to see logs."+ : "No logs match the selected filter."}+ </p>+ </div>+ ) : (+ <div className="space-y-2 font-mono text-xs">+ {filteredLogs.map((log, index) => (+ <div+ key={index}+ className="flex gap-2 p-2 rounded border hover:bg-muted/50"+ >+ <div className="flex-shrink-0 pt-0.5">+ {getLevelIcon(log.level)}+ </div>+ <div className="flex-1 min-w-0">+ <div className="flex items-center gap-2 mb-1">+ <span className="text-muted-foreground">+ {format(new Date(log.timestamp), "HH:mm:ss.SSS")}+ </span>+ <Badge+ variant={getLevelBadgeVariant(log.level)}+ className="text-xs"+ >+ {log.level}+ </Badge>+ </div>+ <div className={getLevelColor(log.level)}>+ {log.message}+ </div>+ {log.metadata && Object.keys(log.metadata).length > 0 && (+ <pre className="mt-1 text-xs text-muted-foreground overflow-x-auto">+ {JSON.stringify(log.metadata, null, 2)}+ </pre>+ )}+ </div>+ </div>+ ))}+ </div>+ )}+ </ScrollArea>+ </CardContent>+ </Card>+ );+}diff --git a/src/components/automations/RunHistoryList.tsx b/src/components/automations/RunHistoryList.tsxnew file mode 100644index 0000000..8f9bf77--- /dev/null+++ b/src/components/automations/RunHistoryList.tsx@@ -0,0 +1,145 @@+"use client";++import { format } from "date-fns";+import {+ Card,+ CardContent,+ CardDescription,+ CardHeader,+ CardTitle,+} from "@/components/ui/card";+import { Badge } from "@/components/ui/badge";+import {+ Table,+ TableBody,+ TableCell,+ TableHead,+ TableHeader,+ TableRow,+} from "@/components/ui/table";+import {+ Tooltip,+ TooltipContent,+ TooltipProvider,+ TooltipTrigger,+} from "@/components/ui/tooltip";+import {+ CheckCircle2,+ XCircle,+ AlertCircle,+ Clock,+ Ban,+ Timer,+ History,+} from "lucide-react";+import type { AutomationRun } from "@/models/automation.model";++interface RunHistoryListProps {+ runs: AutomationRun[];+}++const STATUS_CONFIG = {+ running: { icon: Clock, color: "text-blue-500", variant: "secondary" as const },+ completed: { icon: CheckCircle2, color: "text-green-500", variant: "default" as const },+ failed: { icon: XCircle, color: "text-red-500", variant: "destructive" as const },+ completed_with_errors: { icon: AlertCircle, color: "text-amber-500", variant: "secondary" as const },+ blocked: { icon: Ban, color: "text-red-500", variant: "destructive" as const },+ rate_limited: { icon: Timer, color: "text-amber-500", variant: "secondary" as const },+};++export function RunHistoryList({ runs }: RunHistoryListProps) {+ if (runs.length === 0) {+ return (+ <Card>+ <CardContent className="flex flex-col items-center justify-center py-12">+ <History className="h-12 w-12 text-muted-foreground mb-4" />+ <h3 className="text-lg font-medium">No runs yet</h3>+ <p className="text-muted-foreground text-center mt-2">+ Run history will appear here once the automation runs.+ </p>+ </CardContent>+ </Card>+ );+ }++ return (+ <Card>+ <CardHeader>+ <CardTitle>Run History</CardTitle>+ <CardDescription>+ Recent automation runs and their results+ </CardDescription>+ </CardHeader>+ <CardContent>+ <Table>+ <TableHeader>+ <TableRow>+ <TableHead>Status</TableHead>+ <TableHead>Started</TableHead>+ <TableHead>Duration</TableHead>+ <TableHead className="text-center">Searched</TableHead>+ <TableHead className="text-center">New</TableHead>+ <TableHead className="text-center">Processed</TableHead>+ <TableHead className="text-center">Matched</TableHead>+ <TableHead className="text-center">Saved</TableHead>+ <TableHead>Error</TableHead>+ </TableRow>+ </TableHeader>+ <TableBody>+ {runs.map((run) => {+ const config = STATUS_CONFIG[run.status] || STATUS_CONFIG.failed;+ const StatusIcon = config.icon;+ const duration = run.completedAt+ ? Math.round(+ (new Date(run.completedAt).getTime() - new Date(run.startedAt).getTime()) / 1000+ )+ : null;++ return (+ <TableRow key={run.id}>+ <TableCell>+ <div className="flex items-center gap-2">+ <StatusIcon className={`h-4 w-4 ${config.color}`} />+ <Badge variant={config.variant}>{run.status.replace("_", " ")}</Badge>+ </div>+ </TableCell>+ <TableCell>+ {format(new Date(run.startedAt), "MMM d, h:mm a")}+ </TableCell>+ <TableCell>+ {duration !== null ? `${duration}s` : "-"}+ </TableCell>+ <TableCell className="text-center">{run.jobsSearched}</TableCell>+ <TableCell className="text-center">{run.jobsDeduplicated}</TableCell>+ <TableCell className="text-center">{run.jobsProcessed}</TableCell>+ <TableCell className="text-center">{run.jobsMatched}</TableCell>+ <TableCell className="text-center">+ <span className="font-medium">{run.jobsSaved}</span>+ </TableCell>+ <TableCell>+ {(run.errorMessage || run.blockedReason) && (+ <TooltipProvider>+ <Tooltip>+ <TooltipTrigger>+ <Badge variant="outline" className="max-w-[150px] truncate">+ {run.blockedReason || run.errorMessage}+ </Badge>+ </TooltipTrigger>+ <TooltipContent>+ <p className="max-w-xs">+ {run.blockedReason || run.errorMessage}+ </p>+ </TooltipContent>+ </Tooltip>+ </TooltipProvider>+ )}+ </TableCell>+ </TableRow>+ );+ })}+ </TableBody>+ </Table>+ </CardContent>+ </Card>+ );+}diff --git a/src/components/ui/badge.tsx b/src/components/ui/badge.tsxindex f000e3e..73e8030 100644--- a/src/components/ui/badge.tsx+++ b/src/components/ui/badge.tsx@@ -1,7 +1,7 @@-import * as React from "react"-import { cva, type VariantProps } from "class-variance-authority"+import * as React from "react";+import { cva, type VariantProps } from "class-variance-authority";-import { cn } from "@/lib/utils"+import { cn } from "@/lib/utils";const badgeVariants = cva("inline-flex items-center rounded-full border px-2.5 py-0.5 text-xs font-semibold transition-colors focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2",@@ -20,17 +20,18 @@ const badgeVariants = cva(defaultVariants: {variant: "default",},- }-)+ },+);export interface BadgeProps- extends React.HTMLAttributes<HTMLDivElement>,+ extends+ React.HTMLAttributes<HTMLSpanElement>,VariantProps<typeof badgeVariants> {}function Badge({ className, variant, ...props }: BadgeProps) {return (- <div className={cn(badgeVariants({ variant }), className)} {...props} />- )+ <span className={cn(badgeVariants({ variant }), className)} {...props} />+ );}-export { Badge, badgeVariants }+export { Badge, badgeVariants };diff --git a/src/instrumentation.ts b/src/instrumentation.tsindex 47ae674..6b06111 100644--- a/src/instrumentation.ts+++ b/src/instrumentation.ts@@ -2,5 +2,8 @@ export async function register() {if (process.env.NEXT_RUNTIME === "nodejs") {const { runSeed } = await import("@/lib/seed");await runSeed();++ const { startScheduler } = await import("@/lib/scheduler");+ startScheduler();}}diff --git a/src/lib/automation-logger.ts b/src/lib/automation-logger.tsnew file mode 100644index 0000000..7afc3b0--- /dev/null+++ b/src/lib/automation-logger.ts@@ -0,0 +1,98 @@+export type LogLevel = "info" | "success" | "warning" | "error";++export interface AutomationLog {+ timestamp: Date;+ level: LogLevel;+ message: string;+ metadata?: Record<string, unknown>;+}++export interface LogStore {+ logs: AutomationLog[];+ isRunning: boolean;+ startedAt?: Date;+ completedAt?: Date;+}++class AutomationLoggerService {+ private logStores = new Map<string, LogStore>();+ private readonly MAX_LOGS_PER_RUN = 500;+ private readonly LOG_RETENTION_MS = 1000 * 60 * 60; // 1 hour++ startRun(automationId: string): void {+ console.log(`[Logger] Starting run for automation ${automationId}`);+ this.logStores.set(automationId, {+ logs: [],+ isRunning: true,+ startedAt: new Date(),+ });+ this.log(automationId, "info", "Automation run started");+ console.log(+ `[Logger] Log store initialized with ${this.logStores.get(automationId)?.logs.length} logs`,+ );+ }++ endRun(automationId: string): void {+ const store = this.logStores.get(automationId);+ if (store) {+ store.isRunning = false;+ store.completedAt = new Date();+ this.log(automationId, "info", "Automation run completed");++ // Schedule cleanup after retention period+ setTimeout(() => {+ this.clearLogs(automationId);+ }, this.LOG_RETENTION_MS);+ }+ }++ log(+ automationId: string,+ level: LogLevel,+ message: string,+ metadata?: Record<string, unknown>,+ ): void {+ const store = this.logStores.get(automationId);+ if (!store) {+ console.warn(+ `[Logger] No store found for automation ${automationId}. Log: [${level}] ${message}`,+ );+ return;+ }++ const log: AutomationLog = {+ timestamp: new Date(),+ level,+ message,+ metadata,+ };++ store.logs.push(log);+ console.log(+ `[Logger] Logged [${level}] for ${automationId}: ${message} (total logs: ${store.logs.length})`,+ );++ // Keep only the most recent logs+ if (store.logs.length > this.MAX_LOGS_PER_RUN) {+ store.logs.shift();+ }+ }++ getLogs(automationId: string): AutomationLog[] {+ return this.logStores.get(automationId)?.logs || [];+ }++ getStore(automationId: string): LogStore | undefined {+ return this.logStores.get(automationId);+ }++ clearLogs(automationId: string): void {+ this.logStores.delete(automationId);+ }++ isRunning(automationId: string): boolean {+ return this.logStores.get(automationId)?.isRunning || false;+ }+}++export const automationLogger = new AutomationLoggerService();diff --git a/src/lib/constants.ts b/src/lib/constants.tsindex 4433c6f..ffc4d2d 100644--- a/src/lib/constants.ts+++ b/src/lib/constants.ts@@ -6,6 +6,7 @@ import {UserRound,Sheet,Wrench,+ Zap,} from "lucide-react";export const APP_CONSTANTS = {@@ -15,6 +16,11 @@ export const APP_CONSTANTS = {ACTIVITY_MAX_DURATION_MS: 8 * 60 * 60 * 1000, // 8 hours in milliseconds} as const;+export const SCHEDULER_CONSTANTS = {+ ENABLED: true,+ CRON_EXPRESSION: "0 * * * *", // Every hour at minute 0+} as const;+export const SIDEBAR_LINKS = [{icon: LayoutDashboard,@@ -26,6 +32,11 @@ export const SIDEBAR_LINKS = [route: "/dashboard/myjobs",label: "My Jobs",},+ {+ icon: Zap,+ route: "/dashboard/automations",+ label: "Automations",+ },{icon: SquareCheckBig,route: "/dashboard/tasks",diff --git a/src/lib/scheduler/index.ts b/src/lib/scheduler/index.tsnew file mode 100644index 0000000..1a1b950--- /dev/null+++ b/src/lib/scheduler/index.ts@@ -0,0 +1,110 @@+import cron, { ScheduledTask } from "node-cron";+import { SCHEDULER_CONSTANTS } from "@/lib/constants";+import db from "@/lib/db";+import { runAutomation } from "@/lib/scraper";++let scheduledTask: ScheduledTask | null = null;++async function runDueAutomations() {+ const now = new Date();+ console.log(`[Scheduler] Checking for due automations at ${now.toISOString()}`);++ try {+ const dueAutomations = await db.automation.findMany({+ where: {+ status: "active",+ nextRunAt: { lte: now },+ },+ include: {+ resume: true,+ },+ });++ if (dueAutomations.length === 0) {+ console.log("[Scheduler] No automations due to run");+ return;+ }++ console.log(`[Scheduler] Found ${dueAutomations.length} automation(s) to run`);++ for (const automation of dueAutomations) {+ if (!automation.resume) {+ console.log(`[Scheduler] Skipping automation ${automation.id} - no resume`);+ await db.automationRun.create({+ data: {+ automationId: automation.id,+ status: "failed",+ errorMessage: "resume_missing",+ completedAt: new Date(),+ },+ });+ continue;+ }++ try {+ console.log(`[Scheduler] Running automation: ${automation.name}`);+ const result = await runAutomation({+ id: automation.id,+ userId: automation.userId,+ name: automation.name,+ jobBoard: automation.jobBoard as "jsearch",+ keywords: automation.keywords,+ location: automation.location,+ resumeId: automation.resumeId,+ matchThreshold: automation.matchThreshold,+ scheduleHour: automation.scheduleHour,+ nextRunAt: automation.nextRunAt,+ lastRunAt: automation.lastRunAt,+ status: automation.status as "active" | "paused",+ createdAt: automation.createdAt,+ updatedAt: automation.updatedAt,+ });+ console.log(`[Scheduler] Automation ${automation.name} completed: ${result.status}, saved ${result.jobsSaved} jobs`);+ } catch (error) {+ const message = error instanceof Error ? error.message : "Unknown error";+ console.error(`[Scheduler] Automation ${automation.name} failed:`, message);+ }+ }+ } catch (error) {+ console.error("[Scheduler] Error running due automations:", error);+ }+}++export function startScheduler() {+ if (!SCHEDULER_CONSTANTS.ENABLED) {+ console.log("[Scheduler] Disabled via SCHEDULER_CONSTANTS.ENABLED");+ return;+ }++ if (scheduledTask) {+ console.log("[Scheduler] Already running");+ return;+ }++ const cronExpression = SCHEDULER_CONSTANTS.CRON_EXPRESSION;++ if (!cron.validate(cronExpression)) {+ console.error(`[Scheduler] Invalid cron expression: ${cronExpression}`);+ return;+ }++ console.log(`[Scheduler] Starting with schedule: ${cronExpression}`);++ scheduledTask = cron.schedule(cronExpression, runDueAutomations, {+ timezone: process.env.TZ || "UTC",+ });++ console.log("[Scheduler] Started successfully");+}++export function stopScheduler() {+ if (scheduledTask) {+ scheduledTask.stop();+ scheduledTask = null;+ console.log("[Scheduler] Stopped");+ }+}++export function isSchedulerRunning(): boolean {+ return scheduledTask !== null;+}diff --git a/src/lib/scraper/index.ts b/src/lib/scraper/index.tsnew file mode 100644index 0000000..374ce43--- /dev/null+++ b/src/lib/scraper/index.ts@@ -0,0 +1,6 @@+export * from "./types";+export * from "./utils";+export * from "./mapper";+export * from "./schedule";+export { createJSearchProvider, searchJSearchJobs } from "./jsearch";+export { runAutomation, type RunnerResult } from "./runner";diff --git a/src/lib/scraper/jsearch/index.ts b/src/lib/scraper/jsearch/index.tsnew file mode 100644index 0000000..e26a1d7--- /dev/null+++ b/src/lib/scraper/jsearch/index.ts@@ -0,0 +1,218 @@+import type {+ JobSearchResult,+ JobDetails,+ ScraperResult,+ ScraperService,+} from "../types";++const RAPIDAPI_KEY = process.env.RAPIDAPI_KEY;+const JSEARCH_BASE_URL = "https://jsearch.p.rapidapi.com";++interface JSearchJob {+ job_id: string;+ job_title: string;+ employer_name: string;+ employer_logo: string | null;+ job_publisher: string;+ job_employment_type: string;+ job_apply_link: string;+ job_description: string;+ job_is_remote: boolean;+ job_posted_at_datetime_utc: string;+ job_city: string;+ job_state: string;+ job_country: string;+ job_location: string;+ job_min_salary: number | null;+ job_max_salary: number | null;+ job_salary_period: string | null;+}++interface JSearchResponse {+ status: string;+ request_id: string;+ data: JSearchJob[];+}++export function createJSearchProvider(): ScraperService {+ if (!RAPIDAPI_KEY) {+ throw new Error("RAPIDAPI_KEY environment variable is not set");+ }++ return {+ boardId: "jsearch",+ boardName: "JSearch",++ async search(+ keywords: string,+ location: string,+ ): Promise<ScraperResult<JobSearchResult[]>> {+ try {+ const url = new URL(`${JSEARCH_BASE_URL}/search`);+ url.searchParams.set("query", `${keywords} in ${location}`);+ url.searchParams.set("page", "1");+ url.searchParams.set("num_pages", "1");+ url.searchParams.set("date_posted", "week");++ const response = await fetch(url.toString(), {+ method: "GET",+ headers: {+ "X-RapidAPI-Key": RAPIDAPI_KEY,+ "X-RapidAPI-Host": "jsearch.p.rapidapi.com",+ },+ });+ console.log("JOBS API RESPONSE: ", response);++ if (!response.ok) {+ if (response.status === 429) {+ return {+ success: false,+ error: { type: "rate_limited", retryAfter: 60 },+ };+ }+ if (response.status === 403) {+ return {+ success: false,+ error: {+ type: "blocked",+ reason: "API access denied - check your RapidAPI key",+ },+ };+ }+ return {+ success: false,+ error: {+ type: "network",+ message: `API error: ${response.status} ${response.statusText}`,+ },+ };+ }++ const data: JSearchResponse = await response.json();++ const jobs: JobSearchResult[] = (data.data || []).map((job) => ({+ title: job.job_title,+ company: job.employer_name,+ location: job.job_location || `${job.job_city}, ${job.job_state}`,+ url: job.job_apply_link,+ snippet: job.job_description?.slice(0, 200),+ }));++ return { success: true, data: jobs };+ } catch (error) {+ const message =+ error instanceof Error ? error.message : "Unknown error";+ return { success: false, error: { type: "network", message } };+ }+ },++ async extract(url: string): Promise<ScraperResult<JobDetails>> {+ // JSearch returns full job details in search results+ // This method exists for interface compatibility+ // In practice, we use searchWithDetails instead+ return {+ success: false,+ error: {+ type: "parse",+ message: "Use searchWithDetails for JSearch - extract not supported",+ },+ };+ },++ async close(): Promise<void> {+ // No cleanup needed for API-based provider+ },+ };+}++// Extended search that returns full job details (no separate extract needed)+export async function searchJSearchJobs(+ keywords: string,+ location: string,+): Promise<ScraperResult<JobDetails[]>> {+ if (!RAPIDAPI_KEY) {+ return {+ success: false,+ error: { type: "network", message: "RAPIDAPI_KEY is not configured" },+ };+ }++ try {+ const url = new URL(`${JSEARCH_BASE_URL}/search`);+ url.searchParams.set("query", `${keywords} in ${location}`);+ url.searchParams.set("page", "1");+ url.searchParams.set("num_pages", "1");+ url.searchParams.set("date_posted", "week");++ const response = await fetch(url.toString(), {+ method: "GET",+ headers: {+ "X-RapidAPI-Key": RAPIDAPI_KEY,+ "X-RapidAPI-Host": "jsearch.p.rapidapi.com",+ },+ });++ if (!response.ok) {+ if (response.status === 429) {+ return {+ success: false,+ error: { type: "rate_limited", retryAfter: 60 },+ };+ }+ if (response.status === 403) {+ return {+ success: false,+ error: {+ type: "blocked",+ reason: "API access denied - check your RapidAPI key",+ },+ };+ }+ return {+ success: false,+ error: {+ type: "network",+ message: `API error: ${response.status} ${response.statusText}`,+ },+ };+ }++ const data: JSearchResponse = await response.json();++ const jobs: JobDetails[] = (data.data || []).map((job) => ({+ title: job.job_title,+ company: job.employer_name,+ location: job.job_location || `${job.job_city}, ${job.job_state}`,+ description: job.job_description,+ url: job.job_apply_link,+ postedDate: job.job_posted_at_datetime_utc,+ salary: formatSalary(job),+ }));++ return { success: true, data: jobs };+ } catch (error) {+ const message = error instanceof Error ? error.message : "Unknown error";+ return { success: false, error: { type: "network", message } };+ }+}++function formatSalary(job: JSearchJob): string | undefined {+ if (!job.job_min_salary && !job.job_max_salary) {+ return undefined;+ }++ const min = job.job_min_salary;+ const max = job.job_max_salary;+ const period = job.job_salary_period || "year";++ if (min && max) {+ return `$${min.toLocaleString()} - $${max.toLocaleString()} per ${period}`;+ }+ if (min) {+ return `From $${min.toLocaleString()} per ${period}`;+ }+ if (max) {+ return `Up to $${max.toLocaleString()} per ${period}`;+ }+ return undefined;+}diff --git a/src/lib/scraper/mapper.ts b/src/lib/scraper/mapper.tsnew file mode 100644index 0000000..da4a7fa--- /dev/null+++ b/src/lib/scraper/mapper.ts@@ -0,0 +1,208 @@+import type { ScrapedJobData, DiscoveryStatus } from "@/models/automation.model";+import db from "@/lib/db";+import { normalizeForSearch, extractKeywords, extractCityName } from "./utils";++interface MapperInput {+ scrapedJob: ScrapedJobData;+ userId: string;+ automationId: string;+ matchScore: number;+ matchData: string;+}++interface MapperOutput {+ userId: string;+ automationId: string;+ jobUrl: string;+ description: string;+ jobType: string;+ createdAt: Date;+ applied: boolean;+ statusId: string;+ jobTitleId: string;+ companyId: string;+ jobSourceId: string;+ locationId: string | null;+ matchScore: number;+ matchData: string;+ discoveryStatus: DiscoveryStatus;+ discoveredAt: Date;+}++export async function mapScrapedJobToJobRecord(+ input: MapperInput+): Promise<MapperOutput> {+ const { scrapedJob, userId, automationId, matchScore, matchData } = input;++ const jobTitleId = await findOrCreateJobTitle(scrapedJob.title, userId);+ const locationId = await findOrCreateLocation(scrapedJob.location, userId);+ const companyId = await findOrCreateCompany(scrapedJob.company, userId);+ const jobSourceId = await getOrCreateJobSource(scrapedJob.sourceBoard);+ const statusId = await getDefaultJobStatus();++ return {+ userId,+ automationId,+ jobUrl: scrapedJob.sourceUrl,+ description: scrapedJob.description,+ jobType: "full-time",+ createdAt: new Date(),+ applied: false,+ statusId,+ jobTitleId,+ companyId,+ jobSourceId,+ locationId,+ matchScore,+ matchData,+ discoveryStatus: "new",+ discoveredAt: new Date(),+ };+}++async function findOrCreateJobTitle(+ title: string,+ userId: string+): Promise<string> {+ const normalized = normalizeForSearch(title);++ let existing = await db.jobTitle.findFirst({+ where: { value: normalized },+ });++ if (!existing) {+ const keywords = extractKeywords(title);+ if (keywords.length > 0) {+ existing = await db.jobTitle.findFirst({+ where: {+ OR: keywords.map((keyword) => ({+ value: { contains: keyword },+ })),+ },+ });+ }+ }++ if (existing) {+ return existing.id;+ }++ const newTitle = await db.jobTitle.create({+ data: {+ label: title,+ value: normalized,+ createdBy: userId,+ },+ });+ return newTitle.id;+}++async function findOrCreateLocation(+ location: string,+ userId: string+): Promise<string | null> {+ if (!location) return null;++ const normalized = normalizeForSearch(location);+ const cityName = extractCityName(location);++ let existing = await db.location.findFirst({+ where: {+ value: normalized,+ createdBy: userId,+ },+ });++ if (!existing && cityName) {+ existing = await db.location.findFirst({+ where: {+ createdBy: userId,+ OR: [+ { value: { contains: cityName } },+ { label: { contains: cityName } },+ ],+ },+ });+ }++ if (existing) {+ return existing.id;+ }++ const newLocation = await db.location.create({+ data: {+ label: location,+ value: normalized,+ createdBy: userId,+ },+ });+ return newLocation.id;+}++async function findOrCreateCompany(+ company: string,+ userId: string+): Promise<string> {+ const normalized = normalizeForSearch(company);++ let existing = await db.company.findFirst({+ where: { value: normalized },+ });++ if (!existing) {+ const companyKeywords = extractKeywords(company);+ if (companyKeywords.length > 0) {+ existing = await db.company.findFirst({+ where: {+ OR: companyKeywords.map((keyword) => ({+ label: { contains: keyword },+ })),+ },+ });+ }+ }++ if (existing) {+ return existing.id;+ }++ const newCompany = await db.company.create({+ data: {+ label: company,+ value: normalized,+ createdBy: userId,+ },+ });+ return newCompany.id;+}++async function getOrCreateJobSource(sourceBoard: string): Promise<string> {+ const normalized = sourceBoard.toLowerCase();++ let jobSource = await db.jobSource.findFirst({+ where: { value: normalized },+ });++ if (!jobSource) {+ jobSource = await db.jobSource.create({+ data: {+ label: sourceBoard.charAt(0).toUpperCase() + sourceBoard.slice(1),+ value: normalized,+ },+ });+ }++ return jobSource.id;+}++async function getDefaultJobStatus(): Promise<string> {+ let status = await db.jobStatus.findFirst({ where: { value: "new" } });++ if (!status) {+ status = await db.jobStatus.create({+ data: { label: "New", value: "new" },+ });+ }++ return status.id;+}diff --git a/src/lib/scraper/runner.ts b/src/lib/scraper/runner.tsnew file mode 100644index 0000000..570828e--- /dev/null+++ b/src/lib/scraper/runner.ts@@ -0,0 +1,607 @@+import { generateText, Output } from "ai";+import db from "@/lib/db";+import type {+ Automation,+ AutomationRunStatus,+ ScrapedJobData,+ JobBoard,+} from "@/models/automation.model";+import type { ScraperError, JobDetails } from "./types";+import { searchJSearchJobs } from "./jsearch";+import { mapScrapedJobToJobRecord } from "./mapper";+import { normalizeJobUrl } from "./utils";+import { calculateNextRunAt } from "./schedule";+import {+ getModel,+ JobMatchSchema,+ JOB_MATCH_SYSTEM_PROMPT,+ buildJobMatchPrompt,+} from "@/lib/ai";+import { AiProvider, OllamaModel } from "@/models/ai.model";+import type { Resume as PrismaResume } from "@prisma/client";+import { automationLogger } from "@/lib/automation-logger";++const MAX_JOBS_PER_RUN = 10;++function getErrorMessage(error: ScraperError): string {+ switch (error.type) {+ case "blocked":+ return error.reason;+ case "rate_limited":+ return `Rate limited${error.retryAfter ? ` - retry after ${error.retryAfter}s` : ""}`;+ case "network":+ case "parse":+ return error.message;+ }+}++export interface RunnerResult {+ runId: string;+ status: AutomationRunStatus;+ jobsSearched: number;+ jobsDeduplicated: number;+ jobsProcessed: number;+ jobsMatched: number;+ jobsSaved: number;+ errorMessage?: string;+ blockedReason?: string;+}++interface ResumeWithSections extends PrismaResume {+ ContactInfo: {+ firstName: string;+ lastName: string;+ headline: string;+ email: string;+ phone: string;+ address: string | null;+ } | null;+ ResumeSections: Array<{+ sectionType: string;+ summary?: { content: string } | null;+ workExperiences: Array<{+ description: string;+ startDate: Date;+ endDate: Date | null;+ Company: { label: string };+ jobTitle: { label: string };+ location: { label: string };+ }>;+ educations: Array<{+ institution: string;+ degree: string;+ fieldOfStudy: string;+ startDate: Date;+ endDate: Date | null;+ description: string | null;+ location: { label: string };+ }>;+ }>;+}++export async function runAutomation(+ automation: Automation,+): Promise<RunnerResult> {+ console.log(`[Automation ${automation.id}] Starting automation run`);+ automationLogger.startRun(automation.id);++ const run = await db.automationRun.create({+ data: {+ automationId: automation.id,+ status: "running",+ },+ });++ console.log(`[Automation ${automation.id}] Created run with ID: ${run.id}`);+ automationLogger.log(+ automation.id,+ "info",+ `Created automation run with ID: ${run.id}`,+ );++ try {+ automationLogger.log(automation.id, "info", "Fetching resume data...");++ const resume = await db.resume.findUnique({+ where: { id: automation.resumeId },+ include: {+ ContactInfo: true,+ ResumeSections: {+ include: {+ summary: true,+ workExperiences: {+ include: {+ Company: true,+ jobTitle: true,+ location: true,+ },+ },+ educations: {+ include: {+ location: true,+ },+ },+ },+ },+ },+ });++ if (!resume) {+ automationLogger.log(+ automation.id,+ "error",+ "Resume not found or missing",+ );+ automationLogger.endRun(automation.id);++ return await finalizeRun(run.id, {+ status: "failed",+ errorMessage: "resume_missing",+ jobsSearched: 0,+ jobsDeduplicated: 0,+ jobsProcessed: 0,+ jobsMatched: 0,+ jobsSaved: 0,+ });+ }++ automationLogger.log(+ automation.id,+ "success",+ `Resume loaded: ${resume.title}`,+ );++ automationLogger.log(+ automation.id,+ "info",+ `Searching for jobs: "${automation.keywords}" in ${automation.location}`,+ );++ // Use JSearch API+ const searchResult = await searchJSearchJobs(+ automation.keywords,+ automation.location,+ );++ if (!searchResult.success) {+ automationLogger.log(+ automation.id,+ "error",+ `Search failed: ${searchResult.error.type} - ${getErrorMessage(searchResult.error)}`,+ );+ automationLogger.endRun(automation.id);++ const status = getStatusFromError(searchResult.error);+ return await finalizeRun(run.id, {+ status,+ errorMessage:+ searchResult.error.type === "network"+ ? searchResult.error.message+ : undefined,+ blockedReason:+ searchResult.error.type === "blocked"+ ? searchResult.error.reason+ : undefined,+ jobsSearched: 0,+ jobsDeduplicated: 0,+ jobsProcessed: 0,+ jobsMatched: 0,+ jobsSaved: 0,+ });+ }++ const jobsSearched = searchResult.data.length;++ automationLogger.log(+ automation.id,+ "success",+ `Found ${jobsSearched} jobs from JSearch API`,+ { jobsSearched },+ );++ if (jobsSearched === 0) {+ automationLogger.log(+ automation.id,+ "warning",+ "No jobs found matching search criteria",+ );+ automationLogger.endRun(automation.id);++ return await finalizeRun(run.id, {+ status: "completed",+ jobsSearched: 0,+ jobsDeduplicated: 0,+ jobsProcessed: 0,+ jobsMatched: 0,+ jobsSaved: 0,+ });+ }++ automationLogger.log(+ automation.id,+ "info",+ "Checking for duplicate jobs...",+ );++ const existingJobUrls = await getExistingJobUrls(automation.userId);+ const newJobs = searchResult.data.filter(+ (job) => !existingJobUrls.has(normalizeJobUrl(job.url)),+ );+ const jobsDeduplicated = newJobs.length;++ automationLogger.log(+ automation.id,+ "info",+ `Filtered to ${jobsDeduplicated} new jobs (${jobsSearched - jobsDeduplicated} duplicates removed)`,+ { jobsDeduplicated, duplicates: jobsSearched - jobsDeduplicated },+ );++ const jobsToProcess = newJobs.slice(0, MAX_JOBS_PER_RUN);++ if (jobsToProcess.length < newJobs.length) {+ automationLogger.log(+ automation.id,+ "info",+ `Processing first ${jobsToProcess.length} of ${newJobs.length} new jobs (limit: ${MAX_JOBS_PER_RUN})`,+ );+ }++ let jobsProcessed = 0;+ let jobsMatched = 0;+ let jobsSaved = 0;+ let aiError: string | null = null;++ // JSearch returns full job details, no separate extraction needed+ for (const job of jobsToProcess) {+ automationLogger.log(+ automation.id,+ "info",+ `Processing: ${job.title} at ${job.company}`,+ );++ jobsProcessed++;++ automationLogger.log(+ automation.id,+ "info",+ `Analyzing job match for: ${job.title}`,+ );++ const matchResult = await matchJobToResume(+ job,+ resume as ResumeWithSections,+ automation.jobBoard as JobBoard,+ );++ if (!matchResult.success) {+ if (matchResult.error === "ollama_unavailable") {+ aiError =+ "Ollama is not running. Please start Ollama and try again.";+ automationLogger.log(automation.id, "error", aiError);+ break;+ }+ automationLogger.log(+ automation.id,+ "warning",+ `AI matching failed: ${matchResult.error}`,+ );+ continue;+ }++ automationLogger.log(+ automation.id,+ "info",+ `Match score: ${matchResult.score}% (threshold: ${automation.matchThreshold}%)`,+ { score: matchResult.score, threshold: automation.matchThreshold },+ );++ if (matchResult.score < automation.matchThreshold) {+ automationLogger.log(+ automation.id,+ "info",+ `Job skipped - score below threshold`,+ );+ continue;+ }++ jobsMatched++;++ automationLogger.log(+ automation.id,+ "success",+ `Job matched! Saving to database...`,+ {+ title: job.title,+ company: job.company,+ },+ );++ try {+ const scrapedJob: ScrapedJobData = {+ title: job.title,+ company: job.company,+ location: job.location,+ description: job.description,+ sourceUrl: normalizeJobUrl(job.url),+ sourceBoard: automation.jobBoard as JobBoard,+ };++ const jobRecord = await mapScrapedJobToJobRecord({+ scrapedJob,+ userId: automation.userId,+ automationId: automation.id,+ matchScore: matchResult.score,+ matchData: JSON.stringify(matchResult.data),+ });++ await db.job.create({ data: jobRecord });+ jobsSaved++;++ automationLogger.log(+ automation.id,+ "success",+ `Job saved successfully (${jobsSaved} total)`,+ { jobsSaved },+ );+ } catch (err) {+ const errorMsg = err instanceof Error ? err.message : "Unknown error";+ automationLogger.log(+ automation.id,+ "error",+ `Failed to save job: ${errorMsg}`,+ );+ console.error("Failed to save job:", err);+ }+ }++ const finalStatus: AutomationRunStatus = aiError+ ? "failed"+ : jobsProcessed < jobsToProcess.length+ ? "completed_with_errors"+ : "completed";++ automationLogger.log(+ automation.id,+ finalStatus === "completed"+ ? "success"+ : finalStatus === "failed"+ ? "error"+ : "warning",+ `Run finished with status: ${finalStatus}`,+ {+ status: finalStatus,+ jobsSearched,+ jobsDeduplicated,+ jobsProcessed,+ jobsMatched,+ jobsSaved,+ },+ );++ automationLogger.endRun(automation.id);++ return await finalizeRun(run.id, {+ status: finalStatus,+ errorMessage: aiError || undefined,+ jobsSearched,+ jobsDeduplicated,+ jobsProcessed,+ jobsMatched,+ jobsSaved,+ });+ } catch (error) {+ const message = error instanceof Error ? error.message : "Unknown error";+ automationLogger.log(+ automation.id,+ "error",+ `Automation run failed: ${message}`,+ );+ automationLogger.endRun(automation.id);++ console.error("Automation run failed:", error);+ return await finalizeRun(run.id, {+ status: "failed",+ errorMessage: message,+ jobsSearched: 0,+ jobsDeduplicated: 0,+ jobsProcessed: 0,+ jobsMatched: 0,+ jobsSaved: 0,+ });+ }+}++async function getExistingJobUrls(userId: string): Promise<Set<string>> {+ const existingJobs = await db.job.findMany({+ where: { userId },+ select: { jobUrl: true },+ });++ const urls = new Set<string>();+ for (const job of existingJobs) {+ if (job.jobUrl) {+ urls.add(normalizeJobUrl(job.jobUrl));+ }+ }+ return urls;+}++interface MatchResult {+ success: boolean;+ score: number;+ data?: object;+ error?: string;+}++async function matchJobToResume(+ job: JobDetails,+ resume: ResumeWithSections,+ sourceBoard: JobBoard,+): Promise<MatchResult> {+ try {+ const resumeText = await convertResumeForMatch(resume);+ const jobText = `+Title: ${job.title}+Company: ${job.company}+Location: ${job.location}+${job.salary ? `Salary: ${job.salary}` : ""}++Description:+${job.description}+`.trim();++ const model = getModel(AiProvider.OLLAMA, OllamaModel.LLAMA3_2);++ const result = await generateText({+ model,+ output: Output.object({+ schema: JobMatchSchema,+ }),+ system: JOB_MATCH_SYSTEM_PROMPT,+ prompt: buildJobMatchPrompt(resumeText, jobText),+ temperature: 0.3,+ });++ const matchData = result.experimental_output;+ if (!matchData) {+ return { success: false, score: 0, error: "No match data returned" };+ }++ return {+ success: true,+ score: matchData.matchScore,+ data: matchData,+ };+ } catch (error) {+ const message =+ error instanceof Error ? error.message : "AI matching failed";+ console.error("AI matching error:", message);++ if (+ message.includes("ECONNREFUSED") ||+ message.includes("fetch failed") ||+ message.includes("network") ||+ message.includes("Failed to fetch")+ ) {+ return { success: false, score: 0, error: "ollama_unavailable" };+ }++ return { success: false, score: 0, error: message };+ }+}++async function convertResumeForMatch(+ resume: ResumeWithSections,+): Promise<string> {+ const parts: string[] = [`# ${resume.title}`];++ if (resume.ContactInfo) {+ const contact = resume.ContactInfo;+ parts.push(+ "## CONTACT",+ `Name: ${contact.firstName} ${contact.lastName}`,+ contact.headline ? `Headline: ${contact.headline}` : "",+ contact.email ? `Email: ${contact.email}` : "",+ contact.phone ? `Phone: ${contact.phone}` : "",+ );+ }++ for (const section of resume.ResumeSections) {+ if (section.sectionType === "summary" && section.summary?.content) {+ parts.push("## SUMMARY", section.summary.content);+ }++ if (+ section.sectionType === "experience" &&+ section.workExperiences.length > 0+ ) {+ parts.push("## EXPERIENCE");+ for (const exp of section.workExperiences) {+ parts.push(+ `Company: ${exp.Company.label}`,+ `Job Title: ${exp.jobTitle.label}`,+ `Location: ${exp.location.label}`,+ `Description: ${exp.description}`,+ "",+ );+ }+ }++ if (section.sectionType === "education" && section.educations.length > 0) {+ parts.push("## EDUCATION");+ for (const edu of section.educations) {+ parts.push(+ `Institution: ${edu.institution}`,+ `Degree: ${edu.degree}`,+ `Field: ${edu.fieldOfStudy}`,+ edu.description ? `Description: ${edu.description}` : "",+ "",+ );+ }+ }+ }++ return parts.filter(Boolean).join("\n");+}++function getStatusFromError(error: ScraperError): AutomationRunStatus {+ switch (error.type) {+ case "blocked":+ return "blocked";+ case "rate_limited":+ return "rate_limited";+ default:+ return "failed";+ }+}++interface FinalizeData {+ status: AutomationRunStatus;+ errorMessage?: string;+ blockedReason?: string;+ jobsSearched: number;+ jobsDeduplicated: number;+ jobsProcessed: number;+ jobsMatched: number;+ jobsSaved: number;+}++async function finalizeRun(+ runId: string,+ data: FinalizeData,+): Promise<RunnerResult> {+ const run = await db.automationRun.update({+ where: { id: runId },+ data: {+ status: data.status,+ errorMessage: data.errorMessage,+ blockedReason: data.blockedReason,+ jobsSearched: data.jobsSearched,+ jobsDeduplicated: data.jobsDeduplicated,+ jobsProcessed: data.jobsProcessed,+ jobsMatched: data.jobsMatched,+ jobsSaved: data.jobsSaved,+ completedAt: new Date(),+ },+ });++ await db.automation.update({+ where: { id: run.automationId },+ data: {+ lastRunAt: new Date(),+ nextRunAt: calculateNextRunAt(+ (+ await db.automation.findUnique({+ where: { id: run.automationId },+ select: { scheduleHour: true },+ })+ )?.scheduleHour || 8,+ ),+ },+ });++ return {+ runId: run.id,+ ...data,+ };+}diff --git a/src/lib/scraper/schedule.ts b/src/lib/scraper/schedule.tsnew file mode 100644index 0000000..73036f4--- /dev/null+++ b/src/lib/scraper/schedule.ts@@ -0,0 +1,17 @@+export function calculateNextRunAt(scheduleHour: number): Date {+ const now = new Date();+ const next = new Date();++ next.setHours(scheduleHour, 0, 0, 0);++ if (next <= now) {+ next.setDate(next.getDate() + 1);+ }++ return next;+}++export function isAutomationDue(nextRunAt: Date | null): boolean {+ if (!nextRunAt) return false;+ return new Date() >= nextRunAt;+}diff --git a/src/lib/scraper/types.ts b/src/lib/scraper/types.tsnew file mode 100644index 0000000..1b51002--- /dev/null+++ b/src/lib/scraper/types.ts@@ -0,0 +1,38 @@+export interface JobSearchResult {+ title: string;+ company: string;+ location: string;+ url: string;+ snippet?: string;+}++export interface JobDetails {+ title: string;+ company: string;+ location: string;+ description: string;+ url: string;+ postedDate?: string;+ salary?: string;+}++export type ScraperError =+ | { type: "blocked"; reason: string }+ | { type: "rate_limited"; retryAfter?: number }+ | { type: "network"; message: string }+ | { type: "parse"; message: string };++export type ScraperResult<T> =+ | { success: true; data: T }+ | { success: false; error: ScraperError };++export interface ScraperService {+ readonly boardId: string;+ readonly boardName: string;+ search(+ keywords: string,+ location: string,+ ): Promise<ScraperResult<JobSearchResult[]>>;+ extract(url: string): Promise<ScraperResult<JobDetails>>;+ close(): Promise<void>;+}diff --git a/src/lib/scraper/utils.ts b/src/lib/scraper/utils.tsnew file mode 100644index 0000000..51b0ae4--- /dev/null+++ b/src/lib/scraper/utils.ts@@ -0,0 +1,67 @@+const TRACKING_PARAMS = [+ "utm_source",+ "utm_medium",+ "utm_campaign",+ "utm_term",+ "utm_content",+ "ref",+ "source",+ "fbclid",+ "gclid",+ "msclkid",+ "tk",+ "from",+ "vjk",+];++export function normalizeJobUrl(url: string): string {+ try {+ const parsed = new URL(url);+ TRACKING_PARAMS.forEach((param) => {+ parsed.searchParams.delete(param);+ });+ return parsed.toString();+ } catch {+ return url;+ }+}++export function normalizeForSearch(str: string): string {+ return str+ .toLowerCase()+ .trim()+ .replace(/\s+/g, "-")+ .replace(/[^a-z0-9-]/g, "");+}++const STOP_WORDS = [+ "senior",+ "jr",+ "junior",+ "sr",+ "inc",+ "llc",+ "ltd",+ "corp",+ "corporation",+ "the",+ "a",+ "an",+ "co",+ "company",+];++export function extractKeywords(str: string): string[] {+ return str+ .toLowerCase()+ .split(/[\s\-_,\.]+/)+ .filter((word) => word.length > 2 && !STOP_WORDS.includes(word));+}++export function extractCityName(location: string): string | null {+ const parts = location.split(",");+ if (parts.length > 0) {+ return parts[0].trim().toLowerCase();+ }+ return null;+}diff --git a/src/models/automation.model.ts b/src/models/automation.model.tsnew file mode 100644index 0000000..04eec19--- /dev/null+++ b/src/models/automation.model.ts@@ -0,0 +1,84 @@+// Automation types and interfaces++export type AutomationStatus = "active" | "paused";+export type AutomationRunStatus =+ | "running"+ | "completed"+ | "failed"+ | "completed_with_errors"+ | "blocked"+ | "rate_limited";+export type DiscoveryStatus = "new" | "accepted" | "dismissed";+export type JobBoard = "jsearch";++export interface Automation {+ id: string;+ userId: string;+ name: string;+ jobBoard: JobBoard;+ keywords: string;+ location: string;+ resumeId: string;+ matchThreshold: number;+ scheduleHour: number;+ nextRunAt: Date | null;+ lastRunAt: Date | null;+ status: AutomationStatus;+ createdAt: Date;+ updatedAt: Date;+}++export interface AutomationWithResume extends Automation {+ resume: {+ id: string;+ title: string;+ };+}++export interface AutomationRun {+ id: string;+ automationId: string;+ jobsSearched: number;+ jobsDeduplicated: number;+ jobsProcessed: number;+ jobsMatched: number;+ jobsSaved: number;+ status: AutomationRunStatus;+ errorMessage: string | null;+ blockedReason: string | null;+ startedAt: Date;+ completedAt: Date | null;+}++export interface DiscoveredJob {+ id: string;+ userId: string;+ automationId: string;+ automation?: {+ id: string;+ name: string;+ };+ jobUrl: string | null;+ description: string;+ jobType: string;+ createdAt: Date;+ jobTitleId: string;+ companyId: string;+ locationId: string | null;+ matchScore: number;+ matchData: string | null;+ discoveryStatus: DiscoveryStatus;+ discoveredAt: Date;+ JobTitle: { label: string };+ Company: { label: string };+ Location?: { label: string } | null;+}++export interface ScrapedJobData {+ title: string;+ company: string;+ location: string;+ description: string;+ sourceUrl: string;+ sourceBoard: JobBoard;+}diff --git a/src/models/automation.schema.ts b/src/models/automation.schema.tsnew file mode 100644index 0000000..f2b3e01--- /dev/null+++ b/src/models/automation.schema.ts@@ -0,0 +1,31 @@+import { z } from "zod";++export const JobBoardSchema = z.enum(["jsearch"]);++export const AutomationStatusSchema = z.enum(["active", "paused"]);++export const AutomationRunStatusSchema = z.enum([+ "running",+ "completed",+ "failed",+ "completed_with_errors",+ "blocked",+ "rate_limited",+]);++export const DiscoveryStatusSchema = z.enum(["new", "accepted", "dismissed"]);++export const CreateAutomationSchema = z.object({+ name: z.string().min(1, "Name is required").max(100),+ jobBoard: JobBoardSchema,+ keywords: z.string().min(1, "Keywords are required").max(200),+ location: z.string().min(1, "Location is required").max(100),+ resumeId: z.string().uuid("Invalid resume"),+ matchThreshold: z.number().min(0).max(100),+ scheduleHour: z.number().min(0).max(23),+});++export const UpdateAutomationSchema = CreateAutomationSchema.partial();++export type CreateAutomationInput = z.infer<typeof CreateAutomationSchema>;+export type UpdateAutomationInput = z.infer<typeof UpdateAutomationSchema>;