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
+190
View File
@@ -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" });
}
}
+61
View File
@@ -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 });
}
+63
View File
@@ -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 });
}
+54
View File
@@ -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();
}
+204
View File
@@ -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 });
}
}
+93
View File
@@ -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 });
}
}
+67
View File
@@ -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();
}
+30
View File
@@ -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();
}