release: 2026-08-01

This commit is contained in:
moaljumaa
2026-08-01 14:01:17 +02:00
commit 7d8b930bc3
137 changed files with 34695 additions and 0 deletions
+49
View File
@@ -0,0 +1,49 @@
import type { NextApiRequest, NextApiResponse } from "next";
import { getDb } from "@/lib/db";
// Add EXISTING contacts to a list by id (membership only — does not create
// contacts). Idempotent: already-member ids are skipped. This is the inverse of
// remove-members and the way to UNDO a removal (feed back removed_contact_ids).
export default function handler(req: NextApiRequest, res: NextApiResponse) {
if (req.method !== "POST") return res.status(405).end();
const db = getDb();
const list_id = req.query.id as string;
const list = db.prepare("SELECT id FROM lists WHERE id = ?").get(list_id);
if (!list) return res.status(404).json({ error: "List not found" });
const { contact_ids } = req.body as { contact_ids?: string[] };
if (!Array.isArray(contact_ids) || contact_ids.length === 0) {
return res.status(400).json({ error: "contact_ids[] is required." });
}
// Only add ids that actually exist as contacts (ignore unknown ids rather
// than failing the whole batch).
const placeholders = contact_ids.map(() => "?").join(", ");
const existing = db
.prepare(`SELECT id, full_name, title FROM targets WHERE id IN (${placeholders})`)
.all(...contact_ids) as Array<{ id: string; full_name: string | null; title: string | null }>;
const existingIds = new Set(existing.map((r) => r.id));
const unknown = contact_ids.filter((id) => !existingIds.has(id));
const insert = db.prepare("INSERT OR IGNORE INTO list_targets (list_id, target_id) VALUES (?, ?)");
let added = 0;
const addTx = db.transaction((ids: string[]) => {
for (const id of ids) {
const info = insert.run(list_id, id);
if (info.changes > 0) added++;
}
});
addTx([...existingIds]);
const total = (db.prepare("SELECT COUNT(*) as c FROM list_targets WHERE list_id = ?").get(list_id) as { c: number }).c;
return res.json({
added,
already_members: existingIds.size - added,
unknown_contact_ids: unknown,
list_total: total,
contacts_added: existing,
});
}
+35
View File
@@ -0,0 +1,35 @@
import type { NextApiRequest, NextApiResponse } from "next";
import { getDb } from "@/lib/db";
// Title + location breakdown for a list — used to spot irrelevant contacts before cleaning.
export default function handler(req: NextApiRequest, res: NextApiResponse) {
if (req.method !== "GET") return res.status(405).end();
const db = getDb();
const list_id = req.query.id as string;
const list = db.prepare("SELECT id, name FROM lists WHERE id = ?").get(list_id);
if (!list) return res.status(404).json({ error: "List not found" });
const total = (db.prepare("SELECT COUNT(*) as c FROM list_targets WHERE list_id = ?").get(list_id) as { c: number }).c;
const titles = db.prepare(`
SELECT t.title, COUNT(*) as count
FROM list_targets lt
JOIN targets t ON t.id = lt.target_id
WHERE lt.list_id = ? AND t.title IS NOT NULL
GROUP BY t.title
ORDER BY count DESC
`).all(list_id);
const locations = db.prepare(`
SELECT t.location, COUNT(*) as count
FROM list_targets lt
JOIN targets t ON t.id = lt.target_id
WHERE lt.list_id = ? AND t.location IS NOT NULL
GROUP BY t.location
ORDER BY count DESC
`).all(list_id);
return res.json({ list, total, titles, locations });
}
+198
View File
@@ -0,0 +1,198 @@
import type { NextApiRequest, NextApiResponse } from "next";
import { getDb } from "@/lib/db";
import { matchPerson } from "@/lib/apollo";
import { randomUUID } from "crypto";
import { decryptSecret } from "@/lib/crypto";
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
if (req.method !== "POST") {
res.setHeader("Allow", ["POST"]);
return res.status(405).end();
}
const db = getDb();
const listId = req.query.id as string;
const list = db.prepare("SELECT id FROM lists WHERE id = ?").get(listId);
if (!list) return res.status(404).json({ error: "List not found" });
const integration = db.prepare("SELECT api_key FROM integrations WHERE key = 'apollo'").get() as
| { api_key: string }
| undefined;
if (!integration?.api_key) {
return res.status(400).json({ error: "Apollo integration not configured" });
}
const apiKey = decryptSecret(integration.api_key)!;
// Optional: target_ids in body to enrich specific contacts only
const { target_ids } = req.body as { target_ids?: string[] };
let targets: { id: string; linkedin_url: string | null; sales_nav_url: string | null }[];
if (target_ids && target_ids.length > 0) {
const placeholders = target_ids.map(() => "?").join(",");
targets = db.prepare(`
SELECT t.id, t.linkedin_url, t.sales_nav_url
FROM targets t
INNER JOIN list_targets lt ON lt.target_id = t.id
WHERE lt.list_id = ? AND t.id IN (${placeholders}) AND t.email IS NULL
AND (t.linkedin_url IS NOT NULL OR t.sales_nav_url IS NOT NULL)
`).all(listId, ...target_ids) as { id: string; linkedin_url: string | null; sales_nav_url: string | null }[];
} else {
targets = db.prepare(`
SELECT t.id, t.linkedin_url, t.sales_nav_url
FROM targets t
INNER JOIN list_targets lt ON lt.target_id = t.id
WHERE lt.list_id = ? AND t.apollo_enriched_at IS NULL AND t.email IS NULL
AND (t.linkedin_url IS NOT NULL OR t.sales_nav_url IS NOT NULL)
`).all(listId) as { id: string; linkedin_url: string | null; sales_nav_url: string | null }[];
}
let enriched = 0;
let notFound = 0;
let skipped = 0;
for (const target of targets) {
// Prefer real /in/ URL, fall back to sales_nav_url (Apollo accepts both)
const urlToUse = (target.linkedin_url && !target.linkedin_url.includes("/sales/lead/"))
? target.linkedin_url
: target.sales_nav_url;
if (!urlToUse) {
skipped++;
continue;
}
try {
const result = await matchPerson(urlToUse, apiKey);
if (!result) {
notFound++;
// Mark as attempted so we don't retry endlessly
db.prepare("UPDATE targets SET apollo_enriched_at = datetime('now') WHERE id = ?").run(target.id);
continue;
}
// Company association via domain
let companyId: string | null = null;
if (result.organization?.domain) {
const domain = result.organization.domain.replace(/^www\./, "").toLowerCase();
const existing = db.prepare("SELECT id FROM companies WHERE domain = ?").get(domain) as
| { id: string }
| undefined;
const org = result.organization;
if (existing) {
companyId = existing.id;
// Update company with richer data if we have it
db.prepare(`
UPDATE companies SET
industry = COALESCE(industry, ?),
location = COALESCE(location, ?),
linkedin_url = COALESCE(linkedin_url, ?),
website = COALESCE(website, ?),
founded_year = COALESCE(founded_year, ?),
logo_url = COALESCE(logo_url, ?),
phone = COALESCE(phone, ?),
annual_revenue = COALESCE(annual_revenue, ?),
technology_names = COALESCE(technology_names, ?),
keywords = COALESCE(keywords, ?),
city = COALESCE(city, ?),
country = COALESCE(country, ?),
description = COALESCE(description, ?),
employee_count = COALESCE(employee_count, ?)
WHERE id = ?
`).run(
org.industry ?? null,
org.location ?? null,
org.linkedin_url ?? null,
org.website_url ?? null,
org.founded_year ?? null,
org.logo_url ?? null,
org.phone ?? null,
org.annual_revenue_printed ?? null,
org.technology_names ? JSON.stringify(org.technology_names) : null,
org.keywords ? JSON.stringify(org.keywords) : null,
org.city ?? null,
org.country ?? null,
org.short_description ?? null,
org.estimated_num_employees ?? null,
existing.id
);
} else {
companyId = randomUUID();
db.prepare(`
INSERT INTO companies (id, name, domain, industry, location, linkedin_url, website, founded_year, logo_url, phone, annual_revenue, technology_names, keywords, city, country, description, employee_count)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
`).run(
companyId,
org.name ?? "",
domain,
org.industry ?? null,
org.location ?? null,
org.linkedin_url ?? null,
org.website_url ?? null,
org.founded_year ?? null,
org.logo_url ?? null,
org.phone ?? null,
org.annual_revenue_printed ?? null,
org.technology_names ? JSON.stringify(org.technology_names) : null,
org.keywords ? JSON.stringify(org.keywords) : null,
org.city ?? null,
org.country ?? null,
org.short_description ?? null,
org.estimated_num_employees ?? null
);
}
}
// Apollo returns a real /in/ URL — always write it, even if target already has a Sales Nav URL
const apolloLinkedinUrl = result.linkedin_url?.includes("/in/") ? result.linkedin_url : null;
db.prepare(`
UPDATE targets SET
apollo_id = ?,
seniority = ?,
apollo_functions = ?,
apollo_departments = ?,
email = COALESCE(email, ?),
email_status = COALESCE(email_status, ?),
email_domain_catchall = ?,
city = COALESCE(city, ?),
country = COALESCE(country, ?),
time_zone = COALESCE(time_zone, ?),
headline = COALESCE(headline, ?),
positions_json = COALESCE(positions_json, ?),
company_id = COALESCE(company_id, ?),
linkedin_url = COALESCE(?, linkedin_url),
company_size = COALESCE(company_size, ?),
apollo_enriched_at = datetime('now')
WHERE id = ?
`).run(
result.apollo_id,
result.seniority ?? null,
result.functions ? JSON.stringify(result.functions) : null,
result.departments ? JSON.stringify(result.departments) : null,
result.email ?? null,
result.email_status ?? null,
result.email_domain_catchall ? 1 : 0,
result.city ?? null,
result.country ?? null,
result.time_zone ?? null,
result.headline ?? null,
result.positions_json ?? null,
companyId,
apolloLinkedinUrl,
result.organization?.estimated_num_employees ?? null,
target.id
);
enriched++;
} catch {
skipped++;
}
}
return res.json({ enriched, notFound, skipped, total: targets.length });
}
export const config = {
api: { responseLimit: false },
};
+35
View File
@@ -0,0 +1,35 @@
import type { NextApiRequest, NextApiResponse } from "next";
import { getDb } from "@/lib/db";
// GET /api/lists/[id]/conflicts
// Returns how many prospects in this list are already active in a running/paused workflow
export default function handler(req: NextApiRequest, res: NextApiResponse) {
if (req.method !== "GET") {
res.setHeader("Allow", ["GET"]);
return res.status(405).end();
}
const db = getDb();
const listId = req.query.id as string;
const total = (db.prepare(
"SELECT COUNT(*) as c FROM list_targets WHERE list_id = ?"
).get(listId) as { c: number }).c;
const blocked = (db.prepare(
`SELECT COUNT(DISTINCT lt.target_id) as blocked
FROM list_targets lt
WHERE lt.list_id = ?
AND lt.target_id IN (
SELECT 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')
)
)`
).get(listId) as { blocked: number }).blocked;
return res.json({ total, blocked });
}
+14
View File
@@ -0,0 +1,14 @@
import type { NextApiRequest, NextApiResponse } from "next";
import { buildCsvTemplate } from "@/lib/csv-import";
export default function handler(req: NextApiRequest, res: NextApiResponse) {
if (req.method !== "GET") {
res.setHeader("Allow", ["GET"]);
return res.status(405).end();
}
const csv = buildCsvTemplate();
res.setHeader("Content-Type", "text/csv");
res.setHeader("Content-Disposition", `attachment; filename="linki-import-template.csv"`);
res.status(200).send(csv);
}
+51
View File
@@ -0,0 +1,51 @@
import type { NextApiRequest, NextApiResponse } from "next";
import { getDb } from "@/lib/db";
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
if (req.method !== "POST") {
res.setHeader("Allow", ["POST"]);
return res.status(405).end();
}
const db = getDb();
const listId = req.query.id as string;
const list = db.prepare("SELECT * FROM lists WHERE id = ?").get(listId);
if (!list) return res.status(404).json({ error: "List not found" });
const { account_id } = req.body;
if (!account_id) return res.status(400).json({ error: "account_id required" });
const account = db.prepare("SELECT * FROM accounts WHERE id = ?").get(account_id) as
| { cookies_json: string | null; is_authenticated: number }
| undefined;
if (!account) return res.status(400).json({ error: "Account not found" });
if (!account.is_authenticated || !account.cookies_json) {
return res.status(400).json({ error: "Account not authenticated" });
}
const pending = db.prepare(`
SELECT COUNT(*) as c FROM targets t
JOIN list_targets lt ON lt.target_id = t.id
WHERE lt.list_id = ? AND t.sales_nav_url IS NOT NULL AND t.enriched_profile_at IS NULL
`).get(listId) as { c: number };
// Respond immediately — enrichment runs in background
res.json({ started: true, profiles: pending.c });
// Fire and forget — do not await
setImmediate(async () => {
try {
const { getSessionContext } = await import("@/lib/linkedin/session");
const { enrichList } = await import("@/lib/linkedin/enrich");
const ctx = await getSessionContext(account_id);
await enrichList(ctx, listId);
} catch (err) {
console.error("[enrich] background enrichment failed:", err instanceof Error ? err.message : err);
}
});
}
export const config = {
api: { responseLimit: false },
};
+24
View File
@@ -0,0 +1,24 @@
import type { NextApiRequest, NextApiResponse } from "next";
import { getDb } from "@/lib/db";
import { importCsv } from "@/lib/csv-import";
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 listId = req.query.id as string;
const list = db.prepare("SELECT id FROM lists WHERE id = ?").get(listId) as { id: string } | undefined;
if (!list) return res.status(404).json({ error: "List not found" });
const { csv } = req.body as { csv?: string };
if (!csv || typeof csv !== "string" || !csv.trim()) {
return res.status(400).json({ error: "csv content is required" });
}
const result = importCsv(db, listId, csv);
res.json(result);
}
+48
View File
@@ -0,0 +1,48 @@
import type { NextApiRequest, NextApiResponse } from "next";
import { getDb } from "@/lib/db";
import { getDailyImportCap } from "@/lib/import-jobs";
export default function handler(req: NextApiRequest, res: NextApiResponse) {
if (req.method !== "GET") {
res.setHeader("Allow", ["GET"]);
return res.status(405).end();
}
const db = getDb();
const listId = req.query.id as string;
const dailyCap = getDailyImportCap(db);
// All batches for this list, newest first
const batches = db.prepare(`
SELECT id, status, phase, page, total_pages, count, total, imported, skipped, error,
scheduled_for, start_page, batch_index, started_at, finished_at
FROM list_imports
WHERE list_id = ?
ORDER BY batch_index ASC, started_at DESC
`).all(listId) as Array<{
id: string; status: string; phase: string | null; page: number; total_pages: number;
count: number; total: number; imported: number; skipped: number; error: string | null;
scheduled_for: string | null; start_page: number; batch_index: number;
started_at: string; finished_at: string | null;
}>;
if (batches.length === 0) return res.json({ status: "idle", dailyCap });
// The "current" batch = running > scheduled > most recent — drives the old single-job UI
const current =
batches.find((b) => b.status === "running") ??
batches.find((b) => b.status === "scheduled") ??
batches[batches.length - 1];
const total = batches.reduce((m, b) => Math.max(m, b.total || 0), 0);
const importedSoFar = batches.reduce((s, b) => s + (b.imported || 0), 0);
const remaining = total > 0 ? Math.max(0, total - importedSoFar) : 0;
return res.json({
...current,
dailyCap,
batches,
// Plan summary: is this list being split across days?
plan: { total, importedSoFar, remaining, exceedsCap: total > dailyCap, dailyCap },
});
}
+48
View File
@@ -0,0 +1,48 @@
import type { NextApiRequest, NextApiResponse } from "next";
import { getDb } from "@/lib/db";
import { startImport, getDailyImportCap } from "@/lib/import-jobs";
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
if (req.method !== "POST") {
res.setHeader("Allow", ["POST"]);
return res.status(405).end();
}
const db = getDb();
const listId = req.query.id as string;
const list = db.prepare("SELECT * FROM lists WHERE id = ?").get(listId);
if (!list) return res.status(404).json({ error: "List not found" });
const { sales_nav_url, account_id, enrich } = req.body as {
sales_nav_url?: string;
account_id?: string;
enrich?: boolean;
};
if (!sales_nav_url) return res.status(400).json({ error: "sales_nav_url required" });
if (!account_id) return res.status(400).json({ error: "account_id required" });
const account = db.prepare("SELECT * FROM accounts WHERE id = ?").get(account_id) as
| { cookies_json: string | null; is_authenticated: number }
| undefined;
if (!account) return res.status(400).json({ error: "Account not found" });
if (!account.is_authenticated || !account.cookies_json) {
return res.status(400).json({ error: "Account not authenticated. Please authenticate first." });
}
// Already an active import for this list?
const existing = db
.prepare("SELECT id FROM list_imports WHERE list_id = ? AND status IN ('running','scheduled')")
.get(listId);
if (existing) {
return res.status(409).json({ error: "An import is already queued or running for this list" });
}
// Save the Sales Nav URL on the list for reference
db.prepare("UPDATE lists SET sales_nav_url = ? WHERE id = ?").run(sales_nav_url, listId);
// Queue the first batch — the runner scheduler picks it up (one import at a time)
const { importId } = startImport(db, { listId, accountId: account_id, salesNavUrl: sales_nav_url, enrich });
res.json({ started: true, importId, dailyCap: getDailyImportCap(db) });
}
+38
View File
@@ -0,0 +1,38 @@
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 list = db.prepare("SELECT * FROM lists WHERE id = ?").get(id);
if (!list) return res.status(404).json({ error: "Not found" });
const targets = db
.prepare(
`SELECT t.* FROM targets t
JOIN list_targets lt ON lt.target_id = t.id
WHERE lt.list_id = ?
ORDER BY t.created_at DESC`
)
.all(id);
return res.json({ ...list, targets });
}
if (req.method === "PUT") {
const { name, description } = req.body;
db.prepare(
"UPDATE lists SET name = COALESCE(?, name), description = COALESCE(?, description) WHERE id = ?"
).run(name, description, id);
return res.json(db.prepare("SELECT * FROM lists WHERE id = ?").get(id));
}
if (req.method === "DELETE") {
db.prepare("DELETE FROM runs WHERE list_id = ?").run(id);
db.prepare("DELETE FROM lists WHERE id = ?").run(id);
return res.status(204).end();
}
res.setHeader("Allow", ["GET", "PUT", "DELETE"]);
res.status(405).end();
}
+45
View File
@@ -0,0 +1,45 @@
import type { NextApiRequest, NextApiResponse } from "next";
import { getDb } from "@/lib/db";
// POST /api/lists/[id]/move-targets
// body: { target_ids: string[], destination_list_id: string }
// Moves targets from source list to destination list (removes from source, adds to destination)
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 sourceListId = req.query.id as string;
const { target_ids, destination_list_id } = req.body as {
target_ids: string[];
destination_list_id: string;
};
if (!Array.isArray(target_ids) || target_ids.length === 0)
return res.status(400).json({ error: "target_ids must be a non-empty array" });
if (!destination_list_id)
return res.status(400).json({ error: "destination_list_id required" });
if (destination_list_id === sourceListId)
return res.status(400).json({ error: "Source and destination list are the same" });
const dest = db.prepare("SELECT id FROM lists WHERE id = ?").get(destination_list_id);
if (!dest) return res.status(404).json({ error: "Destination list not found" });
const placeholders = target_ids.map(() => "?").join(",");
db.transaction(() => {
db.prepare(
`DELETE FROM list_targets WHERE list_id = ? AND target_id IN (${placeholders})`
).run(sourceListId, ...target_ids);
for (const tid of target_ids) {
db.prepare(
`INSERT OR IGNORE INTO list_targets (list_id, target_id) VALUES (?, ?)`
).run(destination_list_id, tid);
}
})();
return res.json({ moved: target_ids.length });
}
+92
View File
@@ -0,0 +1,92 @@
import type { NextApiRequest, NextApiResponse } from "next";
import { getDb } from "@/lib/db";
// Remove contacts from a list (membership only — never deletes the contact). Filters are OR'd:
// titles (exact), title_patterns (LIKE %p%), exclude_location_substrings (LIKE %l%). dry_run previews.
export default function handler(req: NextApiRequest, res: NextApiResponse) {
if (req.method !== "POST") return res.status(405).end();
const db = getDb();
const list_id = req.query.id as string;
const list = db.prepare("SELECT id FROM lists WHERE id = ?").get(list_id);
if (!list) return res.status(404).json({ error: "List not found" });
const { contact_ids, titles, title_patterns, exclude_location_substrings, dry_run = true } = req.body as {
contact_ids?: string[];
titles?: string[];
title_patterns?: string[];
exclude_location_substrings?: string[];
dry_run?: boolean;
};
const conditions: string[] = [];
const params: unknown[] = [list_id];
// Precise, ID-scoped removal — safest path (no title collisions). When
// contact_ids is given it is OR'd in like any other filter, so a curated set
// (built manually or by an LLM pass) removes exactly those contacts.
if (contact_ids && contact_ids.length > 0) {
const placeholders = contact_ids.map(() => "?").join(", ");
conditions.push(`t.id IN (${placeholders})`);
params.push(...contact_ids);
}
if (titles && titles.length > 0) {
const placeholders = titles.map(() => "?").join(", ");
conditions.push(`t.title IN (${placeholders})`);
params.push(...titles);
}
if (title_patterns && title_patterns.length > 0) {
const patternClauses = title_patterns.map(() => "t.title LIKE ?").join(" OR ");
conditions.push(`(${patternClauses})`);
for (const p of title_patterns) params.push(`%${p}%`);
}
if (exclude_location_substrings && exclude_location_substrings.length > 0) {
const locClauses = exclude_location_substrings.map(() => "t.location LIKE ?").join(" OR ");
conditions.push(`(${locClauses})`);
for (const l of exclude_location_substrings) params.push(`%${l}%`);
}
if (conditions.length === 0) {
return res.status(400).json({ error: "No filters provided — nothing to remove." });
}
const whereFilter = conditions.join(" OR ");
const preview = db.prepare(`
SELECT t.id, t.full_name, t.title, t.location
FROM list_targets lt
JOIN targets t ON t.id = lt.target_id
WHERE lt.list_id = ? AND (${whereFilter})
ORDER BY t.title
`).all(...params);
if (dry_run) {
return res.json({ dry_run: true, would_remove: preview.length, contacts: preview });
}
db.prepare(`
DELETE FROM list_targets
WHERE list_id = ?
AND target_id IN (
SELECT t.id FROM list_targets lt
JOIN targets t ON t.id = lt.target_id
WHERE lt.list_id = ? AND (${whereFilter})
)
`).run(list_id, list_id, ...params.slice(1));
const remaining = (db.prepare("SELECT COUNT(*) as c FROM list_targets WHERE list_id = ?").get(list_id) as { c: number }).c;
// Surface the exact removed IDs so a removal is trivially reversible:
// feed removed_contact_ids straight into add_to_list to undo this batch.
const removedIds = (preview as Array<{ id: string }>).map((c) => c.id);
return res.json({
dry_run: false,
removed: preview.length,
remaining,
contacts_removed: preview,
removed_contact_ids: removedIds,
undo_hint: "To undo, call add_to_list with these removed_contact_ids.",
});
}
+66
View File
@@ -0,0 +1,66 @@
import type { NextApiRequest, NextApiResponse } from "next";
import { getDb } from "@/lib/db";
// POST /api/lists/[id]/sync-status body: { account_id: number }
// Re-fetches the Sales Nav list and updates degree for non-connected targets.
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
if (req.method !== "POST") {
res.setHeader("Allow", ["POST"]);
return res.status(405).end();
}
const db = getDb();
const listId = req.query.id as string;
const list = db.prepare("SELECT * FROM lists WHERE id = ?").get(listId) as
| { sales_nav_url?: string }
| undefined;
if (!list) return res.status(404).json({ error: "List not found" });
if (!list.sales_nav_url) return res.status(400).json({ error: "No Sales Navigator URL saved for this list — run an import first" });
const { account_id } = req.body as { account_id: string };
if (!account_id) return res.status(400).json({ error: "account_id required" });
const account = db.prepare("SELECT * FROM accounts WHERE id = ?").get(account_id) as
| { cookies_json: string | null; is_authenticated: number }
| undefined;
if (!account?.is_authenticated) return res.status(400).json({ error: "Account not authenticated" });
const { getSessionContext } = await import("@/lib/linkedin/session");
const { scrapeNavigatorList } = await import("@/lib/linkedin/scraper");
try {
const ctx = await getSessionContext(account_id);
const { profiles } = await scrapeNavigatorList(ctx, list.sales_nav_url, { maxPages: 300 });
const updateDegree = db.prepare("UPDATE targets SET degree = ? WHERE linkedin_url = ?");
const markConnected = db.prepare(
`UPDATE targets SET degree = ?, connected_at = CASE
WHEN (degree IS NULL OR degree != 1) AND connected_at IS NULL THEN datetime('now')
ELSE connected_at
END
WHERE linkedin_url = ?`
);
let updated = 0;
db.transaction(() => {
for (const p of profiles) {
if (p.degree === 1) {
markConnected.run(p.degree, p.salesNavUrl);
} else {
updateDegree.run(p.degree, p.salesNavUrl);
}
updated++;
}
})();
return res.json({ updated, total: profiles.length });
} catch (err: unknown) {
const message = err instanceof Error ? err.message : String(err);
return res.status(500).json({ error: message });
}
}
export const config = {
api: { responseLimit: false },
};
+26
View File
@@ -0,0 +1,26 @@
import type { NextApiRequest, NextApiResponse } from "next";
import { getDb } from "@/lib/db";
// DELETE /api/lists/[id]/targets body: { target_ids: number[] }
// Removes targets from the list (list_targets rows only, does not delete the target itself)
export default function handler(req: NextApiRequest, res: NextApiResponse) {
if (req.method !== "DELETE") {
res.setHeader("Allow", ["DELETE"]);
return res.status(405).end();
}
const db = getDb();
const listId = 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 must be a non-empty array" });
}
const placeholders = target_ids.map(() => "?").join(",");
const result = db
.prepare(`DELETE FROM list_targets WHERE list_id = ? AND target_id IN (${placeholders})`)
.run(listId, ...target_ids);
return res.json({ removed: result.changes });
}
+33
View File
@@ -0,0 +1,33 @@
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 lists = db
.prepare(
`SELECT l.*, COUNT(lt.target_id) as target_count
FROM lists l
LEFT JOIN list_targets lt ON lt.list_id = l.id
GROUP BY l.id
ORDER BY l.created_at DESC`
)
.all();
return res.json(lists);
}
if (req.method === "POST") {
const { name, description } = req.body;
if (!name) return res.status(400).json({ error: "name required" });
const id = randomUUID();
db
.prepare("INSERT INTO lists (id, name, description) VALUES (?, ?, ?)")
.run(id, name, description ?? null);
return res.status(201).json(db.prepare("SELECT * FROM lists WHERE id = ?").get(id));
}
res.setHeader("Allow", ["GET", "POST"]);
res.status(405).end();
}