Compare commits
29 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 948b38a016 | |||
| d44cacb778 | |||
| e04f1e6086 | |||
| ae27830893 | |||
| 84cb5c66b5 | |||
| 1fc1a28d96 | |||
| 0c7b3231ef | |||
| 7a312a1ace | |||
| eb7e1f7995 | |||
| 988b46f6e7 | |||
| 8e2fe315ce | |||
| 462eb7f036 | |||
| facc50e82f | |||
| 413f8d43b6 | |||
| cd8015ada8 | |||
| e70904a219 | |||
| 036ed84255 | |||
| 7bcd1a2a2d | |||
| efd31d9293 | |||
| a2a7e71f59 | |||
| 28907acf0e | |||
| 54add81187 | |||
| 4ad0decad0 | |||
| 0b433790a5 | |||
| 7982c243c0 | |||
| 1490fa3460 | |||
| 36f43d7d2a | |||
| 46aa7a767c | |||
| 4b50d682e6 |
@@ -0,0 +1,240 @@
|
||||
# Messaging UI SDK — Design
|
||||
|
||||
**Date:** 2026-07-17
|
||||
**Status:** Approved, pending implementation plan
|
||||
|
||||
## Problem
|
||||
|
||||
Messaging UI is rewritten from scratch in every app that needs it. `lynkeduppro-crm`
|
||||
has a rich, working messenger — conversation list, thread view, bubbles, reactions,
|
||||
reply threading, typing, read receipts — built as 352 lines in
|
||||
`src/components/dashboard/messenger.tsx` over 371 lines in `src/lib/messenger-api.ts`.
|
||||
None of it is reusable.
|
||||
|
||||
### Why not just use `@insignia/iios-message-web`?
|
||||
|
||||
Because it does not solve this problem, and the CRM already rejected it.
|
||||
|
||||
`iios-message-web` is 109 lines across 2 files. It is fully headless: its only JSX is
|
||||
the context provider element itself. It exports `MessageProvider`, `useThread`,
|
||||
`useMessages` and a `Message` type — nothing more. It ships no components, no CSS, no
|
||||
theming.
|
||||
|
||||
It also guessed its API wrong. `useMessages.send` narrows the options bag to
|
||||
`{ contentRef? }`, while the underlying `MessageSocket.sendMessage` accepts
|
||||
`parentInteractionId`, `mentions`, and `attachment`. Threading, mentions and
|
||||
attachments are unreachable through its public API. The socket is held in a
|
||||
module-private context with no escape hatch. It has zero consumers outside the iios
|
||||
repo, and its own docs reference a `useSendMessage` hook that does not exist.
|
||||
|
||||
The CRM consequently bypassed it and depends on `@insignia/iios-kernel-client`
|
||||
directly.
|
||||
|
||||
**The lesson drives this design:** the headless layer is already an SDK
|
||||
(`iios-kernel-client` — sockets, threads, receipts, typing, published, consumed). A
|
||||
second headless package saves no app any work. The unsolved part is the UI.
|
||||
|
||||
### Why tower is not a consumer
|
||||
|
||||
Tower's messaging is a WhatsApp group ingest → moderate → forward pipeline, not chat.
|
||||
There is no `Conversation` model; `Message` is a captured group post keyed by
|
||||
`senderJid` + `sourceGroupId` with a moderation `status` enum
|
||||
(`RAW/PENDING/APPROVED/...`) — no recipient, no delivery state. "Send" is a BullMQ job
|
||||
rate-limited to 20 forwards/minute to avoid WhatsApp bans. There is no
|
||||
socket.io/websocket/SSE in the browser anywhere in the repo. Its `threads` and
|
||||
`drafts` mean different things than a chat SDK's would.
|
||||
|
||||
Tower would pay the abstraction cost for realtime machinery it never turns on. It is
|
||||
explicitly out of scope.
|
||||
|
||||
## Constraint: one real consumer
|
||||
|
||||
`lynkeduppro-crm` is the only consumer. Genericity is not achievable by intent — it is
|
||||
forced by a second consumer. This design therefore ports only what is already proven
|
||||
in production and refuses to invent abstraction for imagined needs. `iios-message-web`
|
||||
is the cautionary example of the opposite approach.
|
||||
|
||||
## Architecture
|
||||
|
||||
One package, `@insignia/messaging-ui`, published to the existing Gitea registry
|
||||
(`https://git.lynkedup.cloud/api/packages/insignia/npm/`). React as a peer dependency.
|
||||
|
||||
```
|
||||
@insignia/messaging-ui
|
||||
. → components + provider + hooks
|
||||
./styles.css → structural CSS + token defaults
|
||||
./adapters/kernel → optional iios-kernel-client adapter
|
||||
./adapters/mock → in-memory adapter for demos/tests
|
||||
```
|
||||
|
||||
**The core has zero transport knowledge.** `iios-kernel-client` is reachable only via
|
||||
the optional `./adapters/kernel` subpath, so an app on a different backend never pulls
|
||||
socket code. This is the specific mistake `iios-message-web` made by welding itself to
|
||||
`MessageSocket`.
|
||||
|
||||
This boundary is load-bearing for the actual consumer: the CRM does **not** talk to
|
||||
iios directly. It routes messaging through be-crm's data door (`crm.messenger.*`) via
|
||||
`@abe-kap/appshell-sdk`, socket-primary with a 4s REST poll fallback. An SDK that
|
||||
hardcoded `iios-kernel-client` could not be adopted by the only app that wants it.
|
||||
|
||||
## The adapter contract
|
||||
|
||||
Lifted from the existing `MessengerData`/`ThreadData` interfaces in
|
||||
`src/lib/messenger-api.ts`, which already survived two implementations (live + mock).
|
||||
Two implementations is the minimum real evidence that a seam is genuine rather than
|
||||
imagined. This contract was not designed for an SDK — it earned its shape.
|
||||
|
||||
```ts
|
||||
interface MessagingAdapter {
|
||||
listConversations(): Promise<Conversation[]>;
|
||||
openThread(p: { participantIds: string[]; subject?: string }): Promise<{ threadId: string }>;
|
||||
history(threadId: string): Promise<Message[]>;
|
||||
send(threadId: string, content: string, opts?: SendOpts): Promise<Message>;
|
||||
subscribe(threadId: string, cb: (e: MessageEvent) => void): Unsubscribe;
|
||||
sendTyping(threadId: string): void;
|
||||
markRead(threadId: string, messageId: string): Promise<void>;
|
||||
react?(messageId: string, emoji: string): Promise<void>;
|
||||
upload?(file: File): Promise<{ url: string; mime: string; name: string }>;
|
||||
currentActorId(): string | null;
|
||||
}
|
||||
|
||||
interface SendOpts {
|
||||
parentInteractionId?: string;
|
||||
attachment?: { url: string; mime: string; name: string };
|
||||
}
|
||||
```
|
||||
|
||||
### Graceful degradation
|
||||
|
||||
`react` and `upload` are optional. When an adapter omits them the UI hides the
|
||||
reaction picker or the attach button respectively. This is how one component set
|
||||
serves both a full CRM messenger and a stripped-down widget without a `mode` prop.
|
||||
|
||||
### `currentActorId` fixes a live bug
|
||||
|
||||
Today the CRM infers the current actor id by scanning for a message you sent:
|
||||
|
||||
```ts
|
||||
// src/lib/messenger-socket.tsx — current behaviour
|
||||
const mine = socketMsgs.find((m) => m.mine && m.actorId);
|
||||
if (mine?.actorId && mine.actorId !== myActorId) setMyActorId(mine.actorId);
|
||||
```
|
||||
|
||||
Until you have sent a message in a thread, `myActorId` is `null`. Because the REST
|
||||
poll fallback computes `mine: !!myActorId && m.actorId === myActorId`, **every message
|
||||
renders as not-yours** in that state. The root cause is that the kernel's receipt
|
||||
event carries no `threadId`, making it a global stream the CRM compensates for.
|
||||
|
||||
Making identity an explicit adapter responsibility eliminates this class of bug rather
|
||||
than porting it. The two-tier socket/poll fallback stays in the adapter, not the SDK —
|
||||
the CRM's adapter keeps its 4s poll; a socket-only app implements `subscribe` and
|
||||
never polls.
|
||||
|
||||
## Components
|
||||
|
||||
Composable primitives plus one all-in-one for drop-in use:
|
||||
|
||||
```tsx
|
||||
<MessagingProvider adapter={adapter}>
|
||||
<Messenger onNewChat={openPicker} /> {/* all-in-one: list + thread */}
|
||||
|
||||
{/* ...or compose: */}
|
||||
<ConversationList onSelect={setId} renderRow={custom} />
|
||||
<ThreadView threadId={id} />
|
||||
<Composer threadId={id} />
|
||||
</MessagingProvider>
|
||||
```
|
||||
|
||||
Hooks remain exported (`useConversations`, `useThread`, `useMessages`) so a host
|
||||
wanting entirely custom UI can use the SDK headlessly. This makes `iios-message-web`'s
|
||||
use case a strict subset of this package rather than a competitor.
|
||||
|
||||
### Explicitly out of scope
|
||||
|
||||
- **Inbox.** Coupled to iios semantics, not chat transport. Items are projected
|
||||
server-side by iios from domain events (`MENTION`, `NEEDS_REPLY`, `SUPPORT_UPDATE`,
|
||||
`CRM_OWNER_INTEREST`); authz is OPA policy. A chat SDK cannot own this.
|
||||
- **People picker / directory.** Fed by `crm.messenger.directory`. "Who exists and who
|
||||
may I message" is host and tenant territory. `<Messenger>` takes an `onNewChat`
|
||||
callback; the host renders its own picker.
|
||||
- **Presence.** No consumer needs it.
|
||||
|
||||
## Theming
|
||||
|
||||
Structural CSS with token defaults, overridden by the host. No Tailwind, no CSS-in-JS,
|
||||
no build coupling — the CRM has no shadcn and near-zero Tailwind (its real styling is
|
||||
1142 lines of hand-rolled `dashboard.css` plus inline style objects), so a
|
||||
Tailwind-based SDK would force a restyle of the only consumer.
|
||||
|
||||
```css
|
||||
:root {
|
||||
--msg-font; --msg-radius; --msg-gap;
|
||||
--msg-bubble-own-bg; --msg-bubble-other-bg;
|
||||
--msg-accent; --msg-muted; --msg-surface; --msg-border;
|
||||
}
|
||||
```
|
||||
|
||||
Every component accepts `className`; `<Messenger>` accepts a `classNames` slot map for
|
||||
per-part overrides. The CRM's existing `#6366f1 → #8b5cf6` group-avatar gradient
|
||||
becomes a token value rather than a hardcode.
|
||||
|
||||
## Attachments
|
||||
|
||||
The SDK renders attachments (image thumbnail, file chip, download) and calls
|
||||
`adapter.upload(file)`, passing the result into `send`. **Storage, auth, and
|
||||
size/mime limits are host concerns** — baking in an upload target would break the next
|
||||
app. The attach button is hidden when `upload` is absent.
|
||||
|
||||
`MessageSocket.sendMessage` already accepts an `attachment` field, so this exercises
|
||||
an existing wire contract rather than inventing one. No consumer has exercised it yet;
|
||||
the CRM has no file upload anywhere today.
|
||||
|
||||
## Data flow
|
||||
|
||||
1. Host constructs an adapter (CRM: wrapping appshell data door + socket).
|
||||
2. `MessagingProvider` holds the adapter in context.
|
||||
3. `useConversations` calls `listConversations`; `useMessages(threadId)` calls
|
||||
`history` then `subscribe`.
|
||||
4. `Composer` calls `send` with optimistic append; on rejection the optimistic message
|
||||
is rolled back and the input text restored (matching current CRM behaviour).
|
||||
5. `subscribe` events reconcile against optimistic state by message id.
|
||||
|
||||
## Error handling
|
||||
|
||||
- Adapter method rejection surfaces via hook `error` state; components render an
|
||||
inline error affordance, never throw.
|
||||
- Optimistic send failure restores composer text — the CRM's current behaviour, kept.
|
||||
- `subscribe` disconnect is the adapter's problem, not the SDK's. The SDK renders a
|
||||
`connected: boolean` from the adapter as a banner (the CRM's existing "Demo mode"
|
||||
banner generalises to this).
|
||||
|
||||
## Validation
|
||||
|
||||
The migration is the validation. There is no second app, so the honest bar is:
|
||||
|
||||
1. Rewrite the CRM's `messenger.tsx` to consume the SDK; its data-door implementation
|
||||
becomes `CrmMessagingAdapter`. **Success = identical behaviour with the 352-line
|
||||
component deleted**, and the mock adapter preserving demo-mode fallback.
|
||||
2. Then `support.tsx`'s `MessageCenter` — currently pure `setTimeout` theatre with no
|
||||
backend — becomes a zero-risk second surface.
|
||||
|
||||
Two surfaces in one app is not a true second consumer. It is the best honest test
|
||||
available of the adapter boundary, and it should be understood as such. **The design
|
||||
should be revisited when a genuine second app appears** rather than treated as settled.
|
||||
|
||||
## Testing
|
||||
|
||||
- **Component tests against the mock adapter** — no network. This is the payoff of the
|
||||
injected seam.
|
||||
- **`CrmMessagingAdapter` tested against the contract** independently of UI.
|
||||
- **A shared adapter conformance suite** any adapter can run, so the kernel and CRM
|
||||
adapters are verified against one definition of correct.
|
||||
- Explicit regression test for the `currentActorId` bug: messages render as own before
|
||||
the user has sent anything in the thread.
|
||||
|
||||
## Open questions
|
||||
|
||||
- Package name: `@insignia/messaging-ui` assumed, not confirmed.
|
||||
- Whether `CrmMessagingAdapter` lives in the CRM repo or ships as
|
||||
`./adapters/crm`. Preference: the CRM repo — it depends on appshell-sdk, which the
|
||||
SDK must not.
|
||||
+2
-2
@@ -1,8 +1,8 @@
|
||||
import type { NextConfig } from "next";
|
||||
|
||||
const nextConfig: NextConfig = {
|
||||
// The SDK ships ESM/TS; let Next transpile it.
|
||||
transpilePackages: ["@abe-kap/appshell-sdk"],
|
||||
// The SDKs ship ESM; let Next transpile them.
|
||||
transpilePackages: ["@abe-kap/appshell-sdk", "@insignia/iios-messaging-ui"],
|
||||
// The browser calls the Shell BFF same-origin under /shell (so the HttpOnly
|
||||
// session cookie flows). We deliberately use /shell (NOT /api) to avoid
|
||||
// clobbering the existing /api/geo route. Point BFF_ORIGIN at the deployed BFF.
|
||||
|
||||
Generated
+16
@@ -10,6 +10,7 @@
|
||||
"dependencies": {
|
||||
"@abe-kap/appshell-sdk": "^0.2.6",
|
||||
"@insignia/iios-kernel-client": "^0.1.4",
|
||||
"@insignia/iios-messaging-ui": "^0.1.2",
|
||||
"clsx": "^2.1.1",
|
||||
"lucide-react": "^1.21.0",
|
||||
"next": "16.2.9",
|
||||
@@ -1026,6 +1027,21 @@
|
||||
"socket.io-client": "^4.8.1"
|
||||
}
|
||||
},
|
||||
"node_modules/@insignia/iios-messaging-ui": {
|
||||
"version": "0.1.2",
|
||||
"resolved": "https://git.lynkedup.cloud/api/packages/insignia/npm/%40insignia%2Fiios-messaging-ui/-/0.1.2/iios-messaging-ui-0.1.2.tgz",
|
||||
"integrity": "sha512-YsoTM9vmjQ+dk6Hch5nXuqMFAdybd3luAZepfaliOw727ylc8FPAtwTMMcIWQ3WOQPa2eKeGLiEpo61QCO0GrA==",
|
||||
"peerDependencies": {
|
||||
"@insignia/iios-kernel-client": "*",
|
||||
"react": ">=18",
|
||||
"react-dom": ">=18"
|
||||
},
|
||||
"peerDependenciesMeta": {
|
||||
"@insignia/iios-kernel-client": {
|
||||
"optional": true
|
||||
}
|
||||
}
|
||||
},
|
||||
"node_modules/@jridgewell/gen-mapping": {
|
||||
"version": "0.3.13",
|
||||
"resolved": "https://registry.npmjs.org/@jridgewell/gen-mapping/-/gen-mapping-0.3.13.tgz",
|
||||
|
||||
@@ -11,6 +11,7 @@
|
||||
"dependencies": {
|
||||
"@abe-kap/appshell-sdk": "^0.2.6",
|
||||
"@insignia/iios-kernel-client": "^0.1.4",
|
||||
"@insignia/iios-messaging-ui": "^0.1.2",
|
||||
"clsx": "^2.1.1",
|
||||
"lucide-react": "^1.21.0",
|
||||
"next": "16.2.9",
|
||||
|
||||
@@ -134,6 +134,21 @@
|
||||
.dash-content { padding: 22px 28px 40px; width: 100%; }
|
||||
.sec-title { font-size: 15px; font-weight: 700; margin: 6px 0 14px; }
|
||||
|
||||
/* Host for @insignia/iios-messaging-ui: a fixed-height card that maps the SDK's --miu-* tokens
|
||||
onto the CRM design system, so the drop-in SDK matches the rest of the app. */
|
||||
.dash-root .miu-host { height: 620px; border: 1px solid var(--border); border-radius: 16px; overflow: hidden; }
|
||||
.dash-root .miu-host .miu-messenger,
|
||||
.dash-root .miu-host .miu-inbox {
|
||||
--miu-bg: var(--bg);
|
||||
--miu-panel: var(--panel);
|
||||
--miu-panel-2: var(--panel-2);
|
||||
--miu-border: var(--border);
|
||||
--miu-text: var(--text);
|
||||
--miu-muted: var(--muted);
|
||||
--miu-accent: var(--orange);
|
||||
--miu-accent-text: #1a1206;
|
||||
}
|
||||
|
||||
/* ---- grid helpers ---- */
|
||||
.grid { display: grid; gap: 16px; }
|
||||
.row { display: flex; align-items: center; }
|
||||
@@ -432,12 +447,14 @@
|
||||
.dash-root .ds-modal.size-sm { max-width: 400px; }
|
||||
.dash-root .ds-modal.size-md { max-width: 540px; }
|
||||
.dash-root .ds-modal.size-lg { max-width: 760px; }
|
||||
.dash-root .ds-modal.size-xl { max-width: 980px; }
|
||||
.dash-root .ds-modal-head { display: flex; align-items: flex-start; justify-content: space-between; gap: 12px; padding: 20px 20px 14px; border-bottom: 1px solid var(--border); }
|
||||
.dash-root .ds-modal-head-l { display: flex; gap: 12px; align-items: center; }
|
||||
.dash-root .ds-modal-head-r { display: flex; gap: 8px; align-items: center; flex: 0 0 auto; }
|
||||
.dash-root .ds-modal-ic { width: 38px; height: 38px; border-radius: 11px; flex: 0 0 auto; display: grid; place-items: center; color: var(--orange); background: color-mix(in srgb, var(--orange) 14%, transparent); }
|
||||
.dash-root .ds-modal-head h3 { font-size: 16px; font-weight: 700; }
|
||||
.dash-root .ds-modal-head p { font-size: 12.5px; color: var(--muted); margin-top: 3px; }
|
||||
.dash-root .ds-modal-body { padding: 18px 20px; overflow-y: auto; }
|
||||
.dash-root .ds-modal-body { padding: 18px 20px; overflow-y: auto; flex: 1 1 auto; min-height: 0; }
|
||||
.dash-root .ds-modal-foot { display: flex; justify-content: flex-end; gap: 10px; padding: 14px 20px; border-top: 1px solid var(--border); }
|
||||
|
||||
/* ---- Toasts ---- */
|
||||
@@ -907,7 +924,7 @@
|
||||
.dash-root .tm .ds-btn.v-primary { background: rgba(253, 169, 19, 0.92); color: #fff; border-radius: 9.132px; box-shadow: 0 8px 20px -10px rgba(253, 169, 19, 0.75); }
|
||||
.dash-root .tm .ds-btn.v-primary svg { color: #fff; }
|
||||
.dash-root .tm .ds-btn.v-primary:not(:disabled):hover { background: rgba(253, 169, 19, 1); }
|
||||
.dash-root .tm-toolbar { display: flex; align-items: center; gap: 12px; flex-wrap: wrap; }
|
||||
.dash-root .tm-toolbar { display: flex; align-items: center; gap: 12px; flex-wrap: wrap; margin-bottom: 12px; }
|
||||
.dash-root .tm-search { display: flex; align-items: center; gap: 8px; flex: 1; min-width: 220px; height: 44px; padding: 0 13px; border-radius: 13px; border: 1px solid var(--border-2); background: var(--panel-2); color: var(--muted); transition: 0.14s; }
|
||||
.dash-root .tm-search:focus-within { border-color: var(--orange); box-shadow: 0 0 0 3px var(--ring); color: var(--orange); }
|
||||
.dash-root .tm-search .ds-input { flex: 1; }
|
||||
@@ -1139,5 +1156,57 @@
|
||||
.dash-root .ai-caps { grid-template-columns: 1fr; }
|
||||
.dash-root .ai-bubble { max-width: 86%; }
|
||||
.dash-root .ai-view { height: calc(100vh - 150px); }
|
||||
.dash-root .proj-row { grid-template-columns: 1fr !important; row-gap: 8px; padding: 14px 16px; }
|
||||
.dash-root .proj-head { display: none; }
|
||||
.dash-root .proj-c-act { justify-self: end; }
|
||||
}
|
||||
|
||||
/* ---- Projects (Construction + Pipeline Leads) ---- */
|
||||
.dash-root .proj-toolbar .tm-tabs { flex: 0 0 auto; }
|
||||
.dash-root .proj-toolbar .tm-chips { flex: 0 0 auto; margin-left: auto; }
|
||||
.dash-root .proj-table { display: flex; flex-direction: column; }
|
||||
.dash-root .proj-row { display: grid; align-items: center; gap: 14px; padding: 13px 18px; border-bottom: 1px solid var(--border); }
|
||||
.dash-root .proj-row:last-child { border-bottom: 0; }
|
||||
.dash-root .proj-head { color: var(--faint); font-size: 10.5px; font-weight: 700; letter-spacing: 0.08em; text-transform: uppercase; text-align: center; }
|
||||
.dash-root .proj-row:not(.proj-head):hover { background: color-mix(in srgb, var(--panel-2) 60%, transparent); }
|
||||
.dash-root .proj-lead { min-width: 0; }
|
||||
.dash-root .proj-lead-name { font-size: 13.5px; font-weight: 700; }
|
||||
.dash-root .proj-lead-sub { font-size: 12px; color: var(--muted); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
|
||||
.dash-root .proj-text { font-size: 13px; color: var(--text-2); text-align: center; }
|
||||
.dash-root .proj-c-num { text-align: center; }
|
||||
.dash-root .proj-row .ds-pill { justify-self: center; justify-content: center; }
|
||||
.dash-root .proj-c-act { display: flex; justify-content: center; align-items: center; gap: 6px; position: relative; }
|
||||
.dash-root .proj-cd-search { margin-bottom: 14px; }
|
||||
.dash-root .proj-cd-table { margin-bottom: 14px; }
|
||||
.dash-root .proj-progress { display: flex; align-items: center; gap: 8px; }
|
||||
.dash-root .proj-progress-track { flex: 1; display: block; height: 6px; border-radius: 99px; background: var(--track); overflow: hidden; }
|
||||
.dash-root .proj-progress-fill { display: block; height: 100%; border-radius: 99px; background: var(--orange); transition: width 0.5s cubic-bezier(0.2,0.7,0.2,1); }
|
||||
.dash-root .proj-progress b { font-size: 12px; font-weight: 700; color: var(--text-2); flex: 0 0 auto; }
|
||||
.dash-root .proj-health { font-weight: 800; text-align: center; }
|
||||
.dash-root .proj-empty { display: flex; flex-direction: column; align-items: center; gap: 12px; padding: 54px 20px; color: var(--muted); text-align: center; }
|
||||
.dash-root .proj-foot { display: flex; align-items: center; justify-content: space-between; padding: 16px 4px 0; font-size: 12.5px; color: var(--muted); }
|
||||
.dash-root .proj-foot b { color: var(--text); font-size: 15px; font-weight: 800; }
|
||||
.dash-root .proj-detail-row { display: flex; align-items: center; justify-content: space-between; padding: 9px 0; border-bottom: 1px solid var(--border); font-size: 13px; }
|
||||
.dash-root .proj-detail-row span { color: var(--muted); }
|
||||
.dash-root .proj-detail-row b { color: var(--text); font-weight: 700; }
|
||||
|
||||
/* ---- Org Settings → Integrations ---- */
|
||||
.dash-root .settings-section { margin-top: 8px; }
|
||||
.dash-root .settings-section-title { font-size: 13px; font-weight: 700; letter-spacing: 0.02em; text-transform: uppercase; color: var(--muted); margin: 0 0 14px; }
|
||||
.dash-root .settings-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(340px, 1fr)); gap: 16px; }
|
||||
.dash-root .settings-card { border: 1px solid var(--border); background: var(--panel); border-radius: 16px; padding: 18px; display: flex; flex-direction: column; gap: 16px; }
|
||||
.dash-root .settings-card.is-soon { opacity: 0.6; }
|
||||
.dash-root .settings-card-head { display: flex; align-items: flex-start; gap: 12px; }
|
||||
.dash-root .settings-card-ic { flex: 0 0 auto; width: 38px; height: 38px; display: grid; place-items: center; border-radius: 11px; background: color-mix(in srgb, var(--orange) 14%, transparent); color: var(--orange); }
|
||||
.dash-root .settings-card-titles { flex: 1 1 auto; min-width: 0; }
|
||||
.dash-root .settings-card-name { font-size: 15px; font-weight: 700; color: var(--text); }
|
||||
.dash-root .settings-card-sub { font-weight: 500; color: var(--muted); }
|
||||
.dash-root .settings-card-desc { font-size: 12.5px; color: var(--muted); margin-top: 2px; }
|
||||
.dash-root .settings-card-body { display: flex; flex-direction: column; gap: 12px; }
|
||||
.dash-root .settings-kv { display: grid; gap: 10px; margin: 0; }
|
||||
.dash-root .settings-kv > div { display: flex; justify-content: space-between; align-items: baseline; gap: 12px; border-bottom: 1px solid var(--border); padding-bottom: 8px; }
|
||||
.dash-root .settings-kv > div:last-child { border-bottom: 0; padding-bottom: 0; }
|
||||
.dash-root .settings-kv dt { font-size: 12.5px; color: var(--muted); }
|
||||
.dash-root .settings-kv dd { margin: 0; font-size: 13px; font-weight: 600; color: var(--text); font-variant-numeric: tabular-nums; }
|
||||
.dash-root .settings-card-actions { display: flex; gap: 8px; align-items: center; margin-top: 2px; }
|
||||
.dash-root .settings-card-note { font-size: 12px; color: var(--muted); background: var(--panel-2); border: 1px solid var(--border); border-radius: 10px; padding: 8px 12px; }
|
||||
|
||||
@@ -15,8 +15,10 @@ import { Support } from "./support";
|
||||
import { Rules } from "./rules";
|
||||
import { AiAssistant } from "./ai-assistant";
|
||||
import { TeamManagement } from "./team-management";
|
||||
import { Messenger } from "./messenger";
|
||||
import { Inbox } from "./inbox";
|
||||
import { MessengerSdk } from "./messenger-sdk";
|
||||
import { InboxSdk } from "./inbox-sdk";
|
||||
import { Settings } from "./settings";
|
||||
import { Projects } from "./projects";
|
||||
import "../../app/dashboard/dashboard.css";
|
||||
|
||||
export function Dashboard() {
|
||||
@@ -47,9 +49,11 @@ export function Dashboard() {
|
||||
: active === "support" ? <Support />
|
||||
: active === "rules" ? <Rules />
|
||||
: active === "ai" ? <AiAssistant />
|
||||
: active === "messenger" ? <Messenger />
|
||||
: active === "inbox" ? <Inbox />
|
||||
: active === "messenger" ? <MessengerSdk />
|
||||
: active === "inbox" ? <InboxSdk />
|
||||
: active === "settings" ? <Settings />
|
||||
: active === "team" ? <TeamManagement />
|
||||
: active === "projects" ? <Projects />
|
||||
: <ComingSoon title={title} icon={item?.icon ?? "dashboard"} onGo={setActive} />}
|
||||
</ToastProvider>
|
||||
</div>
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
"use client";
|
||||
|
||||
// The CRM Inbox, rendered by @insignia/iios-messaging-ui instead of the bespoke in-CRM inbox.
|
||||
// Live = the be-crm data door (CrmInboxAdapter over crm.inbox.* + crm.mail.*); demo = the SDK's
|
||||
// MockInboxAdapter.
|
||||
|
||||
import { useMemo } from "react";
|
||||
import { useAppShell } from "@abe-kap/appshell-sdk/react";
|
||||
import { InboxProvider, Inbox as SdkInbox, type InboxAdapter } from "@insignia/iios-messaging-ui";
|
||||
import { MockInboxAdapter } from "@insignia/iios-messaging-ui/adapters/mock-inbox";
|
||||
import "@insignia/iios-messaging-ui/styles.css";
|
||||
import { isShellConfigured } from "@/lib/appshell";
|
||||
import { CrmInboxAdapter } from "@/lib/crm-inbox-adapter";
|
||||
import type { DataDoor } from "@/lib/crm-messaging-adapter";
|
||||
|
||||
const SHELL = isShellConfigured();
|
||||
|
||||
export function InboxSdk() {
|
||||
return (
|
||||
<div className="view">
|
||||
{!SHELL && (
|
||||
<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 the SDK's mock inbox adapter.
|
||||
</div>
|
||||
)}
|
||||
<div className="miu-host miu-host-inbox">{SHELL ? <LiveInbox /> : <DemoInbox />}</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function DemoInbox() {
|
||||
const adapter = useMemo<InboxAdapter>(() => new MockInboxAdapter(), []);
|
||||
return (
|
||||
<InboxProvider adapter={adapter}>
|
||||
<SdkInbox />
|
||||
</InboxProvider>
|
||||
);
|
||||
}
|
||||
|
||||
function LiveInbox() {
|
||||
const { sdk } = useAppShell();
|
||||
const adapter = useMemo<InboxAdapter>(() => new CrmInboxAdapter(sdk as unknown as DataDoor), [sdk]);
|
||||
return (
|
||||
<InboxProvider adapter={adapter}>
|
||||
<SdkInbox />
|
||||
</InboxProvider>
|
||||
);
|
||||
}
|
||||
@@ -1,85 +0,0 @@
|
||||
"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,89 @@
|
||||
"use client";
|
||||
|
||||
// The CRM messenger, now rendered by the shared @insignia/iios-messaging-ui SDK instead of a
|
||||
// bespoke in-CRM implementation. The CRM only supplies an adapter (transport) + theming; all the
|
||||
// UI + messaging logic lives in the SDK. Live path = the be-crm data door (CrmMessagingAdapter);
|
||||
// demo path = the SDK's own MockAdapter.
|
||||
|
||||
import { useEffect, useMemo, useState } from "react";
|
||||
import { useAppShell, useAuth, useQuery } from "@abe-kap/appshell-sdk/react";
|
||||
import { MessageSocket } from "@insignia/iios-kernel-client";
|
||||
import { MessagingProvider, Messenger as SdkMessenger, type MessagingAdapter } from "@insignia/iios-messaging-ui";
|
||||
import { MockAdapter } from "@insignia/iios-messaging-ui/adapters/mock";
|
||||
import "@insignia/iios-messaging-ui/styles.css";
|
||||
import { isShellConfigured } from "@/lib/appshell";
|
||||
import { CrmMessagingAdapter, type DataDoor } from "@/lib/crm-messaging-adapter";
|
||||
|
||||
interface RealtimeDTO { url: string; audience: string; token?: string }
|
||||
|
||||
/** Open the IIOS message socket with the delegated token the BFF mints (crm.messenger.realtime). */
|
||||
function useRealtimeSocket(): MessageSocket | null {
|
||||
const rt = useQuery<RealtimeDTO>("crm.messenger.realtime", {});
|
||||
const [socket, setSocket] = useState<MessageSocket | null>(null);
|
||||
const url = rt.data?.url;
|
||||
const token = rt.data?.token;
|
||||
useEffect(() => {
|
||||
if (!url || !token) return;
|
||||
const s = new MessageSocket({ serviceUrl: url, token, autoConnect: false });
|
||||
s.connect();
|
||||
setSocket(s);
|
||||
return () => {
|
||||
s.disconnect();
|
||||
setSocket(null);
|
||||
};
|
||||
}, [url, token]);
|
||||
return socket;
|
||||
}
|
||||
|
||||
const SHELL = isShellConfigured();
|
||||
|
||||
export function MessengerSdk() {
|
||||
return (
|
||||
<div className="view">
|
||||
{!SHELL && (
|
||||
<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 the SDK's mock adapter.
|
||||
</div>
|
||||
)}
|
||||
<div className="miu-host">{SHELL ? <LiveHost /> : <DemoHost />}</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// SHELL is a build-time constant, so exactly one of these mounts for the life of the app
|
||||
// (Rules-of-Hooks safe — the other branch never renders).
|
||||
function DemoHost() {
|
||||
const adapter = useMemo<MessagingAdapter>(() => new MockAdapter(), []);
|
||||
return (
|
||||
<MessagingProvider adapter={adapter}>
|
||||
<SdkMessenger />
|
||||
</MessagingProvider>
|
||||
);
|
||||
}
|
||||
|
||||
function LiveHost() {
|
||||
const { sdk } = useAppShell();
|
||||
const { user } = useAuth();
|
||||
const socket = useRealtimeSocket();
|
||||
// Rebuilds once the socket connects: the first adapter (no socket) polls; the second runs live.
|
||||
const adapter = useMemo<MessagingAdapter | null>(
|
||||
() => (user?.id ? new CrmMessagingAdapter(sdk as unknown as DataDoor, user.id, socket ?? undefined) : null),
|
||||
[sdk, user?.id, socket],
|
||||
);
|
||||
if (!adapter) return <div className="miu-empty">Loading…</div>;
|
||||
return (
|
||||
<MessagingProvider adapter={adapter}>
|
||||
<SdkMessenger />
|
||||
</MessagingProvider>
|
||||
);
|
||||
}
|
||||
@@ -1,352 +0,0 @@
|
||||
"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>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,148 @@
|
||||
// ============================================================
|
||||
// LynkedUp Pro — Projects mock data (Construction jobs + Pipeline
|
||||
// leads). Used only when the Shell isn't configured, so the demo
|
||||
// stays fully interactive without a backend — mirrors team-data.ts.
|
||||
// ============================================================
|
||||
|
||||
export type ConstructionStatus = "active" | "complete" | "stuck" | "followup";
|
||||
|
||||
export type ConstructionLead = {
|
||||
id: string;
|
||||
name: string;
|
||||
address: string;
|
||||
status: ConstructionStatus;
|
||||
stage: string;
|
||||
jobType: string;
|
||||
agent: string;
|
||||
progress: number; // 0-100
|
||||
health: number; // 0-100
|
||||
value: number; // dollars
|
||||
};
|
||||
|
||||
// The first 8 rows mirror the reference design exactly (name, address, job
|
||||
// type, stage, status, progress and health). The rest extend the set to 15
|
||||
// construction jobs with a realistic status/stage spread so the quick
|
||||
// filters (Active/Complete/Stuck/Follow-up) all have something to show.
|
||||
export const constructionLeads: ConstructionLead[] = [
|
||||
{ id: "c1", name: "Derek Holloway", address: "2814 Ravenswood Dr, Plano TX 75023", status: "active", stage: "New Lead", jobType: "Roof Replacement", agent: "Cody Tatum", progress: 14, health: 65, value: 28500 },
|
||||
{ id: "c2", name: "Brenda Castillo", address: "5501 Shady Brook Ln, Plano TX 75093", status: "active", stage: "New Lead", jobType: "Roof Inspection", agent: "Cody Tatum", progress: 14, health: 65, value: 15400 },
|
||||
{ id: "c3", name: "Antonio Reyes", address: "1122 Custer Rd, Plano TX 75075", status: "active", stage: "New Lead", jobType: "Gutter Replacement", agent: "Cody Tatum", progress: 14, health: 65, value: 19200 },
|
||||
{ id: "c4", name: "Sylvia Nguyen", address: "3308 Roundrock Trl, Plano TX 75023", status: "active", stage: "New Lead", jobType: "Siding Repair", agent: "Cody Tatum", progress: 14, health: 65, value: 21900 },
|
||||
{ id: "c5", name: "Raymond Osei", address: "2814 Ravenswood Dr, Plano TX 75023", status: "active", stage: "New Lead", jobType: "Roof Replacement", agent: "Cody Tatum", progress: 14, health: 65, value: 31200 },
|
||||
{ id: "c6", name: "Carolyn Estrada", address: "2814 Ravenswood Dr, Plano TX 75023", status: "active", stage: "New Lead", jobType: "Window Replacement", agent: "Cody Tatum", progress: 14, health: 65, value: 22400 },
|
||||
{ id: "c7", name: "Marcus Tillman", address: "2814 Ravenswood Dr, Plano TX 75023", status: "active", stage: "New Lead", jobType: "Roof Replacement", agent: "Cody Tatum", progress: 14, health: 65, value: 26800 },
|
||||
{ id: "c8", name: "Diane Kowalski", address: "815 Independence Pkwy, Plano TX 75023", status: "active", stage: "New Lead", jobType: "Roof Replacement", agent: "Cody Tatum", progress: 14, health: 65, value: 29500 },
|
||||
{ id: "c9", name: "Felicia Grant", address: "9021 Legacy Dr, Plano TX 75024", status: "complete", stage: "Completed", jobType: "Gutter Replacement", agent: "Emma Wilson", progress: 100, health: 92, value: 18600 },
|
||||
{ id: "c10", name: "Harold Jennings", address: "4477 Coit Rd, Plano TX 75075", status: "stuck", stage: "Permit Hold", jobType: "Siding Repair", agent: "Liam Foster", progress: 42, health: 38, value: 24800 },
|
||||
{ id: "c11", name: "Yolanda Brooks", address: "6650 Parker Rd, Plano TX 75093", status: "followup", stage: "Awaiting Customer", jobType: "Window Replacement", agent: "Sophie Turner", progress: 55, health: 51, value: 20700 },
|
||||
{ id: "c12", name: "Preston Wallace", address: "3312 Alma Dr, Plano TX 75075", status: "active", stage: "Scheduled", jobType: "Roof Repair", agent: "Cody Tatum", progress: 30, health: 70, value: 27500 },
|
||||
{ id: "c13", name: "Nadia Ferreira", address: "8890 Independence Pkwy, Plano TX 75025", status: "complete", stage: "Completed", jobType: "Roof Inspection", agent: "Emma Wilson", progress: 100, health: 95, value: 16200 },
|
||||
{ id: "c14", name: "Louis Abernathy", address: "2200 K Ave, Plano TX 75074", status: "stuck", stage: "Material Delay", jobType: "Roof Replacement", agent: "Liam Foster", progress: 60, health: 44, value: 24900 },
|
||||
{ id: "c15", name: "Grace Delgado", address: "7301 Ohio Dr, Plano TX 75093", status: "active", stage: "In Progress", jobType: "Roof Replacement", agent: "Cody Tatum", progress: 68, health: 78, value: 51600 },
|
||||
];
|
||||
|
||||
export type CollectionStatus = "paid" | "pending" | "overdue";
|
||||
|
||||
export type CollectionRecord = {
|
||||
id: string;
|
||||
name: string;
|
||||
address: string;
|
||||
referenceId: string;
|
||||
date: string; // YYYY-MM-DD
|
||||
type: string; // "Deposit — 30%", "Progress Payment — 40%", "Final Payment — 30%"
|
||||
status: CollectionStatus;
|
||||
amount: number; // dollars
|
||||
};
|
||||
|
||||
// Deterministic 3-installment payment schedule per construction job (deposit /
|
||||
// progress / final), so "Total Collected" has something real to show without a
|
||||
// billing backend. Which installments are PAID vs PENDING/OVERDUE follows the
|
||||
// job's own status — a completed job is fully paid, a stuck job has an overdue
|
||||
// progress payment, etc.
|
||||
const INSTALLMENTS = [
|
||||
{ label: "Deposit — 30%", pct: 0.3 },
|
||||
{ label: "Progress Payment — 40%", pct: 0.4 },
|
||||
{ label: "Final Payment — 30%", pct: 0.3 },
|
||||
] as const;
|
||||
|
||||
function statusFor(jobStatus: ConstructionStatus, i: number): CollectionStatus {
|
||||
if (jobStatus === "complete") return "paid";
|
||||
if (i === 0) return "paid"; // deposit is always collected up front
|
||||
if (jobStatus === "stuck" && i === 1) return "overdue";
|
||||
return "pending";
|
||||
}
|
||||
|
||||
export function collectionsFor(lead: ConstructionLead, leadIndex: number): CollectionRecord[] {
|
||||
const deposit = Math.round(lead.value * INSTALLMENTS[0].pct);
|
||||
const progress = Math.round(lead.value * INSTALLMENTS[1].pct);
|
||||
const final = lead.value - deposit - progress; // remainder avoids rounding drift
|
||||
const amounts = [deposit, progress, final];
|
||||
const ref = `PRJ-2026-${String(leadIndex + 1).padStart(3, "0")}`;
|
||||
return INSTALLMENTS.map((inst, i) => {
|
||||
const month = ((leadIndex * 2 + i * 2) % 12) + 1;
|
||||
const day = ((leadIndex * 5 + i * 7) % 27) + 1;
|
||||
return {
|
||||
id: `${lead.id}-r${i + 1}`,
|
||||
name: lead.name,
|
||||
address: lead.address,
|
||||
referenceId: `${ref}-R${i + 1}`,
|
||||
date: `2026-${String(month).padStart(2, "0")}-${String(day).padStart(2, "0")}`,
|
||||
type: inst.label,
|
||||
status: statusFor(lead.status, i),
|
||||
amount: amounts[i],
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
export type PipelineLead = {
|
||||
id: string;
|
||||
name: string;
|
||||
address: string;
|
||||
jobType: string;
|
||||
stage: string;
|
||||
agent: string;
|
||||
createdAgo: string;
|
||||
};
|
||||
|
||||
const FIRST_NAMES = [
|
||||
"Wesley", "Ivy", "Corey", "Renata", "Miles", "Paula", "Jasper", "Dana",
|
||||
"Terrence", "Alina", "Grant", "Bethany", "Owen", "Marisol", "Kurt",
|
||||
"Tanya", "Reggie", "Selena", "Blake", "Vivian", "Colton", "Priya",
|
||||
"Gerald", "Fiona",
|
||||
];
|
||||
const LAST_NAMES = [
|
||||
"Whitfield", "Caldwell", "Rourke", "Sanborn", "Delacroix", "Winters",
|
||||
"Blackwood", "Herrera", "Sweeney", "Okafor", "Lindgren", "Pruitt",
|
||||
"Castellano", "Marsh", "Yaeger", "Doyle", "Kowalczyk", "Beaumont",
|
||||
"Ashworth", "Nakamura", "Villanueva", "Prescott", "Hutchins",
|
||||
"Loomis", "Stanhope", "Everly", "Boone",
|
||||
];
|
||||
const STREETS = [
|
||||
"Independence Pkwy", "Legacy Dr", "Coit Rd", "Parker Rd", "Alma Dr",
|
||||
"K Ave", "Ohio Dr", "Preston Rd", "Spring Creek Pkwy", "Custer Rd",
|
||||
"Shady Brook Ln", "Roundrock Trl", "Ridgeview Dr", "Chisholm Trl",
|
||||
"Los Rios Blvd",
|
||||
];
|
||||
const ZIPS = ["75023", "75024", "75025", "75074", "75075", "75093"];
|
||||
const LEAD_JOB_TYPES = ["Roof Replacement", "Roof Inspection", "Gutter Replacement", "Siding Repair", "Window Replacement", "Roof Repair"];
|
||||
const LEAD_STAGES = ["New Inquiry", "Contacted", "Qualifying", "Quote Requested", "Nurture"];
|
||||
const LEAD_AGENTS = ["Cody Tatum", "Emma Wilson", "Liam Foster", "Sophie Turner", "Chloe Adams", "Unassigned"];
|
||||
|
||||
// Deterministic (no Math.random/Date.now) so server- and client-render match.
|
||||
export const pipelineLeads: PipelineLead[] = Array.from({ length: 45 }, (_, i) => {
|
||||
const first = FIRST_NAMES[i % FIRST_NAMES.length];
|
||||
const last = LAST_NAMES[(i * 7) % LAST_NAMES.length];
|
||||
const streetNum = 1000 + ((i * 137) % 8900);
|
||||
const street = STREETS[(i * 3) % STREETS.length];
|
||||
const zip = ZIPS[i % ZIPS.length];
|
||||
const daysAgo = ((i * 3) % 21) + 1;
|
||||
return {
|
||||
id: `p${i + 1}`,
|
||||
name: `${first} ${last}`,
|
||||
address: `${streetNum} ${street}, Plano TX ${zip}`,
|
||||
jobType: LEAD_JOB_TYPES[i % LEAD_JOB_TYPES.length],
|
||||
stage: LEAD_STAGES[(i * 2) % LEAD_STAGES.length],
|
||||
agent: LEAD_AGENTS[(i * 5) % LEAD_AGENTS.length],
|
||||
createdAgo: daysAgo === 1 ? "1 day ago" : `${daysAgo} days ago`,
|
||||
};
|
||||
});
|
||||
@@ -0,0 +1,258 @@
|
||||
"use client";
|
||||
|
||||
// ============================================================
|
||||
// Projects — Construction jobs + Pipeline leads.
|
||||
// Data comes from useProjectsData(): the local mock when the
|
||||
// Shell isn't configured, or the live be-crm data door
|
||||
// (crm.project.*) when it is. be-crm's Project model is generic
|
||||
// (name/status/value/owner/address/dates) — mock mode additionally
|
||||
// carries stage, job type, progress and health, which the live
|
||||
// table simply doesn't render (nothing backs them).
|
||||
// ============================================================
|
||||
|
||||
import { useMemo, useState } from "react";
|
||||
import { Btn, Icon, Modal, PageHead, Pill } from "./ui";
|
||||
import {
|
||||
QUICK_FILTERS, STATUS_LABEL, STATUS_TONE, useProjectsData,
|
||||
type UiCollectionRecord, type UiProject, type UiProjectStatus,
|
||||
} from "@/lib/projects-api";
|
||||
|
||||
const money = (n: number) => `$${Math.round(n).toLocaleString()}`;
|
||||
// The collections ledger shows cents (matches invoice-style amounts); the rest of the page rounds to whole dollars.
|
||||
const moneyExact = (n: number) => `$${n.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`;
|
||||
|
||||
const COLLECTION_STATUS_LABEL: Record<UiCollectionRecord["status"], string> = { paid: "Paid", pending: "Pending", overdue: "Overdue" };
|
||||
const COLLECTION_STATUS_TONE: Record<UiCollectionRecord["status"], string> = { paid: "green", pending: "orange", overdue: "red" };
|
||||
|
||||
export function Projects() {
|
||||
const data = useProjectsData();
|
||||
const { projects, live } = data;
|
||||
|
||||
const [tab, setTab] = useState<"construction" | "pipeline">("construction");
|
||||
const [query, setQuery] = useState("");
|
||||
const [statusFilter, setStatusFilter] = useState<"all" | UiProjectStatus>("all");
|
||||
const [viewProject, setViewProject] = useState<UiProject | null>(null);
|
||||
|
||||
const construction = useMemo(() => projects.filter((p) => !p.isLead), [projects]);
|
||||
const pipeline = useMemo(() => projects.filter((p) => p.isLead), [projects]);
|
||||
const budgetTotal = useMemo(() => construction.reduce((s, p) => s + (p.value ?? 0), 0), [construction]);
|
||||
|
||||
const list = tab === "construction" ? construction : pipeline;
|
||||
const filtered = useMemo(() => {
|
||||
const q = query.trim().toLowerCase();
|
||||
return list.filter((p) => {
|
||||
const matchesStatus = tab === "pipeline" || statusFilter === "all" || p.status === statusFilter;
|
||||
const matchesQ = !q
|
||||
|| p.name.toLowerCase().includes(q)
|
||||
|| (p.address ?? "").toLowerCase().includes(q)
|
||||
|| (p.jobType ?? "").toLowerCase().includes(q)
|
||||
|| p.agent.toLowerCase().includes(q);
|
||||
return matchesStatus && matchesQ;
|
||||
});
|
||||
}, [list, statusFilter, query, tab]);
|
||||
|
||||
// Mock construction (richest): Lead | Status | Stage | Job Type | Agent | Progress | Health | ⋯
|
||||
// Mock pipeline: Lead | Job Type | Stage | Agent | Created | ⋯
|
||||
// Live (either tab, leaner — only fields be-crm actually stores): Lead | Status | Owner | Value | Due date | ⋯
|
||||
const template = live
|
||||
? "minmax(220px,2.3fr) 110px 160px 120px 130px 48px"
|
||||
: tab === "construction"
|
||||
? "minmax(220px,2.2fr) 104px 130px 150px 130px 130px 76px 48px"
|
||||
: "minmax(220px,2.2fr) 150px 140px 130px 120px 48px";
|
||||
|
||||
return (
|
||||
<div className="view proj">
|
||||
<PageHead
|
||||
title="Projects"
|
||||
subtitle={`${construction.length} construction · ${pipeline.length} pipeline leads · ${money(budgetTotal)} budget`}
|
||||
/>
|
||||
|
||||
{data.error && <div className="card proj-empty" style={{ borderColor: "var(--red, #ef4444)" }}><p>Couldn't load projects: {data.error}</p></div>}
|
||||
|
||||
<div className="tm-toolbar proj-toolbar">
|
||||
<div className="tm-tabs" role="tablist">
|
||||
<button role="tab" aria-selected={tab === "construction"} className={`tm-tab ${tab === "construction" ? "active" : ""}`} onClick={() => setTab("construction")}>
|
||||
<Icon name="owners" size={16} /> <span>Construction</span>
|
||||
<span className="tm-tab-badge">{construction.length}</span>
|
||||
</button>
|
||||
<button role="tab" aria-selected={tab === "pipeline"} className={`tm-tab ${tab === "pipeline" ? "active" : ""}`} onClick={() => setTab("pipeline")}>
|
||||
<Icon name="pipeline" size={16} /> <span>Pipeline Leads</span>
|
||||
<span className="tm-tab-badge">{pipeline.length}</span>
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div className="tm-search">
|
||||
<Icon name="search" size={16} />
|
||||
<input className="ds-input flush" placeholder="Search leads by name, address, job type, agent…" value={query} onChange={(e) => setQuery(e.target.value)} />
|
||||
{query && <button className="tm-search-x" aria-label="Clear" onClick={() => setQuery("")}><Icon name="x" size={14} /></button>}
|
||||
</div>
|
||||
|
||||
{tab === "construction" && (
|
||||
<div className="tm-chips">
|
||||
<button className={`tm-chip ${statusFilter === "all" ? "on" : ""}`} onClick={() => setStatusFilter("all")}>
|
||||
All <i>{construction.length}</i>
|
||||
</button>
|
||||
{QUICK_FILTERS.map((s) => (
|
||||
<button key={s} className={`tm-chip ${statusFilter === s ? "on" : ""}`} style={{ ["--rc" as string]: `var(--${STATUS_TONE[s] === "muted" ? "faint" : STATUS_TONE[s]})` }} onClick={() => setStatusFilter(s)}>
|
||||
{STATUS_LABEL[s]} <i>{construction.filter((p) => p.status === s).length}</i>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{data.live && data.loading && projects.length === 0 ? (
|
||||
<div className="card proj-empty"><span className="tm-empty-ic"><Icon name="owners" size={24} /></span><p>Loading projects…</p></div>
|
||||
) : filtered.length === 0 ? (
|
||||
<div className="card proj-empty">
|
||||
<span className="tm-empty-ic"><Icon name="search" size={24} /></span>
|
||||
<p>No {tab === "construction" ? "projects" : "leads"} match your search.</p>
|
||||
<Btn variant="soft" size="sm" onClick={() => { setQuery(""); setStatusFilter("all"); }}>Clear filters</Btn>
|
||||
</div>
|
||||
) : (
|
||||
<div className="card card-pad-0 proj-table">
|
||||
<div className="proj-row proj-head" style={{ gridTemplateColumns: template }}>
|
||||
<span>Lead</span>
|
||||
{live ? (
|
||||
<><span>Status</span><span>Owner</span><span className="proj-c-num">Value</span><span>Due date</span></>
|
||||
) : tab === "construction" ? (
|
||||
<><span>Status</span><span>Stage</span><span>Job type</span><span>Agent</span><span>Progress</span><span className="proj-c-num">Health</span></>
|
||||
) : (
|
||||
<><span>Job type</span><span>Stage</span><span>Agent</span><span>Created</span></>
|
||||
)}
|
||||
<span className="proj-c-act" />
|
||||
</div>
|
||||
|
||||
{filtered.map((p) => (
|
||||
<div className="proj-row" key={p.id} style={{ gridTemplateColumns: template }}>
|
||||
<div className="proj-lead">
|
||||
<div className="proj-lead-name">{p.name}</div>
|
||||
{p.address && <div className="proj-lead-sub">{p.address}</div>}
|
||||
</div>
|
||||
|
||||
{live ? (
|
||||
<>
|
||||
<Pill tone={STATUS_TONE[p.status]}>{STATUS_LABEL[p.status].toUpperCase()}</Pill>
|
||||
<span className="proj-text">{p.agent}</span>
|
||||
<span className="proj-c-num">{p.value != null ? money(p.value) : <span className="tm-dash">—</span>}</span>
|
||||
<span className="proj-text">{p.dueDate ? new Date(p.dueDate).toLocaleDateString(undefined, { day: "numeric", month: "short", year: "numeric" }) : <span className="tm-dash">—</span>}</span>
|
||||
</>
|
||||
) : tab === "construction" ? (
|
||||
<>
|
||||
<Pill tone={STATUS_TONE[p.status]}>{STATUS_LABEL[p.status].toUpperCase()}</Pill>
|
||||
<Pill tone="blue">{p.stage}</Pill>
|
||||
<span className="proj-text">{p.jobType}</span>
|
||||
<span className="proj-text">{p.agent}</span>
|
||||
<div className="proj-progress" title={`${p.progress}%`}>
|
||||
<span className="proj-progress-track"><span className="proj-progress-fill" style={{ width: `${p.progress ?? 0}%` }} /></span>
|
||||
<b>{p.progress}%</b>
|
||||
</div>
|
||||
<span className="proj-c-num proj-health">{p.health}</span>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<span className="proj-text">{p.jobType}</span>
|
||||
<Pill tone="blue">{p.stage}</Pill>
|
||||
<span className="proj-text">{p.agent}</span>
|
||||
<span className="proj-text">{p.createdAgo}</span>
|
||||
</>
|
||||
)}
|
||||
|
||||
<div className="proj-c-act">
|
||||
<button className="ds-iconbtn" aria-label={`View collections for ${p.name}`} onClick={() => setViewProject(p)}><Icon name="eye" size={17} /></button>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="proj-foot">
|
||||
<span>Showing {filtered.length} of {list.length} {tab === "construction" ? "projects" : "leads"}</span>
|
||||
{tab === "construction" && <b>{money(budgetTotal)} total</b>}
|
||||
</div>
|
||||
|
||||
<CollectedDetailsModal project={viewProject} onClose={() => setViewProject(null)} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/* ---------------------------------------------------------- */
|
||||
/* Collected details modal — payment ledger for one project */
|
||||
/* ---------------------------------------------------------- */
|
||||
|
||||
function CollectedDetailsModal({ project, onClose }: { project: UiProject | null; onClose: () => void }) {
|
||||
const [query, setQuery] = useState("");
|
||||
const records = project?.collections ?? [];
|
||||
const total = useMemo(() => records.reduce((s, r) => s + r.amount, 0), [records]);
|
||||
if (!project) return null;
|
||||
|
||||
const q = query.trim().toLowerCase();
|
||||
const filtered = records.filter((r) =>
|
||||
!q || r.name.toLowerCase().includes(q) || r.referenceId.toLowerCase().includes(q) || r.type.toLowerCase().includes(q));
|
||||
const netTotal = filtered.reduce((s, r) => s + r.amount, 0);
|
||||
const projectName = project.name;
|
||||
|
||||
function downloadCsv() {
|
||||
const header = ["Name/Project", "Reference ID", "Date", "Type", "Status", "Amount"];
|
||||
const rows = filtered.map((r) => [r.name, r.referenceId, r.date, r.type, COLLECTION_STATUS_LABEL[r.status], r.amount.toFixed(2)]);
|
||||
const csv = [header, ...rows].map((row) => row.map((c) => `"${String(c).replace(/"/g, '""')}"`).join(",")).join("\n");
|
||||
const blob = new Blob([csv], { type: "text/csv;charset=utf-8;" });
|
||||
const url = URL.createObjectURL(blob);
|
||||
const a = document.createElement("a");
|
||||
a.href = url;
|
||||
a.download = `${projectName.replace(/\s+/g, "-").toLowerCase()}-collections.csv`;
|
||||
a.click();
|
||||
URL.revokeObjectURL(url);
|
||||
}
|
||||
|
||||
return (
|
||||
<Modal
|
||||
open={!!project}
|
||||
onClose={onClose}
|
||||
title="Total Collected Details"
|
||||
subtitle={<>Total: <b>{moneyExact(total)}</b></>}
|
||||
size="xl"
|
||||
headerExtra={records.length > 0 && (
|
||||
<button className="ds-iconbtn" aria-label="Download CSV" onClick={downloadCsv}><Icon name="download" size={18} /></button>
|
||||
)}
|
||||
>
|
||||
{project.collections === null ? (
|
||||
<div className="tm-empty"><span className="tm-empty-ic"><Icon name="card" size={24} /></span><p>Collections aren't available yet for live projects — this needs a billing module in be-crm.</p></div>
|
||||
) : records.length === 0 ? (
|
||||
<div className="tm-empty"><span className="tm-empty-ic"><Icon name="card" size={24} /></span><p>No payments collected yet for {project.name}.</p></div>
|
||||
) : (
|
||||
<>
|
||||
<div className="tm-search proj-cd-search">
|
||||
<Icon name="search" size={16} />
|
||||
<input className="ds-input flush" placeholder="Search leads by name, address, job type, agent…" value={query} onChange={(e) => setQuery(e.target.value)} />
|
||||
{query && <button className="tm-search-x" aria-label="Clear" onClick={() => setQuery("")}><Icon name="x" size={14} /></button>}
|
||||
</div>
|
||||
|
||||
<div className="card card-pad-0 proj-table proj-cd-table">
|
||||
<div className="proj-row proj-head" style={{ gridTemplateColumns: "minmax(180px,2fr) 140px 100px 170px 100px 120px" }}>
|
||||
<span>Name / Project</span><span>Reference ID</span><span>Date</span><span>Type</span><span>Status</span><span className="proj-c-num">Amount</span>
|
||||
</div>
|
||||
{filtered.map((r) => (
|
||||
<div className="proj-row" key={r.id} style={{ gridTemplateColumns: "minmax(180px,2fr) 140px 100px 170px 100px 120px" }}>
|
||||
<div className="proj-lead">
|
||||
<div className="proj-lead-name">{r.name}</div>
|
||||
<div className="proj-lead-sub">{r.address}</div>
|
||||
</div>
|
||||
<span className="proj-text">{r.referenceId}</span>
|
||||
<span className="proj-text">{r.date}</span>
|
||||
<span className="proj-text">{r.type}</span>
|
||||
<Pill tone={COLLECTION_STATUS_TONE[r.status]}>{COLLECTION_STATUS_LABEL[r.status].toUpperCase()}</Pill>
|
||||
<span className="proj-c-num">{moneyExact(r.amount)}</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<div className="proj-foot">
|
||||
<span>Showing {filtered.length} record{filtered.length === 1 ? "" : "s"}</span>
|
||||
<b>Net Total: {moneyExact(netTotal)}</b>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,136 @@
|
||||
"use client";
|
||||
|
||||
// ============================================================
|
||||
// Org Settings → Integrations. Today: SMS (Twilio) — a tenant
|
||||
// brings its OWN Twilio credentials, which be-crm seals in IIOS
|
||||
// (per-scope) and resolves at send time. The auth token is
|
||||
// write-only: sealed in IIOS, never read back, so status shows
|
||||
// only masked hints (from-number + SID last-4). Email (SMTP) is
|
||||
// the next provider on the same generic credential registry.
|
||||
// ============================================================
|
||||
|
||||
import { useState } from "react";
|
||||
import { Btn, Field, Icon, PageHead, Pill, useToast } from "./ui";
|
||||
import { useSmsSettings } from "@/lib/sms-settings-api";
|
||||
|
||||
const SID_RE = /^AC[0-9a-fA-F]{32}$/;
|
||||
const E164_RE = /^\+[1-9]\d{6,14}$/;
|
||||
|
||||
export function Settings() {
|
||||
return (
|
||||
<div className="view">
|
||||
<PageHead
|
||||
eyebrow="Configuration"
|
||||
title="Org Settings"
|
||||
subtitle="Integrations and workspace configuration"
|
||||
icon="settings"
|
||||
/>
|
||||
<section className="settings-section">
|
||||
<h3 className="settings-section-title">Integrations</h3>
|
||||
<div className="settings-grid">
|
||||
<TwilioCard />
|
||||
<SmtpComingSoon />
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function TwilioCard() {
|
||||
const toast = useToast();
|
||||
const { status, loading, live, configure } = useSmsSettings();
|
||||
const [editing, setEditing] = useState(false);
|
||||
const [accountSid, setAccountSid] = useState("");
|
||||
const [authToken, setAuthToken] = useState("");
|
||||
const [fromNumber, setFromNumber] = useState("");
|
||||
const [errors, setErrors] = useState<{ accountSid?: string; authToken?: string; fromNumber?: string }>({});
|
||||
const [saving, setSaving] = useState(false);
|
||||
|
||||
const showForm = editing || (!loading && !status.configured);
|
||||
|
||||
function validate(): boolean {
|
||||
const e: typeof errors = {};
|
||||
if (!SID_RE.test(accountSid.trim())) e.accountSid = "Must be a Twilio Account SID (AC + 32 hex chars).";
|
||||
if (!authToken.trim()) e.authToken = "Auth token is required.";
|
||||
if (!E164_RE.test(fromNumber.trim())) e.fromNumber = "Must be E.164, e.g. +15551234567.";
|
||||
setErrors(e);
|
||||
return Object.keys(e).length === 0;
|
||||
}
|
||||
|
||||
async function save() {
|
||||
if (!validate()) return;
|
||||
setSaving(true);
|
||||
try {
|
||||
await configure({ accountSid: accountSid.trim(), authToken: authToken.trim(), fromNumber: fromNumber.trim() });
|
||||
toast.push({ tone: "success", title: "Twilio connected", desc: "Your SMS credentials are saved and encrypted." });
|
||||
setAccountSid(""); setAuthToken(""); setFromNumber(""); setErrors({}); setEditing(false);
|
||||
} catch (err) {
|
||||
toast.push({ tone: "error", title: "Couldn't save credentials", desc: (err as Error).message });
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="settings-card">
|
||||
<div className="settings-card-head">
|
||||
<span className="settings-card-ic" aria-hidden="true"><Icon name="send" size={20} /></span>
|
||||
<div className="settings-card-titles">
|
||||
<div className="settings-card-name">
|
||||
SMS <span className="settings-card-sub">· Twilio</span>
|
||||
</div>
|
||||
<div className="settings-card-desc">Send texts from your own Twilio number.</div>
|
||||
</div>
|
||||
{status.configured
|
||||
? <Pill tone="green">Connected</Pill>
|
||||
: <Pill tone="muted">Not connected</Pill>}
|
||||
</div>
|
||||
|
||||
{status.configured && !editing ? (
|
||||
<div className="settings-card-body">
|
||||
<dl className="settings-kv">
|
||||
<div><dt>From number</dt><dd>{status.fromNumber ?? "—"}</dd></div>
|
||||
<div><dt>Account SID</dt><dd>{status.sidLast4 ? `AC ···· ${status.sidLast4}` : "—"}</dd></div>
|
||||
<div><dt>Status</dt><dd>{status.enabled ? "Active" : "Disabled"}</dd></div>
|
||||
</dl>
|
||||
<Btn variant="outline" icon="settings" onClick={() => setEditing(true)}>Update credentials</Btn>
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{showForm ? (
|
||||
<div className="settings-card-body">
|
||||
<Field label="Account SID" required error={errors.accountSid} hint="Twilio Console → Account Info.">
|
||||
<input className="ds-input" value={accountSid} onChange={(e) => setAccountSid(e.target.value)} placeholder="ACxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" autoComplete="off" />
|
||||
</Field>
|
||||
<Field label="Auth Token" required error={errors.authToken} hint="Encrypted on save and never shown again.">
|
||||
<input className="ds-input" type="password" value={authToken} onChange={(e) => setAuthToken(e.target.value)} placeholder="••••••••••••••••••••••••••••••••" autoComplete="off" />
|
||||
</Field>
|
||||
<Field label="From number" required error={errors.fromNumber} hint="A Twilio number in E.164 format.">
|
||||
<input className="ds-input" value={fromNumber} onChange={(e) => setFromNumber(e.target.value)} placeholder="+15551234567" autoComplete="off" />
|
||||
</Field>
|
||||
<div className="settings-card-actions">
|
||||
<Btn icon="check-circle" onClick={save} disabled={saving}>{saving ? "Saving…" : status.configured ? "Update" : "Connect Twilio"}</Btn>
|
||||
{status.configured ? <Btn variant="ghost" onClick={() => { setEditing(false); setErrors({}); }}>Cancel</Btn> : null}
|
||||
</div>
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{!live ? <div className="settings-card-note">Demo mode — credentials are stored locally and not sent to Twilio.</div> : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function SmtpComingSoon() {
|
||||
return (
|
||||
<div className="settings-card is-soon">
|
||||
<div className="settings-card-head">
|
||||
<span className="settings-card-ic" aria-hidden="true"><Icon name="mail" size={20} /></span>
|
||||
<div className="settings-card-titles">
|
||||
<div className="settings-card-name">Email <span className="settings-card-sub">· SMTP</span></div>
|
||||
<div className="settings-card-desc">Bring your own SMTP server for outbound email.</div>
|
||||
</div>
|
||||
<Pill tone="muted">Coming soon</Pill>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -33,7 +33,7 @@ export const NAV_GROUPS: NavGroup[] = [
|
||||
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" },
|
||||
{ key: "inbox", label: "Inbox", icon: "bell", subtitle: "Mentions, messages, alerts and mail — all in one" },
|
||||
],
|
||||
},
|
||||
{
|
||||
@@ -86,6 +86,7 @@ const NAV_PERMISSION: Record<string, string | undefined> = {
|
||||
leads: "leads.manage",
|
||||
verify: "leads.manage",
|
||||
pipeline: "pipeline.manage",
|
||||
projects: "pipeline.manage",
|
||||
estimates: "estimates.create",
|
||||
procanvas: "estimates.create",
|
||||
dispatch: "dispatch.manage",
|
||||
|
||||
@@ -14,6 +14,7 @@ import {
|
||||
createContext, useCallback, useContext, useEffect, useId,
|
||||
useRef, useState, type ReactNode,
|
||||
} from "react";
|
||||
import { createPortal } from "react-dom";
|
||||
import {
|
||||
MessageCircle, Ticket, Phone, Mail, BookOpen, Rocket, Shield, ShieldCheck,
|
||||
Lock, CreditCard, User, Bell, Eye, EyeOff, Camera, Upload, Plus, Star, Send,
|
||||
@@ -23,7 +24,7 @@ import {
|
||||
LayoutDashboard, Building2, FolderKanban, UserPlus, BadgeCheck, Filter,
|
||||
Truck, CloudLightning, Map as MapIcon, PenTool, Calculator, CalendarDays,
|
||||
Trophy, ListChecks, Users, Settings, Sparkles, MoreHorizontal,
|
||||
UsersRound, type LucideIcon,
|
||||
UsersRound, Download, type LucideIcon,
|
||||
} from "lucide-react";
|
||||
|
||||
/* ---------------------------------------------------------- */
|
||||
@@ -48,7 +49,7 @@ const ICONS: Record<string, LucideIcon> = {
|
||||
storm: CloudLightning, territory: MapIcon, procanvas: PenTool,
|
||||
estimates: Calculator, schedule: CalendarDays, leaderboard: Trophy,
|
||||
subtasks: ListChecks, people: Users, settings: Settings, ai: Sparkles,
|
||||
team: UsersRound, dots: MoreHorizontal,
|
||||
team: UsersRound, dots: MoreHorizontal, download: Download,
|
||||
};
|
||||
|
||||
export function Icon({ name, size = 18, className, strokeWidth = 2 }: { name: string; size?: number; className?: string; strokeWidth?: number }) {
|
||||
@@ -216,11 +217,16 @@ export function OtpField({ length = 6, value, onChange, autoFocus = true }: { le
|
||||
/* Modal */
|
||||
/* ---------------------------------------------------------- */
|
||||
|
||||
export function Modal({ open, onClose, title, subtitle, icon, children, footer, size = "md" }: {
|
||||
open: boolean; onClose: () => void; title: string; subtitle?: string; icon?: string;
|
||||
children: ReactNode; footer?: ReactNode; size?: "sm" | "md" | "lg";
|
||||
export function Modal({ open, onClose, title, subtitle, icon, children, footer, size = "md", headerExtra }: {
|
||||
open: boolean; onClose: () => void; title: string; subtitle?: ReactNode; icon?: string;
|
||||
children: ReactNode; footer?: ReactNode; size?: "sm" | "md" | "lg" | "xl"; headerExtra?: ReactNode;
|
||||
}) {
|
||||
const titleId = useId();
|
||||
// Portal the overlay up to `.dash-root` so its position:fixed anchors to the viewport,
|
||||
// not to a transformed/overflow panel ancestor (which would clip or offset the modal).
|
||||
const [host, setHost] = useState<Element | null>(null);
|
||||
const [mounted, setMounted] = useState(false);
|
||||
useEffect(() => { setHost(document.querySelector(".dash-root")); setMounted(true); }, []);
|
||||
useEffect(() => {
|
||||
if (!open) return;
|
||||
const onKey = (e: KeyboardEvent) => { if (e.key === "Escape") onClose(); };
|
||||
@@ -228,8 +234,8 @@ export function Modal({ open, onClose, title, subtitle, icon, children, footer,
|
||||
return () => document.removeEventListener("keydown", onKey);
|
||||
}, [open, onClose]);
|
||||
|
||||
if (!open) return null;
|
||||
return (
|
||||
if (!open || !mounted) return null;
|
||||
const overlay = (
|
||||
<div className="ds-modal-overlay" onMouseDown={onClose}>
|
||||
<div className={`ds-modal size-${size}`} role="dialog" aria-modal="true" aria-labelledby={titleId} onMouseDown={(e) => e.stopPropagation()}>
|
||||
<div className="ds-modal-head">
|
||||
@@ -240,13 +246,17 @@ export function Modal({ open, onClose, title, subtitle, icon, children, footer,
|
||||
{subtitle && <p>{subtitle}</p>}
|
||||
</div>
|
||||
</div>
|
||||
<div className="ds-modal-head-r">
|
||||
{headerExtra}
|
||||
<button className="ds-iconbtn" aria-label="Close" onClick={onClose}><Icon name="x" size={18} /></button>
|
||||
</div>
|
||||
</div>
|
||||
<div className="ds-modal-body">{children}</div>
|
||||
{footer && <div className="ds-modal-foot">{footer}</div>}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
return host ? createPortal(overlay, host) : overlay;
|
||||
}
|
||||
|
||||
/* ---------------------------------------------------------- */
|
||||
|
||||
@@ -0,0 +1,121 @@
|
||||
// The CRM's InboxAdapter — the SDK <Inbox> rendered over the be-crm data door
|
||||
// (crm.inbox.* + crm.mail.*). Folds mail threads into the unified inbox exactly as the old
|
||||
// inbox-api did; the CRM keeps auth/tenancy server-side.
|
||||
|
||||
import type {
|
||||
InboxAdapter,
|
||||
InboxItem,
|
||||
InboxState,
|
||||
MailAttachment,
|
||||
MailMessage,
|
||||
MailPerson,
|
||||
} from "@insignia/iios-messaging-ui";
|
||||
import type { DataDoor } from "./crm-messaging-adapter";
|
||||
|
||||
const MAX_ATTACHMENT_BYTES = 26 * 1024 * 1024; // matches IIOS's cap
|
||||
|
||||
// Some types (notably .md) have no OS-registered MIME, so the browser reports an empty file.type.
|
||||
const EXT_MIME: Record<string, string> = {
|
||||
md: "text/markdown", markdown: "text/markdown", html: "text/html", htm: "text/html", txt: "text/plain", csv: "text/csv",
|
||||
};
|
||||
function mimeForFile(file: File): string {
|
||||
if (file.type) return file.type;
|
||||
const ext = file.name.toLowerCase().split(".").pop() ?? "";
|
||||
return EXT_MIME[ext] ?? "application/octet-stream";
|
||||
}
|
||||
|
||||
interface InboxItemDTO {
|
||||
id: string; kind: string; state: InboxState; title: string; summary?: string; priority: string; threadId?: string; createdAt: string;
|
||||
}
|
||||
interface MailThreadDTO { threadId: string; subject: string | null; participants: string[]; unread: number; lastMessage?: string; lastAt?: string }
|
||||
interface MailMessageDTO {
|
||||
interactionId: string; actorId: string | null; kind: string; occurredAt: string;
|
||||
html: string | null; text: string | null;
|
||||
attachment: { contentRef: string; mimeType: string; sizeBytes: number; filename: string | null } | null;
|
||||
}
|
||||
interface DirectoryDTO { id: string; displayName: string; kind: "staff" | "customer" }
|
||||
|
||||
const escapeHtml = (s: string): string => s.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">");
|
||||
|
||||
export class CrmInboxAdapter implements InboxAdapter {
|
||||
constructor(private readonly sdk: DataDoor) {}
|
||||
|
||||
async listInbox(state?: InboxState): Promise<InboxItem[]> {
|
||||
const showMail = !state || state === "OPEN";
|
||||
const [items, mail] = await Promise.all([
|
||||
this.sdk.query<InboxItemDTO[]>("crm.inbox.list", state ? { state } : {}),
|
||||
showMail ? this.sdk.query<MailThreadDTO[]>("crm.mail.list", {}) : Promise.resolve([] as MailThreadDTO[]),
|
||||
]);
|
||||
const mailItems: InboxItem[] = mail.map((t) => ({
|
||||
id: `mail:${t.threadId}`,
|
||||
kind: "MAIL",
|
||||
state: "OPEN",
|
||||
title: t.subject || "(no subject)",
|
||||
...(t.lastMessage ? { summary: t.lastMessage } : {}),
|
||||
priority: t.unread > 0 ? "HIGH" : "LOW",
|
||||
threadId: t.threadId,
|
||||
createdAt: t.lastAt ?? "",
|
||||
}));
|
||||
return [...mailItems, ...items].sort((a, b) => (b.createdAt ?? "").localeCompare(a.createdAt ?? ""));
|
||||
}
|
||||
|
||||
async transition(id: string, state: InboxState): Promise<void> {
|
||||
await this.sdk.command("crm.inbox.transition", { id, state });
|
||||
}
|
||||
|
||||
async mailHistory(threadId: string): Promise<MailMessage[]> {
|
||||
const rows = await this.sdk.query<MailMessageDTO[]>("crm.mail.history", { threadId });
|
||||
return rows.map((m) => ({
|
||||
id: m.interactionId,
|
||||
actorId: m.actorId,
|
||||
kind: m.kind,
|
||||
at: m.occurredAt,
|
||||
html: m.html,
|
||||
text: m.text,
|
||||
attachment: m.attachment,
|
||||
}));
|
||||
}
|
||||
|
||||
async mailReply(threadId: string, content: string, attachment?: MailAttachment): Promise<void> {
|
||||
await this.sdk.command("crm.mail.reply", {
|
||||
threadId,
|
||||
content,
|
||||
...(attachment ? { attachment: { filename: attachment.filename ?? "attachment", contentRef: attachment.contentRef, mimeType: attachment.mimeType, sizeBytes: attachment.sizeBytes } } : {}),
|
||||
});
|
||||
}
|
||||
|
||||
async uploadAttachment(file: File): Promise<MailAttachment> {
|
||||
if (file.size > MAX_ATTACHMENT_BYTES) throw new Error("File is too large (max 25 MB).");
|
||||
const mime = mimeForFile(file);
|
||||
const { objectKey, uploadUrl } = await this.sdk.command<{ objectKey: string; uploadUrl: string }>("crm.media.presignUpload", { mime, sizeBytes: file.size });
|
||||
const res = await fetch(uploadUrl, { method: "PUT", body: file });
|
||||
if (!res.ok) throw new Error(`Upload failed (${res.status}).`);
|
||||
return { contentRef: objectKey, mimeType: mime, sizeBytes: file.size, filename: file.name };
|
||||
}
|
||||
|
||||
async downloadAttachment(attachment: MailAttachment): Promise<string> {
|
||||
const { url } = await this.sdk.command<{ url: string }>("crm.media.presignDownload", {
|
||||
contentRef: attachment.contentRef,
|
||||
...(attachment.mimeType ? { mime: attachment.mimeType } : {}),
|
||||
});
|
||||
return url;
|
||||
}
|
||||
|
||||
async directory(): Promise<MailPerson[]> {
|
||||
const rows = await this.sdk.query<DirectoryDTO[]>("crm.messenger.directory", { kind: "all", limit: 100 });
|
||||
return rows.map((d) => ({ id: d.id, name: d.displayName, kind: d.kind }));
|
||||
}
|
||||
|
||||
async composeInternal(recipientUserId: string, subject: string, text: string, attachments?: MailAttachment[]): Promise<void> {
|
||||
await this.sdk.command("crm.mail.internal", { recipientUserId, subject, text, html: `<p>${escapeHtml(text)}</p>`, ...attachmentsVar(attachments) });
|
||||
}
|
||||
|
||||
async composeExternal(target: string, subject: string, text: string, attachments?: MailAttachment[]): Promise<void> {
|
||||
await this.sdk.command("crm.mail.send", { target, subject, text, html: `<p>${escapeHtml(text)}</p>`, ...attachmentsVar(attachments) });
|
||||
}
|
||||
}
|
||||
|
||||
function attachmentsVar(attachments?: MailAttachment[]): { attachments?: Array<{ filename: string; contentRef: string; mimeType: string; sizeBytes: number }> } {
|
||||
if (!attachments || attachments.length === 0) return {};
|
||||
return { attachments: attachments.map((a) => ({ filename: a.filename ?? "attachment", contentRef: a.contentRef, mimeType: a.mimeType, sizeBytes: a.sizeBytes })) };
|
||||
}
|
||||
@@ -0,0 +1,303 @@
|
||||
// The CRM's implementation of the SDK's MessagingAdapter. HYBRID transport:
|
||||
// • BFF (appshell crm.messenger.*) for the conversation list, thread creation, and directory
|
||||
// — these need server-side tenancy/auth.
|
||||
// • IIOS MessageSocket (delegated token from crm.messenger.realtime) for everything live:
|
||||
// history+join, send, typing, read receipts, reactions.
|
||||
// When no socket is available (token failed / demo), it degrades to a 4s history poll.
|
||||
|
||||
import type {
|
||||
ChannelSummary,
|
||||
ChannelVisibility,
|
||||
Conversation,
|
||||
CreateChannelInput,
|
||||
Membership,
|
||||
Message,
|
||||
MessageEvent,
|
||||
MessagingAdapter,
|
||||
Person,
|
||||
Reaction,
|
||||
SendOpts,
|
||||
Unsubscribe,
|
||||
} from "@insignia/iios-messaging-ui";
|
||||
import type { MessageSocket, Message as KernelMessage } from "@insignia/iios-kernel-client";
|
||||
|
||||
/** The imperative appshell data door (useAppShell().sdk). Typed structurally, not to its class. */
|
||||
export interface DataDoor {
|
||||
query<T>(action: string, variables?: Record<string, unknown>): Promise<T>;
|
||||
command<T>(action: string, variables?: Record<string, unknown>): Promise<T>;
|
||||
}
|
||||
|
||||
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 POLL_MS = 4000;
|
||||
const REACTION = "reaction";
|
||||
|
||||
interface Poll { seen: Set<string>; primed: boolean; timer: ReturnType<typeof setInterval> | null }
|
||||
|
||||
export class CrmMessagingAdapter implements MessagingAdapter {
|
||||
private names: Map<string, string> | null = null;
|
||||
private readonly listeners = new Map<string, Set<(e: MessageEvent) => void>>();
|
||||
private readonly polls = new Map<string, Poll>();
|
||||
private readonly joined = new Set<string>();
|
||||
/** messageId → emoji → userSet, so a single annotation delta can be re-emitted as a full set. */
|
||||
private readonly reactions = new Map<string, Map<string, Set<string>>>();
|
||||
|
||||
/** Only present with a socket — the UI hides the reaction affordance without it. */
|
||||
react?: (threadId: string, messageId: string, emoji: string) => Promise<void>;
|
||||
|
||||
constructor(
|
||||
private readonly sdk: DataDoor,
|
||||
private readonly me: string,
|
||||
private readonly socket?: MessageSocket,
|
||||
) {
|
||||
if (socket) {
|
||||
socket.on("message", (m) => {
|
||||
this.ingestReactions(m);
|
||||
this.emit(m.threadId, { kind: "message", message: this.fromKernel(m) });
|
||||
});
|
||||
socket.on("typing", (e) => this.emit(e.threadId, { kind: "typing", userId: e.userId }));
|
||||
// Receipts carry no threadId → fan to all open threads; the UI filters by messageId.
|
||||
socket.on("receipt", (e) => this.broadcast({ kind: "receipt", messageId: e.interactionId, actorId: e.actorId }));
|
||||
socket.on("annotation", (e) => {
|
||||
if (e.type !== REACTION) return;
|
||||
this.setReactionUsers(e.interactionId, e.value, e.users);
|
||||
this.emit(e.threadId, { kind: "reaction", messageId: e.interactionId, reactions: this.reactionsOf(e.interactionId) });
|
||||
});
|
||||
this.react = async (threadId, messageId, emoji) => {
|
||||
await socket.react(threadId, messageId, emoji);
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
currentActorId(): string {
|
||||
return this.me;
|
||||
}
|
||||
|
||||
async listConversations(): Promise<Conversation[]> {
|
||||
const [convs, names] = await Promise.all([
|
||||
this.sdk.query<ConversationDTO[]>("crm.messenger.conversation.list", {}),
|
||||
this.directoryMap(),
|
||||
]);
|
||||
return convs.map((c) => this.toConversation(c, names));
|
||||
}
|
||||
|
||||
async openThread(p: { participantIds: string[]; membership?: Membership; subject?: string }): Promise<{ threadId: string }> {
|
||||
const res = await this.sdk.command<{ threadId: string }>("crm.messenger.conversation.open", {
|
||||
participantIds: p.participantIds,
|
||||
...(p.membership ? { membership: p.membership } : {}),
|
||||
...(p.subject ? { subject: p.subject } : {}),
|
||||
});
|
||||
return { threadId: res.threadId };
|
||||
}
|
||||
|
||||
async history(threadId: string): Promise<Message[]> {
|
||||
if (this.socket) {
|
||||
const res = await this.socket.openThread(threadId); // joins so live events flow
|
||||
this.joined.add(threadId);
|
||||
return res.history.map((m) => {
|
||||
this.ingestReactions(m);
|
||||
return this.fromKernel(m);
|
||||
});
|
||||
}
|
||||
const msgs = await this.sdk.query<MessageDTO[]>("crm.messenger.history", { threadId });
|
||||
return msgs.map((m) => this.fromDto(m));
|
||||
}
|
||||
|
||||
async send(threadId: string, content: string, opts?: SendOpts): Promise<Message> {
|
||||
if (this.socket) {
|
||||
const sendOpts = {
|
||||
...(opts?.parentInteractionId ? { parentInteractionId: opts.parentInteractionId } : {}),
|
||||
...(opts?.mentions && opts.mentions.length ? { mentions: opts.mentions } : {}),
|
||||
};
|
||||
const m = await this.socket.sendMessage(threadId, content, Object.keys(sendOpts).length ? sendOpts : undefined);
|
||||
return this.fromKernel(m);
|
||||
}
|
||||
const m = await this.sdk.command<MessageDTO>("crm.messenger.send", { threadId, content });
|
||||
const msg = this.fromDto(m);
|
||||
this.polls.get(threadId)?.seen.add(msg.id);
|
||||
return msg;
|
||||
}
|
||||
|
||||
subscribe(threadId: string, cb: (e: MessageEvent) => void): Unsubscribe {
|
||||
if (!this.listeners.has(threadId)) this.listeners.set(threadId, new Set());
|
||||
this.listeners.get(threadId)!.add(cb);
|
||||
|
||||
if (this.socket) {
|
||||
if (!this.joined.has(threadId)) {
|
||||
this.joined.add(threadId);
|
||||
void this.socket.openThread(threadId).catch(() => this.joined.delete(threadId));
|
||||
}
|
||||
} else {
|
||||
this.startPoll(threadId);
|
||||
}
|
||||
|
||||
return () => {
|
||||
const set = this.listeners.get(threadId);
|
||||
set?.delete(cb);
|
||||
if (set && set.size === 0) {
|
||||
this.listeners.delete(threadId);
|
||||
const poll = this.polls.get(threadId);
|
||||
if (poll?.timer) clearInterval(poll.timer);
|
||||
this.polls.delete(threadId);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
sendTyping(threadId: string): void {
|
||||
this.socket?.typing(threadId);
|
||||
}
|
||||
|
||||
async markRead(threadId: string, messageId: string): Promise<void> {
|
||||
if (this.socket) await this.socket.markRead(threadId, messageId);
|
||||
}
|
||||
|
||||
// ── channels + members (BFF, except join which is a governed socket self-join) ──
|
||||
async browseChannels(): Promise<ChannelSummary[]> {
|
||||
const rows = await this.sdk.query<Array<{ threadId: string; name: string; topic: string | null; visibility: string; memberCount: number; joined: boolean }>>(
|
||||
"crm.messenger.channel.browse",
|
||||
{},
|
||||
);
|
||||
return rows.map((c) => ({
|
||||
threadId: c.threadId,
|
||||
name: c.name,
|
||||
topic: c.topic,
|
||||
visibility: (c.visibility === "private" ? "private" : "public") as ChannelVisibility,
|
||||
memberCount: c.memberCount,
|
||||
joined: c.joined,
|
||||
}));
|
||||
}
|
||||
|
||||
async createChannel(input: CreateChannelInput): Promise<{ threadId: string }> {
|
||||
return this.sdk.command<{ threadId: string }>("crm.messenger.channel.create", {
|
||||
name: input.name,
|
||||
...(input.topic ? { topic: input.topic } : {}),
|
||||
visibility: input.visibility,
|
||||
});
|
||||
}
|
||||
|
||||
async joinChannel(threadId: string): Promise<void> {
|
||||
// Governed public self-join over the socket (the BFF has no join verb; OPA enforces it).
|
||||
if (!this.socket) throw new Error("joining a channel needs a live connection");
|
||||
await this.socket.openThread(threadId);
|
||||
this.joined.add(threadId);
|
||||
}
|
||||
|
||||
async leaveChannel(threadId: string): Promise<void> {
|
||||
await this.sdk.command("crm.messenger.channel.leave", { threadId });
|
||||
}
|
||||
|
||||
async listMembers(threadId: string): Promise<Person[]> {
|
||||
const rows = await this.sdk.query<Array<{ userId: string; displayName: string; role: string }>>("crm.messenger.members", { threadId });
|
||||
return rows.map((r) => ({ id: r.userId, name: r.displayName, kind: "staff" as const }));
|
||||
}
|
||||
|
||||
// ── polling fallback (no socket) ───────────────────────────────
|
||||
private startPoll(threadId: string): void {
|
||||
if (this.polls.has(threadId)) return;
|
||||
const poll: Poll = { seen: new Set(), primed: false, timer: null };
|
||||
this.polls.set(threadId, poll);
|
||||
const tick = async (): Promise<void> => {
|
||||
if (!this.polls.has(threadId)) return;
|
||||
try {
|
||||
const msgs = await this.sdk.query<MessageDTO[]>("crm.messenger.history", { threadId });
|
||||
for (const m of msgs) {
|
||||
if (poll.seen.has(m.interactionId)) continue;
|
||||
poll.seen.add(m.interactionId);
|
||||
if (poll.primed) this.emit(threadId, { kind: "message", message: this.fromDto(m) });
|
||||
}
|
||||
poll.primed = true;
|
||||
} catch {
|
||||
/* transient — retry next tick */
|
||||
}
|
||||
};
|
||||
void tick();
|
||||
poll.timer = setInterval(tick, POLL_MS);
|
||||
}
|
||||
|
||||
/** The org directory — people you can start a DM/group with. Drives the "New message" picker. */
|
||||
async directory(): Promise<Person[]> {
|
||||
const dir = await this.sdk.query<DirectoryDTO[]>("crm.messenger.directory", { kind: "all", limit: 100 });
|
||||
return dir.map((d) => ({ id: d.id, name: d.displayName, kind: d.kind }));
|
||||
}
|
||||
|
||||
// ── mapping ────────────────────────────────────────────────────
|
||||
private async directoryMap(): Promise<Map<string, string>> {
|
||||
if (!this.names) {
|
||||
this.names = new Map((await this.directory()).map((p) => [p.id, p.name]));
|
||||
}
|
||||
return this.names;
|
||||
}
|
||||
|
||||
private toConversation(c: ConversationDTO, names: Map<string, string>): Conversation {
|
||||
const others = c.participants.filter((p) => p !== this.me);
|
||||
const title = c.subject?.trim() || others.map((id) => names.get(id) ?? id).join(", ") || "Conversation";
|
||||
return {
|
||||
threadId: c.threadId,
|
||||
title,
|
||||
subject: c.subject,
|
||||
membership: c.membership,
|
||||
participants: c.participants,
|
||||
unread: c.unread,
|
||||
...(c.lastMessage ? { lastMessage: c.lastMessage } : {}),
|
||||
...(c.lastAt ? { lastAt: c.lastAt } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
/** Kernel Message (socket) → SDK Message. actorId = senderId (userId space), matching currentActorId. */
|
||||
private fromKernel(m: KernelMessage): Message {
|
||||
return {
|
||||
id: m.id,
|
||||
actorId: m.senderId ?? null,
|
||||
text: m.content ?? "",
|
||||
at: m.createdAt,
|
||||
parentInteractionId: m.parentInteractionId ?? null,
|
||||
reactions: this.reactionsOf(m.id),
|
||||
};
|
||||
}
|
||||
|
||||
/** BFF DTO (poll fallback) → SDK Message. Note: actorId is IIOS actor-id space here. */
|
||||
private fromDto(m: MessageDTO): Message {
|
||||
return { id: m.interactionId, actorId: m.actorId, text: m.text ?? "", at: m.occurredAt };
|
||||
}
|
||||
|
||||
// ── reaction state ─────────────────────────────────────────────
|
||||
private ingestReactions(m: KernelMessage): void {
|
||||
for (const a of m.annotations ?? []) {
|
||||
if (a.type === REACTION) this.setReactionUsers(m.id, a.value, a.users);
|
||||
}
|
||||
}
|
||||
|
||||
private setReactionUsers(messageId: string, emoji: string, users: string[]): void {
|
||||
let byEmoji = this.reactions.get(messageId);
|
||||
if (!byEmoji) {
|
||||
byEmoji = new Map();
|
||||
this.reactions.set(messageId, byEmoji);
|
||||
}
|
||||
if (users.length === 0) byEmoji.delete(emoji);
|
||||
else byEmoji.set(emoji, new Set(users));
|
||||
}
|
||||
|
||||
private reactionsOf(messageId: string): Reaction[] {
|
||||
const byEmoji = this.reactions.get(messageId);
|
||||
if (!byEmoji) return [];
|
||||
const out: Reaction[] = [];
|
||||
for (const [emoji, users] of byEmoji) {
|
||||
if (users.size > 0) out.push({ emoji, count: users.size, mine: users.has(this.me) });
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
// ── event fan-out ──────────────────────────────────────────────
|
||||
private emit(threadId: string, e: MessageEvent): void {
|
||||
this.listeners.get(threadId)?.forEach((cb) => cb(e));
|
||||
}
|
||||
|
||||
private broadcast(e: MessageEvent): void {
|
||||
for (const set of this.listeners.values()) set.forEach((cb) => cb(e));
|
||||
}
|
||||
}
|
||||
@@ -1,57 +0,0 @@
|
||||
"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: () => {} };
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
"use client";
|
||||
|
||||
// Media (attachment) helpers over the be-crm data door (crm.media.*). The browser transfers bytes
|
||||
// DIRECTLY to IIOS storage via the signed URLs — be-crm only mints them. Used by Messenger + Mail.
|
||||
|
||||
import { useCallback } from "react";
|
||||
import { useAppShell } from "@abe-kap/appshell-sdk/react";
|
||||
|
||||
export interface UploadedAttachment { contentRef: string; mimeType: string; sizeBytes: number; filename: string }
|
||||
|
||||
export const MAX_ATTACHMENT_BYTES = 26 * 1024 * 1024; // matches IIOS's cap
|
||||
|
||||
export function isImage(mime?: string | null): boolean {
|
||||
return !!mime && mime.startsWith("image/");
|
||||
}
|
||||
|
||||
// Some types (notably .md) have no OS-registered MIME, so the browser reports an empty file.type.
|
||||
// Fall back to the extension for the text types IIOS allows, else a generic binary.
|
||||
const EXT_MIME: Record<string, string> = {
|
||||
md: "text/markdown", markdown: "text/markdown",
|
||||
html: "text/html", htm: "text/html",
|
||||
txt: "text/plain", csv: "text/csv",
|
||||
};
|
||||
function mimeForFile(file: File): string {
|
||||
if (file.type) return file.type;
|
||||
const ext = file.name.toLowerCase().split(".").pop() ?? "";
|
||||
return EXT_MIME[ext] ?? "application/octet-stream";
|
||||
}
|
||||
|
||||
/** Upload a File → { contentRef, mimeType, sizeBytes, filename }. Throws on oversize / failure. */
|
||||
export function useUploadAttachment() {
|
||||
const { sdk } = useAppShell();
|
||||
return useCallback(async (file: File): Promise<UploadedAttachment> => {
|
||||
if (file.size > MAX_ATTACHMENT_BYTES) throw new Error("File is too large (max 25 MB).");
|
||||
const mime = mimeForFile(file);
|
||||
const { objectKey, uploadUrl } = (await sdk.command("crm.media.presignUpload", { mime, sizeBytes: file.size })) as { objectKey: string; uploadUrl: string };
|
||||
const res = await fetch(uploadUrl, { method: "PUT", body: file });
|
||||
if (!res.ok) throw new Error(`Upload failed (${res.status}).`);
|
||||
return { contentRef: objectKey, mimeType: mime, sizeBytes: file.size, filename: file.name };
|
||||
}, [sdk]);
|
||||
}
|
||||
|
||||
/** Mint a short-lived signed URL to display/download an attachment by its contentRef. */
|
||||
export function useDownloadUrl() {
|
||||
const { sdk } = useAppShell();
|
||||
return useCallback(async (contentRef: string, mime?: string): Promise<string> => {
|
||||
const { url } = (await sdk.command("crm.media.presignDownload", { contentRef, ...(mime ? { mime } : {}) })) as { url: string };
|
||||
return url;
|
||||
}, [sdk]);
|
||||
}
|
||||
@@ -1,371 +0,0 @@
|
||||
"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,
|
||||
};
|
||||
}
|
||||
@@ -1,144 +0,0 @@
|
||||
"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>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,201 @@
|
||||
"use client";
|
||||
|
||||
// Projects data layer. Serves EITHER the local mock (when the Shell isn't
|
||||
// configured — the polished demo keeps working) OR the live be-crm data door
|
||||
// (crm.project.*), behind one interface so the component is mode-agnostic.
|
||||
// Mirrors team-api.ts.
|
||||
//
|
||||
// Live contract (be-crm):
|
||||
// query crm.project.list { perPage } -> { items: ProjectDTO[], meta }
|
||||
// cmd crm.project.create { name, status?, value?, address?, dueDate?, ... }
|
||||
// cmd crm.project.setStatus { id, status }
|
||||
// cmd crm.project.remove { id }
|
||||
//
|
||||
// be-crm's Project model is generic (name/status/value/owner/address/dates) —
|
||||
// it has no stage, job type, progress or health score. Those are mock-only
|
||||
// fields (undefined in live mode); the Projects screen renders a leaner
|
||||
// column set when `live` is true.
|
||||
|
||||
import { useCallback, useMemo, useState } from "react";
|
||||
import { useAppShell, useQuery } from "@abe-kap/appshell-sdk/react";
|
||||
import { isShellConfigured } from "./appshell";
|
||||
import {
|
||||
collectionsFor, constructionLeads, pipelineLeads,
|
||||
type CollectionRecord, type ConstructionStatus,
|
||||
} from "@/components/dashboard/projects-data";
|
||||
|
||||
export type UiCollectionRecord = CollectionRecord;
|
||||
|
||||
/* ---- UI-facing shapes ---------------------------------------------------- */
|
||||
|
||||
// "lead" / "archived" round out the mock's four (active/complete/stuck/followup)
|
||||
// so every be-crm ProjectStatus has somewhere to map to.
|
||||
export type UiProjectStatus = ConstructionStatus | "lead" | "archived";
|
||||
|
||||
export interface UiProject {
|
||||
id: string;
|
||||
name: string;
|
||||
address: string | null;
|
||||
status: UiProjectStatus;
|
||||
stage: string | null; // mock only
|
||||
jobType: string | null; // mock only
|
||||
agent: string;
|
||||
progress: number | null; // mock only
|
||||
health: number | null; // mock only
|
||||
value: number | null; // dollars
|
||||
dueDate: string | null;
|
||||
createdAgo: string | null; // mock pipeline leads only
|
||||
collections: UiCollectionRecord[] | null; // mock only — no billing backend yet
|
||||
isLead: boolean; // true → "Pipeline Leads" tab
|
||||
}
|
||||
|
||||
export interface NewProjectInput {
|
||||
name: string;
|
||||
status: UiProjectStatus;
|
||||
value?: number; // dollars
|
||||
}
|
||||
|
||||
export interface ProjectsData {
|
||||
live: boolean;
|
||||
loading: boolean;
|
||||
error: string | null;
|
||||
projects: UiProject[];
|
||||
create: (p: NewProjectInput) => Promise<void>;
|
||||
setStatus: (id: string, status: UiProjectStatus) => Promise<void>;
|
||||
remove: (id: string) => Promise<void>;
|
||||
refetch: () => void;
|
||||
}
|
||||
|
||||
export const STATUS_LABEL: Record<UiProjectStatus, string> = {
|
||||
lead: "Lead", active: "Active", complete: "Complete", stuck: "Stuck", followup: "Follow-up", archived: "Archived",
|
||||
};
|
||||
export const STATUS_TONE: Record<UiProjectStatus, string> = {
|
||||
lead: "purple", active: "green", complete: "blue", stuck: "red", followup: "orange", archived: "muted",
|
||||
};
|
||||
// Quick-filter chips only cover the four "in-flight job" statuses (mirrors the design).
|
||||
export const QUICK_FILTERS: UiProjectStatus[] = ["active", "complete", "stuck", "followup"];
|
||||
|
||||
/* ---- mock → UI ------------------------------------------------------------ */
|
||||
|
||||
function mockConstruction(c: (typeof constructionLeads)[number], index: number): UiProject {
|
||||
return {
|
||||
id: c.id, name: c.name, address: c.address, status: c.status, stage: c.stage, jobType: c.jobType,
|
||||
agent: c.agent, progress: c.progress, health: c.health, value: c.value, dueDate: null, createdAgo: null,
|
||||
collections: collectionsFor(c, index), isLead: false,
|
||||
};
|
||||
}
|
||||
function mockPipeline(p: (typeof pipelineLeads)[number]): UiProject {
|
||||
return {
|
||||
id: p.id, name: p.name, address: p.address, status: "lead", stage: p.stage, jobType: p.jobType,
|
||||
agent: p.agent, progress: null, health: null, value: null, dueDate: null, createdAgo: p.createdAgo,
|
||||
collections: [], isLead: true,
|
||||
};
|
||||
}
|
||||
|
||||
/* ======================================================================== */
|
||||
/* Mock implementation (no Shell configured) */
|
||||
/* ======================================================================== */
|
||||
|
||||
let mockSeq = 1;
|
||||
|
||||
function useMockProjects(): ProjectsData {
|
||||
const [projects, setProjects] = useState<UiProject[]>(() => [
|
||||
...constructionLeads.map(mockConstruction),
|
||||
...pipelineLeads.map(mockPipeline),
|
||||
]);
|
||||
|
||||
const create = useCallback(async (p: NewProjectInput) => {
|
||||
const isLead = p.status === "lead";
|
||||
const next: UiProject = {
|
||||
id: `new_${mockSeq++}`, name: p.name, address: null, status: p.status,
|
||||
stage: isLead ? "New Inquiry" : "New Lead", jobType: null, agent: "Unassigned",
|
||||
progress: isLead ? null : 0, health: isLead ? null : 70, value: isLead ? null : (p.value ?? null),
|
||||
dueDate: null, createdAgo: isLead ? "Just now" : null, collections: [], isLead,
|
||||
};
|
||||
setProjects((l) => [next, ...l]);
|
||||
}, []);
|
||||
const setStatus = useCallback(async (id: string, status: UiProjectStatus) => {
|
||||
setProjects((l) => l.map((p) => (p.id === id ? { ...p, status, isLead: status === "lead" } : p)));
|
||||
}, []);
|
||||
const remove = useCallback(async (id: string) => { setProjects((l) => l.filter((p) => p.id !== id)); }, []);
|
||||
|
||||
return { live: false, loading: false, error: null, projects, create, setStatus, remove, refetch: () => {} };
|
||||
}
|
||||
|
||||
/* ======================================================================== */
|
||||
/* Live implementation (be-crm data door) */
|
||||
/* ======================================================================== */
|
||||
|
||||
type BackendStatus = "lead" | "active" | "on_hold" | "won" | "lost" | "archived";
|
||||
const BACKEND_TO_UI: Record<BackendStatus, UiProjectStatus> = {
|
||||
lead: "lead", active: "active", on_hold: "stuck", won: "complete", lost: "followup", archived: "archived",
|
||||
};
|
||||
const UI_TO_BACKEND: Record<UiProjectStatus, BackendStatus> = {
|
||||
lead: "lead", active: "active", stuck: "on_hold", complete: "won", followup: "lost", archived: "archived",
|
||||
};
|
||||
|
||||
interface ProjectAddressDTO { line1?: string | null; city?: string | null; state?: string | null; postalCode?: string | null }
|
||||
interface ProjectDTO {
|
||||
id: string; name: string; status: BackendStatus; ownerPrincipalId: string | null;
|
||||
value: number | null; address: ProjectAddressDTO | null; dueDate: string | null;
|
||||
}
|
||||
interface MemberRef { principalId: string; displayName: string | null; jobTitle: string | null }
|
||||
|
||||
const fmtAddress = (a: ProjectAddressDTO | null): string | null => {
|
||||
if (!a) return null;
|
||||
const cityState = [a.city, a.state].filter(Boolean).join(" ");
|
||||
const parts = [a.line1, [cityState, a.postalCode].filter(Boolean).join(" ")].filter(Boolean);
|
||||
return parts.length ? parts.join(", ") : null;
|
||||
};
|
||||
|
||||
function useLiveProjects(): ProjectsData {
|
||||
const { sdk } = useAppShell();
|
||||
const listQ = useQuery<{ items: ProjectDTO[] }>("crm.project.list", { perPage: 100 });
|
||||
// Resolve ownerPrincipalId → a real name for the "Owner" column (crm.project.list
|
||||
// only returns the raw id).
|
||||
const membersQ = useQuery<{ items: MemberRef[] }>("crm.team.member.search", { perPage: 100 });
|
||||
|
||||
const refetch = useCallback(() => { listQ.refetch(); membersQ.refetch(); }, [listQ, membersQ]);
|
||||
const cmd = useCallback(async (action: string, variables: Record<string, unknown>) => {
|
||||
await sdk.command(action, variables);
|
||||
refetch();
|
||||
}, [sdk, refetch]);
|
||||
|
||||
const nameByPrincipal = useMemo(() => {
|
||||
const m = new Map<string, string>();
|
||||
for (const it of membersQ.data?.items ?? []) if (it.principalId) m.set(it.principalId, it.displayName || it.jobTitle || it.principalId);
|
||||
return m;
|
||||
}, [membersQ.data]);
|
||||
|
||||
const projects: UiProject[] = useMemo(() => (listQ.data?.items ?? []).map((d) => ({
|
||||
id: d.id, name: d.name, address: fmtAddress(d.address),
|
||||
status: BACKEND_TO_UI[d.status] ?? "active",
|
||||
stage: null, jobType: null,
|
||||
agent: d.ownerPrincipalId ? (nameByPrincipal.get(d.ownerPrincipalId) ?? "Unassigned") : "Unassigned",
|
||||
progress: null, health: null,
|
||||
value: d.value != null ? d.value / 100 : null, // minor units → dollars
|
||||
dueDate: d.dueDate, createdAgo: null, collections: null, isLead: d.status === "lead",
|
||||
})), [listQ.data, nameByPrincipal]);
|
||||
|
||||
return {
|
||||
live: true,
|
||||
loading: listQ.loading || membersQ.loading,
|
||||
error: (listQ.error ?? membersQ.error)?.message ?? null,
|
||||
projects,
|
||||
create: (p) => cmd("crm.project.create", {
|
||||
name: p.name, status: UI_TO_BACKEND[p.status],
|
||||
...(p.value != null ? { value: Math.round(p.value * 100) } : {}),
|
||||
}),
|
||||
setStatus: (id, status) => cmd("crm.project.setStatus", { id, status: UI_TO_BACKEND[status] }),
|
||||
remove: (id) => cmd("crm.project.remove", { id }),
|
||||
refetch,
|
||||
};
|
||||
}
|
||||
|
||||
/* ---- public hook: pick the implementation at module-config time --------- */
|
||||
|
||||
const SHELL = isShellConfigured();
|
||||
|
||||
export function useProjectsData(): ProjectsData {
|
||||
return SHELL ? useLiveProjects() : useMockProjects();
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
"use client";
|
||||
|
||||
// SMS settings data layer. Serves EITHER the local mock (Shell not configured — the demo keeps
|
||||
// working) OR the live be-crm data door (crm.settings.sms.*), behind one interface.
|
||||
//
|
||||
// Live contract (be-crm → IIOS BYO credential store):
|
||||
// query crm.settings.sms.status {} -> { configured, enabled?, hints? }
|
||||
// cmd crm.settings.sms.configure { accountSid, authToken, fromNumber } -> masked status
|
||||
// The auth token is write-only: it is sealed in IIOS and NEVER returned — status carries only
|
||||
// non-secret hints (from-number + SID last-4).
|
||||
|
||||
import { useCallback, useState } from "react";
|
||||
import { useAppShell, useQuery } from "@abe-kap/appshell-sdk/react";
|
||||
import { isShellConfigured } from "./appshell";
|
||||
|
||||
export interface SmsCredentials { accountSid: string; authToken: string; fromNumber: string }
|
||||
|
||||
export interface SmsStatus {
|
||||
configured: boolean;
|
||||
enabled: boolean;
|
||||
fromNumber?: string;
|
||||
sidLast4?: string;
|
||||
}
|
||||
|
||||
export interface SmsSettingsData {
|
||||
live: boolean;
|
||||
loading: boolean;
|
||||
error: string | null;
|
||||
status: SmsStatus;
|
||||
configure: (input: SmsCredentials) => Promise<void>;
|
||||
refetch: () => void;
|
||||
}
|
||||
|
||||
interface StatusDTO { configured: boolean; enabled?: boolean; hints?: { fromNumber?: string; sidLast4?: string } }
|
||||
|
||||
function toStatus(dto?: StatusDTO | null): SmsStatus {
|
||||
return {
|
||||
configured: !!dto?.configured,
|
||||
enabled: dto?.enabled ?? false,
|
||||
fromNumber: dto?.hints?.fromNumber,
|
||||
sidLast4: dto?.hints?.sidLast4,
|
||||
};
|
||||
}
|
||||
|
||||
/* ---- Mock (demo mode) — stores only the non-secret hints, mirroring the masked live status ---- */
|
||||
function useMockSms(): SmsSettingsData {
|
||||
const [status, setStatus] = useState<SmsStatus>({ configured: false, enabled: false });
|
||||
const configure = useCallback(async ({ accountSid, fromNumber }: SmsCredentials) => {
|
||||
setStatus({ configured: true, enabled: true, fromNumber, sidLast4: accountSid.slice(-4) });
|
||||
}, []);
|
||||
return { live: false, loading: false, error: null, status, configure, refetch: () => {} };
|
||||
}
|
||||
|
||||
/* ---- Live (be-crm data door) ---- */
|
||||
function useLiveSms(): SmsSettingsData {
|
||||
const { sdk } = useAppShell();
|
||||
const q = useQuery<StatusDTO>("crm.settings.sms.status", {});
|
||||
const configure = useCallback(async (input: SmsCredentials) => {
|
||||
await sdk.command("crm.settings.sms.configure", { ...input });
|
||||
q.refetch();
|
||||
}, [sdk, q]);
|
||||
return {
|
||||
live: true,
|
||||
loading: q.loading,
|
||||
error: q.error ? String(q.error) : null,
|
||||
status: toStatus(q.data),
|
||||
configure,
|
||||
refetch: q.refetch,
|
||||
};
|
||||
}
|
||||
|
||||
const SHELL = isShellConfigured();
|
||||
|
||||
export function useSmsSettings(): SmsSettingsData {
|
||||
// SHELL is constant for the bundle's life (NEXT_PUBLIC_* is build-time), so the same hook path
|
||||
// runs every render — Rules-of-Hooks safe.
|
||||
return SHELL ? useLiveSms() : useMockSms();
|
||||
}
|
||||
Reference in New Issue
Block a user