import Head from "next/head"; import { useState } from "react"; import { GetServerSideProps } from "next"; import { useRouter } from "next/router"; import { getDb } from "@/lib/db"; import { toast } from "sonner"; import { RiAddLine, RiDeleteBinLine, RiArrowRightLine, RiPlayLine, RiPauseLine, RiTimeLine, RiEyeLine, RiLinkedinBoxLine, RiMessage2Line, RiRocketLine, RiTeamLine, RiUserStarLine, RiMailSendLine, RiSuitcaseLine, RiGlobalLine, RiMegaphoneLine, RiShakeHandsLine, RiLightbulbLine, RiCrosshairLine, RiFileCopyLine, RiArchiveLine, RiInboxUnarchiveLine, RiArrowDownSLine, } from "react-icons/ri"; interface WorkflowCard { id: string; name: string; description: string | null; is_archived: number; step_count: number; action_step_count: number; total_prospects: number; completed_prospects: number; connections_sent: number; connections_accepted: number; active_run_id: string | null; active_status: string | null; created_at: string; step_types: string; } const CARD_COLORS = [ { bg: "bg-blue-500/10", border: "border-blue-500/20", icon: "text-blue-400" }, { bg: "bg-violet-500/10", border: "border-violet-500/20", icon: "text-violet-400" }, { bg: "bg-emerald-500/10", border: "border-emerald-500/20", icon: "text-emerald-400" }, { bg: "bg-orange-500/10", border: "border-orange-500/20", icon: "text-orange-400" }, { bg: "bg-pink-500/10", border: "border-pink-500/20", icon: "text-pink-400" }, { bg: "bg-cyan-500/10", border: "border-cyan-500/20", icon: "text-cyan-400" }, { bg: "bg-amber-500/10", border: "border-amber-500/20", icon: "text-amber-400" }, { bg: "bg-rose-500/10", border: "border-rose-500/20", icon: "text-rose-400" }, ]; const CARD_ICONS = [ RiRocketLine, RiTeamLine, RiUserStarLine, RiMailSendLine, RiSuitcaseLine, RiGlobalLine, RiMegaphoneLine, RiShakeHandsLine, RiLightbulbLine, RiCrosshairLine, ]; const STEP_ICON: Record = { visit: RiEyeLine, connect: RiLinkedinBoxLine, message: RiMessage2Line, delay: RiTimeLine, }; const STEP_LABEL: Record = { visit: "Visit", connect: "Connect", message: "Message", }; export const getServerSideProps: GetServerSideProps = async () => { const db = getDb(); // Steps subquery — isolated to avoid row multiplication when joined with runs const stepRows = db.prepare( `SELECT workflow_id, GROUP_CONCAT(step_type ORDER BY step_order) as step_types, COUNT(*) as step_count, SUM(CASE WHEN step_type != 'delay' THEN 1 ELSE 0 END) as action_step_count FROM workflow_steps GROUP BY workflow_id` ).all() as { workflow_id: string; step_types: string; step_count: number; action_step_count: number }[]; const stepMap = Object.fromEntries(stepRows.map(s => [s.workflow_id, s])); // Prospects/runs subquery — separate from steps to avoid GROUP_CONCAT multiplication const prospectRows = db.prepare( `SELECT r.workflow_id, COUNT(DISTINCT rp.id) as total_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 t.connection_requested_at IS NOT NULL THEN rp.target_id END) as connections_sent, COUNT(DISTINCT CASE WHEN t.connected_at IS NOT NULL THEN rp.target_id END) as connections_accepted, MAX(CASE WHEN r.status = 'running' THEN r.id ELSE NULL END) as active_run_id, MAX(CASE WHEN r.status IN ('running','paused') THEN r.status ELSE NULL END) as active_status FROM runs r LEFT JOIN run_profiles rp ON rp.run_id = r.id LEFT JOIN targets t ON t.id = rp.target_id GROUP BY r.workflow_id` ).all() as { workflow_id: string; total_prospects: number; completed_prospects: number; connections_sent: number; connections_accepted: number; active_run_id: string | null; active_status: string | null; }[]; const prospectMap = Object.fromEntries(prospectRows.map(r => [r.workflow_id, r])); const workflows = db.prepare( "SELECT id, name, description, is_archived, created_at FROM workflows ORDER BY created_at DESC" ).all() as { id: string; name: string; description: string | null; is_archived: number; created_at: string }[]; const merged: WorkflowCard[] = workflows.map(w => ({ ...w, is_archived: w.is_archived ?? 0, step_count: stepMap[w.id]?.step_count ?? 0, action_step_count: stepMap[w.id]?.action_step_count ?? 0, step_types: stepMap[w.id]?.step_types ?? "", total_prospects: prospectMap[w.id]?.total_prospects ?? 0, completed_prospects: prospectMap[w.id]?.completed_prospects ?? 0, connections_sent: prospectMap[w.id]?.connections_sent ?? 0, connections_accepted: prospectMap[w.id]?.connections_accepted ?? 0, active_run_id: prospectMap[w.id]?.active_run_id ?? null, active_status: prospectMap[w.id]?.active_status ?? null, })); return { props: { initialWorkflows: merged } }; }; export default function WorkflowsPage({ initialWorkflows }: { initialWorkflows: WorkflowCard[] }) { const router = useRouter(); const [workflows, setWorkflows] = useState(initialWorkflows); const [showModal, setShowModal] = useState(false); const [form, setForm] = useState({ name: "", description: "" }); const [loading, setLoading] = useState(false); const [deleteId, setDeleteId] = useState(null); const [archivedOpen, setArchivedOpen] = useState(false); const activeWorkflows = workflows.filter((w) => !w.is_archived); const archivedWorkflows = workflows.filter((w) => w.is_archived); async function createWorkflow(e: React.FormEvent) { e.preventDefault(); setLoading(true); const res = await fetch("/api/workflows", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(form), }); setLoading(false); if (!res.ok) { toast.error("Failed to create campaign"); return; } const { id } = await res.json(); router.push(`/workflows/${id}?setup=1`); } async function deleteWorkflow(id: string) { await fetch(`/api/workflows/${id}`, { method: "DELETE" }); toast.success("Campaign deleted"); setWorkflows((prev) => prev.filter((w) => w.id !== id)); setDeleteId(null); } async function duplicateWorkflow(id: string, name: string) { const res = await fetch(`/api/workflows/${id}/duplicate`, { method: "POST" }); if (!res.ok) { toast.error("Failed to duplicate"); return; } const { id: newId } = await res.json(); toast.success(`"${name} (copy)" created`); router.push(`/workflows/${newId}`); } async function toggleArchive(id: string, archive: boolean) { await fetch(`/api/workflows/${id}`, { method: "PATCH", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ is_archived: archive }), }); setWorkflows((prev) => prev.map((w) => w.id === id ? { ...w, is_archived: archive ? 1 : 0 } : w)); toast.success(archive ? "Campaign archived" : "Campaign restored"); } async function pauseRun(workflowId: string, runId: string) { await fetch(`/api/runs/${runId}`, { method: "PATCH", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ status: "paused" }) }); toast.success("Paused"); setWorkflows((prev) => prev.map((w) => w.id === workflowId ? { ...w, active_status: "paused" } : w)); } async function resumeRun(workflowId: string, runId: string) { await fetch(`/api/runs/${runId}/start`, { method: "POST" }); toast.success("Resumed"); setWorkflows((prev) => prev.map((w) => w.id === workflowId ? { ...w, active_status: "running" } : w)); } return ( <> Campaigns — Linki

Campaigns

Your outreach sequences

{workflows.length === 0 ? (
No campaigns yet. Create one to start your outreach.
) : ( <> {/* Active campaigns */} {activeWorkflows.length === 0 ? (
No active campaigns. Create one or restore from the archive below.
) : (
{activeWorkflows.map((w) => { const colorIdx = w.id.split("").reduce((acc, c) => acc + c.charCodeAt(0), 0); const style = CARD_COLORS[colorIdx % CARD_COLORS.length]; const Icon = CARD_ICONS[colorIdx % CARD_ICONS.length]; const stepTypes = w.step_types ? w.step_types.split(",") : []; // Collapse duplicate adjacent step types, skip delays (shown implicitly via arrows) const actionSteps: string[] = []; for (const t of stepTypes) { if (t === "delay") continue; if (actionSteps[actionSteps.length - 1] !== t) actionSteps.push(t); } const acceptanceRate = w.connections_sent > 0 ? Math.round((w.connections_accepted / w.connections_sent) * 100) : null; const progress = w.total_prospects > 0 ? Math.round((w.completed_prospects / w.total_prospects) * 100) : 0; const isRunning = w.active_status === "running"; const isPaused = w.active_status === "paused"; return (
router.push(`/workflows/${w.id}`)} > {/* Header: icon + name + status */}
{w.name} {isRunning && ( Active )} {isPaused && ( Paused )}
{/* Step sequence */} {actionSteps.length > 0 && (
{actionSteps.map((type, i) => { const StepIcon = STEP_ICON[type] ?? RiEyeLine; return ( {i > 0 && } {STEP_LABEL[type] ?? type} ); })}
)} {actionSteps.length === 0 && (

No steps configured

)}
{/* Progress */} {w.total_prospects > 0 ? (
{w.completed_prospects} / {w.total_prospects} prospects done {progress}%
{(w.connections_sent > 0 || acceptanceRate !== null) && (
{w.connections_sent > 0 && {w.connections_sent} connected} {acceptanceRate !== null && {acceptanceRate}% accepted}
)}
) : (

No prospects enrolled yet

)} {/* Footer */}
e.stopPropagation()} > {w.action_step_count} step{w.action_step_count !== 1 ? "s" : ""}
{isRunning && w.active_run_id && ( )} {isPaused && w.active_run_id && ( )}
); })}
)} {/* Archived section */} {archivedWorkflows.length > 0 && (
{archivedOpen && (
{archivedWorkflows.map((w) => { const colorIdx = w.id.split("").reduce((acc, c) => acc + c.charCodeAt(0), 0); const style = CARD_COLORS[colorIdx % CARD_COLORS.length]; const Icon = CARD_ICONS[colorIdx % CARD_ICONS.length]; return (

{w.name}

{w.action_step_count} steps · {w.total_prospects} prospects

); })}
)}
)} )} {/* New campaign modal */} {showModal && (

New Campaign

setForm({ ...form, name: e.target.value })} required autoFocus />
setForm({ ...form, description: e.target.value })} />
setShowModal(false)} />
)} {/* Delete confirm */} {deleteId !== null && (

Delete campaign?

This will permanently delete the campaign and all its history. Cannot be undone.

setDeleteId(null)} />
)}
); }