Feat/crm mail ui #30

Merged
maaz519 merged 8 commits from feat/crm-mail-ui into goutamnextflow 2026-07-18 12:31:19 +00:00
4 changed files with 337 additions and 1 deletions
Showing only changes of commit 46aa7a767c - Show all commits
+2
View File
@@ -16,6 +16,7 @@ import { Rules } from "./rules";
import { AiAssistant } from "./ai-assistant"; import { AiAssistant } from "./ai-assistant";
import { TeamManagement } from "./team-management"; import { TeamManagement } from "./team-management";
import { Messenger } from "./messenger"; import { Messenger } from "./messenger";
import { Mail } from "./mail";
import { Inbox } from "./inbox"; import { Inbox } from "./inbox";
import "../../app/dashboard/dashboard.css"; import "../../app/dashboard/dashboard.css";
@@ -48,6 +49,7 @@ export function Dashboard() {
: active === "rules" ? <Rules /> : active === "rules" ? <Rules />
: active === "ai" ? <AiAssistant /> : active === "ai" ? <AiAssistant />
: active === "messenger" ? <Messenger /> : active === "messenger" ? <Messenger />
: active === "mail" ? <Mail />
: active === "inbox" ? <Inbox /> : active === "inbox" ? <Inbox />
: active === "team" ? <TeamManagement /> : active === "team" ? <TeamManagement />
: <ComingSoon title={title} icon={item?.icon ?? "dashboard"} onGo={setActive} />} : <ComingSoon title={title} icon={item?.icon ?? "dashboard"} onGo={setActive} />}
+216
View File
@@ -0,0 +1,216 @@
"use client";
// ============================================================
// Mail — a dedicated reader for app-to-app and email messages,
// powered by IIOS via the be-crm data door (crm.mail.*). Distinct
// from Messenger (chat) and from the work-item Inbox: this shows the
// actual mail (subject + rendered body) and lets you read + reply +
// compose. HTML bodies render inside a sandboxed iframe (no scripts).
// ============================================================
import { type CSSProperties, useEffect, useState } from "react";
import { Avatar, Btn, Field, Icon, Modal, PageHead, Pill, useToast } from "./ui";
import { useMailThreads, useMailThread, useMailCompose, type MailThread, type MailPerson } from "@/lib/mail-api";
const timeOf = (iso?: string) => {
if (!iso) return "";
const d = new Date(iso);
return Number.isNaN(+d) ? "" : d.toLocaleString([], { month: "short", day: "numeric", hour: "2-digit", minute: "2-digit" });
};
const CUSTOMER_GRAD = "linear-gradient(135deg,#10b981,#059669)";
const inputStyle: CSSProperties = {
width: "100%", padding: "9px 12px", borderRadius: 10, border: "1px solid var(--border)",
background: "var(--panel)", color: "var(--text)", fontSize: 14, outline: "none",
};
export function Mail() {
const list = useMailThreads();
const toast = useToast();
const [selected, setSelected] = useState<string | null>(null);
const [newOpen, setNewOpen] = useState(false);
useEffect(() => {
if ((!selected || !list.threads.some((t) => t.threadId === selected)) && list.threads[0]) {
setSelected(list.threads[0].threadId);
}
}, [list.threads, selected]);
const current = list.threads.find((t) => t.threadId === selected) ?? null;
return (
<div className="view">
<PageHead
eyebrow="Communication" title="Mail" subtitle="Read and send app messages and email — everything in one place" icon="chat"
actions={<Btn icon="plus" onClick={() => setNewOpen(true)}>New mail</Btn>}
/>
{!list.live && (
<div style={{ margin: "0 0 14px", padding: "8px 14px", borderRadius: 10, background: "var(--panel-2)", color: "var(--muted)", fontSize: 13, border: "1px solid var(--border)" }}>
Demo mode running on mock data. It goes live once the Shell + be-crm are connected.
</div>
)}
<div className="card" style={{ display: "flex", height: 640, padding: 0, overflow: "hidden" }}>
<aside style={{ width: 320, borderRight: "1px solid var(--border)", overflowY: "auto", background: "var(--panel)" }}>
{list.loading && <div style={{ padding: 16, color: "var(--muted)" }}>Loading</div>}
{!list.loading && list.threads.length === 0 && (
<div style={{ padding: 16, color: "var(--muted)" }}>No mail yet. Compose a new message.</div>
)}
{list.threads.map((t) => (
<ThreadRow key={t.threadId} t={t} active={t.threadId === selected} onClick={() => setSelected(t.threadId)} />
))}
</aside>
<section style={{ flex: 1, display: "flex", flexDirection: "column", minWidth: 0, background: "var(--bg)" }}>
{current ? (
<Reader key={current.threadId} thread={current} onError={(m) => toast.push({ tone: "error", title: "Failed", desc: m })} />
) : (
<div style={{ margin: "auto", color: "var(--muted)", textAlign: "center" }}>
<Icon name="chat" size={38} /><p>Select or compose a message</p>
</div>
)}
</section>
</div>
<NewMailModal
open={newOpen} onClose={() => setNewOpen(false)}
onSent={() => { setNewOpen(false); list.refetch(); toast.push({ tone: "success", title: "Sent" }); }}
onError={(m) => toast.push({ tone: "error", title: "Couldn't send", desc: m })}
/>
</div>
);
}
function ThreadRow({ t, active, onClick }: { t: MailThread; active: boolean; onClick: () => void }) {
return (
<button
onClick={onClick}
style={{
display: "block", width: "100%", textAlign: "left", padding: "12px 16px", border: "none",
borderBottom: "1px solid var(--border)", cursor: "pointer",
background: active ? "var(--panel-2)" : "transparent", color: "var(--text)",
}}
>
<div style={{ display: "flex", justifyContent: "space-between", gap: 8, alignItems: "center" }}>
<span style={{ fontWeight: 600, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{t.subject || "(no subject)"}</span>
<span style={{ color: "var(--muted)", fontSize: 11, flexShrink: 0 }}>{timeOf(t.lastAt)}</span>
</div>
<div style={{ display: "flex", justifyContent: "space-between", gap: 8, alignItems: "center", marginTop: 3 }}>
<span style={{ color: "var(--muted)", fontSize: 12.5, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{t.lastMessage ?? "No messages"}</span>
{t.unread > 0 && <span style={{ background: "var(--orange)", color: "#fff", borderRadius: 999, fontSize: 11, padding: "1px 7px", flexShrink: 0 }}>{t.unread}</span>}
</div>
</button>
);
}
function Reader({ thread, onError }: { thread: MailThread; onError: (m: string) => void }) {
const t = useMailThread(thread.threadId);
const [draft, setDraft] = useState("");
const [sending, setSending] = useState(false);
async function reply() {
const text = draft.trim();
if (!text || sending) return;
setDraft(""); setSending(true);
try { await t.reply(text); }
catch (e) { setDraft(text); onError((e as Error).message); }
finally { setSending(false); }
}
return (
<>
<header style={{ padding: "14px 20px", borderBottom: "1px solid var(--border)" }}>
<div style={{ fontWeight: 700, fontSize: 16 }}>{thread.subject || "(no subject)"}</div>
<div style={{ color: "var(--muted)", fontSize: 12, marginTop: 2 }}>{thread.participants.length} participant(s)</div>
</header>
<div style={{ flex: 1, overflowY: "auto", padding: 18, display: "flex", flexDirection: "column", gap: 14 }}>
{t.loading && t.messages.length === 0 && <div style={{ margin: "auto", color: "var(--muted)" }}>Loading</div>}
{!t.loading && t.messages.length === 0 && <div style={{ margin: "auto", color: "var(--muted)" }}>No messages in this thread.</div>}
{t.messages.map((m) => (
<div key={m.interactionId} style={{ border: "1px solid var(--border)", borderRadius: 12, background: "var(--panel)", overflow: "hidden" }}>
<div style={{ padding: "8px 14px", borderBottom: "1px solid var(--border)", display: "flex", justifyContent: "space-between", fontSize: 12, color: "var(--muted)" }}>
<span>{m.kind === "EMAIL" ? "Email" : "Reply"}{m.actorId ? ` · ${m.actorId.replace(/^(pp_|cust_)/, "").slice(0, 8)}` : ""}</span>
<span>{timeOf(m.occurredAt)}</span>
</div>
{m.html
? <iframe sandbox="" srcDoc={m.html} title="mail body" style={{ width: "100%", height: 220, border: "none", background: "#fff" }} />
: <div style={{ padding: 14, whiteSpace: "pre-wrap", wordBreak: "break-word", fontSize: 14 }}>{m.text}</div>}
</div>
))}
</div>
<footer style={{ display: "flex", gap: 8, padding: 14, borderTop: "1px solid var(--border)" }}>
<input
value={draft} onChange={(e) => setDraft(e.target.value)}
onKeyDown={(e) => { if (e.key === "Enter" && !e.shiftKey) { e.preventDefault(); void reply(); } }}
placeholder="Reply…" style={inputStyle}
/>
<Btn icon="send" onClick={() => void reply()} disabled={sending || !draft.trim()}>Reply</Btn>
</footer>
</>
);
}
function NewMailModal({ open, onClose, onSent, onError }: { open: boolean; onClose: () => void; onSent: () => void; onError: (m: string) => void }) {
const compose = useMailCompose(onSent);
const [mode, setMode] = useState<"internal" | "external">("internal");
const [recipient, setRecipient] = useState(""); // userId (internal) or email (external)
const [subject, setSubject] = useState("");
const [body, setBody] = useState("");
const [q, setQ] = useState("");
const [busy, setBusy] = useState(false);
useEffect(() => { if (!open) { setMode("internal"); setRecipient(""); setSubject(""); setBody(""); setQ(""); setBusy(false); } }, [open]);
const filtered = compose.directory.filter((p) => p.name.toLowerCase().includes(q.trim().toLowerCase()));
const canSend = !!recipient && !!subject.trim() && !!body.trim() && !busy;
async function send() {
if (!canSend) return;
setBusy(true);
try {
if (mode === "internal") await compose.sendInternal(recipient, subject.trim(), body.trim());
else await compose.sendExternal(recipient.trim(), subject.trim(), body.trim());
} catch (e) { onError((e as Error).message); }
finally { setBusy(false); }
}
return (
<Modal
open={open} onClose={onClose} title="New mail" subtitle={mode === "internal" ? "To a team member or client (in-app)" : "To an email address"} icon="chat"
footer={<>
<Btn variant="ghost" onClick={onClose}>Cancel</Btn>
<Btn icon="send" onClick={() => void send()} disabled={!canSend}>{busy ? "Sending…" : "Send"}</Btn>
</>}
>
<div style={{ display: "flex", gap: 6, marginBottom: 12 }}>
<Btn variant={mode === "internal" ? "primary" : "outline"} onClick={() => { setMode("internal"); setRecipient(""); }}>In-app</Btn>
<Btn variant={mode === "external" ? "primary" : "outline"} onClick={() => { setMode("external"); setRecipient(""); }}>Email</Btn>
</div>
{mode === "internal" ? (
<Field label="To (person)">
<input value={q} onChange={(e) => setQ(e.target.value)} placeholder="Search people…" style={{ ...inputStyle, marginBottom: 8 }} />
<div style={{ maxHeight: 180, overflowY: "auto", display: "flex", flexDirection: "column", gap: 2 }}>
{filtered.length === 0 && <div style={{ color: "var(--muted)", padding: 8 }}>No people found.</div>}
{filtered.map((p: MailPerson) => (
<label key={p.id} style={{ display: "flex", alignItems: "center", gap: 10, padding: "7px 10px", borderRadius: 10, cursor: "pointer", background: recipient === p.id ? "var(--panel-2)" : "transparent" }}>
<input type="radio" checked={recipient === p.id} onChange={() => setRecipient(p.id)} />
<Avatar initials={(p.name.split(/\s+/).map((s) => s[0]).join("").slice(0, 2) || "?").toUpperCase()} size={26} gradient={p.kind === "customer" ? CUSTOMER_GRAD : undefined} />
<span style={{ flex: 1 }}>{p.name}</span>
<Pill tone="muted">{p.kind}</Pill>
</label>
))}
</div>
</Field>
) : (
<Field label="To (email)">
<input value={recipient} onChange={(e) => setRecipient(e.target.value)} placeholder="name@company.com" style={inputStyle} />
</Field>
)}
<Field label="Subject"><input value={subject} onChange={(e) => setSubject(e.target.value)} placeholder="Subject" style={inputStyle} /></Field>
<Field label="Message"><textarea value={body} onChange={(e) => setBody(e.target.value)} placeholder="Write your message…" rows={6} style={{ ...inputStyle, resize: "vertical" }} /></Field>
</Modal>
);
}
+2 -1
View File
@@ -33,6 +33,7 @@ export const NAV_GROUPS: NavGroup[] = [
title: "Communication", title: "Communication",
items: [ items: [
{ key: "messenger", label: "Messenger", icon: "send", subtitle: "Chat with your team and clients" }, { key: "messenger", label: "Messenger", icon: "send", subtitle: "Chat with your team and clients" },
{ key: "mail", label: "Mail", icon: "chat", subtitle: "Read and send app messages and email" },
{ key: "inbox", label: "Inbox", icon: "bell", subtitle: "Mentions, replies and updates for you" }, { key: "inbox", label: "Inbox", icon: "bell", subtitle: "Mentions, replies and updates for you" },
], ],
}, },
@@ -79,7 +80,7 @@ export const NAV_ITEMS: NavItem[] = NAV_GROUPS.flatMap((g) => g.items);
// brand-new user with no membership); every other item requires membership, and the // brand-new user with no membership); every other item requires membership, and the
// items mapped here additionally require the given permission. Unmapped items are // items mapped here additionally require the given permission. Unmapped items are
// shown to any member. This is UX only — be-crm still enforces every action. // shown to any member. This is UX only — be-crm still enforces every action.
const ALWAYS_VISIBLE = new Set(["dashboard", "profile", "messenger", "inbox"]); const ALWAYS_VISIBLE = new Set(["dashboard", "profile", "messenger", "mail", "inbox"]);
const NAV_PERMISSION: Record<string, string | undefined> = { const NAV_PERMISSION: Record<string, string | undefined> = {
team: "team.manage", team: "team.manage",
people: "team.manage", people: "team.manage",
+117
View File
@@ -0,0 +1,117 @@
"use client";
// Mail data layer. A dedicated Mail reader over the be-crm data door (crm.mail.*), distinct from
// the Messenger chat and from the work-item Inbox. Live via the AppShell SDK; a small mock keeps the
// demo working before the Shell + be-crm are connected.
//
// Live contract (be-crm):
// query crm.mail.list {} -> MailThread[]
// query crm.mail.history { threadId } -> MailMessage[]
// cmd crm.mail.reply { threadId, content } -> { interactionId, threadId }
// cmd crm.mail.internal { recipientUserId, subject?, text?, html? } -> { threadId }
// cmd crm.mail.send { target, subject?, text?, html?, mirrorToUserId? } -> { commandId }
// query crm.messenger.directory { kind, limit } -> people to compose to (reused)
import { useCallback, useMemo, useState } from "react";
import { useAppShell, useQuery } from "@abe-kap/appshell-sdk/react";
import { isShellConfigured } from "./appshell";
export interface MailThread {
threadId: string; subject: string | null; participants: string[]; unread: number; lastMessage?: string; lastAt?: string;
}
export interface MailMessage {
interactionId: string; actorId: string | null; kind: string; occurredAt: string; html: string | null; text: string | null;
}
export interface MailPerson { id: string; name: string; kind: "staff" | "customer" }
const SHELL = isShellConfigured();
/* ============================ Thread list ============================ */
export interface MailListData {
live: boolean; loading: boolean; error: string | null; threads: MailThread[]; refetch: () => void;
}
export function useMailThreads(): MailListData {
if (SHELL) {
const q = useQuery<MailThread[]>("crm.mail.list", {});
return { live: true, loading: q.loading, error: q.error?.message ?? null, threads: q.data ?? [], refetch: q.refetch };
}
return { live: false, loading: false, error: null, threads: MOCK_THREADS, refetch: () => {} };
}
/* ============================ One thread ============================ */
export interface MailThreadData {
loading: boolean; error: string | null; messages: MailMessage[]; reply: (content: string) => Promise<void>; refetch: () => void;
}
export function useMailThread(threadId: string | null): MailThreadData {
if (SHELL) return useLiveThread(threadId);
return useMockThread(threadId);
}
function useLiveThread(threadId: string | null): MailThreadData {
const { sdk } = useAppShell();
const q = useQuery<MailMessage[]>("crm.mail.history", threadId ? { threadId } : { threadId: "" });
const reply = useCallback(async (content: string) => {
if (!threadId) return;
await sdk.command("crm.mail.reply", { threadId, content });
q.refetch();
}, [sdk, threadId, q]);
return { loading: q.loading, error: q.error?.message ?? null, messages: threadId ? (q.data ?? []) : [], reply, refetch: q.refetch };
}
/* ============================ Compose ============================ */
export interface ComposeData {
directory: MailPerson[];
sendInternal: (recipientUserId: string, subject: string, text: string) => Promise<void>;
sendExternal: (target: string, subject: string, text: string, mirrorToUserId?: string) => Promise<void>;
}
export function useMailCompose(onSent: () => void): ComposeData {
if (SHELL) {
const { sdk } = useAppShell();
const dirQ = useQuery<MailPerson[]>("crm.messenger.directory", { kind: "all", limit: 100 });
const directory = useMemo(() => (dirQ.data ?? []).map((d) => ({ id: (d as unknown as { id: string }).id, name: (d as unknown as { displayName?: string; name?: string }).displayName ?? (d as unknown as { name?: string }).name ?? "", kind: (d as MailPerson).kind })), [dirQ.data]);
const sendInternal = useCallback(async (recipientUserId: string, subject: string, text: string) => {
await sdk.command("crm.mail.internal", { recipientUserId, subject, text, html: `<p>${escapeHtml(text)}</p>` });
onSent();
}, [sdk, onSent]);
const sendExternal = useCallback(async (target: string, subject: string, text: string, mirrorToUserId?: string) => {
await sdk.command("crm.mail.send", { target, subject, text, html: `<p>${escapeHtml(text)}</p>`, ...(mirrorToUserId ? { mirrorToUserId } : {}) });
onSent();
}, [sdk, onSent]);
return { directory, sendInternal, sendExternal };
}
return { directory: MOCK_PEOPLE, sendInternal: async () => onSent(), sendExternal: async () => onSent() };
}
function escapeHtml(s: string): string {
return s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
}
/* ============================ Mock (demo mode) ============================ */
const now = () => new Date().toISOString();
const MOCK_PEOPLE: MailPerson[] = [
{ id: "pp_sofia", name: "Sofia Ramirez", kind: "staff" },
{ id: "cust_acme", name: "Acme Roofing (Client)", kind: "customer" },
];
const MOCK_THREADS: MailThread[] = [
{ threadId: "mt_1", subject: "Welcome to the Founders Club", participants: ["you", "system"], unread: 1, lastMessage: "Thanks for joining…", lastAt: now() },
{ threadId: "mt_2", subject: "Storm response — East side", participants: ["you", "pp_sofia"], unread: 0, lastMessage: "Crew rolling out at 7", lastAt: now() },
];
function useMockThread(threadId: string | null): MailThreadData {
const [extra, setExtra] = useState<MailMessage[]>([]);
const base: MailMessage[] = threadId === "mt_1"
? [{ interactionId: "m1", actorId: "system", kind: "EMAIL", occurredAt: now(), html: "<p>Thanks for joining the <b>Founders Club</b>. Set up your account to get started.</p>", text: "Thanks for joining the Founders Club." }]
: threadId === "mt_2"
? [{ interactionId: "m2", actorId: "pp_sofia", kind: "EMAIL", occurredAt: now(), html: "<p>Crew is rolling out at 7. Confirm the Henderson scope?</p>", text: "Crew rolling out at 7." }]
: [];
const reply = useCallback(async (content: string) => {
setExtra((l) => [...l, { interactionId: `r_${l.length}`, actorId: "you", kind: "MESSAGE", occurredAt: now(), html: null, text: content }]);
}, []);
return { loading: false, error: null, messages: threadId ? [...base, ...extra] : [], reply, refetch: () => {} };
}