release: 2026-08-01
This commit is contained in:
@@ -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();
|
||||
});
|
||||
}
|
||||
Reference in New Issue
Block a user