release: 2026-08-01
This commit is contained in:
@@ -0,0 +1,124 @@
|
||||
import type { NextApiRequest, NextApiResponse } from "next";
|
||||
import { getDb } from "@/lib/db";
|
||||
import { randomUUID } from "crypto";
|
||||
|
||||
export default function handler(req: NextApiRequest, res: NextApiResponse) {
|
||||
if (req.method !== "POST") {
|
||||
res.setHeader("Allow", ["POST"]);
|
||||
return res.status(405).end();
|
||||
}
|
||||
|
||||
const db = getDb();
|
||||
const runId = req.query.id as string;
|
||||
const { target_ids } = req.body as { target_ids?: string[] };
|
||||
|
||||
if (!Array.isArray(target_ids) || target_ids.length === 0) {
|
||||
return res.status(400).json({ error: "target_ids required" });
|
||||
}
|
||||
|
||||
const run = db
|
||||
.prepare("SELECT id, workflow_id FROM runs WHERE id = ?")
|
||||
.get(runId) as { id: string; workflow_id: string } | undefined;
|
||||
if (!run) return res.status(404).json({ error: "run_not_found" });
|
||||
|
||||
// Tracks defined on this workflow
|
||||
const workflowTracks = [...new Set(
|
||||
(db.prepare("SELECT DISTINCT track FROM workflow_steps WHERE workflow_id = ?").all(run.workflow_id) as { track: string }[]).map((r) => r.track)
|
||||
)];
|
||||
if (workflowTracks.length === 0) workflowTracks.push("linkedin");
|
||||
|
||||
// Existing email-account pool for this run (used as round-robin pool for new enrollments)
|
||||
const emailAccountPool: string[] = (db
|
||||
.prepare(
|
||||
`SELECT DISTINCT email_account_id FROM run_profiles
|
||||
WHERE run_id = ? AND email_account_id IS NOT NULL`
|
||||
)
|
||||
.all(runId) as Array<{ email_account_id: string }>).map((r) => r.email_account_id);
|
||||
|
||||
// Dedup: already enrolled in this workflow at all
|
||||
const alreadyEnrolled = new Set(
|
||||
(db
|
||||
.prepare(
|
||||
`SELECT DISTINCT rp.target_id FROM run_profiles rp
|
||||
JOIN runs r ON r.id = rp.run_id
|
||||
WHERE r.workflow_id = ?`
|
||||
)
|
||||
.all(run.workflow_id) as { target_id: string }[]).map((r) => r.target_id)
|
||||
);
|
||||
|
||||
// Active elsewhere (in some other running/paused run with an in-progress track)
|
||||
const activeElsewhere = new Set(
|
||||
(db
|
||||
.prepare(
|
||||
`SELECT DISTINCT rp.target_id FROM run_profiles rp
|
||||
JOIN runs r ON r.id = rp.run_id
|
||||
WHERE r.status IN ('running', 'paused')
|
||||
AND EXISTS (
|
||||
SELECT 1 FROM run_profile_tracks rt
|
||||
WHERE rt.run_profile_id = rp.id AND rt.state NOT IN ('completed', 'failed', 'skipped')
|
||||
)`
|
||||
)
|
||||
.all() as { target_id: string }[]).map((r) => r.target_id)
|
||||
);
|
||||
|
||||
let skipped_already_enrolled = 0;
|
||||
let skipped_active_elsewhere = 0;
|
||||
const eligible: string[] = [];
|
||||
for (const tid of target_ids) {
|
||||
if (alreadyEnrolled.has(tid)) { skipped_already_enrolled++; continue; }
|
||||
if (activeElsewhere.has(tid)) { skipped_active_elsewhere++; continue; }
|
||||
eligible.push(tid);
|
||||
}
|
||||
|
||||
if (eligible.length === 0) {
|
||||
return res.json({ enrolled: 0, skipped_already_enrolled, skipped_active_elsewhere });
|
||||
}
|
||||
|
||||
// Assign email accounts: company-grouped round-robin (same as run creation)
|
||||
const emailAssignment = new Map<string, string | null>();
|
||||
if (emailAccountPool.length > 0) {
|
||||
const placeholders = eligible.map(() => "?").join(",");
|
||||
const companyRows = db
|
||||
.prepare(`SELECT id, company_id FROM targets WHERE id IN (${placeholders})`)
|
||||
.all(...eligible) as { id: string; company_id: string | null }[];
|
||||
const companyAccountMap = new Map<string, string>();
|
||||
let cursor = 0;
|
||||
for (const row of companyRows) {
|
||||
if (row.company_id) {
|
||||
if (!companyAccountMap.has(row.company_id)) {
|
||||
companyAccountMap.set(row.company_id, emailAccountPool[cursor % emailAccountPool.length]);
|
||||
cursor++;
|
||||
}
|
||||
emailAssignment.set(row.id, companyAccountMap.get(row.company_id)!);
|
||||
} else {
|
||||
emailAssignment.set(row.id, emailAccountPool[cursor % emailAccountPool.length]);
|
||||
cursor++;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const insertProfile = db.prepare(
|
||||
"INSERT INTO run_profiles (id, run_id, target_id, email_account_id) VALUES (?, ?, ?, ?)"
|
||||
);
|
||||
const insertTrack = db.prepare(
|
||||
"INSERT INTO run_profile_tracks (id, run_profile_id, track, state, current_step) VALUES (?, ?, ?, 'pending', 0)"
|
||||
);
|
||||
const insertMany = db.transaction((ids: string[]) => {
|
||||
for (const tid of ids) {
|
||||
const assignedEmailAccountId = emailAssignment.get(tid) ?? null;
|
||||
const rpId = randomUUID();
|
||||
insertProfile.run(rpId, runId, tid, assignedEmailAccountId);
|
||||
for (const track of workflowTracks) {
|
||||
if (track === "email" && !assignedEmailAccountId) continue;
|
||||
insertTrack.run(randomUUID(), rpId, track);
|
||||
}
|
||||
}
|
||||
});
|
||||
insertMany(eligible);
|
||||
|
||||
return res.json({
|
||||
enrolled: eligible.length,
|
||||
skipped_already_enrolled,
|
||||
skipped_active_elsewhere,
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
import type { NextApiRequest, NextApiResponse } from "next";
|
||||
import { getDb } from "@/lib/db";
|
||||
|
||||
export default function handler(req: NextApiRequest, res: NextApiResponse) {
|
||||
const db = getDb();
|
||||
const id = req.query.id as string;
|
||||
|
||||
if (req.method === "GET") {
|
||||
const run = db
|
||||
.prepare(
|
||||
`SELECT r.*,
|
||||
w.name as workflow_name,
|
||||
l.name as list_name,
|
||||
a.name as account_name
|
||||
FROM runs r
|
||||
LEFT JOIN workflows w ON w.id = r.workflow_id
|
||||
LEFT JOIN lists l ON l.id = r.list_id
|
||||
LEFT JOIN accounts a ON a.id = r.account_id
|
||||
WHERE r.id = ?`
|
||||
)
|
||||
.get(id);
|
||||
if (!run) return res.status(404).json({ error: "not found" });
|
||||
|
||||
// Paging + optional target_id filter — a run can hold hundreds of profiles, so callers
|
||||
// (incl. the MCP) can page or pull a single contact instead of the whole set.
|
||||
const targetId = req.query.target_id as string | undefined;
|
||||
const hasPaging = req.query.limit !== undefined || req.query.page !== undefined;
|
||||
const limit = Math.min(Math.max(Number(req.query.limit) || 50, 1), 500);
|
||||
const offset = (Number(req.query.page) || 0) * limit;
|
||||
|
||||
const profileWhere = targetId ? "rp.run_id = ? AND rp.target_id = ?" : "rp.run_id = ?";
|
||||
const profileArgs: unknown[] = targetId ? [id, targetId] : [id];
|
||||
const profilesTotal = (db.prepare(
|
||||
`SELECT COUNT(*) as c FROM run_profiles rp WHERE ${profileWhere}`
|
||||
).get(...profileArgs) as { c: number }).c;
|
||||
|
||||
const pageClause = (targetId || hasPaging) ? " LIMIT ? OFFSET ?" : "";
|
||||
const pageArgs = (targetId || hasPaging) ? [limit, offset] : [];
|
||||
|
||||
const profiles = db
|
||||
.prepare(
|
||||
`SELECT rp.id, rp.run_id, rp.target_id, rp.email_account_id, rp.created_at,
|
||||
COALESCE(rt_li.state, 'pending') as state,
|
||||
COALESCE(rt_li.current_step, 0) as current_step,
|
||||
rt_li.next_step_at, rt_li.error_message,
|
||||
rt_email.state as email_state,
|
||||
rt_email.current_step as email_current_step,
|
||||
t.full_name, t.linkedin_url, t.title, t.company
|
||||
FROM run_profiles rp
|
||||
LEFT JOIN targets t ON t.id = rp.target_id
|
||||
LEFT JOIN run_profile_tracks rt_li ON rt_li.run_profile_id = rp.id AND rt_li.track = 'linkedin'
|
||||
LEFT JOIN run_profile_tracks rt_email ON rt_email.run_profile_id = rp.id AND rt_email.track = 'email'
|
||||
WHERE ${profileWhere}
|
||||
ORDER BY rp.id${pageClause}`
|
||||
)
|
||||
.all(...profileArgs, ...pageArgs);
|
||||
|
||||
const logs = db
|
||||
.prepare(
|
||||
`SELECT lg.*, t.full_name as target_name
|
||||
FROM logs lg
|
||||
LEFT JOIN targets t ON t.id = lg.target_id
|
||||
WHERE lg.run_id = ?
|
||||
ORDER BY lg.created_at DESC
|
||||
LIMIT 100`
|
||||
)
|
||||
.all(id);
|
||||
|
||||
return res.json({ ...run as object, profiles, profiles_total: profilesTotal, logs });
|
||||
}
|
||||
|
||||
if (req.method === "PATCH") {
|
||||
const { status } = req.body;
|
||||
if (!status) return res.status(400).json({ error: "status required" });
|
||||
db.prepare("UPDATE runs SET status = ? WHERE id = ?").run(status, id);
|
||||
return res.json({ ok: true });
|
||||
}
|
||||
|
||||
if (req.method === "DELETE") {
|
||||
db.prepare("DELETE FROM runs WHERE id = ?").run(id);
|
||||
return res.json({ ok: true });
|
||||
}
|
||||
|
||||
res.status(405).end();
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
import type { NextApiRequest, NextApiResponse } from "next";
|
||||
import { getDb } from "@/lib/db";
|
||||
|
||||
export default function handler(req: NextApiRequest, res: NextApiResponse) {
|
||||
if (req.method !== "POST") return res.status(405).end();
|
||||
|
||||
const db = getDb();
|
||||
const runId = req.query.id as string;
|
||||
const { target_ids } = req.body as { target_ids: string[] };
|
||||
|
||||
if (!target_ids?.length) return res.status(400).json({ error: "target_ids required" });
|
||||
|
||||
const placeholders = target_ids.map(() => "?").join(",");
|
||||
const result = db
|
||||
.prepare(
|
||||
`DELETE FROM run_profiles
|
||||
WHERE run_id = ? AND target_id IN (${placeholders})`
|
||||
)
|
||||
.run(runId, ...target_ids);
|
||||
|
||||
return res.json({ ok: true, removed: result.changes });
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
import type { NextApiRequest, NextApiResponse } from "next";
|
||||
import { getDb } from "@/lib/db";
|
||||
|
||||
export default function handler(req: NextApiRequest, res: NextApiResponse) {
|
||||
if (req.method !== "POST") return res.status(405).end();
|
||||
|
||||
const db = getDb();
|
||||
const runId = req.query.id as string;
|
||||
const { target_ids } = req.body as { target_ids: string[] };
|
||||
|
||||
if (!target_ids?.length) return res.status(400).json({ error: "target_ids required" });
|
||||
|
||||
const placeholders = target_ids.map(() => "?").join(",");
|
||||
// Retry: reset all failed track-runs for these profiles back to in_progress
|
||||
const rpRows = db.prepare(
|
||||
`SELECT id FROM run_profiles WHERE run_id = ? AND target_id IN (${placeholders})`
|
||||
).all(runId, ...target_ids) as { id: string }[];
|
||||
|
||||
let retried = 0;
|
||||
for (const rp of rpRows) {
|
||||
const r = db.prepare(
|
||||
`UPDATE run_profile_tracks SET state = 'in_progress', error_message = NULL, next_step_at = NULL
|
||||
WHERE run_profile_id = ? AND state = 'failed'`
|
||||
).run(rp.id);
|
||||
retried += r.changes;
|
||||
}
|
||||
|
||||
return res.json({ ok: true, retried });
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
import type { NextApiRequest, NextApiResponse } from "next";
|
||||
import { getDb } from "@/lib/db";
|
||||
import { ensureGlobalRunnerStarted } from "@/lib/linkedin/runner";
|
||||
|
||||
export default function handler(req: NextApiRequest, res: NextApiResponse) {
|
||||
if (req.method !== "POST") return res.status(405).end();
|
||||
|
||||
const db = getDb();
|
||||
const id = req.query.id as string;
|
||||
|
||||
const run = db.prepare("SELECT status FROM runs WHERE id = ?").get(id) as { status: string } | undefined;
|
||||
if (!run) return res.status(404).json({ error: "Run not found" });
|
||||
if (run.status === "running") return res.status(400).json({ error: "Run already running" });
|
||||
|
||||
db.prepare(
|
||||
"UPDATE runs SET status = 'running', started_at = COALESCE(started_at, datetime('now')) WHERE id = ?"
|
||||
).run(id);
|
||||
|
||||
ensureGlobalRunnerStarted();
|
||||
|
||||
return res.json({ ok: true });
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
import type { NextApiRequest, NextApiResponse } from "next";
|
||||
import { getDb } from "@/lib/db";
|
||||
|
||||
export default function handler(req: NextApiRequest, res: NextApiResponse) {
|
||||
if (req.method !== "POST") return res.status(405).end();
|
||||
|
||||
const db = getDb();
|
||||
const runId = req.query.id as string;
|
||||
const { target_id } = req.body as { target_id: string };
|
||||
|
||||
if (!target_id) return res.status(400).json({ error: "target_id required" });
|
||||
|
||||
// Unenroll: mark all track-runs for this profile as skipped
|
||||
const rp = db.prepare(
|
||||
"SELECT id FROM run_profiles WHERE run_id = ? AND target_id = ?"
|
||||
).get(runId, target_id) as { id: string } | undefined;
|
||||
|
||||
if (!rp) return res.status(404).json({ error: "Profile not found" });
|
||||
|
||||
const result = db.prepare(
|
||||
`UPDATE run_profile_tracks SET state = 'skipped', error_message = 'Manually unenrolled'
|
||||
WHERE run_profile_id = ? AND state IN ('pending', 'in_progress')`
|
||||
).run(rp.id);
|
||||
|
||||
if (result.changes === 0) {
|
||||
return res.status(404).json({ error: "Profile not found or already completed/skipped" });
|
||||
}
|
||||
|
||||
return res.json({ ok: true });
|
||||
}
|
||||
@@ -0,0 +1,160 @@
|
||||
import type { NextApiRequest, NextApiResponse } from "next";
|
||||
import { getDb } from "@/lib/db";
|
||||
import { randomUUID } from "crypto";
|
||||
|
||||
export default function handler(req: NextApiRequest, res: NextApiResponse) {
|
||||
const db = getDb();
|
||||
|
||||
if (req.method === "GET") {
|
||||
const runs = db
|
||||
.prepare(
|
||||
`SELECT r.*,
|
||||
w.name as workflow_name,
|
||||
l.name as list_name,
|
||||
a.name as account_name,
|
||||
COUNT(DISTINCT rp.id) as total_profiles,
|
||||
COUNT(DISTINCT CASE WHEN NOT EXISTS (
|
||||
SELECT 1 FROM run_profile_tracks rt2
|
||||
WHERE rt2.run_profile_id = rp.id AND rt2.state NOT IN ('completed', 'failed', 'skipped')
|
||||
) AND EXISTS (
|
||||
SELECT 1 FROM run_profile_tracks rt3
|
||||
WHERE rt3.run_profile_id = rp.id AND rt3.state = 'completed'
|
||||
) THEN rp.id END) as completed_profiles
|
||||
FROM runs r
|
||||
LEFT JOIN workflows w ON w.id = r.workflow_id
|
||||
LEFT JOIN lists l ON l.id = r.list_id
|
||||
LEFT JOIN accounts a ON a.id = r.account_id
|
||||
LEFT JOIN run_profiles rp ON rp.run_id = r.id
|
||||
GROUP BY r.id
|
||||
ORDER BY r.created_at DESC`
|
||||
)
|
||||
.all();
|
||||
return res.json(runs);
|
||||
}
|
||||
|
||||
if (req.method === "POST") {
|
||||
const { workflow_id, list_id, account_id, email_account_id, email_account_ids, target_ids } = req.body;
|
||||
if (!workflow_id || !list_id || !account_id)
|
||||
return res.status(400).json({ error: "workflow_id, list_id, account_id required" });
|
||||
|
||||
// Normalise email account list — prefer the new array, fall back to legacy single-id
|
||||
const emailAccountPool: string[] = Array.isArray(email_account_ids) && email_account_ids.length > 0
|
||||
? email_account_ids
|
||||
: (email_account_id ? [email_account_id] : []);
|
||||
|
||||
// Check 1: only one active run per workflow
|
||||
const activeRun = db.prepare(
|
||||
"SELECT id FROM runs WHERE workflow_id = ? AND status IN ('running', 'paused') LIMIT 1"
|
||||
).get(workflow_id) as { id: string } | undefined;
|
||||
if (activeRun) {
|
||||
return res.status(400).json({
|
||||
error: "workflow_already_active",
|
||||
message: "This workflow is already running. Stop or pause it before enrolling a new list.",
|
||||
});
|
||||
}
|
||||
|
||||
const runId = randomUUID();
|
||||
// For backwards compat, store first email account on the run row (may be null for no-email campaigns)
|
||||
db
|
||||
.prepare("INSERT INTO runs (id, workflow_id, list_id, account_id, email_account_id) VALUES (?, ?, ?, ?, ?)")
|
||||
.run(runId, workflow_id, list_id, account_id, emailAccountPool[0] ?? null);
|
||||
|
||||
// Create run_profiles — either for selected targets or all targets in the list
|
||||
const candidates: { target_id: string }[] = Array.isArray(target_ids) && target_ids.length > 0
|
||||
? (target_ids as string[]).map((id) => ({ target_id: id }))
|
||||
: db.prepare("SELECT target_id FROM list_targets WHERE list_id = ?").all(list_id) as { target_id: string }[];
|
||||
|
||||
// Exclude targets already enrolled in any run of this workflow
|
||||
const alreadyEnrolled = new Set(
|
||||
(db.prepare(
|
||||
`SELECT DISTINCT rp.target_id FROM run_profiles rp
|
||||
JOIN runs r ON r.id = rp.run_id
|
||||
WHERE r.workflow_id = ?`
|
||||
).all(workflow_id) as { target_id: string }[]).map((r) => r.target_id)
|
||||
);
|
||||
|
||||
// Exclude targets currently active in any other running/paused workflow
|
||||
const activeElsewhere = new Set(
|
||||
(db.prepare(
|
||||
`SELECT DISTINCT rp.target_id FROM run_profiles rp
|
||||
JOIN runs r ON r.id = rp.run_id
|
||||
WHERE r.status IN ('running', 'paused')
|
||||
AND EXISTS (
|
||||
SELECT 1 FROM run_profile_tracks rt
|
||||
WHERE rt.run_profile_id = rp.id AND rt.state NOT IN ('completed', 'failed', 'skipped')
|
||||
)`
|
||||
).all() as { target_id: string }[]).map((r) => r.target_id)
|
||||
);
|
||||
|
||||
const targets = candidates.filter((t) => !alreadyEnrolled.has(t.target_id) && !activeElsewhere.has(t.target_id));
|
||||
|
||||
if (targets.length === 0) {
|
||||
// Clean up the run we just created since there's nothing to enroll
|
||||
db.prepare("DELETE FROM runs WHERE id = ?").run(runId);
|
||||
return res.status(400).json({
|
||||
error: "all_already_enrolled",
|
||||
message: "All selected contacts are already enrolled in this workflow.",
|
||||
});
|
||||
}
|
||||
|
||||
// Assign email accounts: company-grouped round-robin
|
||||
// All targets at the same company get the same sender; companies cycle through the pool
|
||||
let emailAssignment: Map<string, string | null> = new Map();
|
||||
if (emailAccountPool.length > 0) {
|
||||
// Load company_id for each candidate target
|
||||
const targetIds = targets.map(t => t.target_id);
|
||||
const placeholders = targetIds.map(() => "?").join(",");
|
||||
const companyRows = db.prepare(
|
||||
`SELECT id, company_id FROM targets WHERE id IN (${placeholders})`
|
||||
).all(...targetIds) as { id: string; company_id: string | null }[];
|
||||
|
||||
const companyAccountMap = new Map<string, string>(); // company_id → email_account_id
|
||||
let poolCursor = 0;
|
||||
|
||||
for (const row of companyRows) {
|
||||
if (row.company_id) {
|
||||
if (!companyAccountMap.has(row.company_id)) {
|
||||
companyAccountMap.set(row.company_id, emailAccountPool[poolCursor % emailAccountPool.length]);
|
||||
poolCursor++;
|
||||
}
|
||||
emailAssignment.set(row.id, companyAccountMap.get(row.company_id)!);
|
||||
} else {
|
||||
// No company — assign individually round-robin
|
||||
emailAssignment.set(row.id, emailAccountPool[poolCursor % emailAccountPool.length]);
|
||||
poolCursor++;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Determine which tracks this workflow has steps for
|
||||
const workflowTracks = [...new Set(
|
||||
(db.prepare("SELECT DISTINCT track FROM workflow_steps WHERE workflow_id = ?").all(workflow_id) as { track: string }[]).map(r => r.track)
|
||||
)];
|
||||
// If no track column exists yet (old DB), default to linkedin-only
|
||||
if (workflowTracks.length === 0) workflowTracks.push("linkedin");
|
||||
|
||||
const insertProfile = db.prepare(
|
||||
"INSERT INTO run_profiles (id, run_id, target_id, email_account_id) VALUES (?, ?, ?, ?)"
|
||||
);
|
||||
const insertTrack = db.prepare(
|
||||
"INSERT INTO run_profile_tracks (id, run_profile_id, track, state, current_step) VALUES (?, ?, ?, 'pending', 0)"
|
||||
);
|
||||
const insertMany = db.transaction((ts: { target_id: string }[]) => {
|
||||
for (const t of ts) {
|
||||
const assignedEmailAccountId = emailAssignment.get(t.target_id) ?? null;
|
||||
const rpId = randomUUID();
|
||||
insertProfile.run(rpId, runId, t.target_id, assignedEmailAccountId);
|
||||
for (const track of workflowTracks) {
|
||||
// Skip email track if no email account is configured on this run
|
||||
if (track === "email" && !assignedEmailAccountId) continue;
|
||||
insertTrack.run(randomUUID(), rpId, track);
|
||||
}
|
||||
}
|
||||
});
|
||||
insertMany(targets);
|
||||
|
||||
return res.status(201).json({ id: runId });
|
||||
}
|
||||
|
||||
res.status(405).end();
|
||||
}
|
||||
Reference in New Issue
Block a user