release: 2026-08-01
This commit is contained in:
@@ -0,0 +1,65 @@
|
||||
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 target = db.prepare("SELECT * FROM targets WHERE id = ?").get(id);
|
||||
if (!target) return res.status(404).json({ error: "Not found" });
|
||||
|
||||
const company = db.prepare("SELECT * FROM companies WHERE id = (SELECT company_id FROM targets WHERE id = ?)").get(id);
|
||||
const lists = db.prepare(`
|
||||
SELECT l.id, l.name FROM lists l
|
||||
INNER JOIN list_targets lt ON lt.list_id = l.id
|
||||
WHERE lt.target_id = ?
|
||||
ORDER BY l.name COLLATE NOCASE
|
||||
`).all(id);
|
||||
|
||||
return res.json({ ...target as object, company: company ?? null, lists });
|
||||
}
|
||||
|
||||
if (req.method === "PATCH") {
|
||||
const target = db.prepare("SELECT id FROM targets WHERE id = ?").get(id);
|
||||
if (!target) return res.status(404).json({ error: "Not found" });
|
||||
|
||||
// Editable contact fields (CRM hygiene). Anything else is owned by enrichment/automation.
|
||||
const EDITABLE = [
|
||||
"first_name", "last_name", "full_name", "title", "company", "location",
|
||||
"email", "phone", "headline", "summary", "notes",
|
||||
] as const;
|
||||
|
||||
const body = req.body as Record<string, unknown>;
|
||||
const fields: string[] = [];
|
||||
const params: unknown[] = [];
|
||||
for (const col of EDITABLE) {
|
||||
if (body[col] !== undefined) {
|
||||
const v = body[col];
|
||||
fields.push(`${col} = ?`);
|
||||
params.push(typeof v === "string" ? (v.trim() || null) : v);
|
||||
}
|
||||
}
|
||||
if (fields.length === 0) return res.status(400).json({ error: "No editable fields provided" });
|
||||
params.push(id);
|
||||
db.prepare(`UPDATE targets SET ${fields.join(", ")} WHERE id = ?`).run(...params);
|
||||
|
||||
return res.json(db.prepare("SELECT * FROM targets WHERE id = ?").get(id));
|
||||
}
|
||||
|
||||
if (req.method === "DELETE") {
|
||||
const target = db.prepare("SELECT id FROM targets WHERE id = ?").get(id);
|
||||
if (!target) return res.status(404).json({ error: "Not found" });
|
||||
// Some references (run_profiles, logs) have no ON DELETE CASCADE — clear them first so the
|
||||
// FK constraint doesn't block the delete. run_profile_tracks cascade off run_profiles.
|
||||
db.transaction(() => {
|
||||
db.prepare("DELETE FROM run_profiles WHERE target_id = ?").run(id);
|
||||
db.prepare("DELETE FROM logs WHERE target_id = ?").run(id);
|
||||
db.prepare("DELETE FROM targets WHERE id = ?").run(id);
|
||||
})();
|
||||
return res.json({ ok: true });
|
||||
}
|
||||
|
||||
res.setHeader("Allow", ["GET", "PATCH", "DELETE"]);
|
||||
return res.status(405).end();
|
||||
}
|
||||
@@ -0,0 +1,193 @@
|
||||
import type { NextApiRequest, NextApiResponse } from "next";
|
||||
import Imap from "imap";
|
||||
import { simpleParser } from "mailparser";
|
||||
import { getDb } from "@/lib/db";
|
||||
import { sendEmail, type EmailAccount } from "@/lib/email/sender";
|
||||
import { decryptSecret } from "@/lib/crypto";
|
||||
|
||||
// Email conversation for one contact, account-resolved automatically so callers (incl. the MCP)
|
||||
// never need to know the email_account_id.
|
||||
// GET → the IMAP thread (sent + received) with this contact.
|
||||
// POST → send an email to this contact as the Linki sending identity (subject optional → reply).
|
||||
//
|
||||
// Account resolution order: explicit email_account_id → the contact's most recent run_profile
|
||||
// assignment → the single configured account if there's exactly one.
|
||||
|
||||
type AccountRow = {
|
||||
id: string; from_email: string; from_name: string | null; reply_to: string | null;
|
||||
smtp_host: string; smtp_port: number; smtp_secure: number;
|
||||
imap_host: string | null; imap_port: number | null;
|
||||
username: string; password: string;
|
||||
imap_username: string | null; imap_password: string | null;
|
||||
};
|
||||
|
||||
function resolveAccount(db: ReturnType<typeof getDb>, targetId: string, explicitId?: string): AccountRow | null {
|
||||
const cols = `id, from_email, from_name, reply_to, smtp_host, smtp_port, smtp_secure,
|
||||
imap_host, imap_port, username, password, imap_username, imap_password`;
|
||||
if (explicitId) {
|
||||
return (db.prepare(`SELECT ${cols} FROM email_accounts WHERE id = ?`).get(explicitId) as AccountRow) ?? null;
|
||||
}
|
||||
const assigned = db.prepare(`
|
||||
SELECT rp.email_account_id FROM run_profiles rp
|
||||
WHERE rp.target_id = ? AND rp.email_account_id IS NOT NULL
|
||||
ORDER BY rp.created_at DESC LIMIT 1
|
||||
`).get(targetId) as { email_account_id: string } | undefined;
|
||||
if (assigned?.email_account_id) {
|
||||
return (db.prepare(`SELECT ${cols} FROM email_accounts WHERE id = ?`).get(assigned.email_account_id) as AccountRow) ?? null;
|
||||
}
|
||||
const all = db.prepare(`SELECT ${cols} FROM email_accounts`).all() as AccountRow[];
|
||||
return all.length === 1 ? all[0] : null;
|
||||
}
|
||||
|
||||
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
|
||||
const db = getDb();
|
||||
const targetId = req.query.id as string;
|
||||
|
||||
const target = db.prepare("SELECT id, email FROM targets WHERE id = ?").get(targetId) as
|
||||
| { id: string; email: string | null } | undefined;
|
||||
if (!target) return res.status(404).json({ error: "Contact not found" });
|
||||
if (!target.email) return res.status(400).json({ error: "Contact has no email address" });
|
||||
|
||||
// ── Read thread ──
|
||||
if (req.method === "GET") {
|
||||
const account = resolveAccount(db, targetId, req.query.email_account_id as string | undefined);
|
||||
if (!account?.imap_host) {
|
||||
return res.status(400).json({ error: "No email account with IMAP config could be resolved for this contact" });
|
||||
}
|
||||
const cfg = {
|
||||
host: account.imap_host,
|
||||
port: account.imap_port ?? 993,
|
||||
user: account.imap_username ?? account.username,
|
||||
password: decryptSecret(account.imap_password) ?? decryptSecret(account.password)!,
|
||||
};
|
||||
// Transient IMAP failures (dropped connection, auth timeout) are common — retry once
|
||||
// before surfacing a structured error rather than an opaque 500.
|
||||
let lastErr: unknown = null;
|
||||
for (let attempt = 1; attempt <= 2; attempt++) {
|
||||
try {
|
||||
const messages = await fetchThread(cfg, target.email.toLowerCase());
|
||||
return res.json({ email_account_id: account.id, contact_email: target.email, messages });
|
||||
} catch (err) {
|
||||
lastErr = err;
|
||||
console.warn(`[targets/emails] IMAP attempt ${attempt} failed:`, err instanceof Error ? err.message : err);
|
||||
if (attempt < 2) await new Promise((r) => setTimeout(r, 800));
|
||||
}
|
||||
}
|
||||
return res.status(502).json({
|
||||
error: "IMAP fetch failed",
|
||||
detail: lastErr instanceof Error ? lastErr.message : String(lastErr),
|
||||
email_account_id: account.id,
|
||||
mailbox: "INBOX",
|
||||
contact_email: target.email,
|
||||
hint: "Transient IMAP error after 1 retry. For reliable reply retrieval use get_replies, which reads stored replies and never hits IMAP live.",
|
||||
});
|
||||
}
|
||||
|
||||
// ── Send / reply ──
|
||||
if (req.method === "POST") {
|
||||
const { subject, body, email_account_id } = req.body as {
|
||||
subject?: string; body?: string; email_account_id?: string;
|
||||
};
|
||||
if (!body?.trim()) return res.status(400).json({ error: "body is required" });
|
||||
|
||||
const account = resolveAccount(db, targetId, email_account_id);
|
||||
if (!account) return res.status(400).json({ error: "No email account could be resolved for this contact" });
|
||||
|
||||
// No subject → treat as a reply: reuse the last subject in the thread (Re: …) or a sane default.
|
||||
let finalSubject = subject?.trim();
|
||||
if (!finalSubject) {
|
||||
const lastReply = db.prepare(
|
||||
"SELECT subject FROM email_replies WHERE target_id = ? AND subject IS NOT NULL ORDER BY received_at DESC LIMIT 1"
|
||||
).get(targetId) as { subject: string } | undefined;
|
||||
finalSubject = lastReply?.subject
|
||||
? (/^re:/i.test(lastReply.subject) ? lastReply.subject : `Re: ${lastReply.subject}`)
|
||||
: "Re:";
|
||||
}
|
||||
|
||||
try {
|
||||
await sendEmail(
|
||||
{ ...account, password: decryptSecret(account.password)! } as EmailAccount,
|
||||
target.email, finalSubject, body
|
||||
);
|
||||
return res.json({ ok: true, email_account_id: account.id, to: target.email, subject: finalSubject });
|
||||
} catch (err) {
|
||||
console.error("[targets/emails] send failed:", err);
|
||||
return res.status(500).json({ error: err instanceof Error ? err.message : "Send failed" });
|
||||
}
|
||||
}
|
||||
|
||||
res.setHeader("Allow", ["GET", "POST"]);
|
||||
return res.status(405).end();
|
||||
}
|
||||
|
||||
interface ImapConfig { host: string; port: number; user: string; password: string; }
|
||||
interface EmailMessage {
|
||||
uid: number; from: string; to: string; subject: string; date: string;
|
||||
text: string; messageId: string | null;
|
||||
}
|
||||
|
||||
async function fetchThread(cfg: ImapConfig, contactEmail: string): Promise<EmailMessage[]> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const imap = new Imap({
|
||||
host: cfg.host, port: cfg.port, tls: true,
|
||||
tlsOptions: { rejectUnauthorized: false },
|
||||
user: cfg.user, password: cfg.password,
|
||||
authTimeout: 10_000, connTimeout: 12_000,
|
||||
});
|
||||
const done = (err?: Error) => { try { imap.end(); } catch { /* ignore */ } if (err) reject(err); };
|
||||
const messages: EmailMessage[] = [];
|
||||
|
||||
imap.once("error", (err: Error) => done(err));
|
||||
imap.once("ready", () => {
|
||||
imap.openBox("INBOX", true, (boxErr) => {
|
||||
if (boxErr) { done(boxErr); return; }
|
||||
imap.search([["OR", ["FROM", contactEmail], ["TO", contactEmail]]], (searchErr, uids) => {
|
||||
if (searchErr) { done(searchErr); return; }
|
||||
if (uids.length === 0) { resolve([]); done(); return; }
|
||||
const toFetch = uids.slice(-20);
|
||||
const fetch = imap.fetch(toFetch, { bodies: "", struct: false });
|
||||
const pending: Promise<void>[] = [];
|
||||
|
||||
fetch.on("message", (msg) => {
|
||||
let uid = 0;
|
||||
msg.on("attributes", (attrs) => { uid = attrs.uid; });
|
||||
const p = new Promise<void>((res2) => {
|
||||
const chunks: Buffer[] = [];
|
||||
let bodyEnded = false;
|
||||
msg.on("body", (stream) => {
|
||||
stream.on("data", (c: Buffer) => chunks.push(c));
|
||||
stream.once("end", async () => {
|
||||
bodyEnded = true;
|
||||
try {
|
||||
const parsed = await simpleParser(Buffer.concat(chunks));
|
||||
messages.push({
|
||||
uid,
|
||||
from: parsed.from?.text ?? "",
|
||||
to: parsed.to ? (Array.isArray(parsed.to) ? parsed.to.map(a => a.text).join(", ") : parsed.to.text) : "",
|
||||
subject: parsed.subject ?? "(no subject)",
|
||||
date: parsed.date?.toISOString() ?? new Date().toISOString(),
|
||||
text: parsed.text ?? "",
|
||||
messageId: parsed.messageId ?? null,
|
||||
});
|
||||
} catch { /* skip malformed */ }
|
||||
res2();
|
||||
});
|
||||
});
|
||||
msg.once("end", () => { if (!bodyEnded) res2(); });
|
||||
});
|
||||
pending.push(p);
|
||||
});
|
||||
|
||||
fetch.once("error", (fetchErr: Error) => done(fetchErr));
|
||||
fetch.once("end", async () => {
|
||||
await Promise.allSettled(pending);
|
||||
messages.sort((a, b) => a.date.localeCompare(b.date));
|
||||
resolve(messages);
|
||||
done();
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
imap.connect();
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
import type { NextApiRequest, NextApiResponse } from "next";
|
||||
import { getDb } from "@/lib/db";
|
||||
import { getSessionContext } from "@/lib/linkedin/session";
|
||||
import { scrapeProfile } from "@/lib/linkedin/profile-scrape";
|
||||
import { resolveLinkedInAccount } from "@/lib/linkedin/resolve-account";
|
||||
|
||||
// POST /api/targets/[id]/profile-scrape
|
||||
// Live-scrapes a lead's LinkedIn profile (Sales Nav career + recent posts) and
|
||||
// returns clean structured JSON. Read-only on LinkedIn's side; does not persist.
|
||||
// Account auto-resolved (explicit account_id → contact's last run → sole account).
|
||||
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
|
||||
if (req.method !== "POST") return res.status(405).json({ error: "Method not allowed" });
|
||||
|
||||
const db = getDb();
|
||||
const id = req.query.id as string;
|
||||
const target = db.prepare(
|
||||
"SELECT id, full_name, linkedin_url, sales_nav_url FROM targets WHERE id = ?"
|
||||
).get(id) as { id: string; full_name: string | null; linkedin_url: string | null; sales_nav_url: string | null } | undefined;
|
||||
|
||||
if (!target) return res.status(404).json({ error: "Contact not found" });
|
||||
if (!target.sales_nav_url) {
|
||||
return res.status(400).json({ error: "Contact has no Sales Navigator URL — re-import the list to capture it." });
|
||||
}
|
||||
|
||||
const account = resolveLinkedInAccount(db, id, req.body?.account_id);
|
||||
if (!account) return res.status(400).json({ error: "No authenticated LinkedIn account could be resolved." });
|
||||
|
||||
try {
|
||||
const ctx = await getSessionContext(account.id);
|
||||
const profile = await scrapeProfile(ctx, target);
|
||||
|
||||
// Persist what we scraped so it isn't thrown away: posts + the career fields
|
||||
// we already have columns for (headline/summary/positions). Cheap and lets the
|
||||
// runner's AI writer reuse it without re-scraping.
|
||||
db.prepare(`
|
||||
UPDATE targets SET
|
||||
posts_json = CASE WHEN ? IS NOT NULL THEN ? ELSE posts_json END,
|
||||
posts_scraped_at = datetime('now'),
|
||||
headline = COALESCE(?, headline),
|
||||
summary = COALESCE(?, summary),
|
||||
positions_json = CASE WHEN ? IS NOT NULL THEN ? ELSE positions_json END
|
||||
WHERE id = ?
|
||||
`).run(
|
||||
profile.recent_posts.length ? "1" : null,
|
||||
profile.recent_posts.length ? JSON.stringify(profile.recent_posts) : null,
|
||||
profile.headline,
|
||||
profile.summary,
|
||||
profile.positions.length ? "1" : null,
|
||||
profile.positions.length ? JSON.stringify(profile.positions) : null,
|
||||
id
|
||||
);
|
||||
|
||||
return res.json({ contact_id: id, account_id: account.id, profile });
|
||||
} catch (err) {
|
||||
const message = err instanceof Error ? err.message : String(err);
|
||||
// A dead session surfaces as "No data intercepted" / re-auth — flag it so the runner stops.
|
||||
if (/re-authentication|No data intercepted|login|checkpoint/i.test(message)) {
|
||||
try {
|
||||
const { markNeedsReauth } = await import("@/lib/linkedin/session");
|
||||
await markNeedsReauth(account.id);
|
||||
} catch { /* ignore */ }
|
||||
return res.status(502).json({ error: `LinkedIn session needs re-authentication: ${message}` });
|
||||
}
|
||||
return res.status(500).json({ error: message });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
import type { NextApiRequest, NextApiResponse } from "next";
|
||||
import { getDb } from "@/lib/db";
|
||||
|
||||
// Which runs/campaigns a contact is enrolled in, with per-track (linkedin/email) state + step.
|
||||
// Answers "is this person in a campaign, and where are they in it?" without scanning a whole run.
|
||||
export default function handler(req: NextApiRequest, res: NextApiResponse) {
|
||||
if (req.method !== "GET") return res.status(405).end();
|
||||
|
||||
const db = getDb();
|
||||
const targetId = req.query.id as string;
|
||||
|
||||
const target = db.prepare("SELECT id FROM targets WHERE id = ?").get(targetId);
|
||||
if (!target) return res.status(404).json({ error: "Not found" });
|
||||
|
||||
const rows = db.prepare(`
|
||||
SELECT
|
||||
rp.id AS run_profile_id,
|
||||
r.id AS run_id,
|
||||
r.status AS run_status,
|
||||
r.workflow_id,
|
||||
w.name AS workflow_name,
|
||||
l.id AS list_id,
|
||||
l.name AS list_name,
|
||||
rp.email_account_id,
|
||||
rt.track,
|
||||
rt.state,
|
||||
rt.current_step,
|
||||
rt.next_step_at,
|
||||
rt.error_message
|
||||
FROM run_profiles rp
|
||||
JOIN runs r ON r.id = rp.run_id
|
||||
LEFT JOIN workflows w ON w.id = r.workflow_id
|
||||
LEFT JOIN lists l ON l.id = r.list_id
|
||||
LEFT JOIN run_profile_tracks rt ON rt.run_profile_id = rp.id
|
||||
WHERE rp.target_id = ?
|
||||
ORDER BY r.created_at DESC, rt.track
|
||||
`).all(targetId) as Array<Record<string, unknown>>;
|
||||
|
||||
// Group tracks under their run.
|
||||
const byRun = new Map<string, Record<string, unknown>>();
|
||||
for (const row of rows) {
|
||||
const rid = row.run_id as string;
|
||||
if (!byRun.has(rid)) {
|
||||
byRun.set(rid, {
|
||||
run_id: rid,
|
||||
run_profile_id: row.run_profile_id,
|
||||
run_status: row.run_status,
|
||||
workflow_id: row.workflow_id,
|
||||
workflow_name: row.workflow_name,
|
||||
list_id: row.list_id,
|
||||
list_name: row.list_name,
|
||||
email_account_id: row.email_account_id,
|
||||
tracks: [],
|
||||
});
|
||||
}
|
||||
if (row.track) {
|
||||
(byRun.get(rid)!.tracks as unknown[]).push({
|
||||
track: row.track,
|
||||
state: row.state,
|
||||
current_step: row.current_step,
|
||||
next_step_at: row.next_step_at,
|
||||
error_message: row.error_message,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return res.json({ runs: Array.from(byRun.values()) });
|
||||
}
|
||||
@@ -0,0 +1,232 @@
|
||||
import type { NextApiRequest, NextApiResponse } from "next";
|
||||
import { getDb } from "@/lib/db";
|
||||
import { randomUUID } from "crypto";
|
||||
import type { ActiveFilter, FilterOp } from "@/components/ui/FilterBar";
|
||||
|
||||
// Parse f[0][field], f[0][op], f[0][value], f[1][field], ... from query
|
||||
function parseFilters(query: NextApiRequest["query"]): ActiveFilter[] {
|
||||
const filters: ActiveFilter[] = [];
|
||||
let i = 0;
|
||||
while (query[`f[${i}][field]`]) {
|
||||
const field = query[`f[${i}][field]`] as string;
|
||||
const op = query[`f[${i}][op]`] as FilterOp;
|
||||
const value = query[`f[${i}][value]`] as string | undefined;
|
||||
filters.push({ id: String(i), field, op, value });
|
||||
i++;
|
||||
}
|
||||
return filters;
|
||||
}
|
||||
|
||||
function buildFilterClause(filters: ActiveFilter[]): { sql: string; params: unknown[] } {
|
||||
const parts: string[] = [];
|
||||
const params: unknown[] = [];
|
||||
|
||||
for (const f of filters) {
|
||||
// connection_status is derived — map to real columns
|
||||
if (f.field === "connection_status") {
|
||||
let expr: string;
|
||||
switch (f.value) {
|
||||
case "replied":
|
||||
expr = "t.last_replied_at IS NOT NULL";
|
||||
break;
|
||||
case "messaged":
|
||||
expr = "t.message_sent_at IS NOT NULL AND t.last_replied_at IS NULL";
|
||||
break;
|
||||
case "connected":
|
||||
expr = "t.degree = 1 AND t.message_sent_at IS NULL";
|
||||
break;
|
||||
case "request_sent":
|
||||
expr = "t.connection_requested_at IS NOT NULL AND (t.degree IS NULL OR t.degree != 1)";
|
||||
break;
|
||||
case "not_contacted":
|
||||
default:
|
||||
expr = "t.connection_requested_at IS NULL AND t.message_sent_at IS NULL";
|
||||
}
|
||||
if (f.op === "is_not") expr = `NOT (${expr})`;
|
||||
parts.push(expr);
|
||||
continue;
|
||||
}
|
||||
|
||||
// Safe-list of allowed columns
|
||||
const ALLOWED: Record<string, string> = {
|
||||
seniority: "t.seniority",
|
||||
email_status: "t.email_status",
|
||||
degree: "t.degree",
|
||||
email: "t.email",
|
||||
apollo_enriched_at: "t.apollo_enriched_at",
|
||||
connection_requested_at: "t.connection_requested_at",
|
||||
connected_at: "t.connected_at",
|
||||
message_sent_at: "t.message_sent_at",
|
||||
last_replied_at: "t.last_replied_at",
|
||||
open_link: "t.open_link",
|
||||
email_domain_catchall: "t.email_domain_catchall",
|
||||
company_size: "t.company_size",
|
||||
tenure_months: "t.tenure_months",
|
||||
country: "t.country",
|
||||
company_industry: "t.company_industry",
|
||||
company: "t.company",
|
||||
};
|
||||
|
||||
const col = ALLOWED[f.field];
|
||||
if (!col) continue;
|
||||
|
||||
switch (f.op) {
|
||||
case "is_set":
|
||||
parts.push(`${col} IS NOT NULL AND ${col} != ''`);
|
||||
break;
|
||||
case "is_not_set":
|
||||
parts.push(`(${col} IS NULL OR ${col} = '')`);
|
||||
break;
|
||||
case "is_true":
|
||||
parts.push(`${col} = 1`);
|
||||
break;
|
||||
case "is_false":
|
||||
parts.push(`(${col} = 0 OR ${col} IS NULL)`);
|
||||
break;
|
||||
case "is":
|
||||
parts.push(`LOWER(${col}) = LOWER(?)`);
|
||||
params.push(f.value ?? "");
|
||||
break;
|
||||
case "is_not":
|
||||
parts.push(`LOWER(${col}) != LOWER(?)`);
|
||||
params.push(f.value ?? "");
|
||||
break;
|
||||
case "contains":
|
||||
parts.push(`${col} LIKE ?`);
|
||||
params.push(`%${f.value ?? ""}%`);
|
||||
break;
|
||||
case "gt":
|
||||
parts.push(`CAST(${col} AS REAL) > ?`);
|
||||
params.push(Number(f.value ?? 0));
|
||||
break;
|
||||
case "lt":
|
||||
parts.push(`CAST(${col} AS REAL) < ?`);
|
||||
params.push(Number(f.value ?? 0));
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
sql: parts.length > 0 ? " AND " + parts.join(" AND ") : "",
|
||||
params,
|
||||
};
|
||||
}
|
||||
|
||||
export default function handler(req: NextApiRequest, res: NextApiResponse) {
|
||||
if (req.method === "POST") {
|
||||
const db = getDb();
|
||||
const { full_name, linkedin_url, title, company, location, email, phone, list_id } = req.body;
|
||||
if (!full_name || !linkedin_url) {
|
||||
return res.status(400).json({ error: "full_name and linkedin_url are required" });
|
||||
}
|
||||
const id = randomUUID();
|
||||
try {
|
||||
db.prepare(
|
||||
`INSERT INTO targets (id, full_name, linkedin_url, title, company, location, email, phone)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?)`
|
||||
).run(id, full_name, linkedin_url, title ?? null, company ?? null, location ?? null, email ?? null, phone ?? null);
|
||||
} catch (e: unknown) {
|
||||
if (e instanceof Error && e.message.includes("UNIQUE")) {
|
||||
return res.status(409).json({ error: "A contact with this LinkedIn URL already exists" });
|
||||
}
|
||||
throw e;
|
||||
}
|
||||
if (list_id) {
|
||||
try {
|
||||
db.prepare("INSERT OR IGNORE INTO list_targets (list_id, target_id) VALUES (?, ?)").run(list_id, id);
|
||||
} catch { /* ignore */ }
|
||||
}
|
||||
return res.status(201).json(db.prepare("SELECT * FROM targets WHERE id = ?").get(id));
|
||||
}
|
||||
|
||||
if (req.method === "DELETE") {
|
||||
const db = getDb();
|
||||
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 must be a non-empty array" });
|
||||
}
|
||||
const placeholders = target_ids.map(() => "?").join(",");
|
||||
// run_profiles/logs have no ON DELETE CASCADE — clear them first so the FK
|
||||
// constraint doesn't block the delete. run_profile_tracks cascade off run_profiles.
|
||||
const result = db.transaction(() => {
|
||||
db.prepare(`DELETE FROM run_profiles WHERE target_id IN (${placeholders})`).run(...target_ids);
|
||||
db.prepare(`DELETE FROM logs WHERE target_id IN (${placeholders})`).run(...target_ids);
|
||||
return db.prepare(`DELETE FROM targets WHERE id IN (${placeholders})`).run(...target_ids);
|
||||
})();
|
||||
return res.json({ deleted: result.changes });
|
||||
}
|
||||
|
||||
if (req.method !== "GET") {
|
||||
res.setHeader("Allow", ["GET", "POST", "DELETE"]);
|
||||
return res.status(405).end();
|
||||
}
|
||||
|
||||
const db = getDb();
|
||||
const { list_id, page = "0", limit = "50", search } = req.query;
|
||||
const offset = Number(page) * Number(limit);
|
||||
|
||||
const extraClauses: string[] = [];
|
||||
const extraParams: unknown[] = [];
|
||||
|
||||
if (search && typeof search === "string" && search.trim()) {
|
||||
const like = `%${search.trim()}%`;
|
||||
extraClauses.push("(t.full_name LIKE ? OR t.company LIKE ? OR t.title LIKE ?)");
|
||||
extraParams.push(like, like, like);
|
||||
}
|
||||
|
||||
const filters = parseFilters(req.query);
|
||||
const { sql: filterSql, params: filterParams } = buildFilterClause(filters);
|
||||
|
||||
const extraWhere =
|
||||
(extraClauses.length > 0 ? " AND " + extraClauses.join(" AND ") : "") + filterSql;
|
||||
const allExtraParams = [...extraParams, ...filterParams];
|
||||
|
||||
const SELECT = `SELECT t.id, t.linkedin_url, t.full_name, t.title, t.company, t.location,
|
||||
t.email, t.email_status, t.degree,
|
||||
t.connection_requested_at, t.connected_at, t.message_sent_at, t.last_replied_at,
|
||||
t.apollo_enriched_at, t.seniority, t.created_at
|
||||
FROM targets t`;
|
||||
|
||||
let rows: unknown[];
|
||||
let total: number;
|
||||
|
||||
if (list_id) {
|
||||
rows = db
|
||||
.prepare(
|
||||
`${SELECT}
|
||||
JOIN list_targets lt ON lt.target_id = t.id
|
||||
WHERE lt.list_id = ?${extraWhere}
|
||||
ORDER BY t.full_name ASC
|
||||
LIMIT ? OFFSET ?`
|
||||
)
|
||||
.all(list_id, ...allExtraParams, Number(limit), offset);
|
||||
total = (
|
||||
db
|
||||
.prepare(
|
||||
`SELECT COUNT(*) as c FROM targets t
|
||||
JOIN list_targets lt ON lt.target_id = t.id
|
||||
WHERE lt.list_id = ?${extraWhere}`
|
||||
)
|
||||
.get(list_id, ...allExtraParams) as { c: number }
|
||||
).c;
|
||||
} else {
|
||||
// All contacts — including list-less ones (e.g. created via the MCP without a list_id).
|
||||
// Previously gated behind EXISTS(list_targets), which hid them entirely.
|
||||
const whereClause = extraWhere ? `WHERE 1=1${extraWhere}` : "";
|
||||
rows = db
|
||||
.prepare(
|
||||
`${SELECT}
|
||||
${whereClause}
|
||||
ORDER BY t.full_name ASC
|
||||
LIMIT ? OFFSET ?`
|
||||
)
|
||||
.all(...allExtraParams, Number(limit), offset);
|
||||
total = (
|
||||
db
|
||||
.prepare(`SELECT COUNT(*) as c FROM targets t ${whereClause}`)
|
||||
.get(...allExtraParams) as { c: number }
|
||||
).c;
|
||||
}
|
||||
|
||||
return res.json({ contacts: rows, total });
|
||||
}
|
||||
Reference in New Issue
Block a user