release: 2026-08-01

This commit is contained in:
moaljumaa
2026-08-01 14:01:17 +02:00
commit 7d8b930bc3
137 changed files with 34695 additions and 0 deletions
+46
View File
@@ -0,0 +1,46 @@
import "@/styles/globals.css";
import type { AppProps } from "next/app";
import { SessionProvider, useSession } from "next-auth/react";
import { useRouter } from "next/router";
import { useEffect } from "react";
import Layout from "@/components/layout/Layout";
import { Toaster } from "sonner";
const PUBLIC_PATHS = ["/login"];
function AuthGuard({ children }: { children: React.ReactNode }) {
const { data: session, status } = useSession();
const router = useRouter();
useEffect(() => {
if (status === "loading") return;
if (!session && !PUBLIC_PATHS.includes(router.pathname)) {
router.replace("/login");
}
}, [session, status, router]);
if (status === "loading") {
return (
<div className="min-h-screen bg-base-100 flex items-center justify-center">
<span className="loading loading-spinner loading-sm text-base-content/40" />
</div>
);
}
if (!session && !PUBLIC_PATHS.includes(router.pathname)) return null;
return <>{children}</>;
}
export default function App({ Component, pageProps: { session, ...pageProps } }: AppProps) {
return (
<SessionProvider session={session}>
<AuthGuard>
<Layout>
<Component {...pageProps} />
<Toaster theme="dark" position="bottom-right" />
</Layout>
</AuthGuard>
</SessionProvider>
);
}
+17
View File
@@ -0,0 +1,17 @@
import { Html, Head, Main, NextScript } from "next/document";
export default function Document() {
return (
<Html lang="en" data-theme="notion">
<Head>
<link rel="icon" type="image/x-icon" href="/logo_linki.ico" />
<link rel="icon" type="image/png" href="/logo_linki.png" />
<link rel="apple-touch-icon" href="/logo_linki.png" />
</Head>
<body className="min-h-screen bg-base-100 text-base-content antialiased">
<Main />
<NextScript />
</body>
</Html>
);
}
+50
View File
@@ -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 });
}
+46
View File
@@ -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();
}
+36
View File
@@ -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(() => {});
}
}
+46
View File
@@ -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 });
}
}
+72
View File
@@ -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(() => {});
}
}
+43
View File
@@ -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();
}
+48
View File
@@ -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);
+39
View File
@@ -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 });
}
+48
View File
@@ -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 });
}
+45
View File
@@ -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();
}
+57
View File
@@ -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();
}
+38
View File
@@ -0,0 +1,38 @@
import type { NextApiRequest, NextApiResponse } from "next";
import { getDb } from "@/lib/db";
export default function handler(req: NextApiRequest, res: NextApiResponse) {
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" });
}
}
+170
View File
@@ -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;
}
+78
View File
@@ -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}`;
}
+68
View File
@@ -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,
});
}
+74
View File
@@ -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();
}
+96
View File
@@ -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 });
}
+13
View File
@@ -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" });
}
+21
View File
@@ -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 });
}
+32
View File
@@ -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 });
}
+119
View File
@@ -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 });
}
+40
View File
@@ -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" });
}
}
+143
View File
@@ -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();
});
}
+47
View File
@@ -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();
}
+49
View File
@@ -0,0 +1,49 @@
import type { NextApiRequest, NextApiResponse } from "next";
import { getDb } from "@/lib/db";
// Add EXISTING contacts to a list by id (membership only — does not create
// contacts). Idempotent: already-member ids are skipped. This is the inverse of
// remove-members and the way to UNDO a removal (feed back removed_contact_ids).
export default function handler(req: NextApiRequest, res: NextApiResponse) {
if (req.method !== "POST") return res.status(405).end();
const db = getDb();
const list_id = req.query.id as string;
const list = db.prepare("SELECT id FROM lists WHERE id = ?").get(list_id);
if (!list) return res.status(404).json({ error: "List not found" });
const { contact_ids } = req.body as { contact_ids?: string[] };
if (!Array.isArray(contact_ids) || contact_ids.length === 0) {
return res.status(400).json({ error: "contact_ids[] is required." });
}
// Only add ids that actually exist as contacts (ignore unknown ids rather
// than failing the whole batch).
const placeholders = contact_ids.map(() => "?").join(", ");
const existing = db
.prepare(`SELECT id, full_name, title FROM targets WHERE id IN (${placeholders})`)
.all(...contact_ids) as Array<{ id: string; full_name: string | null; title: string | null }>;
const existingIds = new Set(existing.map((r) => r.id));
const unknown = contact_ids.filter((id) => !existingIds.has(id));
const insert = db.prepare("INSERT OR IGNORE INTO list_targets (list_id, target_id) VALUES (?, ?)");
let added = 0;
const addTx = db.transaction((ids: string[]) => {
for (const id of ids) {
const info = insert.run(list_id, id);
if (info.changes > 0) added++;
}
});
addTx([...existingIds]);
const total = (db.prepare("SELECT COUNT(*) as c FROM list_targets WHERE list_id = ?").get(list_id) as { c: number }).c;
return res.json({
added,
already_members: existingIds.size - added,
unknown_contact_ids: unknown,
list_total: total,
contacts_added: existing,
});
}
+35
View File
@@ -0,0 +1,35 @@
import type { NextApiRequest, NextApiResponse } from "next";
import { getDb } from "@/lib/db";
// Title + location breakdown for a list — used to spot irrelevant contacts before cleaning.
export default function handler(req: NextApiRequest, res: NextApiResponse) {
if (req.method !== "GET") return res.status(405).end();
const db = getDb();
const list_id = req.query.id as string;
const list = db.prepare("SELECT id, name FROM lists WHERE id = ?").get(list_id);
if (!list) return res.status(404).json({ error: "List not found" });
const total = (db.prepare("SELECT COUNT(*) as c FROM list_targets WHERE list_id = ?").get(list_id) as { c: number }).c;
const titles = db.prepare(`
SELECT t.title, COUNT(*) as count
FROM list_targets lt
JOIN targets t ON t.id = lt.target_id
WHERE lt.list_id = ? AND t.title IS NOT NULL
GROUP BY t.title
ORDER BY count DESC
`).all(list_id);
const locations = db.prepare(`
SELECT t.location, COUNT(*) as count
FROM list_targets lt
JOIN targets t ON t.id = lt.target_id
WHERE lt.list_id = ? AND t.location IS NOT NULL
GROUP BY t.location
ORDER BY count DESC
`).all(list_id);
return res.json({ list, total, titles, locations });
}

Some files were not shown because too many files have changed in this diff Show More