release: 2026-08-01
This commit is contained in:
@@ -0,0 +1,50 @@
|
||||
import type { NextApiRequest, NextApiResponse } from "next";
|
||||
import { getDb } from "@/lib/db";
|
||||
import { encryptSecret } from "@/lib/crypto";
|
||||
|
||||
export default async 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 account = db.prepare("SELECT * FROM accounts WHERE id = ?").get(id);
|
||||
if (!account) return res.status(404).json({ error: "Account not found" });
|
||||
|
||||
const { li_at, document_cookie } = req.body as { li_at?: string; document_cookie?: string };
|
||||
if (!li_at) return res.status(400).json({ error: "li_at cookie is required" });
|
||||
|
||||
// Parse document.cookie string into cookie objects
|
||||
const extraCookies: { name: string; value: string; domain: string; path: string }[] = [];
|
||||
if (document_cookie) {
|
||||
for (const part of document_cookie.split(";")) {
|
||||
const eqIdx = part.indexOf("=");
|
||||
if (eqIdx === -1) continue;
|
||||
const name = part.slice(0, eqIdx).trim();
|
||||
const value = part.slice(eqIdx + 1).trim();
|
||||
if (name && value) {
|
||||
extraCookies.push({ name, value, domain: ".linkedin.com", path: "/" });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Build Playwright-compatible storageState
|
||||
const storageState = {
|
||||
cookies: [
|
||||
{ name: "li_at", value: li_at.trim(), domain: ".linkedin.com", path: "/", httpOnly: true, secure: true, sameSite: "None" as const },
|
||||
...extraCookies.filter((c) => c.name !== "li_at"),
|
||||
],
|
||||
origins: [],
|
||||
};
|
||||
|
||||
db.prepare("UPDATE accounts SET cookies_json = ?, is_authenticated = 1 WHERE id = ?").run(
|
||||
encryptSecret(JSON.stringify(storageState)),
|
||||
id
|
||||
);
|
||||
|
||||
// Evict the cached browser context so next import uses the new cookies
|
||||
const { closeSession } = await import("@/lib/linkedin/session");
|
||||
await closeSession(id);
|
||||
|
||||
return res.json({ ok: true });
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
import type { NextApiRequest, NextApiResponse } from "next";
|
||||
import { getDb } from "@/lib/db";
|
||||
|
||||
// Excludes cookies_json — the frontend never uses the raw session blob, only
|
||||
// is_authenticated, so there's no reason to ship it (even encrypted) to the client.
|
||||
const ACCOUNT_COLUMNS = `id, name, email, is_authenticated, daily_connection_limit, daily_message_limit, daily_inmail_limit,
|
||||
active_hours_start, active_hours_end, timezone, working_days, created_at,
|
||||
inbox_synced_at, accepted_sync_at, li_connections, li_pending, li_profile_views,
|
||||
li_stats_synced_at, connections_synced_through_ms`;
|
||||
|
||||
export default function handler(req: NextApiRequest, res: NextApiResponse) {
|
||||
const db = getDb();
|
||||
const id = req.query.id as string;
|
||||
|
||||
if (req.method === "GET") {
|
||||
const account = db.prepare(`SELECT ${ACCOUNT_COLUMNS} FROM accounts WHERE id = ?`).get(id);
|
||||
if (!account) return res.status(404).json({ error: "Not found" });
|
||||
return res.json(account);
|
||||
}
|
||||
|
||||
if (req.method === "PUT") {
|
||||
const { name, email, daily_connection_limit, daily_message_limit, daily_inmail_limit, active_hours_start, active_hours_end, timezone, working_days } = req.body;
|
||||
db.prepare(
|
||||
`UPDATE accounts SET
|
||||
name = COALESCE(?, name),
|
||||
email = COALESCE(?, email),
|
||||
daily_connection_limit = COALESCE(?, daily_connection_limit),
|
||||
daily_message_limit = COALESCE(?, daily_message_limit),
|
||||
daily_inmail_limit = COALESCE(?, daily_inmail_limit),
|
||||
active_hours_start = COALESCE(?, active_hours_start),
|
||||
active_hours_end = COALESCE(?, active_hours_end),
|
||||
timezone = COALESCE(?, timezone),
|
||||
working_days = COALESCE(?, working_days)
|
||||
WHERE id = ?`
|
||||
).run(name, email, daily_connection_limit, daily_message_limit, daily_inmail_limit, active_hours_start, active_hours_end, timezone, working_days, id);
|
||||
return res.json(db.prepare(`SELECT ${ACCOUNT_COLUMNS} FROM accounts WHERE id = ?`).get(id));
|
||||
}
|
||||
|
||||
if (req.method === "DELETE") {
|
||||
db.prepare("DELETE FROM accounts WHERE id = ?").run(id);
|
||||
return res.status(204).end();
|
||||
}
|
||||
|
||||
res.setHeader("Allow", ["GET", "PUT", "DELETE"]);
|
||||
res.status(405).end();
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
import type { NextApiRequest, NextApiResponse } from "next";
|
||||
import { getDb } from "@/lib/db";
|
||||
import { getSessionPage, saveSessionState } from "@/lib/linkedin/session";
|
||||
import { scrapeLinkedInStats } from "@/lib/linkedin/li-stats";
|
||||
|
||||
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
|
||||
if (req.method !== "POST") return res.status(405).end();
|
||||
|
||||
const accountId = req.query.id as string;
|
||||
const db = getDb();
|
||||
const account = db.prepare("SELECT id, is_authenticated FROM accounts WHERE id = ?").get(accountId) as
|
||||
| { id: string; is_authenticated: number }
|
||||
| undefined;
|
||||
|
||||
if (!account) return res.status(404).json({ error: "Account not found" });
|
||||
if (!account.is_authenticated) return res.status(400).json({ error: "Account not authenticated" });
|
||||
|
||||
let page;
|
||||
try {
|
||||
page = await getSessionPage(accountId);
|
||||
const stats = await scrapeLinkedInStats(page);
|
||||
await saveSessionState(accountId);
|
||||
db.prepare(`
|
||||
UPDATE accounts SET
|
||||
li_connections = ?, li_pending = ?, li_profile_views = ?,
|
||||
li_stats_synced_at = datetime('now')
|
||||
WHERE id = ?
|
||||
`).run(stats.connections, stats.pending, stats.profile_views, accountId);
|
||||
return res.json(stats);
|
||||
} catch (err) {
|
||||
console.error("[li-stats]", err);
|
||||
return res.status(500).json({ error: err instanceof Error ? err.message : "Scrape failed" });
|
||||
} finally {
|
||||
await page?.close().catch(() => {});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
import type { NextApiRequest, NextApiResponse } from "next";
|
||||
import { getDb } from "@/lib/db";
|
||||
import { startHeadlessLogin, submitLoginChallenge, awaitLoginApproval } from "@/lib/linkedin/session";
|
||||
|
||||
/**
|
||||
* Server-side headless LinkedIn login.
|
||||
* POST { step: "start", email, password } → begins login (returns authenticated | challenge | error)
|
||||
* POST { step: "verify", code } → submits the email/SMS verification code
|
||||
* POST { step: "await" } → waits for a device/app approval to clear
|
||||
*
|
||||
* The session is born under the same pinned Chromium fingerprint the runner uses
|
||||
* and captures all cookies (incl. httpOnly li_ep_auth_context).
|
||||
*/
|
||||
export default async 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 account = db.prepare("SELECT * FROM accounts WHERE id = ?").get(id) as
|
||||
| { email: string }
|
||||
| undefined;
|
||||
if (!account) return res.status(404).json({ error: "Account not found" });
|
||||
|
||||
const { step } = req.body as { step?: string };
|
||||
|
||||
try {
|
||||
if (step === "verify") {
|
||||
const { code } = req.body as { code?: string };
|
||||
if (!code?.trim()) return res.status(400).json({ error: "code is required" });
|
||||
return res.json(await submitLoginChallenge(id, code.trim()));
|
||||
}
|
||||
|
||||
if (step === "await") {
|
||||
return res.json(await awaitLoginApproval(id));
|
||||
}
|
||||
|
||||
const { email, password } = req.body as { email?: string; password?: string };
|
||||
const loginEmail = (email || account.email || "").trim();
|
||||
if (!loginEmail || !password) {
|
||||
return res.status(400).json({ error: "email and password are required" });
|
||||
}
|
||||
return res.json(await startHeadlessLogin(id, loginEmail, password));
|
||||
} catch (e) {
|
||||
return res.status(500).json({ error: (e as Error).message });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
import type { NextApiRequest, NextApiResponse } from "next";
|
||||
import { getDb } from "@/lib/db";
|
||||
import { getSessionPage, saveSessionState } from "@/lib/linkedin/session";
|
||||
import { scrapePendingInvitationVanityNames } from "@/lib/linkedin/pending-invitations";
|
||||
|
||||
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
|
||||
if (req.method !== "POST") return res.status(405).end();
|
||||
|
||||
const accountId = req.query.id as string;
|
||||
const db = getDb();
|
||||
|
||||
const account = db.prepare("SELECT id, is_authenticated FROM accounts WHERE id = ?").get(accountId) as
|
||||
| { id: string; is_authenticated: number }
|
||||
| undefined;
|
||||
|
||||
if (!account) return res.status(404).json({ error: "Account not found" });
|
||||
if (!account.is_authenticated) return res.status(400).json({ error: "Account not authenticated" });
|
||||
|
||||
let page;
|
||||
try {
|
||||
page = await getSessionPage(accountId);
|
||||
const stillPending = await scrapePendingInvitationVanityNames(page);
|
||||
await saveSessionState(accountId);
|
||||
|
||||
// Find all targets that we sent a request to but haven't marked as connected
|
||||
const waiting = db.prepare(`
|
||||
SELECT id, linkedin_url, full_name
|
||||
FROM targets
|
||||
WHERE connection_requested_at IS NOT NULL
|
||||
AND (degree IS NULL OR degree != 1)
|
||||
AND connected_at IS NULL
|
||||
`).all() as { id: string; linkedin_url: string; full_name: string | null }[];
|
||||
|
||||
const now = new Date().toISOString();
|
||||
const accepted: string[] = [];
|
||||
const skipped: string[] = [];
|
||||
|
||||
const markAccepted = db.prepare(
|
||||
"UPDATE targets SET degree = 1, connected_at = ? WHERE id = ?"
|
||||
);
|
||||
|
||||
db.transaction(() => {
|
||||
for (const target of waiting) {
|
||||
const match = target.linkedin_url?.match(/\/in\/([^/?#]+)/);
|
||||
if (!match) continue; // no /in/ URL — can't check
|
||||
const vanity = match[1].toLowerCase();
|
||||
|
||||
if (!stillPending.has(vanity)) {
|
||||
// Not in the pending list anymore → accepted (or expired, but treat as accepted)
|
||||
markAccepted.run(now, target.id);
|
||||
accepted.push(target.full_name ?? vanity);
|
||||
} else {
|
||||
skipped.push(target.full_name ?? vanity);
|
||||
}
|
||||
}
|
||||
})();
|
||||
|
||||
return res.json({
|
||||
pending_on_linkedin: stillPending.size,
|
||||
waiting_in_db: waiting.length,
|
||||
newly_accepted: accepted.length,
|
||||
still_pending: skipped.length,
|
||||
accepted_names: accepted,
|
||||
});
|
||||
|
||||
} catch (err) {
|
||||
console.error("[sync-accepted]", err);
|
||||
return res.status(500).json({ error: err instanceof Error ? err.message : "Sync failed" });
|
||||
} finally {
|
||||
await page?.close().catch(() => {});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
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();
|
||||
|
||||
// Excludes cookies_json — the frontend never uses the raw session blob, only
|
||||
// is_authenticated, so there's no reason to ship it (even encrypted) to the client.
|
||||
const ACCOUNT_COLUMNS = `a.id, a.name, a.email, a.is_authenticated, a.daily_connection_limit, a.daily_message_limit, a.daily_inmail_limit,
|
||||
a.active_hours_start, a.active_hours_end, a.timezone, a.working_days, a.created_at,
|
||||
a.inbox_synced_at, a.accepted_sync_at, a.li_connections, a.li_pending, a.li_profile_views,
|
||||
a.li_stats_synced_at, a.connections_synced_through_ms`;
|
||||
|
||||
if (req.method === "GET") {
|
||||
const accounts = db.prepare(`
|
||||
SELECT ${ACCOUNT_COLUMNS},
|
||||
(SELECT COUNT(*) FROM runs r WHERE r.account_id = a.id AND r.status IN ('running', 'paused')) AS active_run_count
|
||||
FROM accounts a ORDER BY a.created_at DESC
|
||||
`).all();
|
||||
return res.json(accounts);
|
||||
}
|
||||
|
||||
if (req.method === "POST") {
|
||||
const { name, email, daily_connection_limit = 20, daily_message_limit = 50, daily_inmail_limit = 15 } = req.body;
|
||||
if (!name || !email) return res.status(400).json({ error: "name and email required" });
|
||||
try {
|
||||
const id = randomUUID();
|
||||
db
|
||||
.prepare(
|
||||
"INSERT INTO accounts (id, name, email, daily_connection_limit, daily_message_limit, daily_inmail_limit) VALUES (?, ?, ?, ?, ?, ?)"
|
||||
)
|
||||
.run(id, name, email, daily_connection_limit, daily_message_limit, daily_inmail_limit);
|
||||
const account = db.prepare(`SELECT ${ACCOUNT_COLUMNS} FROM accounts a WHERE a.id = ?`).get(id);
|
||||
return res.status(201).json(account);
|
||||
} catch {
|
||||
return res.status(409).json({ error: "Email already exists" });
|
||||
}
|
||||
}
|
||||
|
||||
res.setHeader("Allow", ["GET", "POST"]);
|
||||
res.status(405).end();
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
import NextAuth, { NextAuthOptions } from "next-auth";
|
||||
import CredentialsProvider from "next-auth/providers/credentials";
|
||||
import bcrypt from "bcryptjs";
|
||||
import { getDb } from "@/lib/db";
|
||||
import { isRateLimited } from "@/lib/rate-limit";
|
||||
|
||||
type UserRow = { id: string; email: string; password_hash: string };
|
||||
|
||||
export const authOptions: NextAuthOptions = {
|
||||
providers: [
|
||||
CredentialsProvider({
|
||||
name: "Credentials",
|
||||
credentials: {
|
||||
email: { label: "Email", type: "email" },
|
||||
password: { label: "Password", type: "password" },
|
||||
},
|
||||
async authorize(credentials, req) {
|
||||
if (!credentials?.email || !credentials?.password) return null;
|
||||
|
||||
// Throttle login attempts per IP — this is the password brute-force surface.
|
||||
if (isRateLimited(req, "login", 10, 15 * 60 * 1000)) {
|
||||
throw new Error("Too many attempts. Try again later.");
|
||||
}
|
||||
|
||||
const db = getDb();
|
||||
const user = db
|
||||
.prepare("SELECT id, email, password_hash FROM users WHERE email = ?")
|
||||
.get(credentials.email) as UserRow | undefined;
|
||||
|
||||
if (!user) return null;
|
||||
|
||||
const valid = await bcrypt.compare(credentials.password, user.password_hash);
|
||||
if (!valid) return null;
|
||||
|
||||
return { id: user.id, email: user.email };
|
||||
},
|
||||
}),
|
||||
],
|
||||
pages: {
|
||||
signIn: "/login",
|
||||
},
|
||||
session: {
|
||||
strategy: "jwt",
|
||||
},
|
||||
secret: process.env.NEXTAUTH_SECRET,
|
||||
};
|
||||
|
||||
export default NextAuth(authOptions);
|
||||
@@ -0,0 +1,39 @@
|
||||
import type { NextApiRequest, NextApiResponse } from "next";
|
||||
import { getServerSession } from "next-auth/next";
|
||||
import { authOptions } from "./[...nextauth]";
|
||||
import bcrypt from "bcryptjs";
|
||||
import { getDb } from "@/lib/db";
|
||||
|
||||
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
|
||||
if (req.method !== "POST") return res.status(405).end();
|
||||
|
||||
const session = await getServerSession(req, res, authOptions);
|
||||
if (!session?.user?.email) return res.status(401).json({ error: "Not authenticated" });
|
||||
|
||||
const { currentPassword, newPassword } = req.body as {
|
||||
currentPassword?: string;
|
||||
newPassword?: string;
|
||||
};
|
||||
|
||||
if (!currentPassword || !newPassword) {
|
||||
return res.status(400).json({ error: "Current and new password are required." });
|
||||
}
|
||||
if (newPassword.length < 8) {
|
||||
return res.status(400).json({ error: "New password must be at least 8 characters." });
|
||||
}
|
||||
|
||||
const db = getDb();
|
||||
const user = db
|
||||
.prepare("SELECT id, password_hash FROM users WHERE email = ?")
|
||||
.get(session.user.email) as { id: string; password_hash: string } | undefined;
|
||||
|
||||
if (!user) return res.status(404).json({ error: "User not found." });
|
||||
|
||||
const valid = await bcrypt.compare(currentPassword, user.password_hash);
|
||||
if (!valid) return res.status(400).json({ error: "Current password is incorrect." });
|
||||
|
||||
const hash = await bcrypt.hash(newPassword, 10);
|
||||
db.prepare("UPDATE users SET password_hash = ? WHERE id = ?").run(hash, user.id);
|
||||
|
||||
return res.status(200).json({ ok: true });
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
import type { NextApiRequest, NextApiResponse } from "next";
|
||||
import bcrypt from "bcryptjs";
|
||||
import { getDb } from "@/lib/db";
|
||||
import { randomUUID } from "crypto";
|
||||
import { isRateLimited } from "@/lib/rate-limit";
|
||||
|
||||
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
|
||||
if (req.method !== "POST") return res.status(405).end();
|
||||
|
||||
// Invite code + password are both guessable secrets — throttle attempts per IP.
|
||||
if (isRateLimited(req, "signup", 10, 15 * 60 * 1000)) {
|
||||
return res.status(429).json({ error: "Too many attempts. Try again later." });
|
||||
}
|
||||
|
||||
const { email, password, inviteCode } = req.body as {
|
||||
email?: string;
|
||||
password?: string;
|
||||
inviteCode?: string;
|
||||
};
|
||||
|
||||
if (!email || !password || !inviteCode) {
|
||||
return res.status(400).json({ error: "Email, password, and invite code are required." });
|
||||
}
|
||||
|
||||
const authPassword = process.env.AUTH_PASSWORD;
|
||||
if (!authPassword) {
|
||||
return res.status(500).json({ error: "AUTH_PASSWORD is not configured on this server." });
|
||||
}
|
||||
|
||||
if (inviteCode !== authPassword) {
|
||||
return res.status(403).json({ error: "Invalid invite code." });
|
||||
}
|
||||
|
||||
if (password.length < 8) {
|
||||
return res.status(400).json({ error: "Password must be at least 8 characters." });
|
||||
}
|
||||
|
||||
const db = getDb();
|
||||
const existing = db.prepare("SELECT id FROM users WHERE email = ?").get(email);
|
||||
if (existing) {
|
||||
return res.status(409).json({ error: "An account with this email already exists." });
|
||||
}
|
||||
|
||||
const hash = await bcrypt.hash(password, 10);
|
||||
db.prepare("INSERT INTO users (id, email, password_hash) VALUES (?, ?, ?)").run(randomUUID(), email, hash);
|
||||
|
||||
return res.status(201).json({ ok: true });
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
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 company = db.prepare("SELECT * FROM companies WHERE id = ?").get(id);
|
||||
if (!company) return res.status(404).json({ error: "not found" });
|
||||
const contacts = db
|
||||
.prepare("SELECT id, full_name, title, email, linkedin_url FROM targets WHERE company_id = ? ORDER BY full_name")
|
||||
.all(id);
|
||||
return res.json({ ...company as object, contacts });
|
||||
}
|
||||
|
||||
if (req.method === "PUT") {
|
||||
const { name, domain, industry, location, linkedin_url, website, notes } = req.body;
|
||||
db.prepare(`
|
||||
UPDATE companies SET
|
||||
name = COALESCE(?, name),
|
||||
domain = ?,
|
||||
industry = ?,
|
||||
location = ?,
|
||||
linkedin_url = ?,
|
||||
website = ?,
|
||||
notes = ?
|
||||
WHERE id = ?
|
||||
`).run(
|
||||
name ?? null, domain ?? null, industry ?? null,
|
||||
location ?? null, linkedin_url ?? null, website ?? null, notes ?? null,
|
||||
id
|
||||
);
|
||||
return res.json(db.prepare("SELECT * FROM companies WHERE id = ?").get(id));
|
||||
}
|
||||
|
||||
if (req.method === "DELETE") {
|
||||
// Unlink contacts first, then delete company
|
||||
db.prepare("UPDATE targets SET company_id = NULL WHERE company_id = ?").run(id);
|
||||
db.prepare("DELETE FROM companies WHERE id = ?").run(id);
|
||||
return res.json({ ok: true });
|
||||
}
|
||||
|
||||
res.status(405).end();
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
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") {
|
||||
// Paging + light default fields — the full enrichment blobs (description, keywords,
|
||||
// technology_names, etc.) are heavy; only return them when full=1 is requested.
|
||||
const full = req.query.full === "1" || req.query.full === "true";
|
||||
const search = (req.query.search as string | undefined)?.trim();
|
||||
// Page by default (trimmed fields). full=1 with no explicit limit returns the whole set
|
||||
// (the companies UI relies on this for its own client-side search/filter).
|
||||
const explicitPaging = req.query.limit !== undefined || req.query.page !== undefined;
|
||||
const hasPaging = explicitPaging || !full;
|
||||
const limit = Math.min(Math.max(Number(req.query.limit) || 50, 1), 500);
|
||||
const offset = (Number(req.query.page) || 0) * limit;
|
||||
|
||||
const where = search ? "WHERE c.name LIKE ?" : "";
|
||||
const whereArgs: unknown[] = search ? [`%${search}%`] : [];
|
||||
|
||||
const select = full
|
||||
? "c.*"
|
||||
: "c.id, c.name, c.domain, c.industry, c.location, c.website, c.employee_count, c.created_at";
|
||||
|
||||
const total = (db.prepare(`SELECT COUNT(*) as c FROM companies c ${where}`).get(...whereArgs) as { c: number }).c;
|
||||
|
||||
const pageClause = hasPaging ? " LIMIT ? OFFSET ?" : "";
|
||||
const pageArgs = hasPaging ? [limit, offset] : [];
|
||||
|
||||
const companies = db.prepare(`
|
||||
SELECT ${select}, COUNT(t.id) as contact_count
|
||||
FROM companies c
|
||||
LEFT JOIN targets t ON t.company_id = c.id
|
||||
${where}
|
||||
GROUP BY c.id
|
||||
ORDER BY c.name COLLATE NOCASE${pageClause}
|
||||
`).all(...whereArgs, ...pageArgs);
|
||||
|
||||
return res.json({ companies, total });
|
||||
}
|
||||
|
||||
if (req.method === "POST") {
|
||||
const { name, domain, industry, location, linkedin_url, website, notes } = req.body;
|
||||
if (!name) return res.status(400).json({ error: "name required" });
|
||||
const id = randomUUID();
|
||||
db.prepare(`
|
||||
INSERT INTO companies (id, name, domain, industry, location, linkedin_url, website, notes)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
|
||||
`).run(id, name, domain ?? null, industry ?? null, location ?? null, linkedin_url ?? null, website ?? null, notes ?? null);
|
||||
return res.status(201).json(db.prepare("SELECT * FROM companies WHERE id = ?").get(id));
|
||||
}
|
||||
|
||||
res.setHeader("Allow", ["GET", "POST"]);
|
||||
res.status(405).end();
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
import type { NextApiRequest, NextApiResponse } from "next";
|
||||
import { getDb } from "@/lib/db";
|
||||
|
||||
export default function handler(req: NextApiRequest, res: NextApiResponse) {
|
||||
if (req.method !== "GET") return res.status(405).end();
|
||||
|
||||
try {
|
||||
const db = getDb();
|
||||
const days = Math.min(Math.max(Number(req.query.days) || 7, 7), 90);
|
||||
|
||||
const daily = db.prepare(`
|
||||
SELECT
|
||||
date(created_at) AS day,
|
||||
SUM(cost_usd) AS cost_usd,
|
||||
SUM(input_tokens) AS input_tokens,
|
||||
SUM(output_tokens) AS output_tokens
|
||||
FROM agent_sessions
|
||||
WHERE created_at >= datetime('now', '-${days} days')
|
||||
GROUP BY date(created_at)
|
||||
ORDER BY day ASC
|
||||
`).all() as { day: string; cost_usd: number; input_tokens: number; output_tokens: number }[];
|
||||
|
||||
// Fill missing days with zeros
|
||||
const filled: typeof daily = [];
|
||||
for (let i = days - 1; i >= 0; i--) {
|
||||
const d = new Date();
|
||||
d.setDate(d.getDate() - i);
|
||||
const key = d.toISOString().slice(0, 10);
|
||||
const found = daily.find(r => r.day === key);
|
||||
filled.push(found ?? { day: key, cost_usd: 0, input_tokens: 0, output_tokens: 0 });
|
||||
}
|
||||
|
||||
res.json({ daily: filled });
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
res.status(500).json({ error: "Failed to load agent stats" });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,170 @@
|
||||
import type { NextApiRequest, NextApiResponse } from "next";
|
||||
import { getDb } from "@/lib/db";
|
||||
|
||||
export default function handler(req: NextApiRequest, res: NextApiResponse) {
|
||||
if (req.method !== "GET") return res.status(405).end();
|
||||
|
||||
try {
|
||||
const db = getDb();
|
||||
|
||||
const listId = req.query.list_id as string | undefined;
|
||||
const workflowId = req.query.workflow_id as string | undefined;
|
||||
const days = Math.min(Math.max(Number(req.query.days) || 7, 7), 90);
|
||||
|
||||
// Fetch lists and workflows for filter dropdowns (always unfiltered)
|
||||
const lists = db.prepare("SELECT id, name FROM lists ORDER BY name").all() as { id: string; name: string }[];
|
||||
const workflows = db.prepare("SELECT id, name FROM workflows ORDER BY name").all() as { id: string; name: string }[];
|
||||
|
||||
// Today's summary (always global — not scoped to filter)
|
||||
const today = db.prepare(`
|
||||
SELECT
|
||||
COUNT(CASE WHEN message LIKE 'Visited%' THEN 1 END) AS visits_today,
|
||||
COUNT(CASE WHEN message LIKE 'Connection request sent%' THEN 1 END) AS connections_today,
|
||||
COUNT(CASE WHEN message LIKE 'Message sent%' THEN 1 END) AS messages_today,
|
||||
COUNT(CASE WHEN message LIKE 'InMail sent%' THEN 1 END) AS inmails_today
|
||||
FROM logs
|
||||
WHERE date(created_at) = date('now')
|
||||
`).get() as Record<string, number>;
|
||||
|
||||
if (!workflowId && !listId) {
|
||||
// ── Unfiltered: use targets fields (fast, global) ──────────────────────
|
||||
const ACTIVE = `id IN (SELECT DISTINCT target_id FROM list_targets)`;
|
||||
|
||||
const totals = db.prepare(`
|
||||
SELECT
|
||||
(SELECT COUNT(*) FROM targets WHERE ${ACTIVE}) AS total_targets,
|
||||
(SELECT COUNT(*) FROM targets WHERE ${ACTIVE} AND connection_requested_at IS NOT NULL) AS connections_requested,
|
||||
(SELECT COUNT(*) FROM targets WHERE ${ACTIVE} AND connected_at IS NOT NULL) AS connected,
|
||||
(SELECT COUNT(*) FROM targets WHERE ${ACTIVE} AND message_sent_at IS NOT NULL) AS messages_sent,
|
||||
(SELECT COUNT(*) FROM targets WHERE ${ACTIVE} AND inmail_sent_at IS NOT NULL) AS inmails_sent,
|
||||
(SELECT COUNT(*) FROM targets WHERE ${ACTIVE} AND last_replied_at IS NOT NULL) AS replies_received,
|
||||
(SELECT COUNT(*) FROM runs WHERE status = 'running') AS active_runs,
|
||||
(SELECT COUNT(*) FROM lists) AS total_lists,
|
||||
(SELECT COUNT(*) FROM workflows) AS total_workflows,
|
||||
(SELECT COUNT(*) FROM logs WHERE message LIKE 'Email sent%') AS emails_sent,
|
||||
(SELECT COUNT(*) FROM targets WHERE ${ACTIVE} AND email_replied_at IS NOT NULL) AS email_replies
|
||||
`).get() as Record<string, number>;
|
||||
|
||||
const activity = db.prepare(`
|
||||
SELECT
|
||||
date(created_at) AS day,
|
||||
COUNT(CASE WHEN message LIKE 'Visited%' THEN 1 END) AS visits,
|
||||
COUNT(CASE WHEN message LIKE 'Connection request sent%' THEN 1 END) AS connections,
|
||||
COUNT(CASE WHEN message LIKE 'Message sent%' THEN 1 END) AS messages,
|
||||
COUNT(CASE WHEN message LIKE 'InMail sent%' THEN 1 END) AS inmails,
|
||||
COUNT(CASE WHEN message LIKE 'Email sent%' THEN 1 END) AS emails
|
||||
FROM logs
|
||||
WHERE created_at >= datetime('now', '-${days} days')
|
||||
GROUP BY date(created_at)
|
||||
ORDER BY day ASC
|
||||
`).all() as { day: string; visits: number; connections: number; messages: number; inmails: number; emails: number }[];
|
||||
|
||||
const filled = fillDays(activity, days);
|
||||
return res.json({ totals, today, activity: filled, lists, workflows });
|
||||
}
|
||||
|
||||
// ── Filtered by workflow or list: use logs as source of truth ─────────────
|
||||
// Build the scoped runs subquery + its single argument
|
||||
let runsSubquery: string;
|
||||
let runsArg: string;
|
||||
if (workflowId) {
|
||||
runsSubquery = `SELECT id FROM runs WHERE workflow_id = ? AND status IN ('running','paused','completed')`;
|
||||
runsArg = workflowId;
|
||||
} else {
|
||||
runsSubquery = `SELECT id FROM runs WHERE list_id = ? AND status IN ('running','paused','completed')`;
|
||||
runsArg = listId!;
|
||||
}
|
||||
|
||||
// Targets in scope = distinct targets that appeared in scoped runs
|
||||
const SCOPED_TARGETS = `SELECT DISTINCT target_id FROM run_profiles WHERE run_id IN (${runsSubquery})`;
|
||||
|
||||
const totals = db.prepare(`
|
||||
SELECT
|
||||
(SELECT COUNT(*) FROM (${SCOPED_TARGETS})) AS total_targets,
|
||||
|
||||
(SELECT COUNT(DISTINCT target_id) FROM logs
|
||||
WHERE run_id IN (${runsSubquery})
|
||||
AND message LIKE 'Connection request sent%') AS connections_requested,
|
||||
|
||||
(SELECT COUNT(DISTINCT l.target_id) FROM logs l
|
||||
JOIN targets t ON t.id = l.target_id
|
||||
WHERE l.run_id IN (${runsSubquery})
|
||||
AND l.message LIKE 'Connection request sent%'
|
||||
AND t.connected_at IS NOT NULL) AS connected,
|
||||
|
||||
(SELECT COUNT(DISTINCT target_id) FROM logs
|
||||
WHERE run_id IN (${runsSubquery})
|
||||
AND message LIKE 'Message sent%') AS messages_sent,
|
||||
|
||||
(SELECT COUNT(DISTINCT target_id) FROM logs
|
||||
WHERE run_id IN (${runsSubquery})
|
||||
AND message LIKE 'InMail sent%') AS inmails_sent,
|
||||
|
||||
(SELECT COUNT(DISTINCT l.target_id) FROM logs l
|
||||
JOIN targets t ON t.id = l.target_id
|
||||
WHERE l.run_id IN (${runsSubquery})
|
||||
AND (l.message LIKE 'Message sent%' OR l.message LIKE 'InMail sent%')
|
||||
AND t.last_replied_at IS NOT NULL) AS replies_received,
|
||||
|
||||
(SELECT COUNT(*) FROM runs WHERE status = 'running') AS active_runs,
|
||||
(SELECT COUNT(*) FROM lists) AS total_lists,
|
||||
(SELECT COUNT(*) FROM workflows) AS total_workflows,
|
||||
|
||||
(SELECT COUNT(DISTINCT target_id) FROM logs
|
||||
WHERE run_id IN (${runsSubquery})
|
||||
AND message LIKE 'Email sent%') AS emails_sent,
|
||||
|
||||
(SELECT COUNT(DISTINCT l.target_id) FROM logs l
|
||||
JOIN targets t ON t.id = l.target_id
|
||||
WHERE l.run_id IN (${runsSubquery})
|
||||
AND l.message LIKE 'Email sent%'
|
||||
AND t.email_replied_at IS NOT NULL) AS email_replies
|
||||
`).get(
|
||||
runsArg, // SCOPED_TARGETS
|
||||
runsArg, // connections_requested
|
||||
runsArg, // connected
|
||||
runsArg, // messages_sent
|
||||
runsArg, // inmails_sent
|
||||
runsArg, // replies_received
|
||||
runsArg, // emails_sent
|
||||
runsArg, // email_replies
|
||||
) as Record<string, number>;
|
||||
|
||||
const activity = db.prepare(`
|
||||
SELECT
|
||||
date(created_at) AS day,
|
||||
COUNT(CASE WHEN message LIKE 'Visited%' THEN 1 END) AS visits,
|
||||
COUNT(CASE WHEN message LIKE 'Connection request sent%' THEN 1 END) AS connections,
|
||||
COUNT(CASE WHEN message LIKE 'Message sent%' THEN 1 END) AS messages,
|
||||
COUNT(CASE WHEN message LIKE 'InMail sent%' THEN 1 END) AS inmails,
|
||||
COUNT(CASE WHEN message LIKE 'Email sent%' THEN 1 END) AS emails
|
||||
FROM logs
|
||||
WHERE created_at >= datetime('now', '-${days} days')
|
||||
AND run_id IN (${runsSubquery})
|
||||
GROUP BY date(created_at)
|
||||
ORDER BY day ASC
|
||||
`).all(runsArg) as { day: string; visits: number; connections: number; messages: number; inmails: number; emails: number }[];
|
||||
|
||||
const filled = fillDays(activity, days);
|
||||
return res.json({ totals, today, activity: filled, lists, workflows });
|
||||
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
res.status(500).json({ error: "Failed to load dashboard stats" });
|
||||
}
|
||||
}
|
||||
|
||||
function fillDays(
|
||||
activity: { day: string; visits: number; connections: number; messages: number; inmails: number; emails: number }[],
|
||||
days: number
|
||||
) {
|
||||
const filled: typeof activity = [];
|
||||
for (let i = days - 1; i >= 0; i--) {
|
||||
const d = new Date();
|
||||
d.setDate(d.getDate() - i);
|
||||
const key = d.toISOString().slice(0, 10);
|
||||
const found = activity.find(r => r.day === key);
|
||||
filled.push(found ?? { day: key, visits: 0, connections: 0, messages: 0, inmails: 0, emails: 0 });
|
||||
}
|
||||
return filled;
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
import type { NextApiRequest, NextApiResponse } from "next";
|
||||
import { getDb } from "@/lib/db";
|
||||
import { encryptSecret } from "@/lib/crypto";
|
||||
|
||||
export default function handler(req: NextApiRequest, res: NextApiResponse) {
|
||||
const db = getDb();
|
||||
const id = req.query.id as string;
|
||||
|
||||
if (req.method === "GET") {
|
||||
const account = db
|
||||
.prepare("SELECT id, name, from_email, from_name, reply_to, smtp_host, smtp_port, smtp_secure, imap_host, imap_port, username, imap_username, daily_email_limit, active_hours_start, active_hours_end, timezone, working_days, is_verified, signature, ramp_up_enabled, ramp_start_date, created_at FROM email_accounts WHERE id = ?")
|
||||
.get(id);
|
||||
if (!account) return res.status(404).json({ error: "not found" });
|
||||
return res.json(account);
|
||||
}
|
||||
|
||||
if (req.method === "PUT") {
|
||||
const {
|
||||
name, from_email, from_name, reply_to,
|
||||
smtp_host, smtp_port, smtp_secure,
|
||||
imap_host, imap_port,
|
||||
username, password,
|
||||
imap_username, imap_password,
|
||||
daily_email_limit,
|
||||
active_hours_start, active_hours_end,
|
||||
timezone, working_days,
|
||||
signature,
|
||||
ramp_up_enabled,
|
||||
ramp_start_date,
|
||||
} = req.body;
|
||||
|
||||
const rampEnabled = ramp_up_enabled != null ? (ramp_up_enabled ? 1 : 0) : null;
|
||||
|
||||
// Build password SET clauses only when provided (don't wipe on partial update)
|
||||
const pwClause = password ? "password = ?," : "";
|
||||
const imapPwClause = imap_password ? "imap_password = ?," : "";
|
||||
|
||||
const pwParams = password ? [encryptSecret(password)] : [];
|
||||
const imapPwParams = imap_password ? [encryptSecret(imap_password)] : [];
|
||||
|
||||
db.prepare(`
|
||||
UPDATE email_accounts SET
|
||||
name = COALESCE(?, name), from_email = COALESCE(?, from_email),
|
||||
from_name = ?, reply_to = ?, smtp_host = COALESCE(?, smtp_host),
|
||||
smtp_port = COALESCE(?, smtp_port), smtp_secure = COALESCE(?, smtp_secure),
|
||||
imap_host = ?, imap_port = COALESCE(?, imap_port),
|
||||
username = COALESCE(?, username), ${pwClause}
|
||||
imap_username = ?, ${imapPwClause}
|
||||
daily_email_limit = COALESCE(?, daily_email_limit),
|
||||
active_hours_start = COALESCE(?, active_hours_start),
|
||||
active_hours_end = COALESCE(?, active_hours_end),
|
||||
timezone = COALESCE(?, timezone), working_days = COALESCE(?, working_days),
|
||||
signature = ?, ramp_up_enabled = COALESCE(?, ramp_up_enabled),
|
||||
ramp_start_date = COALESCE(?, ramp_start_date)
|
||||
WHERE id = ?
|
||||
`).run(
|
||||
name ?? null, from_email ?? null, from_name ?? null, reply_to ?? null,
|
||||
smtp_host ?? null, smtp_port ?? null, smtp_secure ?? null,
|
||||
imap_host ?? null, imap_port ?? null,
|
||||
username ?? null, ...pwParams,
|
||||
imap_username ?? null, ...imapPwParams,
|
||||
daily_email_limit ?? null,
|
||||
active_hours_start ?? null, active_hours_end ?? null,
|
||||
timezone ?? null, working_days ?? null,
|
||||
signature ?? null, rampEnabled, ramp_start_date ?? null,
|
||||
id
|
||||
);
|
||||
|
||||
return res.json({ ok: true });
|
||||
}
|
||||
|
||||
if (req.method === "DELETE") {
|
||||
db.prepare("DELETE FROM email_accounts WHERE id = ?").run(id);
|
||||
return res.json({ ok: true });
|
||||
}
|
||||
|
||||
res.status(405).end();
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
import type { NextApiRequest, NextApiResponse } from "next";
|
||||
import { getDb } from "@/lib/db";
|
||||
import { sendEmail } from "@/lib/email/sender";
|
||||
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 id = req.query.id as string;
|
||||
const { to, subject, body } = req.body as { to?: string; subject?: string; body?: string };
|
||||
|
||||
if (!to) return res.status(400).json({ error: "to is required" });
|
||||
|
||||
const account = db
|
||||
.prepare("SELECT * FROM email_accounts WHERE id = ?")
|
||||
.get(id) as {
|
||||
id: string; from_email: string; from_name: string | null;
|
||||
smtp_host: string; smtp_port: number; smtp_secure: number;
|
||||
username: string; password: string; signature: string | null;
|
||||
} | undefined;
|
||||
|
||||
if (!account) return res.status(404).json({ error: "not found" });
|
||||
|
||||
const fullBody = buildEmailBody(body ?? "", account.signature);
|
||||
|
||||
try {
|
||||
await sendEmail({ ...account, password: decryptSecret(account.password)! }, to, subject ?? "Test email from Linki", fullBody);
|
||||
return res.json({ ok: true });
|
||||
} catch (err) {
|
||||
return res.status(500).json({ error: err instanceof Error ? err.message : String(err) });
|
||||
}
|
||||
}
|
||||
|
||||
function buildEmailBody(body: string, signature: string | null): string {
|
||||
const sig = signature?.trim();
|
||||
if (!sig) return body;
|
||||
return `${body}\n\n--\n${sig}`;
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
import type { NextApiRequest, NextApiResponse } from "next";
|
||||
import { getDb } from "@/lib/db";
|
||||
import { testSmtpConnection, testImapConnection } from "@/lib/email/sender";
|
||||
import { decryptSecret } from "@/lib/crypto";
|
||||
|
||||
interface AccountRow {
|
||||
from_email: string;
|
||||
from_name: string | null;
|
||||
smtp_host: string;
|
||||
smtp_port: number;
|
||||
smtp_secure: number;
|
||||
imap_host: string | null;
|
||||
imap_port: number;
|
||||
username: string;
|
||||
password: string;
|
||||
imap_username: string | null;
|
||||
imap_password: string | null;
|
||||
}
|
||||
|
||||
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 id = req.query.id as string;
|
||||
|
||||
const row = db
|
||||
.prepare("SELECT * FROM email_accounts WHERE id = ?")
|
||||
.get(id) as AccountRow | undefined;
|
||||
|
||||
if (!row) return res.status(404).json({ error: "not found" });
|
||||
|
||||
const account: AccountRow = {
|
||||
...row,
|
||||
password: decryptSecret(row.password)!,
|
||||
imap_password: decryptSecret(row.imap_password),
|
||||
};
|
||||
|
||||
const smtpError = await testSmtpConnection(account);
|
||||
|
||||
let imapError: string | null = null;
|
||||
if (account.imap_host) {
|
||||
imapError = await testImapConnection({
|
||||
imap_host: account.imap_host,
|
||||
imap_port: account.imap_port ?? 993,
|
||||
username: account.username,
|
||||
password: account.password,
|
||||
imap_username: account.imap_username,
|
||||
imap_password: account.imap_password,
|
||||
});
|
||||
}
|
||||
|
||||
const ok = !smtpError && !imapError;
|
||||
|
||||
if (ok) {
|
||||
db.prepare("UPDATE email_accounts SET is_verified = 1 WHERE id = ?").run(id);
|
||||
}
|
||||
|
||||
return res.status(ok ? 200 : 400).json({
|
||||
ok,
|
||||
smtp: smtpError ? { ok: false, error: smtpError } : { ok: true },
|
||||
imap: account.imap_host
|
||||
? (imapError ? { ok: false, error: imapError } : { ok: true })
|
||||
: null,
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
import type { NextApiRequest, NextApiResponse } from "next";
|
||||
import { getDb } from "@/lib/db";
|
||||
import { randomUUID } from "crypto";
|
||||
import { encryptSecret } from "@/lib/crypto";
|
||||
|
||||
export default function handler(req: NextApiRequest, res: NextApiResponse) {
|
||||
const db = getDb();
|
||||
|
||||
if (req.method === "GET") {
|
||||
// Never return passwords to the client
|
||||
const accounts = db
|
||||
.prepare(`
|
||||
SELECT ea.id, ea.name, ea.from_email, ea.from_name, ea.reply_to,
|
||||
ea.smtp_host, ea.smtp_port, ea.smtp_secure,
|
||||
ea.imap_host, ea.imap_port, ea.username, ea.imap_username,
|
||||
ea.daily_email_limit, ea.active_hours_start, ea.active_hours_end,
|
||||
ea.timezone, ea.working_days, ea.is_verified, ea.signature,
|
||||
ea.ramp_up_enabled, ea.ramp_start_date, ea.created_at,
|
||||
(SELECT COUNT(DISTINCT rp.run_id) FROM run_profiles rp
|
||||
JOIN runs r ON rp.run_id = r.id
|
||||
WHERE rp.email_account_id = ea.id
|
||||
AND r.status IN ('running', 'paused')) AS active_run_count
|
||||
FROM email_accounts ea ORDER BY ea.created_at DESC
|
||||
`)
|
||||
.all();
|
||||
return res.json(accounts);
|
||||
}
|
||||
|
||||
if (req.method === "POST") {
|
||||
const {
|
||||
name, from_email, from_name, reply_to,
|
||||
smtp_host, smtp_port = 587, smtp_secure = 0,
|
||||
imap_host, imap_port = 993,
|
||||
username, password,
|
||||
imap_username, imap_password,
|
||||
daily_email_limit = 50,
|
||||
active_hours_start = 9, active_hours_end = 18,
|
||||
timezone = "UTC", working_days = "1,2,3,4,5",
|
||||
signature,
|
||||
ramp_up_enabled = 1,
|
||||
ramp_start_date,
|
||||
} = req.body;
|
||||
|
||||
if (!name || !from_email || !smtp_host || !username || !password) {
|
||||
return res.status(400).json({ error: "name, from_email, smtp_host, username, password required" });
|
||||
}
|
||||
|
||||
const id = randomUUID();
|
||||
const resolvedRampStart = ramp_start_date ?? new Date().toISOString().slice(0, 10);
|
||||
db.prepare(`
|
||||
INSERT INTO email_accounts
|
||||
(id, name, from_email, from_name, reply_to, smtp_host, smtp_port, smtp_secure,
|
||||
imap_host, imap_port, username, password,
|
||||
imap_username, imap_password,
|
||||
daily_email_limit, active_hours_start, active_hours_end, timezone, working_days, signature,
|
||||
ramp_up_enabled, ramp_start_date)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||
`).run(
|
||||
id, name, from_email, from_name ?? null, reply_to ?? null,
|
||||
smtp_host, smtp_port, smtp_secure,
|
||||
imap_host ?? null, imap_port,
|
||||
username, encryptSecret(password),
|
||||
imap_username ?? null, imap_password ? encryptSecret(imap_password) : null,
|
||||
daily_email_limit, active_hours_start, active_hours_end, timezone, working_days,
|
||||
signature ?? null,
|
||||
ramp_up_enabled ? 1 : 0, resolvedRampStart
|
||||
);
|
||||
|
||||
return res.status(201).json({ id });
|
||||
}
|
||||
|
||||
res.setHeader("Allow", ["GET", "POST"]);
|
||||
res.status(405).end();
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
import type { NextApiRequest, NextApiResponse } from "next";
|
||||
import { getDb } from "@/lib/db";
|
||||
|
||||
export default function handler(req: NextApiRequest, res: NextApiResponse) {
|
||||
if (req.method !== "GET") return res.status(405).end();
|
||||
const db = getDb();
|
||||
|
||||
const accounts = db.prepare(`
|
||||
SELECT id, name, from_email, daily_email_limit, ramp_up_enabled, ramp_start_date
|
||||
FROM email_accounts
|
||||
ORDER BY name
|
||||
`).all() as {
|
||||
id: string; name: string; from_email: string;
|
||||
daily_email_limit: number; ramp_up_enabled: number; ramp_start_date: string | null;
|
||||
}[];
|
||||
|
||||
// Sent per account per day for the last 7 days
|
||||
const dailySends = db.prepare(`
|
||||
SELECT rp.email_account_id,
|
||||
date(l.created_at) as day,
|
||||
COUNT(*) as sent
|
||||
FROM logs l
|
||||
JOIN run_profiles rp ON rp.run_id = l.run_id AND rp.target_id = l.target_id
|
||||
WHERE l.message LIKE 'Email sent%'
|
||||
AND l.created_at >= date('now', '-6 days')
|
||||
GROUP BY rp.email_account_id, date(l.created_at)
|
||||
`).all() as { email_account_id: string; day: string; sent: number }[];
|
||||
|
||||
// Last 50 email send log entries across all accounts
|
||||
const recentLogs = db.prepare(`
|
||||
SELECT l.created_at, l.message, rp.email_account_id
|
||||
FROM logs l
|
||||
JOIN run_profiles rp ON rp.run_id = l.run_id AND rp.target_id = l.target_id
|
||||
WHERE l.message LIKE 'Email sent%'
|
||||
ORDER BY l.created_at DESC
|
||||
LIMIT 50
|
||||
`).all() as { created_at: string; message: string; email_account_id: string }[];
|
||||
|
||||
// Guard trips today
|
||||
const guardTrips = db.prepare(`
|
||||
SELECT l.created_at, l.message, rp.email_account_id
|
||||
FROM logs l
|
||||
LEFT JOIN run_profiles rp ON rp.run_id = l.run_id AND rp.target_id = l.target_id
|
||||
WHERE (l.message LIKE '%Daily limit%' OR l.message LIKE '%limit guard%')
|
||||
AND date(l.created_at) = date('now')
|
||||
ORDER BY l.created_at DESC
|
||||
LIMIT 50
|
||||
`).all() as { created_at: string; message: string; email_account_id: string | null }[];
|
||||
|
||||
function effectiveLimit(a: typeof accounts[0], date: Date) {
|
||||
if (!a.ramp_up_enabled || !a.ramp_start_date) return a.daily_email_limit;
|
||||
const start = new Date(a.ramp_start_date);
|
||||
const daysActive = Math.floor((date.getTime() - start.getTime()) / (1000 * 60 * 60 * 24)) + 1;
|
||||
return Math.min(a.daily_email_limit, daysActive * 2);
|
||||
}
|
||||
|
||||
const now = new Date();
|
||||
// Build last 7 days list (UTC dates)
|
||||
const days: string[] = [];
|
||||
for (let i = 6; i >= 0; i--) {
|
||||
const d = new Date(now);
|
||||
d.setUTCDate(d.getUTCDate() - i);
|
||||
days.push(d.toISOString().slice(0, 10));
|
||||
}
|
||||
|
||||
// Index sends: accountId -> day -> count
|
||||
const sendsIndex: Record<string, Record<string, number>> = {};
|
||||
for (const row of dailySends) {
|
||||
if (!sendsIndex[row.email_account_id]) sendsIndex[row.email_account_id] = {};
|
||||
sendsIndex[row.email_account_id][row.day] = row.sent;
|
||||
}
|
||||
|
||||
const today = now.toISOString().slice(0, 10);
|
||||
|
||||
const result = accounts.map(a => {
|
||||
const sentToday = sendsIndex[a.id]?.[today] ?? 0;
|
||||
const limit = effectiveLimit(a, now);
|
||||
return {
|
||||
id: a.id,
|
||||
name: a.name,
|
||||
from_email: a.from_email,
|
||||
daily_email_limit: a.daily_email_limit,
|
||||
ramp_up_enabled: a.ramp_up_enabled,
|
||||
ramp_start_date: a.ramp_start_date,
|
||||
effective_limit_today: limit,
|
||||
sent_today: sentToday,
|
||||
days: days.map(day => ({
|
||||
day,
|
||||
sent: sendsIndex[a.id]?.[day] ?? 0,
|
||||
limit: effectiveLimit(a, new Date(day + "T12:00:00Z")),
|
||||
})),
|
||||
};
|
||||
});
|
||||
|
||||
res.json({ accounts: result, days, recentLogs, guardTrips });
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
// Next.js API route support: https://nextjs.org/docs/api-routes/introduction
|
||||
import type { NextApiRequest, NextApiResponse } from "next";
|
||||
|
||||
type Data = {
|
||||
name: string;
|
||||
};
|
||||
|
||||
export default function handler(
|
||||
req: NextApiRequest,
|
||||
res: NextApiResponse<Data>,
|
||||
) {
|
||||
res.status(200).json({ name: "John Doe" });
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
import type { NextApiRequest, NextApiResponse } from "next";
|
||||
import { getDb } from "@/lib/db";
|
||||
import { cancelImport } from "@/lib/import-jobs";
|
||||
|
||||
/** POST — cancel an import batch. A running batch stops at its next page boundary. */
|
||||
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 id = req.query.id as string;
|
||||
|
||||
const job = db.prepare("SELECT id, status FROM list_imports WHERE id = ?").get(id) as
|
||||
| { id: string; status: string }
|
||||
| undefined;
|
||||
if (!job) return res.status(404).json({ error: "Import not found" });
|
||||
|
||||
cancelImport(db, id);
|
||||
return res.json({ ok: true });
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
import type { NextApiRequest, NextApiResponse } from "next";
|
||||
import { getDb } from "@/lib/db";
|
||||
import { getDailyImportCap, importedToday } from "@/lib/import-jobs";
|
||||
|
||||
/** GET — all import jobs (active first), with list names, for the Jobs panel. */
|
||||
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 jobs = db.prepare(`
|
||||
SELECT li.id, li.list_id, l.name AS list_name, li.status, li.phase,
|
||||
li.page, li.total_pages, li.count, li.total, li.imported, li.skipped, li.error,
|
||||
li.scheduled_for, li.start_page, li.batch_index, li.started_at, li.finished_at
|
||||
FROM list_imports li
|
||||
LEFT JOIN lists l ON l.id = li.list_id
|
||||
WHERE li.status IN ('running', 'scheduled')
|
||||
OR li.finished_at >= datetime('now', '-2 days')
|
||||
ORDER BY
|
||||
CASE li.status WHEN 'running' THEN 0 WHEN 'scheduled' THEN 1 ELSE 2 END,
|
||||
li.scheduled_for ASC,
|
||||
li.started_at DESC
|
||||
`).all();
|
||||
|
||||
return res.json({
|
||||
jobs,
|
||||
dailyCap: getDailyImportCap(db),
|
||||
importedToday: importedToday(db),
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
import type { NextApiRequest, NextApiResponse } from "next";
|
||||
import { randomUUID } from "crypto";
|
||||
import { getDb } from "@/lib/db";
|
||||
|
||||
/**
|
||||
* Cancels a scheduled OOO follow-up: clears the email track's next_step_at +
|
||||
* pending_reply_context and stamps the contact's email_replied_at, so the runner
|
||||
* skips them on the next tick (treats the reply as bucket D retroactively).
|
||||
*/
|
||||
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 replyId = req.query.replyId as string;
|
||||
if (!replyId) return res.status(400).json({ error: "replyId required" });
|
||||
|
||||
const reply = db
|
||||
.prepare("SELECT target_id, run_id FROM email_replies WHERE id = ?")
|
||||
.get(replyId) as { target_id: string; run_id: string | null } | undefined;
|
||||
if (!reply) return res.status(404).json({ error: "reply_not_found" });
|
||||
|
||||
if (reply.run_id) {
|
||||
db.prepare(
|
||||
`UPDATE run_profile_tracks SET state = 'skipped', next_step_at = NULL, pending_reply_context = NULL,
|
||||
error_message = 'Follow-up cancelled from inbox'
|
||||
WHERE track = 'email' AND state IN ('pending', 'in_progress')
|
||||
AND run_profile_id IN (
|
||||
SELECT id FROM run_profiles WHERE run_id = ? AND target_id = ?
|
||||
)`,
|
||||
).run(reply.run_id, reply.target_id);
|
||||
}
|
||||
|
||||
db.prepare("UPDATE targets SET email_replied_at = datetime('now') WHERE id = ?").run(reply.target_id);
|
||||
db.prepare(
|
||||
"INSERT INTO activity_logs (id, target_id, type, body) VALUES (?, ?, 'email', 'Scheduled follow-up cancelled from inbox.')",
|
||||
).run(randomUUID(), reply.target_id);
|
||||
|
||||
db.prepare(
|
||||
"UPDATE email_replies SET dispatch_result_json = ? WHERE id = ?",
|
||||
).run(JSON.stringify({ kind: "cancelled", notes: "Follow-up cancelled from inbox" }), replyId);
|
||||
|
||||
return res.json({ ok: true });
|
||||
}
|
||||
@@ -0,0 +1,119 @@
|
||||
import type { NextApiRequest, NextApiResponse } from "next";
|
||||
import { getDb } from "@/lib/db";
|
||||
|
||||
export interface InboxReply {
|
||||
id: string;
|
||||
full_name: string | null;
|
||||
linkedin_url: string | null;
|
||||
email: string | null;
|
||||
headline: string | null;
|
||||
company: string | null;
|
||||
channel: "email" | "linkedin" | "both";
|
||||
replied_at: string;
|
||||
email_replied_at: string | null;
|
||||
last_replied_at: string | null;
|
||||
// run context
|
||||
run_id: string | null;
|
||||
workflow_id: string | null;
|
||||
workflow_name: string | null;
|
||||
// email account context
|
||||
email_account_id: string | null;
|
||||
email_account_name: string | null;
|
||||
email_account_from: string | null;
|
||||
// classifier / dispatcher context (from the most recent email_replies row)
|
||||
reply_id: string | null;
|
||||
reply_kind: string | null;
|
||||
reply_summary: string | null;
|
||||
reply_body: string | null;
|
||||
classified_at: string | null;
|
||||
classification_error: string | null;
|
||||
dispatched_at: string | null;
|
||||
dispatch_result_json: string | null;
|
||||
manually_edited: number;
|
||||
}
|
||||
|
||||
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 channel = req.query.channel as string | undefined; // "email" | "linkedin" | undefined
|
||||
|
||||
// A target shows in the inbox if it has a reply stamp OR a captured email_replies row.
|
||||
// OOO-followup replies intentionally leave email_replied_at NULL, so we must include
|
||||
// the email_replies source to keep scheduled follow-ups visible.
|
||||
let channelFilter =
|
||||
"AND (t.email_replied_at IS NOT NULL OR t.last_replied_at IS NOT NULL OR er.id IS NOT NULL)";
|
||||
if (channel === "email") channelFilter = "AND (t.email_replied_at IS NOT NULL OR er.id IS NOT NULL)";
|
||||
if (channel === "linkedin") channelFilter = "AND t.last_replied_at IS NOT NULL";
|
||||
|
||||
const rows = db.prepare(`
|
||||
SELECT
|
||||
t.id,
|
||||
t.full_name,
|
||||
t.linkedin_url,
|
||||
t.email,
|
||||
t.headline,
|
||||
t.company,
|
||||
t.email_replied_at,
|
||||
t.last_replied_at,
|
||||
CASE
|
||||
WHEN (t.email_replied_at IS NOT NULL OR er.id IS NOT NULL) AND t.last_replied_at IS NOT NULL THEN 'both'
|
||||
WHEN t.email_replied_at IS NOT NULL OR er.id IS NOT NULL THEN 'email'
|
||||
ELSE 'linkedin'
|
||||
END AS channel,
|
||||
MAX(
|
||||
COALESCE(t.email_replied_at, ''),
|
||||
COALESCE(t.last_replied_at, ''),
|
||||
COALESCE(er.received_at, '')
|
||||
) AS replied_at,
|
||||
r.id AS run_id,
|
||||
r.workflow_id,
|
||||
w.name AS workflow_name,
|
||||
ea.id AS email_account_id,
|
||||
ea.name AS email_account_name,
|
||||
ea.from_email AS email_account_from,
|
||||
er.id AS reply_id,
|
||||
er.classification_json AS classification_json,
|
||||
er.body_text AS reply_body,
|
||||
er.classified_at,
|
||||
er.classification_error,
|
||||
er.dispatched_at,
|
||||
er.dispatch_result_json,
|
||||
COALESCE(er.manually_edited, 0) AS manually_edited
|
||||
FROM targets t
|
||||
LEFT JOIN run_profiles rp ON rp.target_id = t.id
|
||||
LEFT JOIN runs r ON r.id = rp.run_id AND r.status IN ('running', 'paused', 'completed')
|
||||
LEFT JOIN workflows w ON w.id = r.workflow_id
|
||||
LEFT JOIN email_accounts ea ON ea.id = rp.email_account_id
|
||||
LEFT JOIN (
|
||||
SELECT er1.* FROM email_replies er1
|
||||
WHERE er1.received_at = (
|
||||
SELECT MAX(er2.received_at) FROM email_replies er2 WHERE er2.target_id = er1.target_id
|
||||
)
|
||||
) er ON er.target_id = t.id
|
||||
WHERE 1=1
|
||||
${channelFilter}
|
||||
GROUP BY t.id
|
||||
ORDER BY replied_at DESC
|
||||
`).all() as Array<InboxReply & { classification_json: string | null }>;
|
||||
|
||||
const replies: InboxReply[] = rows.map((row) => {
|
||||
let reply_kind: string | null = null;
|
||||
let reply_summary: string | null = null;
|
||||
if (row.classification_json) {
|
||||
try {
|
||||
const cls = JSON.parse(row.classification_json) as { kind?: string; summary?: string };
|
||||
reply_kind = cls.kind ?? null;
|
||||
reply_summary = cls.summary ?? null;
|
||||
} catch { /* malformed — leave null */ }
|
||||
}
|
||||
const { classification_json: _omit, ...rest } = row;
|
||||
void _omit;
|
||||
return { ...rest, reply_kind, reply_summary };
|
||||
});
|
||||
|
||||
return res.json({ replies });
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
import type { NextApiRequest, NextApiResponse } from "next";
|
||||
import { getDb } from "@/lib/db";
|
||||
import { sendEmail } from "@/lib/email/sender";
|
||||
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 { emailAccountId, to, subject, body } = req.body as {
|
||||
emailAccountId?: string;
|
||||
to?: string;
|
||||
subject?: string;
|
||||
body?: string;
|
||||
};
|
||||
|
||||
if (!emailAccountId || !to || !subject || !body) {
|
||||
return res.status(400).json({ error: "emailAccountId, to, subject, and body are required" });
|
||||
}
|
||||
|
||||
const db = getDb();
|
||||
const account = db.prepare(
|
||||
"SELECT id, from_email, from_name, reply_to, smtp_host, smtp_port, smtp_secure, username, password FROM email_accounts WHERE id = ?"
|
||||
).get(emailAccountId) as {
|
||||
id: string; from_email: string; from_name: string | null; reply_to: string | null;
|
||||
smtp_host: string; smtp_port: number; smtp_secure: number; username: string; password: string;
|
||||
} | undefined;
|
||||
|
||||
if (!account) return res.status(404).json({ error: "Email account not found" });
|
||||
|
||||
try {
|
||||
await sendEmail({ ...account, password: decryptSecret(account.password)! }, to, subject, body);
|
||||
return res.json({ ok: true });
|
||||
} catch (err) {
|
||||
console.error("[inbox/reply] send failed:", err);
|
||||
return res.status(500).json({ error: err instanceof Error ? err.message : "Send failed" });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,143 @@
|
||||
import type { NextApiRequest, NextApiResponse } from "next";
|
||||
import Imap from "imap";
|
||||
import { simpleParser } from "mailparser";
|
||||
import { getDb } from "@/lib/db";
|
||||
import { decryptSecret } from "@/lib/crypto";
|
||||
|
||||
export interface EmailMessage {
|
||||
uid: number;
|
||||
from: string;
|
||||
to: string;
|
||||
subject: string;
|
||||
date: string;
|
||||
text: string;
|
||||
html: string | null;
|
||||
messageId: string | null;
|
||||
}
|
||||
|
||||
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
|
||||
if (req.method !== "GET") {
|
||||
res.setHeader("Allow", ["GET"]);
|
||||
return res.status(405).end();
|
||||
}
|
||||
|
||||
const { targetId, emailAccountId } = req.query as { targetId?: string; emailAccountId?: string };
|
||||
if (!targetId || !emailAccountId) return res.status(400).json({ error: "targetId and emailAccountId required" });
|
||||
|
||||
const db = getDb();
|
||||
|
||||
const target = db.prepare("SELECT email FROM targets WHERE id = ?").get(targetId) as { email: string | null } | undefined;
|
||||
if (!target?.email) return res.status(404).json({ error: "Target has no email" });
|
||||
|
||||
const account = db.prepare(
|
||||
"SELECT imap_host, imap_port, username, password, imap_username, imap_password FROM email_accounts WHERE id = ?"
|
||||
).get(emailAccountId) as {
|
||||
imap_host: string | null; imap_port: number | null;
|
||||
username: string; password: string;
|
||||
imap_username: string | null; imap_password: string | null;
|
||||
} | undefined;
|
||||
|
||||
if (!account?.imap_host) return res.status(404).json({ error: "Email account not found or missing IMAP config" });
|
||||
|
||||
const imapUser = account.imap_username ?? account.username;
|
||||
const imapPass = decryptSecret(account.imap_password) ?? decryptSecret(account.password)!;
|
||||
const targetEmail = target.email.toLowerCase();
|
||||
|
||||
try {
|
||||
const messages = await fetchThread(
|
||||
{ host: account.imap_host, port: account.imap_port ?? 993, user: imapUser, password: imapPass },
|
||||
targetEmail
|
||||
);
|
||||
return res.json({ messages });
|
||||
} catch (err) {
|
||||
console.error("[inbox/thread] IMAP error:", err);
|
||||
return res.status(500).json({ error: "IMAP fetch failed" });
|
||||
}
|
||||
}
|
||||
|
||||
interface ImapConfig { host: string; port: number; user: string; password: string; }
|
||||
|
||||
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; }
|
||||
|
||||
// Search for messages FROM or TO the contact
|
||||
imap.search([["OR", ["FROM", contactEmail], ["TO", contactEmail]]], (searchErr, uids) => {
|
||||
if (searchErr) { done(searchErr); return; }
|
||||
if (uids.length === 0) { resolve([]); done(); return; }
|
||||
|
||||
// Fetch the last 20 matching messages max
|
||||
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 ?? "",
|
||||
html: parsed.html || null,
|
||||
messageId: parsed.messageId ?? null,
|
||||
});
|
||||
} catch { /* skip malformed */ }
|
||||
res2();
|
||||
});
|
||||
});
|
||||
|
||||
// Only use msg.end as fallback if no body was received
|
||||
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,47 @@
|
||||
import type { NextApiRequest, NextApiResponse } from "next";
|
||||
import { getDb } from "@/lib/db";
|
||||
import { encryptSecret, decryptSecret } from "@/lib/crypto";
|
||||
|
||||
export default function handler(req: NextApiRequest, res: NextApiResponse) {
|
||||
const db = getDb();
|
||||
|
||||
if (req.method === "GET") {
|
||||
const rows = db.prepare("SELECT key, api_key, updated_at FROM integrations").all() as {
|
||||
key: string;
|
||||
api_key: string | null;
|
||||
updated_at: string;
|
||||
}[];
|
||||
const masked = rows.map((r) => {
|
||||
const plain = decryptSecret(r.api_key);
|
||||
return {
|
||||
key: r.key,
|
||||
updated_at: r.updated_at,
|
||||
api_key_masked: plain ? "••••••••" + plain.slice(-4) : null,
|
||||
configured: !!plain,
|
||||
};
|
||||
});
|
||||
return res.json(masked);
|
||||
}
|
||||
|
||||
if (req.method === "POST") {
|
||||
const { key, api_key } = req.body;
|
||||
if (!key) return res.status(400).json({ error: "key required" });
|
||||
if (!api_key) return res.status(400).json({ error: "api_key required" });
|
||||
db.prepare(`
|
||||
INSERT INTO integrations (key, api_key, updated_at)
|
||||
VALUES (?, ?, datetime('now'))
|
||||
ON CONFLICT(key) DO UPDATE SET api_key = excluded.api_key, updated_at = excluded.updated_at
|
||||
`).run(key, encryptSecret(api_key));
|
||||
return res.json({ ok: true });
|
||||
}
|
||||
|
||||
if (req.method === "DELETE") {
|
||||
const { key } = req.query;
|
||||
if (!key) return res.status(400).json({ error: "key required" });
|
||||
db.prepare("DELETE FROM integrations WHERE key = ?").run(key);
|
||||
return res.json({ ok: true });
|
||||
}
|
||||
|
||||
res.setHeader("Allow", ["GET", "POST", "DELETE"]);
|
||||
res.status(405).end();
|
||||
}
|
||||
@@ -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,
|
||||
});
|
||||
}
|
||||
@@ -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 });
|
||||
}
|
||||
@@ -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 },
|
||||
};
|
||||
@@ -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 });
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
@@ -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 },
|
||||
};
|
||||
@@ -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);
|
||||
}
|
||||
@@ -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 },
|
||||
});
|
||||
}
|
||||
@@ -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) });
|
||||
}
|
||||
@@ -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();
|
||||
}
|
||||
@@ -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 });
|
||||
}
|
||||
@@ -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.",
|
||||
});
|
||||
}
|
||||
@@ -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 },
|
||||
};
|
||||
@@ -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 });
|
||||
}
|
||||
@@ -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();
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
// GET /api/premium-status — open-core endpoint the UI uses to decide whether to render
|
||||
// premium features or an "Upgrade to Premium" affordance. Returns { hasPremium } which is
|
||||
// true in the commercial build (ee/ present) and false in the public open-source build.
|
||||
import type { NextApiRequest, NextApiResponse } from "next";
|
||||
import { hasPremium } from "@/lib/premium";
|
||||
|
||||
export default function handler(_req: NextApiRequest, res: NextApiResponse) {
|
||||
res.status(200).json({ hasPremium });
|
||||
}
|
||||
@@ -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();
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
import type { NextApiRequest, NextApiResponse } from "next";
|
||||
import { getDb } from "@/lib/db";
|
||||
import { getDailyImportCap, setDailyImportCap, DEFAULT_DAILY_CAP } from "@/lib/import-jobs";
|
||||
|
||||
/** GET → { cap }, PUT { cap } → set the global daily import cap. */
|
||||
export default function handler(req: NextApiRequest, res: NextApiResponse) {
|
||||
const db = getDb();
|
||||
|
||||
if (req.method === "GET") {
|
||||
return res.json({ cap: getDailyImportCap(db), default: DEFAULT_DAILY_CAP });
|
||||
}
|
||||
|
||||
if (req.method === "PUT") {
|
||||
const { cap } = req.body as { cap?: number };
|
||||
const n = Number(cap);
|
||||
if (!Number.isFinite(n) || n < 1) return res.status(400).json({ error: "cap must be a positive number" });
|
||||
setDailyImportCap(db, n);
|
||||
return res.json({ cap: getDailyImportCap(db) });
|
||||
}
|
||||
|
||||
res.setHeader("Allow", ["GET", "PUT"]);
|
||||
return res.status(405).end();
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
import type { NextApiRequest, NextApiResponse } from "next";
|
||||
import { getUpdateState } from "@/lib/update-check";
|
||||
|
||||
export default function handler(_req: NextApiRequest, res: NextApiResponse) {
|
||||
res.json(getUpdateState());
|
||||
}
|
||||
@@ -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 });
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
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 t = db.prepare("SELECT * FROM templates WHERE id = ?").get(id);
|
||||
if (!t) return res.status(404).json({ error: "Not found" });
|
||||
return res.json(t);
|
||||
}
|
||||
|
||||
if (req.method === "PUT") {
|
||||
const { name, body } = req.body;
|
||||
db.prepare(
|
||||
"UPDATE templates SET name = COALESCE(?, name), body = COALESCE(?, body) WHERE id = ?"
|
||||
).run(name, body, id);
|
||||
return res.json(db.prepare("SELECT * FROM templates WHERE id = ?").get(id));
|
||||
}
|
||||
|
||||
if (req.method === "DELETE") {
|
||||
db.prepare("DELETE FROM templates WHERE id = ?").run(id);
|
||||
return res.status(204).end();
|
||||
}
|
||||
|
||||
res.setHeader("Allow", ["GET", "PUT", "DELETE"]);
|
||||
res.status(405).end();
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
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 templates = db.prepare("SELECT * FROM templates ORDER BY created_at DESC").all();
|
||||
return res.json(templates);
|
||||
}
|
||||
|
||||
if (req.method === "POST") {
|
||||
const { name, body } = req.body;
|
||||
if (!name || !body) return res.status(400).json({ error: "name and body required" });
|
||||
const id = randomUUID();
|
||||
db.prepare("INSERT INTO templates (id, name, body) VALUES (?, ?, ?)").run(id, name, body);
|
||||
return res.status(201).json(db.prepare("SELECT * FROM templates WHERE id = ?").get(id));
|
||||
}
|
||||
|
||||
res.setHeader("Allow", ["GET", "POST"]);
|
||||
res.status(405).end();
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
import type { NextApiRequest, NextApiResponse } from "next";
|
||||
import { getDb } from "@/lib/db";
|
||||
|
||||
// Per-page product tour "seen" flags, stored as app_settings rows (tour_seen_<page>).
|
||||
// Single-user tool — no per-account state needed, so a global key/value flag is enough.
|
||||
const KEY_PREFIX = "tour_seen_";
|
||||
|
||||
export default function handler(req: NextApiRequest, res: NextApiResponse) {
|
||||
const db = getDb();
|
||||
|
||||
if (req.method === "GET") {
|
||||
const rows = db.prepare("SELECT key FROM app_settings WHERE key LIKE ?").all(`${KEY_PREFIX}%`) as { key: string }[];
|
||||
const seen = rows.map((r) => r.key.slice(KEY_PREFIX.length));
|
||||
return res.json({ seen });
|
||||
}
|
||||
|
||||
if (req.method === "POST") {
|
||||
const { page } = req.body as { page?: string };
|
||||
if (!page) return res.status(400).json({ error: "page is required" });
|
||||
db.prepare(
|
||||
`INSERT INTO app_settings (key, value, updated_at) VALUES (?, '1', datetime('now'))
|
||||
ON CONFLICT(key) DO UPDATE SET value = '1', updated_at = datetime('now')`
|
||||
).run(`${KEY_PREFIX}${page}`);
|
||||
return res.json({ ok: true });
|
||||
}
|
||||
|
||||
res.setHeader("Allow", ["GET", "POST"]);
|
||||
return res.status(405).end();
|
||||
}
|
||||
@@ -0,0 +1,190 @@
|
||||
import type { NextApiRequest, NextApiResponse } from "next";
|
||||
import { getDb } from "@/lib/db";
|
||||
|
||||
export default function handler(req: NextApiRequest, res: NextApiResponse) {
|
||||
if (req.method !== "GET") return res.status(405).end();
|
||||
|
||||
try {
|
||||
const db = getDb();
|
||||
const workflowId = req.query.id as string;
|
||||
const days = Math.min(Math.max(Number(req.query.days) || 30, 7), 90);
|
||||
|
||||
const RUNS = `SELECT id FROM runs WHERE workflow_id = ? AND status IN ('running','paused','completed')`;
|
||||
|
||||
// ── Audience: enrolled vs. addressable ──────────────────────────────────────
|
||||
// The funnel's `total` counts everyone enrolled, but that overstates runway when most
|
||||
// contacts have no deliverable email. `eligible` = enrolled AND has a non-bounced email.
|
||||
// `verified` = the strict subset with a verified email. `email_real_replies` excludes
|
||||
// auto-responders (OOO / substitute / call_task are automated) so the reply signal is honest.
|
||||
const audience = db.prepare(`
|
||||
WITH enrolled AS (
|
||||
SELECT DISTINCT rp.target_id
|
||||
FROM run_profiles rp JOIN runs r ON r.id = rp.run_id
|
||||
WHERE r.workflow_id = ? AND r.status IN ('running','paused','completed')
|
||||
)
|
||||
SELECT
|
||||
(SELECT COUNT(*) FROM enrolled) AS enrolled,
|
||||
(SELECT COUNT(*) FROM enrolled e JOIN targets t ON t.id = e.target_id
|
||||
WHERE t.email IS NOT NULL AND t.email != ''
|
||||
AND (t.email_status IS NULL OR t.email_status NOT IN ('invalid','unavailable'))) AS eligible,
|
||||
(SELECT COUNT(*) FROM enrolled e JOIN targets t ON t.id = e.target_id
|
||||
WHERE t.email_status = 'verified') AS verified,
|
||||
(SELECT COUNT(DISTINCT t.id) FROM enrolled e JOIN targets t ON t.id = e.target_id
|
||||
WHERE t.reply_kind IN ('human_reply','not_interested')) AS email_real_replies,
|
||||
(SELECT COUNT(DISTINCT t.id) FROM enrolled e JOIN targets t ON t.id = e.target_id
|
||||
WHERE t.reply_kind IN ('ooo_followup','substitute','call_task')) AS email_auto_replies
|
||||
`).get(workflowId) as {
|
||||
enrolled: number; eligible: number; verified: number;
|
||||
email_real_replies: number; email_auto_replies: number;
|
||||
};
|
||||
|
||||
// Eligible contacts we've actually emailed at least once (Email sent log).
|
||||
const contactedRow = db.prepare(`
|
||||
SELECT COUNT(DISTINCT l.target_id) AS contacted
|
||||
FROM logs l JOIN targets t ON t.id = l.target_id
|
||||
WHERE l.run_id IN (${RUNS}) AND l.message LIKE 'Email sent%'
|
||||
AND t.email IS NOT NULL AND t.email != ''
|
||||
AND (t.email_status IS NULL OR t.email_status NOT IN ('invalid','unavailable'))
|
||||
`).get(workflowId) as { contacted: number };
|
||||
|
||||
const audienceOut = {
|
||||
enrolled: audience.enrolled,
|
||||
eligible: audience.eligible, // has a deliverable email — the real addressable count
|
||||
verified: audience.verified, // strict subset with a verified email
|
||||
contacted: contactedRow.contacted, // eligible contacts emailed at least once
|
||||
replied: audience.email_real_replies, // genuine human replies (auto-responders excluded)
|
||||
auto_replied: audience.email_auto_replies, // OOO / substitute / call_task (informational)
|
||||
remaining: Math.max(audience.eligible - contactedRow.contacted, 0), // eligible not yet emailed
|
||||
};
|
||||
|
||||
// ── Funnel ────────────────────────────────────────────────────────────────
|
||||
const funnel = db.prepare(`
|
||||
SELECT
|
||||
(SELECT COUNT(DISTINCT rp.target_id)
|
||||
FROM run_profiles rp JOIN runs r ON r.id = rp.run_id
|
||||
WHERE r.workflow_id = ? AND r.status IN ('running','paused','completed')) AS total,
|
||||
|
||||
(SELECT COUNT(DISTINCT target_id) FROM logs
|
||||
WHERE run_id IN (${RUNS}) AND message LIKE 'Connection request sent%') AS connections_sent,
|
||||
|
||||
(SELECT COUNT(DISTINCT l.target_id) FROM logs l
|
||||
JOIN targets t ON t.id = l.target_id
|
||||
WHERE l.run_id IN (${RUNS})
|
||||
AND l.message LIKE 'Connection request sent%'
|
||||
AND t.connected_at IS NOT NULL) AS connected,
|
||||
|
||||
(SELECT COUNT(DISTINCT target_id) FROM logs
|
||||
WHERE run_id IN (${RUNS}) AND message LIKE 'Message sent%') AS messages_sent,
|
||||
|
||||
(SELECT COUNT(DISTINCT target_id) FROM logs
|
||||
WHERE run_id IN (${RUNS}) AND message LIKE 'InMail sent%') AS inmails_sent,
|
||||
|
||||
(SELECT COUNT(DISTINCT l.target_id) FROM logs l
|
||||
JOIN targets t ON t.id = l.target_id
|
||||
WHERE l.run_id IN (${RUNS})
|
||||
AND (l.message LIKE 'Message sent%' OR l.message LIKE 'InMail sent%')
|
||||
AND t.last_replied_at IS NOT NULL) AS li_replies,
|
||||
|
||||
(SELECT COUNT(DISTINCT target_id) FROM logs
|
||||
WHERE run_id IN (${RUNS}) AND message LIKE 'Email sent%') AS emails_sent,
|
||||
|
||||
(SELECT COUNT(DISTINCT l.target_id) FROM logs l
|
||||
JOIN targets t ON t.id = l.target_id
|
||||
WHERE l.run_id IN (${RUNS})
|
||||
AND l.message LIKE 'Email sent%'
|
||||
AND t.email_replied_at IS NOT NULL) AS email_replies,
|
||||
|
||||
(SELECT COUNT(DISTINCT rp.target_id)
|
||||
FROM run_profiles rp JOIN runs r ON r.id = rp.run_id
|
||||
WHERE r.workflow_id = ? AND r.status IN ('running','paused','completed')
|
||||
AND NOT EXISTS (
|
||||
SELECT 1 FROM run_profile_tracks rt
|
||||
WHERE rt.run_profile_id = rp.id AND rt.state NOT IN ('completed', 'failed', 'skipped')
|
||||
)
|
||||
AND EXISTS (
|
||||
SELECT 1 FROM run_profile_tracks rt
|
||||
WHERE rt.run_profile_id = rp.id AND rt.state = 'completed'
|
||||
)) AS completed
|
||||
`).get(
|
||||
workflowId, workflowId, workflowId, workflowId,
|
||||
workflowId, workflowId, workflowId, workflowId, workflowId,
|
||||
) as {
|
||||
total: number; connections_sent: number; connected: number;
|
||||
messages_sent: number; inmails_sent: number; li_replies: number;
|
||||
emails_sent: number; email_replies: number; completed: number;
|
||||
};
|
||||
|
||||
// ── Daily activity ────────────────────────────────────────────────────────
|
||||
const activity = db.prepare(`
|
||||
SELECT
|
||||
date(l.created_at) AS day,
|
||||
COUNT(CASE WHEN l.message LIKE 'Visited%' THEN 1 END) AS visits,
|
||||
COUNT(CASE WHEN l.message LIKE 'Connection request sent%' THEN 1 END) AS connections,
|
||||
COUNT(CASE WHEN l.message LIKE 'Message sent%' THEN 1 END) AS messages,
|
||||
COUNT(CASE WHEN l.message LIKE 'InMail sent%' THEN 1 END) AS inmails,
|
||||
COUNT(CASE WHEN l.message LIKE 'Email sent%' THEN 1 END) AS emails
|
||||
FROM logs l
|
||||
WHERE l.run_id IN (${RUNS})
|
||||
AND l.created_at >= datetime('now', '-${days} days')
|
||||
GROUP BY date(l.created_at)
|
||||
ORDER BY day ASC
|
||||
`).all(workflowId) as { day: string; visits: number; connections: number; messages: number; inmails: number; emails: number }[];
|
||||
|
||||
const filled: typeof activity = [];
|
||||
for (let i = days - 1; i >= 0; i--) {
|
||||
const d = new Date();
|
||||
d.setDate(d.getDate() - i);
|
||||
const key = d.toISOString().slice(0, 10);
|
||||
const found = activity.find(r => r.day === key);
|
||||
filled.push(found ?? { day: key, visits: 0, connections: 0, messages: 0, inmails: 0, emails: 0 });
|
||||
}
|
||||
|
||||
// ── AI cost — daily time-series scoped to this workflow's runs ────────────
|
||||
const aiDaily = db.prepare(`
|
||||
SELECT
|
||||
date(a.created_at) AS day,
|
||||
SUM(a.cost_usd) AS cost_usd,
|
||||
SUM(a.input_tokens) AS input_tokens,
|
||||
SUM(a.output_tokens) AS output_tokens
|
||||
FROM agent_sessions a
|
||||
WHERE a.run_id IN (${RUNS})
|
||||
AND a.created_at >= datetime('now', '-${days} days')
|
||||
GROUP BY date(a.created_at)
|
||||
ORDER BY day ASC
|
||||
`).all(workflowId) as { day: string; cost_usd: number; input_tokens: number; output_tokens: number }[];
|
||||
|
||||
const aiDailyFilled: typeof aiDaily = [];
|
||||
for (let i = days - 1; i >= 0; i--) {
|
||||
const d = new Date();
|
||||
d.setDate(d.getDate() - i);
|
||||
const key = d.toISOString().slice(0, 10);
|
||||
const found = aiDaily.find(r => r.day === key);
|
||||
aiDailyFilled.push(found ?? { day: key, cost_usd: 0, input_tokens: 0, output_tokens: 0 });
|
||||
}
|
||||
|
||||
// ── AI cost — breakdown per step (step_type + step_order from workflow_steps) ─
|
||||
const aiByStep = db.prepare(`
|
||||
SELECT
|
||||
ws.step_order,
|
||||
ws.step_type,
|
||||
COUNT(a.id) AS call_count,
|
||||
SUM(a.input_tokens) AS input_tokens,
|
||||
SUM(a.output_tokens) AS output_tokens,
|
||||
SUM(a.cost_usd) AS cost_usd,
|
||||
GROUP_CONCAT(DISTINCT a.model) AS models
|
||||
FROM agent_sessions a
|
||||
JOIN workflow_steps ws ON ws.id = a.step_id
|
||||
WHERE a.run_id IN (${RUNS})
|
||||
GROUP BY a.step_id
|
||||
ORDER BY ws.step_order
|
||||
`).all(workflowId) as {
|
||||
step_order: number; step_type: string; call_count: number;
|
||||
input_tokens: number; output_tokens: number; cost_usd: number; models: string;
|
||||
}[];
|
||||
|
||||
res.json({ funnel, audience: audienceOut, activity: filled, aiDaily: aiDailyFilled, aiByStep });
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
res.status(500).json({ error: "Failed to load analytics" });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
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") return res.status(405).end();
|
||||
|
||||
const db = getDb();
|
||||
const sourceId = req.query.id as string;
|
||||
|
||||
const source = db.prepare("SELECT * FROM workflows WHERE id = ?").get(sourceId) as
|
||||
| { id: string; name: string; description: string | null }
|
||||
| undefined;
|
||||
if (!source) return res.status(404).json({ error: "Workflow not found" });
|
||||
|
||||
const newId = randomUUID();
|
||||
db.prepare("INSERT INTO workflows (id, name, description) VALUES (?, ?, ?)").run(
|
||||
newId,
|
||||
`${source.name} (copy)`,
|
||||
source.description ?? null
|
||||
);
|
||||
|
||||
const steps = db
|
||||
.prepare("SELECT * FROM workflow_steps WHERE workflow_id = ? ORDER BY step_order")
|
||||
.all(sourceId) as Array<Record<string, unknown>>;
|
||||
|
||||
const getTemplateIds = db.prepare(
|
||||
"SELECT template_id FROM workflow_step_templates WHERE step_id = ?"
|
||||
);
|
||||
const insertStep = db.prepare(
|
||||
`INSERT INTO workflow_steps
|
||||
(id, workflow_id, step_order, step_type, template_id, delay_seconds,
|
||||
connect_note, message_body, email_subject, email_body,
|
||||
email_position, message_position,
|
||||
ai_enabled, ai_model, ai_prompt, ai_max_words, ai_language)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`
|
||||
);
|
||||
const insertLink = db.prepare(
|
||||
"INSERT OR IGNORE INTO workflow_step_templates (step_id, template_id) VALUES (?, ?)"
|
||||
);
|
||||
|
||||
for (const s of steps) {
|
||||
const newStepId = randomUUID();
|
||||
insertStep.run(
|
||||
newStepId, newId, s.step_order, s.step_type,
|
||||
s.template_id ?? null, s.delay_seconds ?? 0,
|
||||
s.connect_note ?? null, s.message_body ?? null,
|
||||
s.email_subject ?? null, s.email_body ?? null,
|
||||
s.email_position ?? 1, s.message_position ?? 1,
|
||||
s.ai_enabled ?? 0, s.ai_model ?? null,
|
||||
s.ai_prompt ?? null, s.ai_max_words ?? null,
|
||||
s.ai_language ?? null
|
||||
);
|
||||
const links = getTemplateIds.all(s.id) as Array<{ template_id: string }>;
|
||||
for (const { template_id } of links) {
|
||||
insertLink.run(newStepId, template_id);
|
||||
}
|
||||
}
|
||||
|
||||
return res.status(201).json({ id: newId });
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
import type { NextApiRequest, NextApiResponse } from "next";
|
||||
import { getDb } from "@/lib/db";
|
||||
|
||||
// GET /api/workflows/[id]/enrollments
|
||||
// Returns current enrollment list + step groups for live polling
|
||||
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 workflowId = req.query.id as string;
|
||||
|
||||
const enrollments = db.prepare(
|
||||
`SELECT r.id, r.list_id, r.status, r.created_at,
|
||||
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,
|
||||
COUNT(DISTINCT CASE WHEN EXISTS (
|
||||
SELECT 1 FROM run_profile_tracks rt4
|
||||
WHERE rt4.run_profile_id = rp.id AND rt4.state = 'failed'
|
||||
) AND NOT EXISTS (
|
||||
SELECT 1 FROM run_profile_tracks rt5
|
||||
WHERE rt5.run_profile_id = rp.id AND rt5.state NOT IN ('completed','failed','skipped')
|
||||
) THEN rp.id END) as failed_profiles,
|
||||
COUNT(DISTINCT CASE WHEN NOT EXISTS (
|
||||
SELECT 1 FROM run_profile_tracks rt6
|
||||
WHERE rt6.run_profile_id = rp.id AND rt6.state NOT IN ('skipped','completed','failed')
|
||||
) AND EXISTS (
|
||||
SELECT 1 FROM run_profile_tracks rt7
|
||||
WHERE rt7.run_profile_id = rp.id AND rt7.state = 'skipped'
|
||||
) AND NOT EXISTS (
|
||||
SELECT 1 FROM run_profile_tracks rt8
|
||||
WHERE rt8.run_profile_id = rp.id AND rt8.state IN ('completed','failed')
|
||||
) THEN rp.id END) as skipped_profiles
|
||||
FROM runs r
|
||||
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
|
||||
WHERE r.workflow_id = ? GROUP BY r.id ORDER BY r.created_at DESC`
|
||||
).all(workflowId);
|
||||
|
||||
// Step groups: use the linkedin track-run current_step for display (most representative)
|
||||
const stepGroups = db.prepare(
|
||||
`SELECT rt.current_step as step_order, ws.step_type, t.name as template_name, COUNT(*) as count
|
||||
FROM run_profile_tracks rt
|
||||
JOIN run_profiles rp ON rp.id = rt.run_profile_id
|
||||
JOIN runs r ON r.id = rp.run_id
|
||||
JOIN workflow_steps ws ON ws.workflow_id = r.workflow_id AND ws.track = rt.track AND ws.step_order = rt.current_step + 1
|
||||
LEFT JOIN templates t ON t.id = ws.template_id
|
||||
WHERE r.workflow_id = ? AND rt.state NOT IN ('completed', 'failed', 'skipped')
|
||||
GROUP BY rt.current_step, rt.track ORDER BY rt.current_step`
|
||||
).all(workflowId);
|
||||
|
||||
return res.json({ enrollments, stepGroups });
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
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 workflow = db.prepare("SELECT * FROM workflows WHERE id = ?").get(id);
|
||||
if (!workflow) return res.status(404).json({ error: "not found" });
|
||||
const steps = db
|
||||
.prepare(
|
||||
`SELECT ws.*, t.name as template_name
|
||||
FROM workflow_steps ws
|
||||
LEFT JOIN templates t ON t.id = ws.template_id
|
||||
WHERE ws.workflow_id = ?
|
||||
ORDER BY ws.step_order`
|
||||
)
|
||||
.all(id);
|
||||
return res.json({ ...workflow as object, steps });
|
||||
}
|
||||
|
||||
if (req.method === "PUT") {
|
||||
const { name, description, prompt } = req.body;
|
||||
// name/description: COALESCE so a rename-only request doesn't null them out
|
||||
// prompt: always update when present in body (even "" to clear it)
|
||||
if (prompt !== undefined) {
|
||||
db.prepare(
|
||||
"UPDATE workflows SET name = COALESCE(?, name), description = COALESCE(?, description), prompt = ? WHERE id = ?"
|
||||
).run(name ?? null, description ?? null, prompt || null, id);
|
||||
} else {
|
||||
db.prepare(
|
||||
"UPDATE workflows SET name = COALESCE(?, name), description = COALESCE(?, description) WHERE id = ?"
|
||||
).run(name ?? null, description ?? null, id);
|
||||
}
|
||||
return res.json(db.prepare("SELECT * FROM workflows WHERE id = ?").get(id));
|
||||
}
|
||||
|
||||
if (req.method === "PATCH") {
|
||||
const { is_archived } = req.body;
|
||||
if (is_archived !== undefined) {
|
||||
db.prepare("UPDATE workflows SET is_archived = ? WHERE id = ?").run(is_archived ? 1 : 0, id);
|
||||
}
|
||||
return res.json(db.prepare("SELECT * FROM workflows WHERE id = ?").get(id));
|
||||
}
|
||||
|
||||
if (req.method === "DELETE") {
|
||||
db.prepare("DELETE FROM runs WHERE workflow_id = ?").run(id);
|
||||
db.prepare("DELETE FROM workflows WHERE id = ?").run(id);
|
||||
return res.json({ ok: true });
|
||||
}
|
||||
|
||||
res.status(405).end();
|
||||
}
|
||||
@@ -0,0 +1,204 @@
|
||||
import type { NextApiRequest, NextApiResponse } from "next";
|
||||
import { getDb } from "@/lib/db";
|
||||
import type { ActiveFilter, FilterOp } from "@/components/ui/FilterBar";
|
||||
|
||||
function parseFilters(query: NextApiRequest["query"]): ActiveFilter[] {
|
||||
const filters: ActiveFilter[] = [];
|
||||
let i = 0;
|
||||
while (query[`f[${i}][field]`]) {
|
||||
filters.push({
|
||||
id: String(i),
|
||||
field: query[`f[${i}][field]`] as string,
|
||||
op: query[`f[${i}][op]`] as FilterOp,
|
||||
value: query[`f[${i}][value]`] as string | undefined,
|
||||
});
|
||||
i++;
|
||||
}
|
||||
return filters;
|
||||
}
|
||||
|
||||
function buildFilterClause(filters: ActiveFilter[]): { sql: string; params: unknown[] } {
|
||||
const parts: string[] = [];
|
||||
const params: unknown[] = [];
|
||||
|
||||
const ALLOWED: Record<string, string> = {
|
||||
degree: "t.degree",
|
||||
connection_requested_at: "t.connection_requested_at",
|
||||
connected_at: "t.connected_at",
|
||||
message_sent_at: "t.message_sent_at",
|
||||
company: "t.company",
|
||||
title: "t.title",
|
||||
seniority: "t.seniority",
|
||||
country: "t.country",
|
||||
};
|
||||
|
||||
for (const f of filters) {
|
||||
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":
|
||||
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 !== "GET") {
|
||||
res.setHeader("Allow", ["GET"]);
|
||||
return res.status(405).end();
|
||||
}
|
||||
|
||||
try {
|
||||
const db = getDb();
|
||||
const workflowId = req.query.id as string;
|
||||
const stepFilter = req.query.step !== undefined ? Number(req.query.step) : null;
|
||||
const trackFilter = (req.query.track as string | undefined) ?? "linkedin";
|
||||
const stateFilter = req.query.state as string | undefined;
|
||||
const search = req.query.search as string | undefined;
|
||||
const page = req.query.page ? Number(req.query.page) : 0;
|
||||
const limit = 25;
|
||||
const offset = page * limit;
|
||||
|
||||
const conditions: string[] = ["r.workflow_id = ?", "r.status IN ('running', 'paused', 'completed')"];
|
||||
const params: unknown[] = [workflowId];
|
||||
|
||||
if (stepFilter !== null) {
|
||||
const trackAlias = trackFilter === "email" ? "rt_em" : "rt_li";
|
||||
// Only show prospects actively at this step (exclude failed/skipped/completed at that step)
|
||||
conditions.push(`COALESCE(${trackAlias}.current_step, 0) = ? AND ${trackAlias}.state NOT IN ('completed','skipped','failed')`);
|
||||
params.push(stepFilter - 1);
|
||||
}
|
||||
if (stateFilter) {
|
||||
const states = stateFilter.split(",");
|
||||
const stateConditions = states.map((s) => {
|
||||
if (s === "completed") {
|
||||
// No active tracks, at least one completed — matches stats API definition
|
||||
return `NOT EXISTS (SELECT 1 FROM run_profile_tracks rt_sf WHERE rt_sf.run_profile_id = rp.id AND rt_sf.state IN ('in_progress','pending'))
|
||||
AND EXISTS (SELECT 1 FROM run_profile_tracks rt_sf2 WHERE rt_sf2.run_profile_id = rp.id AND rt_sf2.state = 'completed')`;
|
||||
}
|
||||
if (s === "in_progress") {
|
||||
return "EXISTS (SELECT 1 FROM run_profile_tracks rt_sf WHERE rt_sf.run_profile_id = rp.id AND rt_sf.state = 'in_progress')";
|
||||
}
|
||||
if (s === "failed") {
|
||||
// No active tracks, no completed tracks, has a failed track
|
||||
return `NOT EXISTS (SELECT 1 FROM run_profile_tracks rt_sf WHERE rt_sf.run_profile_id = rp.id AND rt_sf.state IN ('in_progress','pending'))
|
||||
AND NOT EXISTS (SELECT 1 FROM run_profile_tracks rt_sf2 WHERE rt_sf2.run_profile_id = rp.id AND rt_sf2.state = 'completed')
|
||||
AND EXISTS (SELECT 1 FROM run_profile_tracks rt_sf3 WHERE rt_sf3.run_profile_id = rp.id AND rt_sf3.state = 'failed')`;
|
||||
}
|
||||
if (s === "skipped") {
|
||||
// No active tracks, no completed, no failed, has a skipped track
|
||||
return `NOT EXISTS (SELECT 1 FROM run_profile_tracks rt_sf WHERE rt_sf.run_profile_id = rp.id AND rt_sf.state IN ('in_progress','pending'))
|
||||
AND NOT EXISTS (SELECT 1 FROM run_profile_tracks rt_sf2 WHERE rt_sf2.run_profile_id = rp.id AND rt_sf2.state = 'completed')
|
||||
AND NOT EXISTS (SELECT 1 FROM run_profile_tracks rt_sf3 WHERE rt_sf3.run_profile_id = rp.id AND rt_sf3.state = 'failed')
|
||||
AND EXISTS (SELECT 1 FROM run_profile_tracks rt_sf4 WHERE rt_sf4.run_profile_id = rp.id AND rt_sf4.state = 'skipped')`;
|
||||
}
|
||||
return "EXISTS (SELECT 1 FROM run_profile_tracks rt_sf WHERE rt_sf.run_profile_id = rp.id AND rt_sf.state = ?)";
|
||||
});
|
||||
const filteredStates = states.filter(s => !["completed","in_progress","failed","skipped"].includes(s));
|
||||
conditions.push(`(${stateConditions.join(" OR ")})`);
|
||||
params.push(...filteredStates);
|
||||
}
|
||||
if (search) {
|
||||
conditions.push("(t.full_name LIKE ? OR t.company LIKE ?)");
|
||||
params.push(`%${search}%`, `%${search}%`);
|
||||
}
|
||||
|
||||
// Extra filters from FilterBar
|
||||
const activeFilters = parseFilters(req.query);
|
||||
const { sql: filterSql, params: filterParams } = buildFilterClause(activeFilters);
|
||||
if (filterSql) {
|
||||
conditions.push(filterSql.replace(/^ AND /, ""));
|
||||
params.push(...filterParams);
|
||||
}
|
||||
|
||||
const where = conditions.join(" AND ");
|
||||
|
||||
const total = (db.prepare(
|
||||
`SELECT COUNT(*) as c
|
||||
FROM run_profiles rp
|
||||
JOIN runs r ON r.id = rp.run_id
|
||||
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_em ON rt_em.run_profile_id = rp.id AND rt_em.track = 'email'
|
||||
WHERE ${where}`
|
||||
).get(...params) as { c: number }).c;
|
||||
|
||||
params.push(limit, offset);
|
||||
|
||||
const prospects = db.prepare(
|
||||
`SELECT rp.id, rp.run_id, rp.target_id,
|
||||
CASE
|
||||
WHEN EXISTS (SELECT 1 FROM run_profile_tracks rt_a WHERE rt_a.run_profile_id = rp.id AND rt_a.state = 'in_progress') THEN 'in_progress'
|
||||
WHEN EXISTS (SELECT 1 FROM run_profile_tracks rt_a WHERE rt_a.run_profile_id = rp.id AND rt_a.state = 'pending') THEN 'pending'
|
||||
WHEN EXISTS (SELECT 1 FROM run_profile_tracks rt_a WHERE rt_a.run_profile_id = rp.id AND rt_a.state = 'failed') THEN 'failed'
|
||||
WHEN EXISTS (SELECT 1 FROM run_profile_tracks rt_a WHERE rt_a.run_profile_id = rp.id AND rt_a.state = 'skipped') THEN 'skipped'
|
||||
ELSE 'completed'
|
||||
END as state,
|
||||
COALESCE(rt_li.current_step, 0) as current_step,
|
||||
COALESCE(rt_li.next_step_at, rt_em.next_step_at) as next_step_at,
|
||||
COALESCE(rt_li.error_message, rt_em.error_message) as error_message,
|
||||
t.full_name, t.title, t.company, t.linkedin_url,
|
||||
t.degree, t.connection_requested_at, t.connected_at, t.message_sent_at,
|
||||
ws_li.step_type as li_step_type,
|
||||
ws_em.step_type as em_step_type,
|
||||
CASE
|
||||
WHEN rt_li.state NOT IN ('completed','skipped') THEN ws_li.step_type
|
||||
ELSE ws_em.step_type
|
||||
END as step_type,
|
||||
CASE
|
||||
WHEN rt_li.state NOT IN ('completed','skipped') THEN ws_li.track
|
||||
ELSE ws_em.track
|
||||
END as step_track
|
||||
FROM run_profiles rp
|
||||
JOIN runs r ON r.id = rp.run_id
|
||||
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_em ON rt_em.run_profile_id = rp.id AND rt_em.track = 'email'
|
||||
LEFT JOIN workflow_steps ws_li ON ws_li.workflow_id = r.workflow_id AND ws_li.track = 'linkedin' AND ws_li.step_order = COALESCE(rt_li.current_step, 0) + 1
|
||||
LEFT JOIN workflow_steps ws_em ON ws_em.workflow_id = r.workflow_id AND ws_em.track = 'email' AND ws_em.step_order = COALESCE(rt_em.current_step, 0) + 1
|
||||
WHERE ${where}
|
||||
ORDER BY
|
||||
CASE
|
||||
WHEN EXISTS (SELECT 1 FROM run_profile_tracks rt_a WHERE rt_a.run_profile_id = rp.id AND rt_a.state = 'in_progress') THEN 0
|
||||
WHEN EXISTS (SELECT 1 FROM run_profile_tracks rt_a WHERE rt_a.run_profile_id = rp.id AND rt_a.state = 'pending') THEN 1
|
||||
WHEN EXISTS (SELECT 1 FROM run_profile_tracks rt_a WHERE rt_a.run_profile_id = rp.id AND rt_a.state = 'failed') THEN 2
|
||||
WHEN EXISTS (SELECT 1 FROM run_profile_tracks rt_a WHERE rt_a.run_profile_id = rp.id AND rt_a.state = 'skipped') THEN 3
|
||||
ELSE 4
|
||||
END,
|
||||
t.full_name
|
||||
LIMIT ? OFFSET ?`
|
||||
).all(...params);
|
||||
|
||||
return res.json({ prospects, total });
|
||||
} catch (err) {
|
||||
const message = err instanceof Error ? err.message : String(err);
|
||||
return res.status(500).json({ error: message });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
import type { NextApiRequest, NextApiResponse } from "next";
|
||||
import { getDb } from "@/lib/db";
|
||||
|
||||
export default function handler(req: NextApiRequest, res: NextApiResponse) {
|
||||
if (req.method !== "GET") {
|
||||
res.setHeader("Allow", ["GET"]);
|
||||
return res.status(405).end();
|
||||
}
|
||||
|
||||
try {
|
||||
const db = getDb();
|
||||
const workflowId = req.query.id as string;
|
||||
|
||||
const RUNS = `SELECT id FROM runs WHERE workflow_id = ? AND status IN ('running','paused','completed')`;
|
||||
|
||||
const counts = db.prepare(`
|
||||
SELECT
|
||||
COUNT(DISTINCT rp.id) AS total_prospects,
|
||||
COUNT(DISTINCT CASE WHEN EXISTS (
|
||||
SELECT 1 FROM run_profile_tracks rt
|
||||
WHERE rt.run_profile_id = rp.id AND rt.state IN ('pending','in_progress')
|
||||
) THEN rp.id END) AS active_prospects,
|
||||
COUNT(DISTINCT CASE WHEN NOT EXISTS (
|
||||
SELECT 1 FROM run_profile_tracks rt
|
||||
WHERE rt.run_profile_id = rp.id AND rt.state NOT IN ('completed','failed','skipped')
|
||||
) AND EXISTS (
|
||||
SELECT 1 FROM run_profile_tracks rt2
|
||||
WHERE rt2.run_profile_id = rp.id AND rt2.state = 'completed'
|
||||
) THEN rp.id END) AS completed_prospects,
|
||||
COUNT(DISTINCT CASE WHEN NOT EXISTS (
|
||||
SELECT 1 FROM run_profile_tracks rt
|
||||
WHERE rt.run_profile_id = rp.id AND rt.state NOT IN ('failed','skipped')
|
||||
) THEN rp.id END) AS failed_prospects,
|
||||
-- Log-based counts scoped to this workflow's runs only
|
||||
(SELECT COUNT(DISTINCT target_id) FROM logs
|
||||
WHERE run_id IN (${RUNS}) AND message LIKE 'Connection request sent%') AS connections_sent,
|
||||
(SELECT COUNT(DISTINCT target_id) FROM logs
|
||||
WHERE run_id IN (${RUNS}) AND message LIKE 'Connection request sent%'
|
||||
AND target_id IN (SELECT id FROM targets WHERE connected_at IS NOT NULL)) AS connections_accepted,
|
||||
(SELECT COUNT(DISTINCT target_id) FROM logs
|
||||
WHERE run_id IN (${RUNS}) AND message LIKE 'Message sent%') AS messages_sent,
|
||||
(SELECT COUNT(DISTINCT target_id) FROM logs
|
||||
WHERE run_id IN (${RUNS}) AND message LIKE 'InMail sent%') AS inmails_sent,
|
||||
(SELECT COUNT(DISTINCT target_id) FROM logs
|
||||
WHERE run_id IN (${RUNS}) AND message LIKE 'Email sent%') AS emails_sent
|
||||
FROM run_profiles rp
|
||||
JOIN runs r ON r.id = rp.run_id
|
||||
WHERE r.workflow_id = ? AND r.status IN ('running','paused','completed')
|
||||
`).get(workflowId, workflowId, workflowId, workflowId, workflowId, workflowId) as {
|
||||
total_prospects: number;
|
||||
active_prospects: number;
|
||||
completed_prospects: number;
|
||||
failed_prospects: number;
|
||||
connections_sent: number;
|
||||
connections_accepted: number;
|
||||
messages_sent: number;
|
||||
inmails_sent: number;
|
||||
emails_sent: number;
|
||||
};
|
||||
|
||||
const connections_sent = counts.connections_sent ?? 0;
|
||||
const connections_accepted = counts.connections_accepted ?? 0;
|
||||
const acceptance_rate = connections_sent > 0
|
||||
? Math.round((connections_accepted / connections_sent) * 100)
|
||||
: 0;
|
||||
|
||||
const activeRun = db.prepare(
|
||||
`SELECT r.id, r.status, r.list_id, l.name as list_name, a.name as account_name
|
||||
FROM runs r
|
||||
LEFT JOIN lists l ON l.id = r.list_id
|
||||
LEFT JOIN accounts a ON a.id = r.account_id
|
||||
WHERE r.workflow_id = ? AND r.status IN ('running', 'paused')
|
||||
LIMIT 1`
|
||||
).get(workflowId) as { id: string; status: string; list_id: string; list_name: string; account_name: string } | undefined;
|
||||
|
||||
return res.json({
|
||||
total_prospects: counts.total_prospects ?? 0,
|
||||
active_prospects: counts.active_prospects ?? 0,
|
||||
completed_prospects: counts.completed_prospects ?? 0,
|
||||
failed_prospects: counts.failed_prospects ?? 0,
|
||||
connections_sent,
|
||||
connections_accepted,
|
||||
acceptance_rate,
|
||||
messages_sent: counts.messages_sent ?? 0,
|
||||
inmails_sent: counts.inmails_sent ?? 0,
|
||||
emails_sent: counts.emails_sent ?? 0,
|
||||
active_run: activeRun ?? null,
|
||||
});
|
||||
} catch (err) {
|
||||
const message = err instanceof Error ? err.message : String(err);
|
||||
return res.status(500).json({ error: message });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
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();
|
||||
const workflowId = req.query.id as string;
|
||||
|
||||
if (req.method === "GET") {
|
||||
const steps = db
|
||||
.prepare(
|
||||
`SELECT ws.*, t.name as template_name
|
||||
FROM workflow_steps ws
|
||||
LEFT JOIN templates t ON t.id = ws.template_id
|
||||
WHERE ws.workflow_id = ?
|
||||
ORDER BY ws.track, ws.step_order`
|
||||
)
|
||||
.all(workflowId);
|
||||
|
||||
// Attach multi-template ids to each step
|
||||
const getTemplateIds = db.prepare(
|
||||
`SELECT wst.template_id, t.name
|
||||
FROM workflow_step_templates wst
|
||||
JOIN templates t ON t.id = wst.template_id
|
||||
WHERE wst.step_id = ?`
|
||||
);
|
||||
const stepsWithTemplates = (steps as Array<Record<string, unknown>>).map((s) => ({
|
||||
...s,
|
||||
template_ids: (getTemplateIds.all(s.id) as Array<{ template_id: string; name: string }>).map((r) => r.template_id),
|
||||
template_names: (getTemplateIds.all(s.id) as Array<{ template_id: string; name: string }>).map((r) => r.name),
|
||||
}));
|
||||
|
||||
return res.json(stepsWithTemplates);
|
||||
}
|
||||
|
||||
if (req.method === "POST") {
|
||||
const { step_type, track: trackIn, template_id, template_ids, delay_seconds, connect_note, message_body, email_subject, email_body, email_signature, email_position, message_position, ai_enabled, ai_model, ai_prompt, ai_max_words, ai_language } = req.body;
|
||||
if (!step_type) return res.status(400).json({ error: "step_type required" });
|
||||
|
||||
// Auto-assign track: email step_type always goes on the email track; everything else linkedin
|
||||
const track: "linkedin" | "email" = trackIn === "email" || step_type === "email" ? "email" : "linkedin";
|
||||
|
||||
const maxRow = db
|
||||
.prepare("SELECT MAX(step_order) as max_order FROM workflow_steps WHERE workflow_id = ? AND track = ?")
|
||||
.get(workflowId, track) as { max_order: number | null };
|
||||
const nextOrder = (maxRow.max_order ?? 0) + 1;
|
||||
|
||||
const id = randomUUID();
|
||||
db.prepare(
|
||||
"INSERT INTO workflow_steps (id, workflow_id, step_order, track, step_type, template_id, delay_seconds, connect_note, message_body, email_subject, email_body, email_signature, email_position, message_position, ai_enabled, ai_model, ai_prompt, ai_max_words, ai_language) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"
|
||||
).run(id, workflowId, nextOrder, track, step_type, template_id ?? null, delay_seconds ?? 0, connect_note ?? null, message_body ?? null, email_subject ?? null, email_body ?? null, email_signature !== undefined ? email_signature : null, email_position ?? 1, message_position ?? 1, ai_enabled ?? 0, ai_model ?? null, ai_prompt ?? null, ai_max_words ?? null, ai_language ?? null);
|
||||
|
||||
// Insert multi-template associations
|
||||
if (Array.isArray(template_ids) && template_ids.length > 0) {
|
||||
const insertLink = db.prepare(
|
||||
"INSERT OR IGNORE INTO workflow_step_templates (step_id, template_id) VALUES (?, ?)"
|
||||
);
|
||||
for (const tid of template_ids) {
|
||||
insertLink.run(id, tid);
|
||||
}
|
||||
}
|
||||
|
||||
return res.status(201).json({ id });
|
||||
}
|
||||
|
||||
res.status(405).end();
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
import type { NextApiRequest, NextApiResponse } from "next";
|
||||
import { getDb } from "@/lib/db";
|
||||
|
||||
export default function handler(req: NextApiRequest, res: NextApiResponse) {
|
||||
const db = getDb();
|
||||
const stepId = req.query.stepId as string;
|
||||
|
||||
if (req.method === "PUT") {
|
||||
const { step_type, template_id, delay_seconds, step_order, connect_note, message_body, email_subject, email_body } = req.body;
|
||||
db.prepare(
|
||||
`UPDATE workflow_steps SET
|
||||
step_type = COALESCE(?, step_type),
|
||||
template_id = COALESCE(?, template_id),
|
||||
delay_seconds = COALESCE(?, delay_seconds),
|
||||
step_order = COALESCE(?, step_order),
|
||||
connect_note = ?,
|
||||
message_body = ?,
|
||||
email_subject = ?,
|
||||
email_body = ?
|
||||
WHERE id = ?`
|
||||
).run(step_type ?? null, template_id ?? null, delay_seconds ?? null, step_order ?? null, connect_note ?? null, message_body ?? null, email_subject ?? null, email_body ?? null, stepId);
|
||||
return res.json({ ok: true });
|
||||
}
|
||||
|
||||
if (req.method === "DELETE") {
|
||||
db.prepare("DELETE FROM workflow_steps WHERE id = ?").run(stepId);
|
||||
return res.json({ ok: true });
|
||||
}
|
||||
|
||||
res.status(405).end();
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
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 workflows = db
|
||||
.prepare(
|
||||
`SELECT w.*, COUNT(ws.id) as step_count
|
||||
FROM workflows w
|
||||
LEFT JOIN workflow_steps ws ON ws.workflow_id = w.id
|
||||
GROUP BY w.id
|
||||
ORDER BY w.created_at DESC`
|
||||
)
|
||||
.all();
|
||||
return res.json(workflows);
|
||||
}
|
||||
|
||||
if (req.method === "POST") {
|
||||
const { name, description, prompt } = req.body;
|
||||
if (!name) return res.status(400).json({ error: "name required" });
|
||||
const id = randomUUID();
|
||||
db.prepare("INSERT INTO workflows (id, name, description, prompt) VALUES (?, ?, ?, ?)").run(id, name, description ?? null, prompt ?? null);
|
||||
return res.status(201).json(db.prepare("SELECT * FROM workflows WHERE id = ?").get(id));
|
||||
}
|
||||
|
||||
res.status(405).end();
|
||||
}
|
||||
Reference in New Issue
Block a user