Compare commits
7 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| adb5a6bb7b | |||
| 2056592d51 | |||
| 49b04e9710 | |||
| e7c042fb1a | |||
| 9eb234935d | |||
| fa538355ae | |||
| 1a2043eaae |
@@ -1,2 +1,6 @@
|
|||||||
@abe-kap:registry=https://npm.pkg.github.com
|
@abe-kap:registry=https://npm.pkg.github.com
|
||||||
//npm.pkg.github.com/:_authToken=${NODE_AUTH_TOKEN}
|
//npm.pkg.github.com/:_authToken=${NODE_AUTH_TOKEN}
|
||||||
|
# @insignia/* (iios-kernel-client — the MessageSocket live stream) resolve from the
|
||||||
|
# self-hosted Gitea npm registry. Install needs a token with `read:package` in GITEA_TOKEN.
|
||||||
|
@insignia:registry=https://git.lynkedup.cloud/api/packages/insignia/npm/
|
||||||
|
//git.lynkedup.cloud/api/packages/insignia/npm/:_authToken=${GITEA_TOKEN}
|
||||||
|
|||||||
Generated
+100
-1
@@ -9,6 +9,7 @@
|
|||||||
"version": "0.1.0",
|
"version": "0.1.0",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@abe-kap/appshell-sdk": "^0.2.6",
|
"@abe-kap/appshell-sdk": "^0.2.6",
|
||||||
|
"@insignia/iios-kernel-client": "^0.1.4",
|
||||||
"clsx": "^2.1.1",
|
"clsx": "^2.1.1",
|
||||||
"lucide-react": "^1.21.0",
|
"lucide-react": "^1.21.0",
|
||||||
"next": "16.2.9",
|
"next": "16.2.9",
|
||||||
@@ -1011,6 +1012,20 @@
|
|||||||
"url": "https://opencollective.com/libvips"
|
"url": "https://opencollective.com/libvips"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/@insignia/iios-contracts": {
|
||||||
|
"version": "0.1.0",
|
||||||
|
"resolved": "https://git.lynkedup.cloud/api/packages/insignia/npm/%40insignia%2Fiios-contracts/-/0.1.0/iios-contracts-0.1.0.tgz",
|
||||||
|
"integrity": "sha512-+ycbP8ORdwllMtn7dmxIL7lnDpDDkV+gHqT2OKJtMplMivjKU03gsuuEveQxnrE1CMvZ3fcSljmfMs10Cw131g=="
|
||||||
|
},
|
||||||
|
"node_modules/@insignia/iios-kernel-client": {
|
||||||
|
"version": "0.1.4",
|
||||||
|
"resolved": "https://git.lynkedup.cloud/api/packages/insignia/npm/%40insignia%2Fiios-kernel-client/-/0.1.4/iios-kernel-client-0.1.4.tgz",
|
||||||
|
"integrity": "sha512-pYBHH21TvgOOm0kp3ogvZx/iEzXLwmU23jHpDzIolh5FrqxCrcpUjRwLDkeYRTTkRVdoJAPTmPES/pU66iNoiA==",
|
||||||
|
"dependencies": {
|
||||||
|
"@insignia/iios-contracts": "0.1.0",
|
||||||
|
"socket.io-client": "^4.8.1"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/@jridgewell/gen-mapping": {
|
"node_modules/@jridgewell/gen-mapping": {
|
||||||
"version": "0.3.13",
|
"version": "0.3.13",
|
||||||
"resolved": "https://registry.npmjs.org/@jridgewell/gen-mapping/-/gen-mapping-0.3.13.tgz",
|
"resolved": "https://registry.npmjs.org/@jridgewell/gen-mapping/-/gen-mapping-0.3.13.tgz",
|
||||||
@@ -1279,6 +1294,12 @@
|
|||||||
"dev": true,
|
"dev": true,
|
||||||
"license": "MIT"
|
"license": "MIT"
|
||||||
},
|
},
|
||||||
|
"node_modules/@socket.io/component-emitter": {
|
||||||
|
"version": "3.1.2",
|
||||||
|
"resolved": "https://registry.npmjs.org/@socket.io/component-emitter/-/component-emitter-3.1.2.tgz",
|
||||||
|
"integrity": "sha512-9BCxFwvbGg/RsZK9tjXd8s4UcwR0MWeFQ1XEKIQVVvAGJyINdrqKMcTRyLoK8Rse1GjzLV9cwjWV1olXRWEXVA==",
|
||||||
|
"license": "MIT"
|
||||||
|
},
|
||||||
"node_modules/@supabase/auth-js": {
|
"node_modules/@supabase/auth-js": {
|
||||||
"version": "2.110.2",
|
"version": "2.110.2",
|
||||||
"resolved": "https://registry.npmjs.org/@supabase/auth-js/-/auth-js-2.110.2.tgz",
|
"resolved": "https://registry.npmjs.org/@supabase/auth-js/-/auth-js-2.110.2.tgz",
|
||||||
@@ -3051,7 +3072,6 @@
|
|||||||
"version": "4.4.3",
|
"version": "4.4.3",
|
||||||
"resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz",
|
"resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz",
|
||||||
"integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==",
|
"integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==",
|
||||||
"dev": true,
|
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"ms": "^2.1.3"
|
"ms": "^2.1.3"
|
||||||
@@ -3205,6 +3225,28 @@
|
|||||||
"node": ">= 0.8"
|
"node": ">= 0.8"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/engine.io-client": {
|
||||||
|
"version": "6.6.6",
|
||||||
|
"resolved": "https://registry.npmjs.org/engine.io-client/-/engine.io-client-6.6.6.tgz",
|
||||||
|
"integrity": "sha512-iY6QdftLQ9pyiPoX082bpf/u1UewnOaJrtJIF9T0++QB34lZrj0uP+Q/bj8AlUsAxqhnkTV2BS8SBZSxOmoV5Q==",
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"@socket.io/component-emitter": "~3.1.0",
|
||||||
|
"debug": "~4.4.1",
|
||||||
|
"engine.io-parser": "~5.2.1",
|
||||||
|
"ws": "~8.21.0",
|
||||||
|
"xmlhttprequest-ssl": "~2.1.1"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/engine.io-parser": {
|
||||||
|
"version": "5.2.3",
|
||||||
|
"resolved": "https://registry.npmjs.org/engine.io-parser/-/engine.io-parser-5.2.3.tgz",
|
||||||
|
"integrity": "sha512-HqD3yTBfnBxIrbnM1DoD6Pcq8NECnh8d4As1Qgh0z5Gg3jRRIqijury0CL3ghu/edArpUYiYqQiDUQBIs4np3Q==",
|
||||||
|
"license": "MIT",
|
||||||
|
"engines": {
|
||||||
|
"node": ">=10.0.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/enhanced-resolve": {
|
"node_modules/enhanced-resolve": {
|
||||||
"version": "5.21.6",
|
"version": "5.21.6",
|
||||||
"resolved": "https://registry.npmjs.org/enhanced-resolve/-/enhanced-resolve-5.21.6.tgz",
|
"resolved": "https://registry.npmjs.org/enhanced-resolve/-/enhanced-resolve-5.21.6.tgz",
|
||||||
@@ -6688,6 +6730,34 @@
|
|||||||
"url": "https://github.com/sponsors/ljharb"
|
"url": "https://github.com/sponsors/ljharb"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/socket.io-client": {
|
||||||
|
"version": "4.8.3",
|
||||||
|
"resolved": "https://registry.npmjs.org/socket.io-client/-/socket.io-client-4.8.3.tgz",
|
||||||
|
"integrity": "sha512-uP0bpjWrjQmUt5DTHq9RuoCBdFJF10cdX9X+a368j/Ft0wmaVgxlrjvK3kjvgCODOMMOz9lcaRzxmso0bTWZ/g==",
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"@socket.io/component-emitter": "~3.1.0",
|
||||||
|
"debug": "~4.4.1",
|
||||||
|
"engine.io-client": "~6.6.1",
|
||||||
|
"socket.io-parser": "~4.2.4"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">=10.0.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/socket.io-parser": {
|
||||||
|
"version": "4.2.6",
|
||||||
|
"resolved": "https://registry.npmjs.org/socket.io-parser/-/socket.io-parser-4.2.6.tgz",
|
||||||
|
"integrity": "sha512-asJqbVBDsBCJx0pTqw3WfesSY0iRX+2xzWEWzrpcH7L6fLzrhyF8WPI8UaeM4YCuDfpwA/cgsdugMsmtz8EJeg==",
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"@socket.io/component-emitter": "~3.1.0",
|
||||||
|
"debug": "~4.4.1"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">=10.0.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/source-map-js": {
|
"node_modules/source-map-js": {
|
||||||
"version": "1.2.1",
|
"version": "1.2.1",
|
||||||
"resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.1.tgz",
|
"resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.1.tgz",
|
||||||
@@ -7448,6 +7518,35 @@
|
|||||||
"node": ">=0.10.0"
|
"node": ">=0.10.0"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/ws": {
|
||||||
|
"version": "8.21.1",
|
||||||
|
"resolved": "https://registry.npmjs.org/ws/-/ws-8.21.1.tgz",
|
||||||
|
"integrity": "sha512-+0NTnW77fFN/DjQi6k/Sq/Yvk4Sgajw7urW8V+asjXnRgDs9gyGkdb7EzgfhA4goXsRIZKE28fzIXBHEzhuiWw==",
|
||||||
|
"license": "MIT",
|
||||||
|
"engines": {
|
||||||
|
"node": ">=10.0.0"
|
||||||
|
},
|
||||||
|
"peerDependencies": {
|
||||||
|
"bufferutil": "^4.0.1",
|
||||||
|
"utf-8-validate": ">=5.0.2"
|
||||||
|
},
|
||||||
|
"peerDependenciesMeta": {
|
||||||
|
"bufferutil": {
|
||||||
|
"optional": true
|
||||||
|
},
|
||||||
|
"utf-8-validate": {
|
||||||
|
"optional": true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/xmlhttprequest-ssl": {
|
||||||
|
"version": "2.1.2",
|
||||||
|
"resolved": "https://registry.npmjs.org/xmlhttprequest-ssl/-/xmlhttprequest-ssl-2.1.2.tgz",
|
||||||
|
"integrity": "sha512-TEU+nJVUUnA4CYJFLvK5X9AOeH4KvDvhIfm0vV1GaQRtchnG0hgK5p8hw/xjv8cunWYCsiPCSDzObPyhEwq3KQ==",
|
||||||
|
"engines": {
|
||||||
|
"node": ">=0.4.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/yallist": {
|
"node_modules/yallist": {
|
||||||
"version": "3.1.1",
|
"version": "3.1.1",
|
||||||
"resolved": "https://registry.npmjs.org/yallist/-/yallist-3.1.1.tgz",
|
"resolved": "https://registry.npmjs.org/yallist/-/yallist-3.1.1.tgz",
|
||||||
|
|||||||
@@ -10,6 +10,7 @@
|
|||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@abe-kap/appshell-sdk": "^0.2.6",
|
"@abe-kap/appshell-sdk": "^0.2.6",
|
||||||
|
"@insignia/iios-kernel-client": "^0.1.4",
|
||||||
"clsx": "^2.1.1",
|
"clsx": "^2.1.1",
|
||||||
"lucide-react": "^1.21.0",
|
"lucide-react": "^1.21.0",
|
||||||
"next": "16.2.9",
|
"next": "16.2.9",
|
||||||
|
|||||||
@@ -1,74 +0,0 @@
|
|||||||
import { NextResponse } from "next/server";
|
|
||||||
import { buildInviteEmail } from "@/lib/invite-email";
|
|
||||||
|
|
||||||
// Sends a team-invitation email via the Twilio Emails API. Server-only: the Twilio
|
|
||||||
// Account SID + Auth Token come from Vercel env (TWILIO_ACCOUNT_SID / TWILIO_AUTH_TOKEN)
|
|
||||||
// and never reach the browser. From EMAIL_FROM_ADDRESS (default support@lynkedup.dev).
|
|
||||||
//
|
|
||||||
// POST /api/email/invite { to, token, roleNames?[] } → { ok }
|
|
||||||
// The email body is a fixed invite template (only `to` + `token` + role names are
|
|
||||||
// caller-supplied), so this can't be used to send arbitrary content.
|
|
||||||
|
|
||||||
export const runtime = "nodejs";
|
|
||||||
|
|
||||||
const TWILIO_EMAILS_URL = "https://comms.twilio.com/v1/Emails";
|
|
||||||
const EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
|
|
||||||
const SESSION_COOKIE = "__Host-insignia_session";
|
|
||||||
|
|
||||||
export async function POST(request: Request) {
|
|
||||||
// Light guard: only a signed-in session (which the invite UI has) may trigger sends,
|
|
||||||
// so this isn't an open email relay. Presence check — the cookie is HttpOnly + __Host-.
|
|
||||||
const cookies = request.headers.get("cookie") ?? "";
|
|
||||||
if (!cookies.includes(`${SESSION_COOKIE}=`)) {
|
|
||||||
return NextResponse.json({ ok: false, error: "unauthorized" }, { status: 401 });
|
|
||||||
}
|
|
||||||
|
|
||||||
const sid = process.env.TWILIO_ACCOUNT_SID ?? "";
|
|
||||||
const authToken = process.env.TWILIO_AUTH_TOKEN ?? "";
|
|
||||||
const from = process.env.EMAIL_FROM_ADDRESS ?? "support@lynkedup.dev";
|
|
||||||
const fromName = process.env.EMAIL_FROM_NAME ?? "LynkedUp Pro";
|
|
||||||
if (!sid || !authToken) {
|
|
||||||
return NextResponse.json({ ok: false, error: "email_not_configured" }, { status: 503 });
|
|
||||||
}
|
|
||||||
|
|
||||||
let body: { to?: string; token?: string; roleNames?: string[] };
|
|
||||||
try {
|
|
||||||
body = await request.json();
|
|
||||||
} catch {
|
|
||||||
return NextResponse.json({ ok: false, error: "invalid_json" }, { status: 400 });
|
|
||||||
}
|
|
||||||
|
|
||||||
const to = (body.to ?? "").trim().toLowerCase();
|
|
||||||
const token = (body.token ?? "").trim();
|
|
||||||
const roleNames = Array.isArray(body.roleNames) ? body.roleNames.filter((r) => typeof r === "string").slice(0, 10) : [];
|
|
||||||
if (!EMAIL_RE.test(to)) return NextResponse.json({ ok: false, error: "invalid_email" }, { status: 400 });
|
|
||||||
if (token.length < 16 || token.length > 256) return NextResponse.json({ ok: false, error: "invalid_token" }, { status: 400 });
|
|
||||||
|
|
||||||
const origin = (process.env.PORTAL_BASE_URL || new URL(request.url).origin).replace(/\/$/, "");
|
|
||||||
const inviteUrl = `${origin}/portal/invite?token=${encodeURIComponent(token)}`;
|
|
||||||
const { subject, html, text } = buildInviteEmail({ inviteUrl, roleNames });
|
|
||||||
|
|
||||||
const payload = {
|
|
||||||
from: { address: from, name: fromName },
|
|
||||||
to: [{ address: to }],
|
|
||||||
content: { subject, html, text },
|
|
||||||
};
|
|
||||||
|
|
||||||
try {
|
|
||||||
const res = await fetch(TWILIO_EMAILS_URL, {
|
|
||||||
method: "POST",
|
|
||||||
headers: {
|
|
||||||
"Content-Type": "application/json",
|
|
||||||
Authorization: `Basic ${Buffer.from(`${sid}:${authToken}`).toString("base64")}`,
|
|
||||||
},
|
|
||||||
body: JSON.stringify(payload),
|
|
||||||
});
|
|
||||||
if (!res.ok) {
|
|
||||||
const detail = await res.text().catch(() => "");
|
|
||||||
return NextResponse.json({ ok: false, error: "send_failed", status: res.status, detail: detail.slice(0, 300) }, { status: 502 });
|
|
||||||
}
|
|
||||||
return NextResponse.json({ ok: true });
|
|
||||||
} catch (e) {
|
|
||||||
return NextResponse.json({ ok: false, error: "send_error", detail: (e as Error).message }, { status: 502 });
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -15,6 +15,8 @@ import { Support } from "./support";
|
|||||||
import { Rules } from "./rules";
|
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 { Inbox } from "./inbox";
|
||||||
import "../../app/dashboard/dashboard.css";
|
import "../../app/dashboard/dashboard.css";
|
||||||
|
|
||||||
export function Dashboard() {
|
export function Dashboard() {
|
||||||
@@ -45,6 +47,8 @@ export function Dashboard() {
|
|||||||
: active === "support" ? <Support />
|
: active === "support" ? <Support />
|
||||||
: active === "rules" ? <Rules />
|
: active === "rules" ? <Rules />
|
||||||
: active === "ai" ? <AiAssistant />
|
: active === "ai" ? <AiAssistant />
|
||||||
|
: active === "messenger" ? <Messenger />
|
||||||
|
: 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} />}
|
||||||
</ToastProvider>
|
</ToastProvider>
|
||||||
|
|||||||
@@ -0,0 +1,85 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
// ============================================================
|
||||||
|
// Inbox — a personalized work/awareness feed IIOS projects from
|
||||||
|
// events (mentions, needs-reply, support updates, …), surfaced via
|
||||||
|
// the be-crm data door (crm.inbox.*). List + filter by state, and
|
||||||
|
// mark items done / snoozed / archived. Items are created by IIOS's
|
||||||
|
// projector, never here. Mock when the Shell isn't configured.
|
||||||
|
// ============================================================
|
||||||
|
|
||||||
|
import { useState } from "react";
|
||||||
|
import { Btn, Icon, PageHead, Pill } from "./ui";
|
||||||
|
import { useInboxData, type InboxState, type UiInboxItem } from "@/lib/inbox-api";
|
||||||
|
|
||||||
|
const KIND_LABEL: Record<string, string> = {
|
||||||
|
MENTION: "Mention", NEEDS_REPLY: "Needs reply", NEEDS_REVIEW: "Needs review", NEEDS_APPROVAL: "Needs approval",
|
||||||
|
SUPPORT_UPDATE: "Support", MEETING_FOLLOWUP: "Meeting", DIGEST: "Digest", SYSTEM_ALERT: "Alert", CRM_OWNER_INTEREST: "Owner",
|
||||||
|
};
|
||||||
|
const FILTERS: { value: InboxState; label: string }[] = [
|
||||||
|
{ value: "OPEN", label: "Open" }, { value: "SNOOZED", label: "Snoozed" }, { value: "DONE", label: "Done" }, { value: "ARCHIVED", label: "Archived" },
|
||||||
|
];
|
||||||
|
|
||||||
|
export function Inbox() {
|
||||||
|
const [filter, setFilter] = useState<InboxState>("OPEN");
|
||||||
|
const inbox = useInboxData(filter);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="view">
|
||||||
|
<PageHead eyebrow="Communication" title="Inbox" subtitle="Mentions, replies and updates that need your attention" icon="bell" />
|
||||||
|
{!inbox.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 style={{ display: "flex", gap: 6, marginBottom: 14, flexWrap: "wrap" }}>
|
||||||
|
{FILTERS.map((f) => (
|
||||||
|
<Btn key={f.value} variant={filter === f.value ? "primary" : "outline"} onClick={() => setFilter(f.value)}>{f.label}</Btn>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="card" style={{ padding: 0, overflow: "hidden" }}>
|
||||||
|
{inbox.loading && <div style={{ padding: 20, color: "var(--muted)" }}>Loading…</div>}
|
||||||
|
{!inbox.loading && inbox.items.length === 0 && (
|
||||||
|
<div style={{ padding: 28, color: "var(--muted)", textAlign: "center" }}>Nothing here — you're all caught up 🎉</div>
|
||||||
|
)}
|
||||||
|
{inbox.items.map((it) => (
|
||||||
|
<InboxRow
|
||||||
|
key={it.id} it={it}
|
||||||
|
onDone={() => inbox.transition(it.id, "DONE")}
|
||||||
|
onSnooze={() => inbox.transition(it.id, "SNOOZED")}
|
||||||
|
onArchive={() => inbox.transition(it.id, "ARCHIVED")}
|
||||||
|
/>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function InboxRow({ it, onDone, onSnooze, onArchive }: { it: UiInboxItem; onDone: () => void; onSnooze: () => void; onArchive: () => void }) {
|
||||||
|
const isMention = it.kind === "MENTION";
|
||||||
|
return (
|
||||||
|
<div style={{ display: "flex", gap: 12, alignItems: "flex-start", padding: "14px 18px", borderBottom: "1px solid var(--border)" }}>
|
||||||
|
<span style={{ marginTop: 2, color: isMention ? "var(--orange)" : "var(--text-2)" }}>
|
||||||
|
<Icon name={isMention ? "chat" : "bell"} size={18} />
|
||||||
|
</span>
|
||||||
|
<div style={{ flex: 1, minWidth: 0 }}>
|
||||||
|
<div style={{ display: "flex", gap: 8, alignItems: "center", flexWrap: "wrap" }}>
|
||||||
|
<Pill tone={isMention ? "warn" : "muted"}>{KIND_LABEL[it.kind] ?? it.kind}</Pill>
|
||||||
|
<span style={{ fontWeight: 600 }}>{it.title}</span>
|
||||||
|
</div>
|
||||||
|
{it.summary && <div style={{ color: "var(--muted)", fontSize: 13, marginTop: 3 }}>{it.summary}</div>}
|
||||||
|
</div>
|
||||||
|
{it.state === "OPEN" ? (
|
||||||
|
<div style={{ display: "flex", gap: 6, flexShrink: 0 }}>
|
||||||
|
<Btn variant="ghost" icon="clock" onClick={onSnooze}>Snooze</Btn>
|
||||||
|
<Btn variant="outline" icon="check" onClick={onDone}>Done</Btn>
|
||||||
|
<Btn variant="ghost" icon="x" onClick={onArchive}>Archive</Btn>
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<Pill tone="muted">{it.state.toLowerCase()}</Pill>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,352 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
// ============================================================
|
||||||
|
// Messenger — internal team + client chat, powered by IIOS via
|
||||||
|
// the be-crm data door (crm.messenger.*). Conversation list ⇄
|
||||||
|
// thread view + composer, with a "new chat" people picker that
|
||||||
|
// creates a DM (1 person) or group (2+). DM-vs-group and who-can-
|
||||||
|
// chat are enforced server-side by IIOS/OPA; this is just UI.
|
||||||
|
// Live messages, typing, read receipts and reactions come over the
|
||||||
|
// IIOS socket (Shell mode); mock keeps the demo working offline.
|
||||||
|
// ============================================================
|
||||||
|
|
||||||
|
import { type CSSProperties, useEffect, useMemo, useRef, useState } from "react";
|
||||||
|
import { Avatar, Btn, Field, Icon, Modal, PageHead, Pill, useToast } from "./ui";
|
||||||
|
import { useMessengerData, useThread, type Membership, type UiConversation, type UiMessage, type UiPerson } from "@/lib/messenger-api";
|
||||||
|
import { MessengerSocketProvider, useMessengerSocket } from "@/lib/messenger-socket";
|
||||||
|
|
||||||
|
const initialsOf = (name: string) =>
|
||||||
|
name.split(/\s+/).filter(Boolean).slice(0, 2).map((p) => p[0]).join("").toUpperCase() || "?";
|
||||||
|
const timeOf = (iso?: string) => {
|
||||||
|
if (!iso) return "";
|
||||||
|
const d = new Date(iso);
|
||||||
|
return Number.isNaN(+d) ? "" : d.toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" });
|
||||||
|
};
|
||||||
|
const GROUP_GRAD = "linear-gradient(135deg,#6366f1,#8b5cf6)";
|
||||||
|
const CUSTOMER_GRAD = "linear-gradient(135deg,#10b981,#059669)";
|
||||||
|
const REACTION_EMOJIS = ["👍", "❤️", "😂", "😮", "😢", "🎉"];
|
||||||
|
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 Messenger() {
|
||||||
|
// One shared IIOS socket for the whole panel (live in Shell mode; no-op in mock).
|
||||||
|
return (
|
||||||
|
<MessengerSocketProvider>
|
||||||
|
<MessengerPanel />
|
||||||
|
</MessengerSocketProvider>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function MessengerPanel() {
|
||||||
|
const m = useMessengerData();
|
||||||
|
const toast = useToast();
|
||||||
|
const [selected, setSelected] = useState<string | null>(null);
|
||||||
|
const [newOpen, setNewOpen] = useState(false);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if ((!selected || !m.conversations.some((c) => c.threadId === selected)) && m.conversations[0]) {
|
||||||
|
setSelected(m.conversations[0].threadId);
|
||||||
|
}
|
||||||
|
}, [m.conversations, selected]);
|
||||||
|
|
||||||
|
const current = m.conversations.find((c) => c.threadId === selected) ?? null;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="view">
|
||||||
|
<PageHead
|
||||||
|
eyebrow="Communication" title="Messenger" subtitle="Chat with your team and clients — direct or in groups" icon="send"
|
||||||
|
actions={<Btn icon="plus" onClick={() => setNewOpen(true)}>New chat</Btn>}
|
||||||
|
/>
|
||||||
|
{!m.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: 620, padding: 0, overflow: "hidden" }}>
|
||||||
|
<aside style={{ width: 296, borderRight: "1px solid var(--border)", overflowY: "auto", background: "var(--panel)" }}>
|
||||||
|
{m.loading && <div style={{ padding: 16, color: "var(--muted)" }}>Loading…</div>}
|
||||||
|
{!m.loading && m.conversations.length === 0 && (
|
||||||
|
<div style={{ padding: 16, color: "var(--muted)" }}>No conversations yet. Start a new chat.</div>
|
||||||
|
)}
|
||||||
|
{m.conversations.map((c) => (
|
||||||
|
<ConversationRow key={c.threadId} c={c} active={c.threadId === selected} onClick={() => setSelected(c.threadId)} />
|
||||||
|
))}
|
||||||
|
</aside>
|
||||||
|
|
||||||
|
<section style={{ flex: 1, display: "flex", flexDirection: "column", minWidth: 0 }}>
|
||||||
|
{current ? (
|
||||||
|
<ThreadView key={current.threadId} conv={current} nameOf={m.nameOf} onError={(msg) => toast.push({ tone: "error", title: "Message failed", desc: msg })} />
|
||||||
|
) : (
|
||||||
|
<div style={{ margin: "auto", color: "var(--muted)", textAlign: "center" }}>
|
||||||
|
<Icon name="send" size={38} />
|
||||||
|
<p>Select or start a conversation</p>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</section>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<NewChatModal
|
||||||
|
open={newOpen} onClose={() => setNewOpen(false)} directory={m.directory}
|
||||||
|
onCreate={async (ids, opts) => {
|
||||||
|
try {
|
||||||
|
const id = await m.openConversation(ids, opts);
|
||||||
|
setSelected(id);
|
||||||
|
setNewOpen(false);
|
||||||
|
} catch (e) {
|
||||||
|
toast.push({ tone: "error", title: "Couldn't start chat", desc: (e as Error).message });
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function ConversationRow({ c, active, onClick }: { c: UiConversation; active: boolean; onClick: () => void }) {
|
||||||
|
return (
|
||||||
|
<button
|
||||||
|
onClick={onClick}
|
||||||
|
style={{
|
||||||
|
display: "flex", gap: 10, alignItems: "center", width: "100%", textAlign: "left",
|
||||||
|
padding: "10px 14px", border: "none", borderBottom: "1px solid var(--border)", cursor: "pointer",
|
||||||
|
background: active ? "var(--panel-2)" : "transparent", color: "var(--text)",
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<Avatar initials={initialsOf(c.title)} size={38} gradient={c.membership === "group" ? GROUP_GRAD : undefined} />
|
||||||
|
<div style={{ flex: 1, minWidth: 0 }}>
|
||||||
|
<div style={{ display: "flex", justifyContent: "space-between", gap: 8, alignItems: "center" }}>
|
||||||
|
<span style={{ fontWeight: 600, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{c.title}</span>
|
||||||
|
<span style={{ color: "var(--muted)", fontSize: 11, flexShrink: 0 }}>{timeOf(c.lastAt)}</span>
|
||||||
|
</div>
|
||||||
|
<div style={{ display: "flex", justifyContent: "space-between", gap: 8, alignItems: "center" }}>
|
||||||
|
<span style={{ color: "var(--muted)", fontSize: 12.5, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>
|
||||||
|
{c.lastMessage ?? "No messages yet"}
|
||||||
|
</span>
|
||||||
|
{c.unread > 0 && (
|
||||||
|
<span style={{ background: "var(--orange)", color: "#fff", borderRadius: 999, fontSize: 11, padding: "1px 7px", flexShrink: 0 }}>{c.unread}</span>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</button>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function ThreadView({ conv, nameOf, onError }: { conv: UiConversation; nameOf: (id: string) => string; onError: (m: string) => void }) {
|
||||||
|
const t = useThread(conv.threadId);
|
||||||
|
const socket = useMessengerSocket();
|
||||||
|
const [draft, setDraft] = useState("");
|
||||||
|
const [sending, setSending] = useState(false);
|
||||||
|
const [replyTo, setReplyTo] = useState<UiMessage | null>(null);
|
||||||
|
const endRef = useRef<HTMLDivElement>(null);
|
||||||
|
const typingSentAt = useRef(0);
|
||||||
|
|
||||||
|
useEffect(() => { endRef.current?.scrollIntoView({ behavior: "smooth" }); }, [t.messages.length]);
|
||||||
|
|
||||||
|
const byId = useMemo(() => Object.fromEntries(t.messages.map((m) => [m.id, m])), [t.messages]);
|
||||||
|
const lastMineId = useMemo(() => [...t.messages].reverse().find((m) => m.mine)?.id ?? null, [t.messages]);
|
||||||
|
|
||||||
|
function onDraftChange(v: string) {
|
||||||
|
setDraft(v);
|
||||||
|
const now = Date.now();
|
||||||
|
if (socket && now - typingSentAt.current > 2000) { socket.sendTyping(conv.threadId); typingSentAt.current = now; }
|
||||||
|
}
|
||||||
|
|
||||||
|
async function submit() {
|
||||||
|
const text = draft.trim();
|
||||||
|
if (!text || sending) return;
|
||||||
|
const parent = replyTo?.id;
|
||||||
|
setDraft(""); setReplyTo(null); setSending(true);
|
||||||
|
try { await t.send(text, parent ? { parentInteractionId: parent } : undefined); }
|
||||||
|
catch (e) { setDraft(text); onError((e as Error).message); }
|
||||||
|
finally { setSending(false); }
|
||||||
|
}
|
||||||
|
|
||||||
|
const typingLabel = t.typingUserIds.length === 1
|
||||||
|
? `${nameOf(t.typingUserIds[0])} is typing…`
|
||||||
|
: t.typingUserIds.length > 1 ? "Several people are typing…" : "";
|
||||||
|
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<header style={{ display: "flex", alignItems: "center", gap: 10, padding: "12px 18px", borderBottom: "1px solid var(--border)" }}>
|
||||||
|
<Avatar initials={initialsOf(conv.title)} size={34} gradient={conv.membership === "group" ? GROUP_GRAD : undefined} />
|
||||||
|
<div>
|
||||||
|
<div style={{ fontWeight: 600 }}>{conv.title}</div>
|
||||||
|
<div style={{ color: "var(--muted)", fontSize: 12 }}>
|
||||||
|
{conv.membership === "group" ? `${conv.participants.length} people` : "Direct message"}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</header>
|
||||||
|
|
||||||
|
<div style={{ flex: 1, overflowY: "auto", padding: 18, display: "flex", flexDirection: "column", gap: 10, background: "var(--bg)" }}>
|
||||||
|
{t.loading && t.messages.length === 0 && <div style={{ margin: "auto", color: "var(--muted)" }}>Loading messages…</div>}
|
||||||
|
{!t.loading && t.messages.length === 0 && <div style={{ margin: "auto", color: "var(--muted)" }}>No messages yet — say hello 👋</div>}
|
||||||
|
{t.messages.map((msg) => (
|
||||||
|
<MessageBubble
|
||||||
|
key={msg.id} msg={msg}
|
||||||
|
parent={msg.parentInteractionId ? byId[msg.parentInteractionId] : undefined}
|
||||||
|
seen={msg.id === lastMineId && t.seenIds.has(msg.id)}
|
||||||
|
showStatus={msg.id === lastMineId}
|
||||||
|
onReact={(emoji) => t.react(msg.id, emoji)}
|
||||||
|
onReply={() => setReplyTo(msg)}
|
||||||
|
/>
|
||||||
|
))}
|
||||||
|
<div ref={endRef} />
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div style={{ minHeight: 18, padding: "0 18px", color: "var(--muted)", fontSize: 12, fontStyle: "italic" }}>{typingLabel}</div>
|
||||||
|
|
||||||
|
{replyTo && (
|
||||||
|
<div style={{ display: "flex", alignItems: "center", gap: 10, margin: "0 14px", padding: "8px 12px", borderRadius: 10, background: "var(--panel-2)", borderLeft: "3px solid var(--orange)" }}>
|
||||||
|
<div style={{ flex: 1, minWidth: 0 }}>
|
||||||
|
<div style={{ fontSize: 11, color: "var(--orange)", fontWeight: 600 }}>Replying to {replyTo.mine ? "yourself" : nameOf(replyTo.senderId ?? "")}</div>
|
||||||
|
<div style={{ fontSize: 12.5, color: "var(--muted)", whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{replyTo.text}</div>
|
||||||
|
</div>
|
||||||
|
<button onClick={() => setReplyTo(null)} style={{ background: "none", border: "none", color: "var(--muted)", cursor: "pointer", fontSize: 16 }} aria-label="Cancel reply">×</button>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<footer style={{ display: "flex", gap: 8, padding: 14, borderTop: "1px solid var(--border)" }}>
|
||||||
|
<input
|
||||||
|
value={draft} onChange={(e) => onDraftChange(e.target.value)}
|
||||||
|
onKeyDown={(e) => { if (e.key === "Enter" && !e.shiftKey) { e.preventDefault(); void submit(); } }}
|
||||||
|
placeholder="Type a message…" style={inputStyle}
|
||||||
|
/>
|
||||||
|
<Btn icon="send" onClick={() => void submit()} disabled={sending || !draft.trim()}>Send</Btn>
|
||||||
|
</footer>
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function MessageBubble({
|
||||||
|
msg, parent, seen, showStatus, onReact, onReply,
|
||||||
|
}: {
|
||||||
|
msg: UiMessage; parent?: UiMessage; seen: boolean; showStatus: boolean;
|
||||||
|
onReact: (emoji: string) => void; onReply: () => void;
|
||||||
|
}) {
|
||||||
|
const [hover, setHover] = useState(false);
|
||||||
|
const [picker, setPicker] = useState(false);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
onMouseEnter={() => setHover(true)}
|
||||||
|
onMouseLeave={() => { setHover(false); setPicker(false); }}
|
||||||
|
style={{ alignSelf: msg.mine ? "flex-end" : "flex-start", maxWidth: "72%", display: "flex", flexDirection: "column", alignItems: msg.mine ? "flex-end" : "flex-start", position: "relative" }}
|
||||||
|
>
|
||||||
|
{parent && (
|
||||||
|
<div style={{ maxWidth: "100%", padding: "4px 10px", marginBottom: 3, borderRadius: 8, background: "var(--panel-2)", borderLeft: "3px solid var(--orange)", fontSize: 12, color: "var(--muted)", whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>
|
||||||
|
<span style={{ opacity: 0.8 }}>↩ {parent.text}</span>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<div style={{ display: "flex", alignItems: "center", gap: 6, flexDirection: msg.mine ? "row-reverse" : "row" }}>
|
||||||
|
<div style={{
|
||||||
|
background: msg.mine ? "var(--grad-brand)" : "var(--panel)", color: msg.mine ? "#fff" : "var(--text)",
|
||||||
|
padding: "8px 12px", borderRadius: 14,
|
||||||
|
borderBottomRightRadius: msg.mine ? 4 : 14, borderBottomLeftRadius: msg.mine ? 14 : 4,
|
||||||
|
border: msg.mine ? "none" : "1px solid var(--border)",
|
||||||
|
whiteSpace: "pre-wrap", wordBreak: "break-word", fontSize: 14,
|
||||||
|
}}>
|
||||||
|
{msg.text}
|
||||||
|
</div>
|
||||||
|
{hover && (
|
||||||
|
<div style={{ display: "flex", gap: 2, position: "relative" }}>
|
||||||
|
<button onClick={() => setPicker((p) => !p)} title="React" style={actionBtnStyle}>🙂</button>
|
||||||
|
<button onClick={onReply} title="Reply" style={actionBtnStyle}>↩</button>
|
||||||
|
{picker && (
|
||||||
|
<div style={{ position: "absolute", bottom: "100%", [msg.mine ? "right" : "left"]: 0, marginBottom: 4, display: "flex", gap: 2, padding: 4, borderRadius: 999, background: "var(--panel)", border: "1px solid var(--border)", boxShadow: "0 6px 20px rgba(0,0,0,0.35)", zIndex: 5 }}>
|
||||||
|
{REACTION_EMOJIS.map((e) => (
|
||||||
|
<button key={e} onClick={() => { onReact(e); setPicker(false); }} style={{ ...actionBtnStyle, fontSize: 16 }}>{e}</button>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{msg.reactions && msg.reactions.length > 0 && (
|
||||||
|
<div style={{ display: "flex", gap: 4, marginTop: 3, flexWrap: "wrap" }}>
|
||||||
|
{msg.reactions.map((r) => (
|
||||||
|
<button
|
||||||
|
key={r.emoji} onClick={() => onReact(r.emoji)}
|
||||||
|
style={{
|
||||||
|
display: "inline-flex", alignItems: "center", gap: 3, padding: "1px 7px", borderRadius: 999, fontSize: 12, cursor: "pointer",
|
||||||
|
background: r.mine ? "rgba(253,169,19,0.18)" : "var(--panel-2)",
|
||||||
|
border: `1px solid ${r.mine ? "var(--orange)" : "var(--border)"}`, color: "var(--text)",
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<span>{r.emoji}</span><span style={{ color: "var(--muted)" }}>{r.count}</span>
|
||||||
|
</button>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<div style={{ fontSize: 10.5, color: "var(--muted)", marginTop: 2 }}>
|
||||||
|
{timeOf(msg.at)}{showStatus && msg.mine ? ` · ${seen ? "Seen" : "Sent"}` : ""}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const actionBtnStyle: CSSProperties = {
|
||||||
|
background: "var(--panel-2)", border: "1px solid var(--border)", borderRadius: 8,
|
||||||
|
width: 26, height: 26, display: "grid", placeItems: "center", cursor: "pointer", fontSize: 13, color: "var(--text)", padding: 0,
|
||||||
|
};
|
||||||
|
|
||||||
|
function NewChatModal({
|
||||||
|
open, onClose, directory, onCreate,
|
||||||
|
}: {
|
||||||
|
open: boolean; onClose: () => void; directory: UiPerson[];
|
||||||
|
onCreate: (ids: string[], opts: { membership: Membership; subject?: string }) => Promise<void>;
|
||||||
|
}) {
|
||||||
|
const [picked, setPicked] = useState<string[]>([]);
|
||||||
|
const [subject, setSubject] = useState("");
|
||||||
|
const [q, setQ] = useState("");
|
||||||
|
const [busy, setBusy] = useState(false);
|
||||||
|
|
||||||
|
useEffect(() => { if (!open) { setPicked([]); setSubject(""); setQ(""); setBusy(false); } }, [open]);
|
||||||
|
|
||||||
|
const membership: Membership = picked.length > 1 ? "group" : "dm";
|
||||||
|
const filtered = directory.filter((p) => p.name.toLowerCase().includes(q.trim().toLowerCase()));
|
||||||
|
const toggle = (id: string) => setPicked((l) => (l.includes(id) ? l.filter((x) => x !== id) : [...l, id]));
|
||||||
|
|
||||||
|
async function create() {
|
||||||
|
if (!picked.length || busy) return;
|
||||||
|
setBusy(true);
|
||||||
|
await onCreate(picked, { membership, ...(membership === "group" && subject.trim() ? { subject: subject.trim() } : {}) });
|
||||||
|
setBusy(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Modal
|
||||||
|
open={open} onClose={onClose} title="New conversation"
|
||||||
|
subtitle={membership === "group" ? "Group chat" : "Direct message"} icon="send"
|
||||||
|
footer={<>
|
||||||
|
<Btn variant="ghost" onClick={onClose}>Cancel</Btn>
|
||||||
|
<Btn icon="send" onClick={() => void create()} disabled={!picked.length || busy}>{busy ? "Starting…" : "Start chat"}</Btn>
|
||||||
|
</>}
|
||||||
|
>
|
||||||
|
<input value={q} onChange={(e) => setQ(e.target.value)} placeholder="Search people…" style={{ ...inputStyle, marginBottom: 10 }} />
|
||||||
|
{membership === "group" && (
|
||||||
|
<Field label="Group name (optional)">
|
||||||
|
<input value={subject} onChange={(e) => setSubject(e.target.value)} placeholder="e.g. Storm response" style={inputStyle} />
|
||||||
|
</Field>
|
||||||
|
)}
|
||||||
|
<div style={{ maxHeight: 320, overflowY: "auto", marginTop: 8, display: "flex", flexDirection: "column", gap: 2 }}>
|
||||||
|
{filtered.length === 0 && <div style={{ color: "var(--muted)", padding: 10 }}>No people found.</div>}
|
||||||
|
{filtered.map((p) => (
|
||||||
|
<label key={p.id} style={{
|
||||||
|
display: "flex", alignItems: "center", gap: 10, padding: "8px 10px", borderRadius: 10, cursor: "pointer",
|
||||||
|
background: picked.includes(p.id) ? "var(--panel-2)" : "transparent",
|
||||||
|
}}>
|
||||||
|
<input type="checkbox" checked={picked.includes(p.id)} onChange={() => toggle(p.id)} />
|
||||||
|
<Avatar initials={initialsOf(p.name)} size={30} gradient={p.kind === "customer" ? CUSTOMER_GRAD : undefined} />
|
||||||
|
<span style={{ flex: 1 }}>{p.name}</span>
|
||||||
|
<Pill tone="muted">{p.kind}</Pill>
|
||||||
|
</label>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</Modal>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -29,6 +29,13 @@ export const NAV_GROUPS: NavGroup[] = [
|
|||||||
{ key: "pipeline", label: "Pipeline", icon: "pipeline" },
|
{ key: "pipeline", label: "Pipeline", icon: "pipeline" },
|
||||||
],
|
],
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
title: "Communication",
|
||||||
|
items: [
|
||||||
|
{ key: "messenger", label: "Messenger", icon: "send", subtitle: "Chat with your team and clients" },
|
||||||
|
{ key: "inbox", label: "Inbox", icon: "bell", subtitle: "Mentions, replies and updates for you" },
|
||||||
|
],
|
||||||
|
},
|
||||||
{
|
{
|
||||||
title: "Workspace",
|
title: "Workspace",
|
||||||
items: [
|
items: [
|
||||||
@@ -72,7 +79,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"]);
|
const ALWAYS_VISIBLE = new Set(["dashboard", "profile", "messenger", "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",
|
||||||
|
|||||||
@@ -47,20 +47,6 @@ export function TeamManagement() {
|
|||||||
}, [members]);
|
}, [members]);
|
||||||
const maxDeals = useMemo(() => Math.max(1, ...members.map((m) => m.deals)), [members]);
|
const maxDeals = useMemo(() => Math.max(1, ...members.map((m) => m.deals)), [members]);
|
||||||
|
|
||||||
// Email the invite link via the serverless route (Twilio). No token (mock mode) → skip.
|
|
||||||
const emailInvite = async (email: string, token: string | undefined, roleIds: string[]): Promise<boolean> => {
|
|
||||||
if (!token) return false;
|
|
||||||
const roleNames = roleIds.map((id) => roleById[id]?.name).filter((n): n is string => !!n);
|
|
||||||
try {
|
|
||||||
const res = await fetch("/api/email/invite", {
|
|
||||||
method: "POST",
|
|
||||||
headers: { "Content-Type": "application/json" },
|
|
||||||
body: JSON.stringify({ to: email, token, roleNames }),
|
|
||||||
});
|
|
||||||
return res.ok;
|
|
||||||
} catch { return false; }
|
|
||||||
};
|
|
||||||
|
|
||||||
const filtered = useMemo(() => {
|
const filtered = useMemo(() => {
|
||||||
const q = query.trim().toLowerCase();
|
const q = query.trim().toLowerCase();
|
||||||
return members.filter((m) => {
|
return members.filter((m) => {
|
||||||
@@ -323,11 +309,8 @@ export function TeamManagement() {
|
|||||||
}}>Copy link</Btn>
|
}}>Copy link</Btn>
|
||||||
)}
|
)}
|
||||||
<Btn variant="soft" size="sm" icon="refresh" onClick={async () => {
|
<Btn variant="soft" size="sm" icon="refresh" onClick={async () => {
|
||||||
try {
|
try { await team.resendInvite(inv.id); toast.push({ tone: "success", title: "Invite resent", desc: `A fresh link was emailed to ${inv.email}.` }); }
|
||||||
const { token } = await team.resendInvite(inv.id);
|
catch (e) { toast.push({ tone: "error", title: "Couldn't resend", desc: (e as Error).message }); }
|
||||||
const emailed = await emailInvite(inv.email, token, inv.roleIds);
|
|
||||||
toast.push({ tone: "success", title: emailed ? "Invite re-emailed" : "Invite resent", desc: emailed ? `A fresh link was emailed to ${inv.email}.` : `A fresh link was generated for ${inv.email}.` });
|
|
||||||
} catch (e) { toast.push({ tone: "error", title: "Couldn't resend", desc: (e as Error).message }); }
|
|
||||||
}}>Resend</Btn>
|
}}>Resend</Btn>
|
||||||
<Btn variant="ghost" size="sm" icon="x" onClick={async () => {
|
<Btn variant="ghost" size="sm" icon="x" onClick={async () => {
|
||||||
try { await team.revokeInvite(inv.id); toast.push({ tone: "info", title: "Invite revoked" }); }
|
try { await team.revokeInvite(inv.id); toast.push({ tone: "info", title: "Invite revoked" }); }
|
||||||
@@ -348,14 +331,9 @@ export function TeamManagement() {
|
|||||||
onInvite={async (email, roleIds) => {
|
onInvite={async (email, roleIds) => {
|
||||||
setInviteOpen(false);
|
setInviteOpen(false);
|
||||||
try {
|
try {
|
||||||
const { token } = await team.invite(email, roleIds);
|
await team.invite(email, roleIds);
|
||||||
setTab("invites");
|
setTab("invites");
|
||||||
const emailed = await emailInvite(email, token, roleIds);
|
toast.push({ tone: "success", title: "Invitation sent", desc: `We emailed an invite to ${email}. You can also copy the link.` });
|
||||||
toast.push({
|
|
||||||
tone: "success",
|
|
||||||
title: emailed ? "Invitation emailed" : "Invitation created",
|
|
||||||
desc: emailed ? `We emailed the invite to ${email}.` : `Invite ready — use “Copy link” to share it with ${email}.`,
|
|
||||||
});
|
|
||||||
} catch (e) { toast.push({ tone: "error", title: "Couldn't send invite", desc: (e as Error).message }); }
|
} catch (e) { toast.push({ tone: "error", title: "Couldn't send invite", desc: (e as Error).message }); }
|
||||||
}}
|
}}
|
||||||
/>
|
/>
|
||||||
|
|||||||
@@ -454,7 +454,14 @@ function OtpVerify({ account, email, initialChannel = "email", remember, setReme
|
|||||||
if (!PHONE_RE.test(phone)) { setError("Enter your phone in international format, e.g. +14155550100."); return; }
|
if (!PHONE_RE.test(phone)) { setError("Enter your phone in international format, e.g. +14155550100."); return; }
|
||||||
await sendPhoneOtp(phone); setSent(true);
|
await sendPhoneOtp(phone); setSent(true);
|
||||||
}
|
}
|
||||||
} catch (e) { setError((e as Error).message); }
|
} catch (e) {
|
||||||
|
// gotrue can throw an error whose message is an unhelpful "{}"/JSON blob (e.g. a
|
||||||
|
// 500 "Error sending magic link email" when SMTP isn't set up). Show something
|
||||||
|
// readable and actionable instead of the raw payload.
|
||||||
|
const raw = (e as { message?: unknown })?.message;
|
||||||
|
const readable = typeof raw === "string" && raw.trim() && !raw.trim().startsWith("{") ? raw.trim() : "";
|
||||||
|
setError(readable || "We couldn't send your sign-in code right now. Please try again shortly, or sign in with your password.");
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async function complete(code: string) {
|
async function complete(code: string) {
|
||||||
|
|||||||
@@ -0,0 +1,57 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
// Inbox data layer. The inbox is a personalized work/awareness feed IIOS projects from events
|
||||||
|
// (NEEDS_REPLY, MENTION, …). The CRM lists it and transitions item state; items are never created
|
||||||
|
// here. Mock when the Shell isn't configured; live via the be-crm data door (crm.inbox.*) otherwise.
|
||||||
|
//
|
||||||
|
// Live contract (be-crm):
|
||||||
|
// query crm.inbox.list { state? } -> InboxItem[]
|
||||||
|
// cmd crm.inbox.transition { id, state, reason? } -> InboxItem
|
||||||
|
|
||||||
|
import { useCallback, useMemo, useState } from "react";
|
||||||
|
import { useAppShell, useQuery } from "@abe-kap/appshell-sdk/react";
|
||||||
|
import { isShellConfigured } from "./appshell";
|
||||||
|
|
||||||
|
export type InboxState = "OPEN" | "SNOOZED" | "DONE" | "ARCHIVED" | "CANCELLED" | "STALE";
|
||||||
|
export interface UiInboxItem {
|
||||||
|
id: string; kind: string; state: InboxState; title: string; summary?: string;
|
||||||
|
priority: string; threadId?: string; createdAt: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
const SHELL = isShellConfigured();
|
||||||
|
|
||||||
|
export interface InboxData {
|
||||||
|
live: boolean; loading: boolean; error: string | null;
|
||||||
|
items: UiInboxItem[];
|
||||||
|
transition: (id: string, state: InboxState) => Promise<void>;
|
||||||
|
refetch: () => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function useInboxData(state?: InboxState): InboxData {
|
||||||
|
return SHELL ? useLiveInbox(state) : useMockInbox(state);
|
||||||
|
}
|
||||||
|
|
||||||
|
function useLiveInbox(state?: InboxState): InboxData {
|
||||||
|
const { sdk } = useAppShell();
|
||||||
|
const q = useQuery<UiInboxItem[]>("crm.inbox.list", state ? { state } : {});
|
||||||
|
const transition = useCallback(async (id: string, next: InboxState) => {
|
||||||
|
await sdk.command("crm.inbox.transition", { id, state: next });
|
||||||
|
q.refetch();
|
||||||
|
}, [sdk, q]);
|
||||||
|
return { live: true, loading: q.loading, error: q.error?.message ?? null, items: q.data ?? [], transition, refetch: q.refetch };
|
||||||
|
}
|
||||||
|
|
||||||
|
const MOCK_ITEMS: UiInboxItem[] = [
|
||||||
|
{ id: "in_1", kind: "MENTION", state: "OPEN", title: "Sofia mentioned you", summary: "@you — can you confirm the Henderson scope?", priority: "HIGH", threadId: "th_mock_1", createdAt: new Date().toISOString() },
|
||||||
|
{ id: "in_2", kind: "NEEDS_REPLY", state: "OPEN", title: "Reply needed — Storm response", summary: "Dan: Crew is rolling out at 7.", priority: "MEDIUM", threadId: "th_mock_2", createdAt: new Date().toISOString() },
|
||||||
|
{ id: "in_3", kind: "SUPPORT_UPDATE", state: "OPEN", title: "Ticket TK-204 updated", summary: "Customer replied on the roof-leak case.", priority: "LOW", createdAt: new Date().toISOString() },
|
||||||
|
];
|
||||||
|
|
||||||
|
function useMockInbox(state?: InboxState): InboxData {
|
||||||
|
const [items, setItems] = useState<UiInboxItem[]>(MOCK_ITEMS);
|
||||||
|
const filtered = useMemo(() => (state ? items.filter((i) => i.state === state) : items), [items, state]);
|
||||||
|
const transition = useCallback(async (id: string, next: InboxState) => {
|
||||||
|
setItems((l) => l.map((i) => (i.id === id ? { ...i, state: next } : i)));
|
||||||
|
}, []);
|
||||||
|
return { live: false, loading: false, error: null, items: filtered, transition, refetch: () => {} };
|
||||||
|
}
|
||||||
@@ -1,59 +0,0 @@
|
|||||||
// Invitation email content (subject/html/text). Server-only helper — no secrets here.
|
|
||||||
// The accept URL points at the frontend's /portal/invite?token=… route.
|
|
||||||
|
|
||||||
export interface InviteEmailInput {
|
|
||||||
inviteUrl: string;
|
|
||||||
roleNames: string[];
|
|
||||||
appName?: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
const escapeHtml = (s: string): string =>
|
|
||||||
s.replace(/[&<>"']/g, (c) =>
|
|
||||||
({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" }[c] as string),
|
|
||||||
);
|
|
||||||
|
|
||||||
export function buildInviteEmail(input: InviteEmailInput): { subject: string; html: string; text: string } {
|
|
||||||
const app = input.appName ?? "LynkedUp Pro";
|
|
||||||
const roles = input.roleNames.filter(Boolean);
|
|
||||||
const roleLabel = roles.length ? roles.join(", ") : "a team member";
|
|
||||||
const url = input.inviteUrl;
|
|
||||||
const safeUrl = escapeHtml(url);
|
|
||||||
const safeRoles = escapeHtml(roleLabel);
|
|
||||||
|
|
||||||
const subject = `You've been invited to join ${app}`;
|
|
||||||
|
|
||||||
const text = [
|
|
||||||
`You've been invited to join ${app} as ${roleLabel}.`,
|
|
||||||
"",
|
|
||||||
"Accept your invitation and set up your account here:",
|
|
||||||
url,
|
|
||||||
"",
|
|
||||||
"If you didn't expect this, you can ignore this email.",
|
|
||||||
"",
|
|
||||||
`— The ${app} team`,
|
|
||||||
].join("\n");
|
|
||||||
|
|
||||||
const html = `<div style="margin:0;padding:0;background:#0b0c11;">
|
|
||||||
<div style="max-width:520px;margin:0 auto;padding:40px 24px;font-family:Arial,Helvetica,sans-serif;color:#f3f4f8;">
|
|
||||||
<div style="font-size:20px;font-weight:800;letter-spacing:-0.02em;color:#fb923c;margin-bottom:24px;">${escapeHtml(app)}</div>
|
|
||||||
<h1 style="font-size:22px;font-weight:800;margin:0 0 12px;color:#f3f4f8;">You're invited to join the team</h1>
|
|
||||||
<p style="font-size:15px;line-height:1.6;color:#a3a8b5;margin:0 0 8px;">
|
|
||||||
You've been invited to join <strong style="color:#f3f4f8;">${escapeHtml(app)}</strong> as
|
|
||||||
<strong style="color:#f3f4f8;">${safeRoles}</strong>.
|
|
||||||
</p>
|
|
||||||
<p style="font-size:15px;line-height:1.6;color:#a3a8b5;margin:0 0 24px;">
|
|
||||||
Click below to accept your invitation and set up your account.
|
|
||||||
</p>
|
|
||||||
<a href="${safeUrl}" style="display:inline-block;background:#f97316;color:#ffffff;text-decoration:none;font-weight:700;font-size:15px;padding:13px 26px;border-radius:10px;">Accept invitation</a>
|
|
||||||
<p style="font-size:12.5px;line-height:1.6;color:#6c7280;margin:24px 0 0;">
|
|
||||||
Or paste this link into your browser:<br/>
|
|
||||||
<a href="${safeUrl}" style="color:#fb923c;word-break:break-all;">${safeUrl}</a>
|
|
||||||
</p>
|
|
||||||
<p style="font-size:12.5px;line-height:1.6;color:#6c7280;margin:24px 0 0;border-top:1px solid rgba(255,255,255,0.09);padding-top:16px;">
|
|
||||||
If you didn't expect this invitation, you can safely ignore this email.
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
</div>`;
|
|
||||||
|
|
||||||
return { subject, html, text };
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,371 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
// Messenger data layer. Serves EITHER a local mock (when the Shell isn't configured — the demo
|
||||||
|
// keeps working) OR the live be-crm data door (crm.messenger.*), behind one interface so the UI is
|
||||||
|
// mode-agnostic. DM-vs-group + who-can-chat are enforced server-side by IIOS/OPA; this is just glue.
|
||||||
|
//
|
||||||
|
// Live contract (be-crm):
|
||||||
|
// query crm.messenger.directory { kind, query?, limit } -> DirectoryEntry[]
|
||||||
|
// query crm.messenger.conversation.list {} -> ConversationSummary[]
|
||||||
|
// cmd crm.messenger.conversation.open { participantIds[], membership?, subject? } -> { threadId, ... }
|
||||||
|
// query crm.messenger.history { threadId } -> MessengerMessage[]
|
||||||
|
// cmd crm.messenger.send { threadId, content } -> MessengerMessage
|
||||||
|
// cmd crm.messenger.participant.add { threadId, userId }
|
||||||
|
//
|
||||||
|
// v1 uses REST + polling for the live stream; v2 layers the IIOS MessageSocket (messenger-socket.tsx)
|
||||||
|
// on top for live messages, typing, read receipts, and reactions.
|
||||||
|
|
||||||
|
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||||
|
import { useAppShell, useAuth, useQuery } from "@abe-kap/appshell-sdk/react";
|
||||||
|
import type { AnnotationEvent, AnnotationGroup } from "@insignia/iios-kernel-client";
|
||||||
|
import { isShellConfigured } from "./appshell";
|
||||||
|
import { useMessengerSocket } from "./messenger-socket";
|
||||||
|
|
||||||
|
export type Membership = "dm" | "group";
|
||||||
|
export interface UiPerson { id: string; name: string; kind: "staff" | "customer" }
|
||||||
|
export interface UiConversation {
|
||||||
|
threadId: string; title: string; subject: string | null; membership: Membership | null;
|
||||||
|
participants: string[]; unread: number; lastMessage?: string; lastAt?: string;
|
||||||
|
}
|
||||||
|
export interface UiReaction { emoji: string; count: number; mine: boolean }
|
||||||
|
export interface UiMessage {
|
||||||
|
id: string; actorId: string | null; senderId?: string | null; text: string; at: string; mine: boolean;
|
||||||
|
parentInteractionId?: string | null;
|
||||||
|
reactions?: UiReaction[];
|
||||||
|
}
|
||||||
|
|
||||||
|
interface DirectoryDTO { id: string; displayName: string; kind: "staff" | "customer" }
|
||||||
|
interface ConversationDTO {
|
||||||
|
threadId: string; subject: string | null; membership: Membership | null;
|
||||||
|
participants: string[]; unread: number; lastMessage?: string; lastAt?: string;
|
||||||
|
}
|
||||||
|
interface MessageDTO { interactionId: string; actorId: string | null; kind: string; occurredAt: string; text: string | null }
|
||||||
|
|
||||||
|
const SHELL = isShellConfigured();
|
||||||
|
const POLL_MS = 4000;
|
||||||
|
const TYPING_TTL_MS = 3500;
|
||||||
|
|
||||||
|
const shortId = (id: string) => id.replace(/^(pp_|cust_)/, "").slice(0, 6);
|
||||||
|
|
||||||
|
/** Turn the kernel's generic annotation aggregates into reaction chips. `users` may hold user or
|
||||||
|
* actor ids depending on the source, so `mine` is best-effort; a fresh annotation event corrects it. */
|
||||||
|
export function toReactions(annotations: AnnotationGroup[] | undefined, myId?: string): UiReaction[] {
|
||||||
|
if (!annotations) return [];
|
||||||
|
return annotations
|
||||||
|
.filter((a) => a.type === "reaction" && a.users.length > 0)
|
||||||
|
.map((a) => ({ emoji: a.value, count: a.users.length, mine: !!myId && a.users.includes(myId) }));
|
||||||
|
}
|
||||||
|
|
||||||
|
function applyAnnotation(prev: UiReaction[] | undefined, e: AnnotationEvent, myId?: string): UiReaction[] {
|
||||||
|
const base = (prev ?? []).filter((r) => r.emoji !== e.value);
|
||||||
|
if (e.type !== "reaction" || e.users.length === 0) return base;
|
||||||
|
return [...base, { emoji: e.value, count: e.users.length, mine: !!myId && e.users.includes(myId) }];
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ======================================================================== */
|
||||||
|
/* Public hooks */
|
||||||
|
/* ======================================================================== */
|
||||||
|
|
||||||
|
export interface MessengerData {
|
||||||
|
live: boolean; loading: boolean; error: string | null;
|
||||||
|
directory: UiPerson[];
|
||||||
|
conversations: UiConversation[];
|
||||||
|
nameOf: (id: string) => string;
|
||||||
|
openConversation: (participantIds: string[], opts?: { membership?: Membership; subject?: string }) => Promise<string>;
|
||||||
|
refetch: () => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ThreadData {
|
||||||
|
loading: boolean; error: string | null;
|
||||||
|
messages: UiMessage[];
|
||||||
|
send: (content: string, opts?: { parentInteractionId?: string }) => Promise<void>;
|
||||||
|
react: (interactionId: string, emoji: string) => void;
|
||||||
|
typingUserIds: string[];
|
||||||
|
seenIds: Set<string>;
|
||||||
|
refetch: () => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function useMessengerData(): MessengerData {
|
||||||
|
return SHELL ? useLiveMessenger() : useMockMessenger();
|
||||||
|
}
|
||||||
|
export function useThread(threadId: string): ThreadData {
|
||||||
|
return SHELL ? useLiveThread(threadId) : useMockThread(threadId);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ======================================================================== */
|
||||||
|
/* Live implementation (be-crm data door + IIOS socket) */
|
||||||
|
/* ======================================================================== */
|
||||||
|
|
||||||
|
function useLiveMessenger(): MessengerData {
|
||||||
|
const { sdk } = useAppShell();
|
||||||
|
const { user } = useAuth();
|
||||||
|
const socket = useMessengerSocket();
|
||||||
|
const myId = user?.id;
|
||||||
|
const dirQ = useQuery<DirectoryDTO[]>("crm.messenger.directory", { kind: "all", limit: 100 });
|
||||||
|
const convQ = useQuery<ConversationDTO[]>("crm.messenger.conversation.list", {});
|
||||||
|
|
||||||
|
const directory: UiPerson[] = useMemo(
|
||||||
|
() => (dirQ.data ?? []).map((d) => ({ id: d.id, name: d.displayName, kind: d.kind })),
|
||||||
|
[dirQ.data],
|
||||||
|
);
|
||||||
|
const nameById = useMemo(() => Object.fromEntries(directory.map((p) => [p.id, p.name])), [directory]);
|
||||||
|
const nameOf = useCallback((id: string) => nameById[id] ?? `User ${shortId(id)}`, [nameById]);
|
||||||
|
|
||||||
|
// Live sidebar previews: patch lastMessage/lastAt the instant a message arrives on any thread,
|
||||||
|
// then reconcile authoritative unread/order with a debounced refetch.
|
||||||
|
const [previews, setPreviews] = useState<Record<string, { lastMessage: string; lastAt: string }>>({});
|
||||||
|
const refetchRef = useRef(convQ.refetch);
|
||||||
|
refetchRef.current = convQ.refetch;
|
||||||
|
useEffect(() => {
|
||||||
|
if (!socket) return;
|
||||||
|
let timer: ReturnType<typeof setTimeout> | null = null;
|
||||||
|
const off = socket.onAnyMessage((threadId, m) => {
|
||||||
|
setPreviews((p) => ({ ...p, [threadId]: { lastMessage: m.text, lastAt: m.at } }));
|
||||||
|
if (timer) clearTimeout(timer);
|
||||||
|
timer = setTimeout(() => refetchRef.current(), 600);
|
||||||
|
});
|
||||||
|
return () => { off(); if (timer) clearTimeout(timer); };
|
||||||
|
}, [socket]);
|
||||||
|
|
||||||
|
const conversations: UiConversation[] = useMemo(
|
||||||
|
() => (convQ.data ?? []).map((c) => shape(c, nameOf, myId, previews[c.threadId])),
|
||||||
|
[convQ.data, nameOf, myId, previews],
|
||||||
|
);
|
||||||
|
|
||||||
|
const refetch = useCallback(() => { dirQ.refetch(); convQ.refetch(); }, [dirQ, convQ]);
|
||||||
|
const openConversation = useCallback(async (participantIds: string[], opts?: { membership?: Membership; subject?: string }) => {
|
||||||
|
const res = (await sdk.command("crm.messenger.conversation.open", {
|
||||||
|
participantIds, ...(opts?.membership ? { membership: opts.membership } : {}), ...(opts?.subject ? { subject: opts.subject } : {}),
|
||||||
|
})) as { threadId: string };
|
||||||
|
convQ.refetch();
|
||||||
|
return res.threadId;
|
||||||
|
}, [sdk, convQ]);
|
||||||
|
|
||||||
|
return {
|
||||||
|
live: true,
|
||||||
|
loading: dirQ.loading || convQ.loading,
|
||||||
|
error: (dirQ.error ?? convQ.error)?.message ?? null,
|
||||||
|
directory, conversations, nameOf, openConversation, refetch,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function useLiveThread(threadId: string): ThreadData {
|
||||||
|
const { sdk } = useAppShell();
|
||||||
|
const socket = useMessengerSocket();
|
||||||
|
const socketReady = socket?.ready ?? false;
|
||||||
|
const q = useQuery<MessageDTO[]>("crm.messenger.history", { threadId });
|
||||||
|
const [socketMsgs, setSocketMsgs] = useState<UiMessage[]>([]);
|
||||||
|
const [myActorId, setMyActorId] = useState<string | null>(null);
|
||||||
|
const myActorIdRef = useRef<string | null>(null);
|
||||||
|
myActorIdRef.current = myActorId;
|
||||||
|
const [typing, setTyping] = useState<Record<string, number>>({}); // userId -> expiry ts
|
||||||
|
const [seenIds, setSeenIds] = useState<Set<string>>(new Set());
|
||||||
|
const myId = socket?.myUserId;
|
||||||
|
|
||||||
|
// REST poll — the fallback whenever the live socket isn't connected.
|
||||||
|
const refetchRef = useRef(q.refetch);
|
||||||
|
refetchRef.current = q.refetch;
|
||||||
|
useEffect(() => {
|
||||||
|
if (socketReady) return;
|
||||||
|
const t = setInterval(() => refetchRef.current(), POLL_MS);
|
||||||
|
return () => clearInterval(t);
|
||||||
|
}, [socketReady, threadId]);
|
||||||
|
|
||||||
|
// Socket (primary): load history + subscribe to live messages, typing, receipts, reactions.
|
||||||
|
useEffect(() => {
|
||||||
|
if (!socket || !socketReady) return;
|
||||||
|
let alive = true;
|
||||||
|
setSocketMsgs([]); setSeenIds(new Set()); setTyping({});
|
||||||
|
void socket.openThread(threadId).then((hist) => { if (alive) setSocketMsgs(hist); }).catch(() => {});
|
||||||
|
|
||||||
|
const offMsg = socket.subscribe(threadId, (m) =>
|
||||||
|
setSocketMsgs((l) => (l.some((x) => x.id === m.id) ? l : [...l, m])),
|
||||||
|
);
|
||||||
|
const offTyping = socket.onTyping(threadId, (userId) =>
|
||||||
|
setTyping((t) => ({ ...t, [userId]: Date.now() + TYPING_TTL_MS })),
|
||||||
|
);
|
||||||
|
// Receipts are a global stream (no threadId). Count only reads by the OTHER side; seenMine then
|
||||||
|
// narrows to my messages in this thread.
|
||||||
|
const offReceipt = socket.onReceipt((e) => {
|
||||||
|
if (e.actorId === myActorIdRef.current) return;
|
||||||
|
setSeenIds((s) => (s.has(e.interactionId) ? s : new Set(s).add(e.interactionId)));
|
||||||
|
});
|
||||||
|
const offAnn = socket.onAnnotation(threadId, (e) =>
|
||||||
|
setSocketMsgs((l) => l.map((m) => (m.id === e.interactionId ? { ...m, reactions: applyAnnotation(m.reactions, e, myId) } : m))),
|
||||||
|
);
|
||||||
|
return () => { alive = false; offMsg(); offTyping(); offReceipt(); offAnn(); };
|
||||||
|
}, [socket, socketReady, threadId, myId]);
|
||||||
|
|
||||||
|
// Learn my own actor id from a message I sent, so receipts from OTHER actors read as "seen".
|
||||||
|
useEffect(() => {
|
||||||
|
const mine = socketMsgs.find((m) => m.mine && m.actorId);
|
||||||
|
if (mine?.actorId && mine.actorId !== myActorId) setMyActorId(mine.actorId);
|
||||||
|
}, [socketMsgs, myActorId]);
|
||||||
|
|
||||||
|
// Tell the server I've read the latest message (drives the other side's "seen" tick).
|
||||||
|
useEffect(() => {
|
||||||
|
if (!socket || !socketReady || socketMsgs.length === 0) return;
|
||||||
|
socket.markRead(threadId, socketMsgs[socketMsgs.length - 1].id);
|
||||||
|
}, [socket, socketReady, threadId, socketMsgs]);
|
||||||
|
|
||||||
|
// Expire stale typing entries.
|
||||||
|
const typingUserIds = useMemo(() => {
|
||||||
|
const now = Date.now();
|
||||||
|
return Object.entries(typing).filter(([, exp]) => exp > now).map(([u]) => u);
|
||||||
|
}, [typing]);
|
||||||
|
useEffect(() => {
|
||||||
|
if (typingUserIds.length === 0) return;
|
||||||
|
const t = setTimeout(() => setTyping((p) => ({ ...p })), TYPING_TTL_MS);
|
||||||
|
return () => clearTimeout(t);
|
||||||
|
}, [typingUserIds.length, typing]);
|
||||||
|
|
||||||
|
const restMsgs: UiMessage[] = useMemo(
|
||||||
|
() => (q.data ?? []).map((m) => ({
|
||||||
|
id: m.interactionId, actorId: m.actorId, senderId: null, text: m.text ?? "", at: m.occurredAt,
|
||||||
|
mine: !!myActorId && m.actorId === myActorId, reactions: [],
|
||||||
|
})),
|
||||||
|
[q.data, myActorId],
|
||||||
|
);
|
||||||
|
|
||||||
|
const messages = socketReady ? socketMsgs : restMsgs;
|
||||||
|
|
||||||
|
// My messages the other side has read (receipts carry the other actor's id).
|
||||||
|
const seenMine = useMemo(() => {
|
||||||
|
const out = new Set<string>();
|
||||||
|
for (const id of seenIds) if (messages.some((m) => m.id === id && m.mine)) out.add(id);
|
||||||
|
return out;
|
||||||
|
}, [seenIds, messages]);
|
||||||
|
|
||||||
|
const send = useCallback(async (content: string, opts?: { parentInteractionId?: string }) => {
|
||||||
|
if (socket && socketReady) {
|
||||||
|
await socket.send(threadId, content, opts); // echoes back over the socket as a 'message' event
|
||||||
|
} else {
|
||||||
|
const m = (await sdk.command("crm.messenger.send", { threadId, content })) as MessageDTO;
|
||||||
|
if (m.actorId) setMyActorId(m.actorId);
|
||||||
|
q.refetch();
|
||||||
|
}
|
||||||
|
}, [socket, socketReady, threadId, sdk, q]);
|
||||||
|
|
||||||
|
const react = useCallback((interactionId: string, emoji: string) => {
|
||||||
|
if (socket && socketReady) socket.react(threadId, interactionId, emoji);
|
||||||
|
}, [socket, socketReady, threadId]);
|
||||||
|
|
||||||
|
return {
|
||||||
|
loading: q.loading && !socketReady, error: q.error?.message ?? null,
|
||||||
|
messages, send, react, typingUserIds, seenIds: seenMine, refetch: q.refetch,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function shape(
|
||||||
|
c: ConversationDTO,
|
||||||
|
nameOf: (id: string) => string,
|
||||||
|
myId: string | undefined,
|
||||||
|
overlay?: { lastMessage: string; lastAt: string },
|
||||||
|
): UiConversation {
|
||||||
|
// A DM's title is the OTHER person — never yourself, and never the raw unknown-id fallback for both.
|
||||||
|
const others = myId ? c.participants.filter((p) => p !== myId) : c.participants;
|
||||||
|
const title = c.subject?.trim()
|
||||||
|
|| (c.membership === "group"
|
||||||
|
? `Group · ${c.participants.length}`
|
||||||
|
: (others.map(nameOf).join(", ") || nameOf(c.participants[0] ?? "") || "Conversation"));
|
||||||
|
const lastMessage = overlay?.lastMessage ?? c.lastMessage;
|
||||||
|
const lastAt = overlay?.lastAt ?? c.lastAt;
|
||||||
|
return {
|
||||||
|
threadId: c.threadId, title, subject: c.subject, membership: c.membership,
|
||||||
|
participants: c.participants, unread: c.unread,
|
||||||
|
...(lastMessage ? { lastMessage } : {}), ...(lastAt ? { lastAt } : {}),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ======================================================================== */
|
||||||
|
/* Mock implementation (no Shell configured — the demo keeps working) */
|
||||||
|
/* ======================================================================== */
|
||||||
|
|
||||||
|
const MOCK_PEOPLE: UiPerson[] = [
|
||||||
|
{ id: "pp_sofia", name: "Sofia Ramirez", kind: "staff" },
|
||||||
|
{ id: "pp_dan", name: "Dan Whitaker", kind: "staff" },
|
||||||
|
{ id: "pp_priya", name: "Priya Nair", kind: "staff" },
|
||||||
|
{ id: "cust_acme", name: "Acme Roofing (Client)", kind: "customer" },
|
||||||
|
{ id: "cust_globex", name: "Globex Homes (Client)", kind: "customer" },
|
||||||
|
];
|
||||||
|
|
||||||
|
interface MockThread { threadId: string; membership: Membership; subject: string | null; participants: string[]; messages: UiMessage[] }
|
||||||
|
const now = () => new Date().toISOString();
|
||||||
|
let MOCK_SEQ = 100;
|
||||||
|
|
||||||
|
// A tiny module-level store both mock hooks share, with a subscribe-on-change so the
|
||||||
|
// conversation list and the open thread stay in sync (no globalThis, no render writes).
|
||||||
|
const MOCK_STORE = new Map<string, MockThread>([
|
||||||
|
["th_mock_1", { threadId: "th_mock_1", membership: "dm", subject: null, participants: ["me", "pp_sofia"],
|
||||||
|
messages: [{ id: "m1", actorId: "pp_sofia", text: "Can you review the Henderson estimate?", at: now(), mine: false, reactions: [] }] }],
|
||||||
|
["th_mock_2", { threadId: "th_mock_2", membership: "group", subject: "Storm response — East side", participants: ["me", "pp_dan", "pp_priya"],
|
||||||
|
messages: [{ id: "m2", actorId: "pp_dan", text: "Crew is rolling out at 7.", at: now(), mine: false, reactions: [] }] }],
|
||||||
|
]);
|
||||||
|
const mockListeners = new Set<() => void>();
|
||||||
|
const notifyMock = () => mockListeners.forEach((l) => l());
|
||||||
|
function useMockSubscription(): void {
|
||||||
|
const [, setV] = useState(0);
|
||||||
|
useEffect(() => {
|
||||||
|
const l = () => setV((n) => n + 1);
|
||||||
|
mockListeners.add(l);
|
||||||
|
return () => { mockListeners.delete(l); };
|
||||||
|
}, []);
|
||||||
|
}
|
||||||
|
|
||||||
|
function useMockMessenger(): MessengerData {
|
||||||
|
useMockSubscription();
|
||||||
|
const nameById = useMemo(() => Object.fromEntries(MOCK_PEOPLE.map((p) => [p.id, p.name])), []);
|
||||||
|
const nameOf = useCallback((id: string) => nameById[id] ?? `User ${shortId(id)}`, [nameById]);
|
||||||
|
|
||||||
|
const conversations: UiConversation[] = [...MOCK_STORE.values()].map((t) => {
|
||||||
|
const last = t.messages[t.messages.length - 1];
|
||||||
|
return {
|
||||||
|
threadId: t.threadId,
|
||||||
|
title: t.subject || t.participants.filter((p) => p !== "me").map(nameOf).join(", ") || "Conversation",
|
||||||
|
subject: t.subject, membership: t.membership, participants: t.participants, unread: 0,
|
||||||
|
...(last ? { lastMessage: last.text, lastAt: last.at } : {}),
|
||||||
|
};
|
||||||
|
});
|
||||||
|
|
||||||
|
const openConversation = useCallback(async (participantIds: string[], opts?: { membership?: Membership; subject?: string }) => {
|
||||||
|
const membership = opts?.membership ?? (participantIds.length === 1 ? "dm" : "group");
|
||||||
|
const threadId = `th_mock_${MOCK_SEQ++}`;
|
||||||
|
MOCK_STORE.set(threadId, { threadId, membership, subject: opts?.subject ?? null, participants: ["me", ...participantIds], messages: [] });
|
||||||
|
notifyMock();
|
||||||
|
return threadId;
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
return { live: false, loading: false, error: null, directory: MOCK_PEOPLE, conversations, nameOf, openConversation, refetch: () => {} };
|
||||||
|
}
|
||||||
|
|
||||||
|
function useMockThread(threadId: string): ThreadData {
|
||||||
|
useMockSubscription();
|
||||||
|
const thread = MOCK_STORE.get(threadId);
|
||||||
|
const send = useCallback(async (content: string, opts?: { parentInteractionId?: string }) => {
|
||||||
|
const t = MOCK_STORE.get(threadId);
|
||||||
|
if (t) {
|
||||||
|
t.messages = [...t.messages, {
|
||||||
|
id: `m_${MOCK_SEQ++}`, actorId: "me", text: content, at: now(), mine: true, reactions: [],
|
||||||
|
...(opts?.parentInteractionId ? { parentInteractionId: opts.parentInteractionId } : {}),
|
||||||
|
}];
|
||||||
|
notifyMock();
|
||||||
|
}
|
||||||
|
}, [threadId]);
|
||||||
|
const react = useCallback((interactionId: string, emoji: string) => {
|
||||||
|
const t = MOCK_STORE.get(threadId);
|
||||||
|
if (!t) return;
|
||||||
|
t.messages = t.messages.map((m) => {
|
||||||
|
if (m.id !== interactionId) return m;
|
||||||
|
const has = (m.reactions ?? []).find((r) => r.emoji === emoji);
|
||||||
|
const reactions = has
|
||||||
|
? (m.reactions ?? []).filter((r) => r.emoji !== emoji)
|
||||||
|
: [...(m.reactions ?? []), { emoji, count: 1, mine: true }];
|
||||||
|
return { ...m, reactions };
|
||||||
|
});
|
||||||
|
notifyMock();
|
||||||
|
}, [threadId]);
|
||||||
|
return {
|
||||||
|
loading: false, error: null, messages: thread?.messages ?? [], send, react,
|
||||||
|
typingUserIds: [], seenIds: new Set(), refetch: notifyMock,
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -0,0 +1,144 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
// v2 live stream: one IIOS MessageSocket for the whole Messenger panel, using the SDK
|
||||||
|
// (@insignia/iios-kernel-client) — not raw socket.io. The delegated realtime token comes from
|
||||||
|
// the be-crm data door (crm.messenger.realtime). Threads subscribe through a context; the socket
|
||||||
|
// re-opens every joined thread on reconnect (handled inside the SDK). In mock mode this is a no-op
|
||||||
|
// passthrough and the thread hook falls back to the REST poll.
|
||||||
|
//
|
||||||
|
// Beyond plain messages, the kernel exposes typing, read receipts, and reactions (generic
|
||||||
|
// annotations). This provider fans each server event out to per-thread listeners so the UI can
|
||||||
|
// render typing indicators, "seen" ticks, and emoji reactions live.
|
||||||
|
|
||||||
|
import { createContext, useCallback, useContext, useEffect, useRef, useState, type ReactNode } from "react";
|
||||||
|
import { MessageSocket, type Message, type AnnotationEvent } from "@insignia/iios-kernel-client";
|
||||||
|
import { useAuth, useQuery } from "@abe-kap/appshell-sdk/react";
|
||||||
|
import { isShellConfigured } from "./appshell";
|
||||||
|
import { toReactions, type UiMessage } from "./messenger-api";
|
||||||
|
|
||||||
|
interface RealtimeDTO { url: string; audience: string; token?: string }
|
||||||
|
|
||||||
|
export interface ReceiptHit { interactionId: string; actorId: string }
|
||||||
|
|
||||||
|
export interface MessengerSocket {
|
||||||
|
ready: boolean;
|
||||||
|
myUserId?: string;
|
||||||
|
openThread: (threadId: string) => Promise<UiMessage[]>;
|
||||||
|
send: (threadId: string, content: string, opts?: { parentInteractionId?: string }) => Promise<void>;
|
||||||
|
subscribe: (threadId: string, cb: (m: UiMessage) => void) => () => void;
|
||||||
|
/** Fires for EVERY inbound message regardless of thread — drives live sidebar previews. */
|
||||||
|
onAnyMessage: (cb: (threadId: string, m: UiMessage) => void) => () => void;
|
||||||
|
sendTyping: (threadId: string) => void;
|
||||||
|
onTyping: (threadId: string, cb: (userId: string) => void) => () => void;
|
||||||
|
markRead: (threadId: string, interactionId: string) => void;
|
||||||
|
/** The kernel's receipt event carries no threadId, so this is a global stream; the thread hook
|
||||||
|
* filters to receipts for its own (mine) messages. */
|
||||||
|
onReceipt: (cb: (e: ReceiptHit) => void) => () => void;
|
||||||
|
react: (threadId: string, interactionId: string, emoji: string) => void;
|
||||||
|
onAnnotation: (threadId: string, cb: (e: AnnotationEvent) => void) => () => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
const Ctx = createContext<MessengerSocket | null>(null);
|
||||||
|
export function useMessengerSocket(): MessengerSocket | null { return useContext(Ctx); }
|
||||||
|
|
||||||
|
const SHELL = isShellConfigured();
|
||||||
|
|
||||||
|
const toUi = (m: Message, myUserId?: string): UiMessage => ({
|
||||||
|
id: m.id, actorId: m.senderActorId ?? null, senderId: m.senderId ?? null, text: m.content ?? "", at: m.createdAt,
|
||||||
|
mine: !!myUserId && m.senderId === myUserId,
|
||||||
|
...(m.parentInteractionId ? { parentInteractionId: m.parentInteractionId } : {}),
|
||||||
|
reactions: toReactions(m.annotations, myUserId),
|
||||||
|
});
|
||||||
|
|
||||||
|
export function MessengerSocketProvider({ children }: { children: ReactNode }) {
|
||||||
|
// SHELL is a build-time constant, so the branch is stable across renders (Rules-of-Hooks safe).
|
||||||
|
if (!SHELL) return <>{children}</>;
|
||||||
|
return <LiveSocketProvider>{children}</LiveSocketProvider>;
|
||||||
|
}
|
||||||
|
|
||||||
|
// A tiny per-thread listener registry, reused for messages / typing / receipts / annotations.
|
||||||
|
function makeRegistry<T>() {
|
||||||
|
const map = new Map<string, Set<(v: T) => void>>();
|
||||||
|
const add = (key: string, cb: (v: T) => void) => {
|
||||||
|
if (!map.has(key)) map.set(key, new Set());
|
||||||
|
map.get(key)!.add(cb);
|
||||||
|
return () => { map.get(key)?.delete(cb); };
|
||||||
|
};
|
||||||
|
const emit = (key: string, v: T) => map.get(key)?.forEach((cb) => cb(v));
|
||||||
|
return { add, emit };
|
||||||
|
}
|
||||||
|
|
||||||
|
function LiveSocketProvider({ children }: { children: ReactNode }) {
|
||||||
|
const { user } = useAuth();
|
||||||
|
const rt = useQuery<RealtimeDTO>("crm.messenger.realtime", {});
|
||||||
|
const [ready, setReady] = useState(false);
|
||||||
|
const socketRef = useRef<MessageSocket | null>(null);
|
||||||
|
const myRef = useRef<string | undefined>(user?.id);
|
||||||
|
myRef.current = user?.id;
|
||||||
|
|
||||||
|
// One registry per event kind, keyed by threadId (plus a global message fan-out).
|
||||||
|
const msgReg = useRef(makeRegistry<UiMessage>()).current;
|
||||||
|
const anyMsg = useRef(new Set<(threadId: string, m: UiMessage) => void>()).current;
|
||||||
|
const typingReg = useRef(makeRegistry<string>()).current;
|
||||||
|
const receiptSet = useRef(new Set<(e: ReceiptHit) => void>()).current;
|
||||||
|
const annReg = useRef(makeRegistry<AnnotationEvent>()).current;
|
||||||
|
|
||||||
|
const url = rt.data?.url;
|
||||||
|
const token = rt.data?.token;
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!url || !token) return;
|
||||||
|
const socket = new MessageSocket({ serviceUrl: url, token, autoConnect: false });
|
||||||
|
socketRef.current = socket;
|
||||||
|
const offConnected = socket.onConnected(() => setReady(true));
|
||||||
|
const offMessage = socket.on("message", (m) => {
|
||||||
|
const ui = toUi(m, myRef.current);
|
||||||
|
msgReg.emit(m.threadId, ui);
|
||||||
|
anyMsg.forEach((cb) => cb(m.threadId, ui));
|
||||||
|
});
|
||||||
|
const offTyping = socket.on("typing", (e) => { if (e.userId !== myRef.current) typingReg.emit(e.threadId, e.userId); });
|
||||||
|
const offReceipt = socket.on("receipt", (e) => receiptSet.forEach((cb) => cb({ interactionId: e.interactionId, actorId: e.actorId })));
|
||||||
|
const offAnn = socket.on("annotation", (e) => annReg.emit(e.threadId, e));
|
||||||
|
socket.connect();
|
||||||
|
return () => {
|
||||||
|
offConnected(); offMessage(); offTyping(); offReceipt(); offAnn();
|
||||||
|
socket.disconnect(); socketRef.current = null; setReady(false);
|
||||||
|
};
|
||||||
|
}, [url, token, msgReg, anyMsg, typingReg, receiptSet, annReg]);
|
||||||
|
|
||||||
|
const openThread = useCallback(async (threadId: string): Promise<UiMessage[]> => {
|
||||||
|
const s = socketRef.current;
|
||||||
|
if (!s) return [];
|
||||||
|
const res = await s.openThread(threadId);
|
||||||
|
return res.history.map((m) => toUi(m, myRef.current));
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const send = useCallback(async (threadId: string, content: string, opts?: { parentInteractionId?: string }) => {
|
||||||
|
const s = socketRef.current;
|
||||||
|
if (!s) throw new Error("Not connected");
|
||||||
|
await s.sendMessage(threadId, content, opts?.parentInteractionId ? { parentInteractionId: opts.parentInteractionId } : undefined);
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const subscribe = useCallback((threadId: string, cb: (m: UiMessage) => void) => msgReg.add(threadId, cb), [msgReg]);
|
||||||
|
const onAnyMessage = useCallback((cb: (threadId: string, m: UiMessage) => void) => {
|
||||||
|
anyMsg.add(cb); return () => { anyMsg.delete(cb); };
|
||||||
|
}, [anyMsg]);
|
||||||
|
const onTyping = useCallback((threadId: string, cb: (userId: string) => void) => typingReg.add(threadId, cb), [typingReg]);
|
||||||
|
const onReceipt = useCallback((cb: (e: ReceiptHit) => void) => {
|
||||||
|
receiptSet.add(cb); return () => { receiptSet.delete(cb); };
|
||||||
|
}, [receiptSet]);
|
||||||
|
const onAnnotation = useCallback((threadId: string, cb: (e: AnnotationEvent) => void) => annReg.add(threadId, cb), [annReg]);
|
||||||
|
|
||||||
|
const sendTyping = useCallback((threadId: string) => socketRef.current?.typing(threadId), []);
|
||||||
|
const markRead = useCallback((threadId: string, interactionId: string) => { void socketRef.current?.markRead(threadId, interactionId); }, []);
|
||||||
|
const react = useCallback((threadId: string, interactionId: string, emoji: string) => { void socketRef.current?.react(threadId, interactionId, emoji); }, []);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Ctx.Provider value={{
|
||||||
|
ready, myUserId: user?.id, openThread, send, subscribe, onAnyMessage,
|
||||||
|
sendTyping, onTyping, markRead, onReceipt, react, onAnnotation,
|
||||||
|
}}>
|
||||||
|
{children}
|
||||||
|
</Ctx.Provider>
|
||||||
|
);
|
||||||
|
}
|
||||||
+7
-16
@@ -48,10 +48,10 @@ export interface TeamData {
|
|||||||
setMemberRoles: (id: string, roleIds: string[]) => Promise<void>;
|
setMemberRoles: (id: string, roleIds: string[]) => Promise<void>;
|
||||||
updateMember: (id: string, patch: { title?: string; roleIds?: string[] }) => Promise<void>;
|
updateMember: (id: string, patch: { title?: string; roleIds?: string[] }) => Promise<void>;
|
||||||
removeMember: (id: string) => Promise<void>;
|
removeMember: (id: string) => Promise<void>;
|
||||||
/** Create an invite; resolves with the accept token so the caller can email the link. */
|
/** Create an invite. be-crm emails the invitee automatically. */
|
||||||
invite: (email: string, roleIds: string[]) => Promise<{ token?: string }>;
|
invite: (email: string, roleIds: string[]) => Promise<void>;
|
||||||
/** Resend an invite (regenerates the token); resolves with the fresh token. */
|
/** Resend an invite (regenerates the token + re-emails it). */
|
||||||
resendInvite: (id: string) => Promise<{ token?: string }>;
|
resendInvite: (id: string) => Promise<void>;
|
||||||
revokeInvite: (id: string) => Promise<void>;
|
revokeInvite: (id: string) => Promise<void>;
|
||||||
setPermission: (roleId: string, permId: string, granted: boolean) => Promise<void>;
|
setPermission: (roleId: string, permId: string, granted: boolean) => Promise<void>;
|
||||||
refetch: () => void;
|
refetch: () => void;
|
||||||
@@ -117,9 +117,8 @@ function useMockTeam(): TeamData {
|
|||||||
const removeMember = useCallback(async (id: string) => { setMembers((l) => l.filter((m) => m.id !== id)); }, []);
|
const removeMember = useCallback(async (id: string) => { setMembers((l) => l.filter((m) => m.id !== id)); }, []);
|
||||||
const invite = useCallback(async (email: string, roleIds: string[]) => {
|
const invite = useCallback(async (email: string, roleIds: string[]) => {
|
||||||
setInvites((l) => [{ id: `inv_${Date.now()}`, email, roleIds, invitedBy: "James Carter", sentAt: "Just now" }, ...l]);
|
setInvites((l) => [{ id: `inv_${Date.now()}`, email, roleIds, invitedBy: "James Carter", sentAt: "Just now" }, ...l]);
|
||||||
return {};
|
|
||||||
}, []);
|
}, []);
|
||||||
const resendInvite = useCallback(async () => ({}), []);
|
const resendInvite = useCallback(async () => {}, []);
|
||||||
const revokeInvite = useCallback(async (id: string) => { setInvites((l) => l.filter((i) => i.id !== id)); }, []);
|
const revokeInvite = useCallback(async (id: string) => { setInvites((l) => l.filter((i) => i.id !== id)); }, []);
|
||||||
const setPermission = useCallback(async (roleId: string, permId: string, granted: boolean) => {
|
const setPermission = useCallback(async (roleId: string, permId: string, granted: boolean) => {
|
||||||
setRoles((l) => l.map((r) => (r.id !== roleId ? r : {
|
setRoles((l) => l.map((r) => (r.id !== roleId ? r : {
|
||||||
@@ -191,16 +190,8 @@ function useLiveTeam(): TeamData {
|
|||||||
id, ...(patch.title !== undefined ? { jobTitle: patch.title } : {}), ...(patch.roleIds ? { roleIds: patch.roleIds } : {}),
|
id, ...(patch.title !== undefined ? { jobTitle: patch.title } : {}), ...(patch.roleIds ? { roleIds: patch.roleIds } : {}),
|
||||||
}),
|
}),
|
||||||
removeMember: (id) => cmd("crm.team.member.remove", { id }),
|
removeMember: (id) => cmd("crm.team.member.remove", { id }),
|
||||||
invite: async (email, roleIds) => {
|
invite: (email, roleIds) => cmd("crm.team.invitation.create", { email, roleIds }),
|
||||||
const dto = (await sdk.command("crm.team.invitation.create", { email, roleIds })) as { token?: string } | undefined;
|
resendInvite: (id) => cmd("crm.team.invitation.resend", { id }),
|
||||||
refetch();
|
|
||||||
return { token: dto?.token };
|
|
||||||
},
|
|
||||||
resendInvite: async (id) => {
|
|
||||||
const res = (await sdk.command("crm.team.invitation.resend", { id })) as { token?: string } | undefined;
|
|
||||||
refetch();
|
|
||||||
return { token: res?.token };
|
|
||||||
},
|
|
||||||
revokeInvite: (id) => cmd("crm.team.invitation.revoke", { id }),
|
revokeInvite: (id) => cmd("crm.team.invitation.revoke", { id }),
|
||||||
setPermission: (roleId, permId, granted) =>
|
setPermission: (roleId, permId, granted) =>
|
||||||
cmd(granted ? "crm.team.role.addPermission" : "crm.team.role.removePermission", { id: roleId, permissionId: permId }),
|
cmd(granted ? "crm.team.role.addPermission" : "crm.team.role.removePermission", { id: roleId, permissionId: permId }),
|
||||||
|
|||||||
Reference in New Issue
Block a user