40 Commits

Author SHA1 Message Date
maaz519 84cb5c66b5 Merge pull request 'Feat/adopt messaging sdk' (#31) from feat/adopt-messaging-sdk into goutamnextflow
Reviewed-on: #31
2026-07-22 19:06:48 +00:00
maaz519 1fc1a28d96 chore(deps): consume @insignia/iios-messaging-ui from the Gitea registry
The SDK is now published to git.lynkedup.cloud (@insignia scope); switch from the
local file: tarball to ^0.1.0 so prod/CI installs resolve it. Install auth uses
GITEA_TOKEN (read:package), same as @insignia/iios-kernel-client.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-23 00:29:18 +05:30
maaz519 0c7b3231ef chore(crm): pull SDK build with un-stretched compose/create buttons 2026-07-22 19:27:27 +05:30
maaz519 7a312a1ace feat(messenger): expose adapter directory() for DM/group picker + pull SDK build
CrmMessagingAdapter.directory() now returns the org people list (Person[]) for the
new 'New message' picker; internal name-resolution uses directoryMap(). The DM/group
create path rides the existing crm.messenger.conversation.open door (dedupe + group).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-22 19:23:57 +05:30
maaz519 eb7e1f7995 chore(crm): pull SDK build with body-portaled compose modal 2026-07-22 18:19:25 +05:30
maaz519 988b46f6e7 refactor(messaging): drop bespoke messenger/inbox/mail + wrapper page headers
Delete the now-dead pre-SDK stack (messenger/inbox/mail components + their
*-api libs + messenger-socket) — both tabs render the @insignia/iios-messaging-ui
SDK. Remove the redundant <PageHead> from the messenger/inbox SDK wrappers (the
Topbar already shows the title); the SDK itself renders no header.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-22 17:55:10 +05:30
maaz519 8e2fe315ce feat(settings): Org Settings → Integrations with BYO Twilio SMS
New Settings tab renders an Integrations section; the SMS (Twilio) card lets a
tenant admin connect their own Twilio account (Account SID / write-only Auth Token
/ E.164 from-number) via crm.settings.sms.configure, and shows the masked status
(from-number + SID last-4) from crm.settings.sms.status. Demo mode stores hints
locally. Email (SMTP) shown as the next provider on the same registry.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-22 17:43:53 +05:30
maaz519 462eb7f036 feat(inbox): wire mail attachments through CrmInboxAdapter
uploadAttachment presigns via crm.media.presignUpload + PUTs bytes to IIOS
storage; mailReply/composeInternal/composeExternal forward attachment refs
to crm.mail.reply/internal/send (server already supported them).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-22 01:05:14 +05:30
maaz519 facc50e82f feat(inbox): migrate CRM Inbox to @insignia/iios-messaging-ui SDK
Replace the bespoke in-CRM inbox with the SDK's <Inbox>, driven by a new
CrmInboxAdapter over the be-crm data door (crm.inbox.* + crm.mail.*).
Demo mode falls back to the SDK MockInboxAdapter. Maps --miu-* tokens for
.miu-inbox to the CRM theme.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-22 00:54:03 +05:30
maaz519 413f8d43b6 feat(messenger): channels + @mentions in the CRM SDK adapter
CrmMessagingAdapter now implements the full SDK contract:
- browseChannels/createChannel/leaveChannel over the be-crm channel door
  (crm.messenger.channel.*); joinChannel is a governed public self-join over
  the socket (openThread) — the BFF has no join verb, OPA enforces it
- listMembers over crm.messenger.members → drives @mention autocomplete
- send forwards mentions[] on the socket path (→ IIOS MENTION inbox items)

So the CRM messenger (rendered by the SDK) now gets sectioned Channels/DMs,
browse+join+create, and @mention autocomplete/highlight — no embedded code.
(SDK re-packed to the local tarball; publish for deploy.) tsc + next build green.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-21 23:35:41 +05:30
maaz519 cd8015ada8 feat(messenger): socket realtime in the CRM SDK adapter (parity with old messenger)
CrmMessagingAdapter is now hybrid: BFF for the conversation list, thread
creation, and directory (server-side tenancy); the IIOS MessageSocket
(delegated crm.messenger.realtime token) for everything live — history+join,
send, typing, read receipts, and reaction annotations. Falls back to the 4s
poll only when no socket is available.

- messenger-sdk useRealtimeSocket() opens the MessageSocket from the BFF token
  and passes it to the adapter (adapter rebuilds live once connected)
- socket path maps senderId (userId space) → actorId so 'mine'/seen work
  consistently, killing the actor-vs-user ambiguity in the poll fallback
- reaction annotations tracked per message and re-emitted as full sets

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-21 19:49:43 +05:30
maaz519 e70904a219 feat(messenger): CRM consumes @insignia/iios-messaging-ui instead of embedding
The messenger tab now renders the shared SDK's <Messenger>, not the bespoke
in-CRM implementation. The CRM only supplies transport + theme:

- CrmMessagingAdapter implements the SDK's MessagingAdapter over the be-crm
  data door (crm.messenger.conversation.list/open, history, send, directory);
  live updates via a 4s poll for now (socket realtime is a follow-up that
  reuses messenger-socket.tsx). Tenancy/auth stay server-side.
- messenger-sdk.tsx wires MessagingProvider + adapter (live = CrmMessagingAdapter,
  demo = the SDK MockAdapter), themed by mapping --miu-* tokens to the CRM
  design system.
- dashboard renders <MessengerSdk/>; the old messenger.tsx is left in place
  for rollback and will be deleted once this is proven live.

NOTE: the SDK is installed from a local tarball (file:) for verification since
it isn't published yet. For deploy: publish @insignia/iios-messaging-ui to the
registry and change the dep to a version range. transpilePackages covers ESM.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-21 19:37:47 +05:30
maaz519 036ed84255 feat(media): infer MIME from extension for empty-type uploads (.md, .html)
Browsers report an empty file.type for files with no OS-registered MIME (esp.
.md), which then went up as application/octet-stream and got rejected. Infer
the type from the extension for the text types IIOS allows (md/markdown/html/
htm/txt/csv) so those attachments upload.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-20 14:29:21 +05:30
maaz519 7bcd1a2a2d fix(inbox): reload mail content when switching items (+ filter refetch)
The appshell SDK useQuery only re-runs when the action changes, not the
variables — so switching mail items (same crm.mail.history action, new
threadId) never refetched and the reader kept the first thread's content
(only the subject, a direct prop, updated). Key MailReader by threadId to
remount it on switch (same pattern Messenger already uses for ThreadView).
Also force a refetch of crm.inbox.list when the filter changes, which hit
the same stale-variables bug.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-18 19:08:47 +05:30
maaz519 efd31d9293 fix(inbox): show sent mail in the unified inbox + fix compose attach button
- inbox merges crm.mail.list threads (kind MAIL) into crm.inbox.list items so
  sent/received mail actually appears in the one surface; mail shows in the
  Open view (it has no inbox work-item state) and opens in MailReader on click.
  Mail rows are read/reply only — no Done/Snooze/Archive (crm.inbox.transition
  doesn't apply to a mail thread).
- compose Attachments block was wrapped in <Field> (a <label>), so the label
  hijacked the Attach button's click via label→file-input association and the
  picker misfired. Use a plain div with the same field styling.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-18 18:53:33 +05:30
maaz519 a2a7e71f59 Merge pull request 'Feat/crm mail ui' (#30) from feat/crm-mail-ui into goutamnextflow
Reviewed-on: #30
2026-07-18 12:31:18 +00:00
maaz519 28907acf0e fix(dashboard): portal modals to .dash-root so they anchor to the viewport
A transformed/overflow panel ancestor was trapping the modal overlay's
position:fixed, so the modal rendered offset inside the messenger/inbox panel
and clipped (Group settings sat inside the thread pane; the compose modal's
top was cut at the panel edge). Portal the overlay up to .dash-root — above
those panels but still inside the scoped design-system CSS — so it centers on
the viewport and the 90vh cap works. Falls back to inline render if no
.dash-root is present.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-18 17:52:32 +05:30
maaz519 54add81187 fix(dashboard): keep tall modal footers on-screen
The modal body is a flex child with overflow-y:auto but had no min-height:0,
so it refused to shrink below content height and pushed the footer past the
90vh cap (visible on the tall Group settings modal — the Done button was
clipped). Add flex:1 1 auto + min-height:0 so the body scrolls and the
footer stays pinned.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-18 17:46:55 +05:30
maaz519 4ad0decad0 feat(messenger): group settings UI — rename, member list, add/remove
- messenger-api: useGroupSettings(threadId) — members query + rename/add/
  remove commands + isAdmin (from the member roles); live + mock
- messenger: a settings (gear) button on group thread headers opens a
  GroupSettingsModal — editable name (admin), member list with role pills,
  admin-gated remove, and add-from-directory search
- controls are admin-gated in the UI; IIOS/OPA re-enforces server-side

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-18 17:43:52 +05:30
maaz519 0b433790a5 feat(inbox): attachments in mail reader + composer
- mail-api: MailMessage carries attachment; reply + sendInternal +
  sendExternal accept uploaded attachments; mock updated
- mail.tsx: MailAttachmentView (inline image or file chip via signed URL),
  StagedChip; attach button in the reply footer and the New Message
  composer (multi-file, up to 10); text optional when a file is attached
- messenger: file-chip icon uses paperclip (was an unknown name)

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-18 17:31:22 +05:30
maaz519 7982c243c0 feat: attachments in Messenger — upload/preview images + files
- media-api: useUploadAttachment (presign → direct PUT to IIOS storage),
  useDownloadUrl (short-lived signed URL), isImage, 25MB cap
- socket + REST send now carry attachment {contentRef, mimeType, sizeBytes}
- composer: 📎 attach button, staged chip, send with attachment (text optional)
- MessageBubble renders AttachmentView (inline image or file chip), aligned
  to the message side; empty bubble suppressed for attachment-only messages

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-18 17:17:45 +05:30
maaz519 1490fa3460 fix(messenger): reply focuses composer + quoted message jumps to original
- Clicking Reply now focuses the composer input (was requiring a manual click).
- A quoted message is clickable → scrolls to the original and flashes it briefly
  (was inert). Message elements register refs by id for the jump.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-18 17:03:44 +05:30
maaz519 36f43d7d2a refactor(inbox): fold mail INTO the Inbox (one unified surface, no Mail tab)
The Inbox is the single communication surface — mentions, needs-reply, system
alerts, support updates AND the mail behind them, all in one list. Removed the
separate Mail tab.

- Inbox is now two-pane: the item list (crm.inbox.*) on the left; clicking an item
  tied to a thread opens its conversation (MailReader) on the right to read + reply.
  Non-threaded items (e.g. system alerts) show their detail. Item actions
  (Done/Snooze/Archive) work for every item.
- Compose new mail (in-app or email) from the Inbox header.
- mail.tsx trimmed to reusable MailReader + NewMailModal (no standalone tab);
  sidebar + dashboard reverted to no Mail entry.
- The existing work-item Inbox stays the notifier; this makes it the reader too.
  HTML bodies still render in a sandboxed iframe. tsc + next build clean.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-18 16:43:48 +05:30
maaz519 46aa7a767c feat(mail): dedicated Mail reader in the CRM
A Mail surface in the Communication group, distinct from Messenger (chat) and the
work-item Inbox: read app-to-app + email messages (subject + rendered body), reply,
and compose (in-app to a person, or external to an email).

- mail-api.ts: crm.mail.list/history/reply + compose (crm.mail.internal/send), reusing
  the messenger directory for the people picker. Live via the AppShell SDK; mock in demo mode.
- mail.tsx: thread list + reader + reply + New-mail composer. HTML bodies render inside a
  SANDBOXED iframe (no scripts) — safe against untrusted email HTML.
- Wired into the sidebar (Communication) + dashboard switch.

The existing work-item Inbox stays as the notifier (IIOS's projector already flags new
mail there); this is where you read it. tsc + next build clean.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-18 16:38:16 +05:30
maaz519 4b50d682e6 Merge pull request 'feat(messenger): reactions, replies, typing, seen ticks + UX fixes' (#29) from feat/messenger-ux into goutamnextflow
Reviewed-on: #29
2026-07-16 11:24:03 +00:00
maaz519 adb5a6bb7b feat(messenger): reactions, replies, typing, seen ticks + UX fixes
Wire the IIOS kernel client's existing realtime affordances into the
Messenger UI and fix three display issues.

- Bubble contrast: incoming bubbles used --panel-2, which equals --bg in
  the dark theme (both #060608) → invisible. Use --panel + a border.
- DM title: mapped all participants (incl. self → unknown-id fallback),
  producing "User d10888, Maaz Ahmed". Now shows the counterpart only.
- Live sidebar preview: lastMessage/time update on any inbound socket
  message, reconciled with a debounced conversation-list refetch.
- Typing indicator: throttled typing() send + auto-expiring "typing…" line.
- Read receipts: markRead() on open/new message; "Sent"/"Seen" under the
  last outgoing message. Receipt event carries no threadId, so it is a
  global stream filtered to my own messages by actor id.
- Reactions: emoji picker on hover, chips with counts, live via annotation.
- Reply/quote: parentInteractionId round-trips; quoted parent renders above
  the reply and in a composer quote bar.

Presence (online + last-seen) is intentionally not included — the kernel
has no presence receive-event yet; that needs an IIOS change + client release.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-16 16:52:29 +05:30
maaz519 2056592d51 Merge pull request 'feat: Messenger + Inbox on the AppShell data door + live IIOS socket' (#28) from feat/messenger-inbox into goutamnextflow
Reviewed-on: #28
2026-07-15 21:23:37 +00:00
maaz519 49b04e9710 feat: Messenger + Inbox on the AppShell data door + live IIOS socket
New "Communication" area in the dashboard, built on the existing appshell-sdk wiring
(useQuery/sdk.command) like Team, with the IIOS MessageSocket for live streaming.

- messenger-api.ts / inbox-api.ts: mock (demo) + live (crm.messenger.* / crm.inbox.*)
  behind one interface, switched by isShellConfigured().
- messenger-socket.tsx: MessengerSocketProvider — one IIOS MessageSocket per panel
  (openThread history + live on("message") + send). REST 4s poll is the automatic
  fallback when the socket isn't connected.
- messenger.tsx: conversation list ⇄ thread + composer + new-chat people picker
  (DM 1 person / group 2+); inbox.tsx: filterable feed with Done/Snooze/Archive.
- sidebar: Communication group (Messenger + Inbox, always-visible); dashboard: panel switch.
- .npmrc: add the @insignia Gitea registry for @insignia/iios-kernel-client.

Works on mock immediately; goes live once NEXT_PUBLIC_SUPABASE_URL + the BFF + be-crm are set.
tsc clean; next build passes.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-15 17:45:47 +05:30
tanweer919 e7c042fb1a Merge pull request 'refactor(email): move invite email to be-crm (AppShell)' (#27) from tanweer919/lynkeduppro-crm:feat/login-methods into goutamnextflow 2026-07-14 10:09:03 +00:00
tanweer919 9eb234935d refactor(email): remove frontend invite email; be-crm sends it now
Per AppShell, email delivery lives in the domain API. Delete the frontend
/api/email/invite route + invite-email template, and the team-management email
wiring. be-crm now emails invitees on create/resend. Copy link stays as a
fallback (invite token still returned in the pending-invite list).
2026-07-14 15:38:53 +05:30
tanweer919 fa538355ae Merge pull request 'fix(login): readable email-OTP send error' (#26) from tanweer919/lynkeduppro-crm:feat/login-methods into goutamnextflow 2026-07-13 15:14:24 +00:00
tanweer919 1a2043eaae fix(login): readable email-OTP send error instead of raw '{}'
gotrue can throw an error whose message is an unhelpful JSON blob (e.g. 500
'Error sending magic link email' when Supabase SMTP isn't configured). Show a
readable, actionable message instead of rendering the raw payload.
2026-07-13 20:44:05 +05:30
tanweer919 70831e189d Merge pull request 'fix(team): real member names + emails' (#25) from tanweer919/lynkeduppro-crm:feat/login-methods into goutamnextflow 2026-07-13 15:03:08 +00:00
tanweer919 eeded95940 fix(team): show member real name + email (no more principal UUIDs)
Use displayName + email now returned by be-crm member search (from CRM
registration). Falls back to the ACE for the current user, then job title —
never the raw principal id as the email.
2026-07-13 20:33:01 +05:30
tanweer919 0643b8c9b2 Merge pull request 'fix(invite): route register vs sign-in + prefill email (public lookup)' (#24) from tanweer919/lynkeduppro-crm:feat/login-methods into goutamnextflow 2026-07-13 14:55:33 +00:00
tanweer919 be4bd5f41d fix(invite): look up the invitation and route correctly (register vs sign in)
The invite link is token-only, so the landing page couldn't tell the invited
email or whether an account existed — it dumped everyone on an empty register
screen. Now it calls a public lookup (/api/invite/lookup → be-crm) and:
- first-time invitee → register with the email prefilled + locked;
- email already registered → sign in with the email prefilled;
- signed-in + registered → accept immediately; signed-in + no profile → onboarding.
Login now redeems the pending invite after sign-in (password/OTP/OAuth), so an
existing user's invite is accepted on login (not only when already logged in).
2026-07-13 20:25:25 +05:30
tanweer919 75417cb4f1 Merge pull request 'feat(email): invitation emails via Twilio (Vercel route)' (#23) from tanweer919/lynkeduppro-crm:feat/login-methods into goutamnextflow 2026-07-13 14:18:31 +00:00
tanweer919 cc71516278 feat(email): send team invitations from a Vercel serverless route (Twilio)
- POST /api/email/invite: sends the invite email via the Twilio Emails API using
  server-only TWILIO_ACCOUNT_SID/TWILIO_AUTH_TOKEN (Vercel env), from
  EMAIL_FROM_ADDRESS (default support@lynkedup.dev). Fixed invite template; gated
  on a session cookie so it isn't an open relay.
- Team Management emails the invite on create and resend (token now returned by
  both), with the Copy-link as a fallback. Mock mode skips email.
2026-07-13 19:48:19 +05:30
tanweer919 6606a55207 Merge pull request 'feat(rbac): invitation-based membership + nav gating; no role at registration' (#22) from tanweer919/lynkeduppro-crm:feat/login-methods into goutamnextflow 2026-07-13 10:56:17 +00:00
tanweer919 103f3ae3a1 feat(rbac): no role at registration; invitation-based membership; nav gating
- Registration no longer asks for a role/persona (removed the role select +
  allottee block); crm.account.register sends no persona.
- New users have no permissions → the sidebar now shows only Dashboard + Profile
  for them, gated on crm.account.me (membership + permissions). Members see the
  areas their permissions allow.
- Add /portal/invite?token=… : accepts the invite for a signed-in registered
  user, or routes an unregistered invitee through register/onboarding, which
  redeems the stashed token on completion (granting the invited role).
- Team Management: 'Copy link' on pending invites builds the invite link from
  the invitation token (no email delivery yet).
2026-07-13 16:25:53 +05:30
23 changed files with 1575 additions and 97 deletions
+4
View File
@@ -1,2 +1,6 @@
@abe-kap:registry=https://npm.pkg.github.com @abe-kap:registry=https://npm.pkg.github.com
//npm.pkg.github.com/:_authToken=${NODE_AUTH_TOKEN} //npm.pkg.github.com/:_authToken=${NODE_AUTH_TOKEN}
# @insignia/* (iios-kernel-client — the MessageSocket live stream) resolve from the
# self-hosted Gitea npm registry. Install needs a token with `read:package` in GITEA_TOKEN.
@insignia:registry=https://git.lynkedup.cloud/api/packages/insignia/npm/
//git.lynkedup.cloud/api/packages/insignia/npm/:_authToken=${GITEA_TOKEN}
@@ -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
View File
@@ -1,8 +1,8 @@
import type { NextConfig } from "next"; import type { NextConfig } from "next";
const nextConfig: NextConfig = { const nextConfig: NextConfig = {
// The SDK ships ESM/TS; let Next transpile it. // The SDKs ship ESM; let Next transpile them.
transpilePackages: ["@abe-kap/appshell-sdk"], transpilePackages: ["@abe-kap/appshell-sdk", "@insignia/iios-messaging-ui"],
// The browser calls the Shell BFF same-origin under /shell (so the HttpOnly // The browser calls the Shell BFF same-origin under /shell (so the HttpOnly
// session cookie flows). We deliberately use /shell (NOT /api) to avoid // session cookie flows). We deliberately use /shell (NOT /api) to avoid
// clobbering the existing /api/geo route. Point BFF_ORIGIN at the deployed BFF. // clobbering the existing /api/geo route. Point BFF_ORIGIN at the deployed BFF.
+116 -1
View File
@@ -9,6 +9,8 @@
"version": "0.1.0", "version": "0.1.0",
"dependencies": { "dependencies": {
"@abe-kap/appshell-sdk": "^0.2.6", "@abe-kap/appshell-sdk": "^0.2.6",
"@insignia/iios-kernel-client": "^0.1.4",
"@insignia/iios-messaging-ui": "^0.1.0",
"clsx": "^2.1.1", "clsx": "^2.1.1",
"lucide-react": "^1.21.0", "lucide-react": "^1.21.0",
"next": "16.2.9", "next": "16.2.9",
@@ -1011,6 +1013,35 @@
"url": "https://opencollective.com/libvips" "url": "https://opencollective.com/libvips"
} }
}, },
"node_modules/@insignia/iios-contracts": {
"version": "0.1.0",
"resolved": "https://git.lynkedup.cloud/api/packages/insignia/npm/%40insignia%2Fiios-contracts/-/0.1.0/iios-contracts-0.1.0.tgz",
"integrity": "sha512-+ycbP8ORdwllMtn7dmxIL7lnDpDDkV+gHqT2OKJtMplMivjKU03gsuuEveQxnrE1CMvZ3fcSljmfMs10Cw131g=="
},
"node_modules/@insignia/iios-kernel-client": {
"version": "0.1.4",
"resolved": "https://git.lynkedup.cloud/api/packages/insignia/npm/%40insignia%2Fiios-kernel-client/-/0.1.4/iios-kernel-client-0.1.4.tgz",
"integrity": "sha512-pYBHH21TvgOOm0kp3ogvZx/iEzXLwmU23jHpDzIolh5FrqxCrcpUjRwLDkeYRTTkRVdoJAPTmPES/pU66iNoiA==",
"dependencies": {
"@insignia/iios-contracts": "0.1.0",
"socket.io-client": "^4.8.1"
}
},
"node_modules/@insignia/iios-messaging-ui": {
"version": "0.1.0",
"resolved": "https://git.lynkedup.cloud/api/packages/insignia/npm/%40insignia%2Fiios-messaging-ui/-/0.1.0/iios-messaging-ui-0.1.0.tgz",
"integrity": "sha512-iGOh/lwJJm+QG2u5YP1Kj4gZyShRWO1o7/dxnl+DE1m/WbE0PDO+baTJ7NFhremubSB7Wc/KSLhf9yLdLbivAQ==",
"peerDependencies": {
"@insignia/iios-kernel-client": "*",
"react": ">=18",
"react-dom": ">=18"
},
"peerDependenciesMeta": {
"@insignia/iios-kernel-client": {
"optional": true
}
}
},
"node_modules/@jridgewell/gen-mapping": { "node_modules/@jridgewell/gen-mapping": {
"version": "0.3.13", "version": "0.3.13",
"resolved": "https://registry.npmjs.org/@jridgewell/gen-mapping/-/gen-mapping-0.3.13.tgz", "resolved": "https://registry.npmjs.org/@jridgewell/gen-mapping/-/gen-mapping-0.3.13.tgz",
@@ -1279,6 +1310,12 @@
"dev": true, "dev": true,
"license": "MIT" "license": "MIT"
}, },
"node_modules/@socket.io/component-emitter": {
"version": "3.1.2",
"resolved": "https://registry.npmjs.org/@socket.io/component-emitter/-/component-emitter-3.1.2.tgz",
"integrity": "sha512-9BCxFwvbGg/RsZK9tjXd8s4UcwR0MWeFQ1XEKIQVVvAGJyINdrqKMcTRyLoK8Rse1GjzLV9cwjWV1olXRWEXVA==",
"license": "MIT"
},
"node_modules/@supabase/auth-js": { "node_modules/@supabase/auth-js": {
"version": "2.110.2", "version": "2.110.2",
"resolved": "https://registry.npmjs.org/@supabase/auth-js/-/auth-js-2.110.2.tgz", "resolved": "https://registry.npmjs.org/@supabase/auth-js/-/auth-js-2.110.2.tgz",
@@ -3051,7 +3088,6 @@
"version": "4.4.3", "version": "4.4.3",
"resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz", "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz",
"integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==", "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==",
"dev": true,
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
"ms": "^2.1.3" "ms": "^2.1.3"
@@ -3205,6 +3241,28 @@
"node": ">= 0.8" "node": ">= 0.8"
} }
}, },
"node_modules/engine.io-client": {
"version": "6.6.6",
"resolved": "https://registry.npmjs.org/engine.io-client/-/engine.io-client-6.6.6.tgz",
"integrity": "sha512-iY6QdftLQ9pyiPoX082bpf/u1UewnOaJrtJIF9T0++QB34lZrj0uP+Q/bj8AlUsAxqhnkTV2BS8SBZSxOmoV5Q==",
"license": "MIT",
"dependencies": {
"@socket.io/component-emitter": "~3.1.0",
"debug": "~4.4.1",
"engine.io-parser": "~5.2.1",
"ws": "~8.21.0",
"xmlhttprequest-ssl": "~2.1.1"
}
},
"node_modules/engine.io-parser": {
"version": "5.2.3",
"resolved": "https://registry.npmjs.org/engine.io-parser/-/engine.io-parser-5.2.3.tgz",
"integrity": "sha512-HqD3yTBfnBxIrbnM1DoD6Pcq8NECnh8d4As1Qgh0z5Gg3jRRIqijury0CL3ghu/edArpUYiYqQiDUQBIs4np3Q==",
"license": "MIT",
"engines": {
"node": ">=10.0.0"
}
},
"node_modules/enhanced-resolve": { "node_modules/enhanced-resolve": {
"version": "5.21.6", "version": "5.21.6",
"resolved": "https://registry.npmjs.org/enhanced-resolve/-/enhanced-resolve-5.21.6.tgz", "resolved": "https://registry.npmjs.org/enhanced-resolve/-/enhanced-resolve-5.21.6.tgz",
@@ -6688,6 +6746,34 @@
"url": "https://github.com/sponsors/ljharb" "url": "https://github.com/sponsors/ljharb"
} }
}, },
"node_modules/socket.io-client": {
"version": "4.8.3",
"resolved": "https://registry.npmjs.org/socket.io-client/-/socket.io-client-4.8.3.tgz",
"integrity": "sha512-uP0bpjWrjQmUt5DTHq9RuoCBdFJF10cdX9X+a368j/Ft0wmaVgxlrjvK3kjvgCODOMMOz9lcaRzxmso0bTWZ/g==",
"license": "MIT",
"dependencies": {
"@socket.io/component-emitter": "~3.1.0",
"debug": "~4.4.1",
"engine.io-client": "~6.6.1",
"socket.io-parser": "~4.2.4"
},
"engines": {
"node": ">=10.0.0"
}
},
"node_modules/socket.io-parser": {
"version": "4.2.6",
"resolved": "https://registry.npmjs.org/socket.io-parser/-/socket.io-parser-4.2.6.tgz",
"integrity": "sha512-asJqbVBDsBCJx0pTqw3WfesSY0iRX+2xzWEWzrpcH7L6fLzrhyF8WPI8UaeM4YCuDfpwA/cgsdugMsmtz8EJeg==",
"license": "MIT",
"dependencies": {
"@socket.io/component-emitter": "~3.1.0",
"debug": "~4.4.1"
},
"engines": {
"node": ">=10.0.0"
}
},
"node_modules/source-map-js": { "node_modules/source-map-js": {
"version": "1.2.1", "version": "1.2.1",
"resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.1.tgz", "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.1.tgz",
@@ -7448,6 +7534,35 @@
"node": ">=0.10.0" "node": ">=0.10.0"
} }
}, },
"node_modules/ws": {
"version": "8.21.1",
"resolved": "https://registry.npmjs.org/ws/-/ws-8.21.1.tgz",
"integrity": "sha512-+0NTnW77fFN/DjQi6k/Sq/Yvk4Sgajw7urW8V+asjXnRgDs9gyGkdb7EzgfhA4goXsRIZKE28fzIXBHEzhuiWw==",
"license": "MIT",
"engines": {
"node": ">=10.0.0"
},
"peerDependencies": {
"bufferutil": "^4.0.1",
"utf-8-validate": ">=5.0.2"
},
"peerDependenciesMeta": {
"bufferutil": {
"optional": true
},
"utf-8-validate": {
"optional": true
}
}
},
"node_modules/xmlhttprequest-ssl": {
"version": "2.1.2",
"resolved": "https://registry.npmjs.org/xmlhttprequest-ssl/-/xmlhttprequest-ssl-2.1.2.tgz",
"integrity": "sha512-TEU+nJVUUnA4CYJFLvK5X9AOeH4KvDvhIfm0vV1GaQRtchnG0hgK5p8hw/xjv8cunWYCsiPCSDzObPyhEwq3KQ==",
"engines": {
"node": ">=0.4.0"
}
},
"node_modules/yallist": { "node_modules/yallist": {
"version": "3.1.1", "version": "3.1.1",
"resolved": "https://registry.npmjs.org/yallist/-/yallist-3.1.1.tgz", "resolved": "https://registry.npmjs.org/yallist/-/yallist-3.1.1.tgz",
+2
View File
@@ -10,6 +10,8 @@
}, },
"dependencies": { "dependencies": {
"@abe-kap/appshell-sdk": "^0.2.6", "@abe-kap/appshell-sdk": "^0.2.6",
"@insignia/iios-kernel-client": "^0.1.4",
"@insignia/iios-messaging-ui": "^0.1.0",
"clsx": "^2.1.1", "clsx": "^2.1.1",
"lucide-react": "^1.21.0", "lucide-react": "^1.21.0",
"next": "16.2.9", "next": "16.2.9",
+28
View File
@@ -0,0 +1,28 @@
import { NextResponse } from "next/server";
// Server-side proxy to be-crm's public invitation lookup, so the invite landing page
// can learn the invited email + roles and whether an account exists — before the
// invitee has a session. Server-to-server avoids CORS. No secrets involved (the token
// is the only credential, and it was emailed to the invitee).
export const runtime = "nodejs";
const CRM_BASE_URL = (process.env.CRM_BASE_URL ?? "https://crm.lynkedup.cloud").replace(/\/$/, "");
export async function GET(request: Request) {
const token = new URL(request.url).searchParams.get("token") ?? "";
if (token.length < 16 || token.length > 256) {
return NextResponse.json({ ok: false, status: "invalid" }, { status: 400 });
}
try {
const res = await fetch(`${CRM_BASE_URL}/public/invitations/lookup?token=${encodeURIComponent(token)}`, {
headers: { Accept: "application/json" },
cache: "no-store",
});
if (!res.ok) return NextResponse.json({ ok: false, status: "unavailable" }, { status: 502 });
const data = await res.json();
return NextResponse.json(data);
} catch {
return NextResponse.json({ ok: false, status: "unavailable" }, { status: 502 });
}
}
+36 -1
View File
@@ -134,6 +134,21 @@
.dash-content { padding: 22px 28px 40px; width: 100%; } .dash-content { padding: 22px 28px 40px; width: 100%; }
.sec-title { font-size: 15px; font-weight: 700; margin: 6px 0 14px; } .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 helpers ---- */
.grid { display: grid; gap: 16px; } .grid { display: grid; gap: 16px; }
.row { display: flex; align-items: center; } .row { display: flex; align-items: center; }
@@ -437,7 +452,7 @@
.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-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 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-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); } .dash-root .ds-modal-foot { display: flex; justify-content: flex-end; gap: 10px; padding: 14px 20px; border-top: 1px solid var(--border); }
/* ---- Toasts ---- */ /* ---- Toasts ---- */
@@ -1141,3 +1156,23 @@
.dash-root .ai-view { height: calc(100vh - 150px); } .dash-root .ai-view { height: calc(100vh - 150px); }
} }
/* ---- 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; }
+113
View File
@@ -0,0 +1,113 @@
"use client";
import { useEffect, useRef, useState } from "react";
import { useRouter } from "next/navigation";
import { useAuth, useAppShell } from "@abe-kap/appshell-sdk/react";
import { PortalAside, PanelBrand } from "@/components/portal/parts";
import { CookieBanner, Spinner } from "@/components/portal/bits";
import { isShellConfigured } from "@/lib/appshell";
interface InviteInfo { ok: boolean; status?: string; email?: string; roleNames?: string[]; hasAccount?: boolean }
/**
* Team invitation landing page (/portal/invite?token=). It looks the token up
* (public, pre-auth) to learn the invited email and whether an account exists, then:
* - signed in + registered accept now (creates the membership with the invited role);
* - signed in, no CRM profile onboarding, which redeems the token on finish;
* - not signed in + email already has an account sign in (email prefilled);
* - not signed in + first-time invitee register (email prefilled + locked).
* The register/login/onboarding flows redeem the stashed token on completion.
*/
export default function InvitePage() {
const router = useRouter();
const { status, getUserEmail } = useAuth();
const { ready, sdk } = useAppShell();
const [error, setError] = useState("");
const started = useRef(false);
useEffect(() => {
let token = "";
try { token = new URLSearchParams(window.location.search).get("token") ?? ""; } catch { /* ignore */ }
if (!token) { setError("This invitation link is invalid or incomplete."); return; }
if (!isShellConfigured()) { try { sessionStorage.setItem("invite_token", token); } catch { /* ignore */ } router.replace("/portal/register"); return; }
if (!ready || started.current) return;
started.current = true;
(async () => {
try { sessionStorage.setItem("invite_token", token); } catch { /* ignore */ }
// Look the invitation up (pre-auth) to get the email + account state.
let info: InviteInfo = { ok: false };
try {
const res = await fetch(`/api/invite/lookup?token=${encodeURIComponent(token)}`, { cache: "no-store" });
info = await res.json();
} catch { /* treat as unavailable below */ }
if (!info.ok) {
const msg = info.status === "expired" ? "This invitation has expired. Ask for a new one."
: info.status === "accepted" ? "This invitation has already been used."
: info.status === "revoked" ? "This invitation was revoked."
: "This invitation link is invalid.";
setError(msg);
try { sessionStorage.removeItem("invite_token"); } catch { /* ignore */ }
return;
}
if (info.email) { try { sessionStorage.setItem("invite_email", info.email); } catch { /* ignore */ } }
// Signed in already: accept if registered, else finish onboarding first.
if (status === "authenticated") {
try {
const st = await sdk.query<{ registered: boolean }>("crm.account.registrationStatus");
if (!st?.registered) {
try { const em = await getUserEmail(); if (em) sessionStorage.setItem("onboard_email", em); } catch { /* ignore */ }
router.replace("/portal/onboarding");
return;
}
} catch { /* fall through to accept */ }
try {
await sdk.command("crm.team.invitation.accept", { token });
try { sessionStorage.removeItem("invite_token"); sessionStorage.removeItem("invite_email"); } catch { /* ignore */ }
router.replace("/dashboard");
} catch {
setError("We couldn't accept this invitation — it may have expired or already been used.");
}
return;
}
// Not signed in: existing account → sign in; first-time invitee → register.
router.replace(info.hasAccount ? "/portal/login" : "/portal/register");
})();
}, [ready, status, router, sdk, getUserEmail]);
return (
<main className="portal-main">
<span className="portal-grid" />
<div className="portal-split anim-in">
<PortalAside />
<section className="portal-panel">
<div style={{ width: "100%", maxWidth: 420 }}>
<PanelBrand />
<div className="card anim-fade-up" style={{ textAlign: "center" }}>
{error ? (
<>
<h1>Invitation problem</h1>
<p className="sub">{error}</p>
<button className="btn btn-primary" style={{ marginTop: 16 }} onClick={() => router.replace("/portal/login")}>
Go to sign in
</button>
</>
) : (
<div className="interstitial">
<Spinner lg />
<h1 style={{ fontSize: 20, marginTop: 8 }}>Checking your invitation</h1>
<p className="sub">One moment while we set things up.</p>
</div>
)}
</div>
</div>
</section>
</div>
<CookieBanner />
</main>
);
}
+6
View File
@@ -15,6 +15,9 @@ import { Support } from "./support";
import { Rules } from "./rules"; import { Rules } from "./rules";
import { AiAssistant } from "./ai-assistant"; import { AiAssistant } from "./ai-assistant";
import { TeamManagement } from "./team-management"; import { TeamManagement } from "./team-management";
import { MessengerSdk } from "./messenger-sdk";
import { InboxSdk } from "./inbox-sdk";
import { Settings } from "./settings";
import "../../app/dashboard/dashboard.css"; import "../../app/dashboard/dashboard.css";
export function Dashboard() { export function Dashboard() {
@@ -45,6 +48,9 @@ export function Dashboard() {
: active === "support" ? <Support /> : active === "support" ? <Support />
: active === "rules" ? <Rules /> : active === "rules" ? <Rules />
: active === "ai" ? <AiAssistant /> : active === "ai" ? <AiAssistant />
: active === "messenger" ? <MessengerSdk />
: active === "inbox" ? <InboxSdk />
: active === "settings" ? <Settings />
: active === "team" ? <TeamManagement /> : active === "team" ? <TeamManagement />
: <ComingSoon title={title} icon={item?.icon ?? "dashboard"} onGo={setActive} />} : <ComingSoon title={title} icon={item?.icon ?? "dashboard"} onGo={setActive} />}
</ToastProvider> </ToastProvider>
+48
View File
@@ -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&apos;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>
);
}
@@ -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&apos;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>
);
}
+136
View File
@@ -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>
);
}
+44 -1
View File
@@ -6,6 +6,7 @@ import { ChevronsUpDown, LogOut } from "lucide-react";
import { useAuth } from "@abe-kap/appshell-sdk/react"; import { useAuth } from "@abe-kap/appshell-sdk/react";
import { Icon } from "./ui"; import { Icon } from "./ui";
import { user } from "./account-data"; import { user } from "./account-data";
import { useMyAccess } from "@/lib/access";
function initialsOf(name: string): string { function initialsOf(name: string): string {
return name.split(/\s+/).filter(Boolean).slice(0, 2).map((p) => p[0]).join("").toUpperCase() || "?"; return name.split(/\s+/).filter(Boolean).slice(0, 2).map((p) => p[0]).join("").toUpperCase() || "?";
@@ -28,6 +29,13 @@ export const NAV_GROUPS: NavGroup[] = [
{ key: "pipeline", label: "Pipeline", icon: "pipeline" }, { key: "pipeline", label: "Pipeline", icon: "pipeline" },
], ],
}, },
{
title: "Communication",
items: [
{ key: "messenger", label: "Messenger", icon: "send", subtitle: "Chat with your team and clients" },
{ key: "inbox", label: "Inbox", icon: "bell", subtitle: "Mentions, messages, alerts and mail — all in one" },
],
},
{ {
title: "Workspace", title: "Workspace",
items: [ items: [
@@ -67,10 +75,45 @@ export const NAV_GROUPS: NavGroup[] = [
export const NAV_ITEMS: NavItem[] = NAV_GROUPS.flatMap((g) => g.items); export const NAV_ITEMS: NavItem[] = NAV_GROUPS.flatMap((g) => g.items);
// Nav visibility by CRM permission. Dashboard + Profile are always visible (even to a
// brand-new user with no membership); every other item requires membership, and the
// items mapped here additionally require the given permission. Unmapped items are
// shown to any member. This is UX only — be-crm still enforces every action.
const ALWAYS_VISIBLE = new Set(["dashboard", "profile", "messenger", "inbox"]);
const NAV_PERMISSION: Record<string, string | undefined> = {
team: "team.manage",
people: "team.manage",
leads: "leads.manage",
verify: "leads.manage",
pipeline: "pipeline.manage",
estimates: "estimates.create",
procanvas: "estimates.create",
dispatch: "dispatch.manage",
schedule: "dispatch.manage",
storm: "dispatch.manage",
territory: "dispatch.manage",
leaderboard: "reports.view",
settings: "settings.manage",
};
export function Sidebar({ active, onSelect }: { active: string; onSelect: (k: string) => void }) { export function Sidebar({ active, onSelect }: { active: string; onSelect: (k: string) => void }) {
const router = useRouter(); const router = useRouter();
const { user: me, logout, context } = useAuth(); const { user: me, logout, context } = useAuth();
const access = useMyAccess();
const [menuOpen, setMenuOpen] = useState(false); const [menuOpen, setMenuOpen] = useState(false);
// A new user with no membership sees only Dashboard + Profile. Members see the areas
// their permissions allow. While access is still loading, keep it minimal to avoid
// flashing items the user can't actually use.
const canSee = (key: string): boolean => {
if (ALWAYS_VISIBLE.has(key)) return true;
if (access.loading || !access.isMember) return false;
const perm = NAV_PERMISSION[key];
return perm ? access.can(perm) : true;
};
const visibleGroups = NAV_GROUPS
.map((g) => ({ ...g, items: g.items.filter((it) => canSee(it.key)) }))
.filter((g) => g.items.length > 0);
// Real signed-in identity from the App Context Envelope; fall back to the static // Real signed-in identity from the App Context Envelope; fall back to the static
// demo user only when the Shell isn't wired. // demo user only when the Shell isn't wired.
const roleLabel = context?.scope?.role ? context.scope.role.charAt(0).toUpperCase() + context.scope.role.slice(1) : ""; const roleLabel = context?.scope?.role ? context.scope.role.charAt(0).toUpperCase() + context.scope.role.slice(1) : "";
@@ -92,7 +135,7 @@ export function Sidebar({ active, onSelect }: { active: string; onSelect: (k: st
</div> </div>
<nav className="dash-nav"> <nav className="dash-nav">
{NAV_GROUPS.map((g, gi) => ( {visibleGroups.map((g, gi) => (
<div className="nav-section" key={gi}> <div className="nav-section" key={gi}>
<div className="nav-group">{g.title}</div> <div className="nav-group">{g.title}</div>
{g.items.map((it) => ( {g.items.map((it) => (
+9 -2
View File
@@ -301,8 +301,15 @@ export function TeamManagement() {
</div> </div>
<RoleChips roleIds={inv.roleIds} roleById={roleById} /> <RoleChips roleIds={inv.roleIds} roleById={roleById} />
<div className="tm-invite-actions"> <div className="tm-invite-actions">
{inv.token && (
<Btn variant="soft" size="sm" icon="copy" onClick={async () => {
const link = `${window.location.origin}/portal/invite?token=${inv.token}`;
try { await navigator.clipboard.writeText(link); toast.push({ tone: "success", title: "Invite link copied", desc: `Send it to ${inv.email} to join.` }); }
catch { toast.push({ tone: "info", title: "Invite link", desc: link }); }
}}>Copy link</Btn>
)}
<Btn variant="soft" size="sm" icon="refresh" onClick={async () => { <Btn variant="soft" size="sm" icon="refresh" onClick={async () => {
try { await team.resendInvite(inv.id); toast.push({ tone: "success", title: "Invite resent", desc: `A fresh link was sent to ${inv.email}.` }); } try { await team.resendInvite(inv.id); toast.push({ tone: "success", title: "Invite resent", desc: `A fresh link was emailed to ${inv.email}.` }); }
catch (e) { toast.push({ tone: "error", title: "Couldn't resend", desc: (e as Error).message }); } catch (e) { toast.push({ tone: "error", title: "Couldn't resend", desc: (e as Error).message }); }
}}>Resend</Btn> }}>Resend</Btn>
<Btn variant="ghost" size="sm" icon="x" onClick={async () => { <Btn variant="ghost" size="sm" icon="x" onClick={async () => {
@@ -326,7 +333,7 @@ export function TeamManagement() {
try { try {
await team.invite(email, roleIds); await team.invite(email, roleIds);
setTab("invites"); setTab("invites");
toast.push({ tone: "success", title: "Invitation sent", desc: `${email} was invited with ${roleIds.length} role${roleIds.length === 1 ? "" : "s"}.` }); toast.push({ tone: "success", title: "Invitation sent", desc: `We emailed an invite to ${email}. You can also copy the link.` });
} catch (e) { toast.push({ tone: "error", title: "Couldn't send invite", desc: (e as Error).message }); } } catch (e) { toast.push({ tone: "error", title: "Couldn't send invite", desc: (e as Error).message }); }
}} }}
/> />
+9 -2
View File
@@ -14,6 +14,7 @@ import {
createContext, useCallback, useContext, useEffect, useId, createContext, useCallback, useContext, useEffect, useId,
useRef, useState, type ReactNode, useRef, useState, type ReactNode,
} from "react"; } from "react";
import { createPortal } from "react-dom";
import { import {
MessageCircle, Ticket, Phone, Mail, BookOpen, Rocket, Shield, ShieldCheck, MessageCircle, Ticket, Phone, Mail, BookOpen, Rocket, Shield, ShieldCheck,
Lock, CreditCard, User, Bell, Eye, EyeOff, Camera, Upload, Plus, Star, Send, Lock, CreditCard, User, Bell, Eye, EyeOff, Camera, Upload, Plus, Star, Send,
@@ -221,6 +222,11 @@ export function Modal({ open, onClose, title, subtitle, icon, children, footer,
children: ReactNode; footer?: ReactNode; size?: "sm" | "md" | "lg"; children: ReactNode; footer?: ReactNode; size?: "sm" | "md" | "lg";
}) { }) {
const titleId = useId(); 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(() => { useEffect(() => {
if (!open) return; if (!open) return;
const onKey = (e: KeyboardEvent) => { if (e.key === "Escape") onClose(); }; 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); return () => document.removeEventListener("keydown", onKey);
}, [open, onClose]); }, [open, onClose]);
if (!open) return null; if (!open || !mounted) return null;
return ( const overlay = (
<div className="ds-modal-overlay" onMouseDown={onClose}> <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 size-${size}`} role="dialog" aria-modal="true" aria-labelledby={titleId} onMouseDown={(e) => e.stopPropagation()}>
<div className="ds-modal-head"> <div className="ds-modal-head">
@@ -247,6 +253,7 @@ export function Modal({ open, onClose, title, subtitle, icon, children, footer,
</div> </div>
</div> </div>
); );
return host ? createPortal(overlay, host) : overlay;
} }
/* ---------------------------------------------------------- */ /* ---------------------------------------------------------- */
+37 -11
View File
@@ -34,6 +34,25 @@ export function LoginFlow() {
const [remember, setRemember] = useState(false); const [remember, setRemember] = useState(false);
const [flash, setFlash] = useState<string>(""); const [flash, setFlash] = useState<string>("");
const [otpChannel, setOtpChannel] = useState<"email" | "sms">("email"); const [otpChannel, setOtpChannel] = useState<"email" | "sms">("email");
const [invited, setInvited] = useState(false);
// Arriving from a team invite for an already-registered email → prefill it.
useEffect(() => {
try { const e = sessionStorage.getItem("invite_email"); if (e) { setEmail(e); setInvited(true); } } catch { /* ignore */ }
}, []);
// After a successful sign-in, redeem a pending team invite (if any), then go to the dashboard.
async function acceptPendingInviteThenDashboard() {
try {
const t = sessionStorage.getItem("invite_token");
if (t) {
await sdk.command("crm.team.invitation.accept", { token: t });
sessionStorage.removeItem("invite_token");
sessionStorage.removeItem("invite_email");
}
} catch { /* invite expired/used — proceed to the dashboard anyway */ }
router.replace("/dashboard");
}
// Minimal account stand-in for passwordless entry points (Shell mode). // Minimal account stand-in for passwordless entry points (Shell mode).
function blankAccount(): Account { function blankAccount(): Account {
@@ -87,7 +106,7 @@ export function LoginFlow() {
registered = !!st?.registered; registered = !!st?.registered;
} catch { registered = false; } } catch { registered = false; }
window.history.replaceState({}, "", "/portal/login"); window.history.replaceState({}, "", "/portal/login");
if (registered) { router.replace("/dashboard"); return; } if (registered) { await acceptPendingInviteThenDashboard(); return; }
// Capture the verified email now (session is fresh) so onboarding prefills it. // Capture the verified email now (session is fresh) so onboarding prefills it.
try { const em = await getUserEmail(); if (em) sessionStorage.setItem("onboard_email", em); } catch { /* ignore */ } try { const em = await getUserEmail(); if (em) sessionStorage.setItem("onboard_email", em); } catch { /* ignore */ }
router.replace("/portal/onboarding"); router.replace("/portal/onboarding");
@@ -154,7 +173,7 @@ export function LoginFlow() {
{step === "identify" && ( {step === "identify" && (
<> <>
{flash && <div style={{ marginBottom: 16 }}><FlashNote tone="error">{flash}</FlashNote></div>} {flash && <div style={{ marginBottom: 16 }}><FlashNote tone="error">{flash}</FlashNote></div>}
<Identify email={email} setEmail={setEmail} onSocial={onSocial} onEmail={identifyEmail} onPhone={startPhoneLogin} toRegister={() => router.push("/portal/register")} /> <Identify email={email} setEmail={setEmail} onSocial={onSocial} onEmail={identifyEmail} onPhone={startPhoneLogin} toRegister={() => router.push("/portal/register")} invited={invited} />
</> </>
)} )}
@@ -201,11 +220,11 @@ export function LoginFlow() {
)} )}
{step === "password" && account && ( {step === "password" && account && (
<Password account={account} email={email} login={login} onAuthenticated={() => router.replace("/dashboard")} flash={flash} onBack={back} onForgot={() => push("fp_confirm")} onOtp={() => { setOtpChannel("email"); replace("otp"); }} onLocked={() => setFlash("This account is temporarily locked.")} onOk={() => afterAuth("password")} /> <Password account={account} email={email} login={login} onAuthenticated={acceptPendingInviteThenDashboard} flash={flash} onBack={back} onForgot={() => push("fp_confirm")} onOtp={() => { setOtpChannel("email"); replace("otp"); }} onLocked={() => setFlash("This account is temporarily locked.")} onOk={() => afterAuth("password")} />
)} )}
{step === "otp" && account && ( {step === "otp" && account && (
<OtpVerify account={account} email={email} initialChannel={otpChannel} remember={remember} setRemember={setRemember} onBack={back} onVerified={() => afterAuth("otp")} onAuthenticated={() => router.replace("/dashboard")} /> <OtpVerify account={account} email={email} initialChannel={otpChannel} remember={remember} setRemember={setRemember} onBack={back} onVerified={() => afterAuth("otp")} onAuthenticated={acceptPendingInviteThenDashboard} />
)} )}
{step === "another" && account && ( {step === "another" && account && (
@@ -269,17 +288,17 @@ export function LoginFlow() {
/* ============================ screens ============================ */ /* ============================ screens ============================ */
function Identify({ email, setEmail, onSocial, onEmail, onPhone, toRegister }: { function Identify({ email, setEmail, onSocial, onEmail, onPhone, toRegister, invited }: {
email: string; setEmail: (v: string) => void; email: string; setEmail: (v: string) => void;
onSocial: (p: "google") => void; onEmail: () => void; onPhone: () => void; toRegister: () => void; onSocial: (p: "google") => void; onEmail: () => void; onPhone: () => void; toRegister: () => void; invited?: boolean;
}) { }) {
const [showEmail, setShowEmail] = useState(false); const [showEmail, setShowEmail] = useState(!!invited);
const valid = EMAIL_RE.test(email); const valid = EMAIL_RE.test(email);
return ( return (
<div> <div>
<div className="kicker">Welcome back</div> <div className="kicker">{invited ? "You're invited" : "Welcome back"}</div>
<h1>Sign in to LynkedUp</h1> <h1>{invited ? "Sign in to join the team" : "Sign in to LynkedUp"}</h1>
<p className="sub">Drone inspections, AI estimates and insurance-ready reports all in one place.</p> <p className="sub">{invited ? "You already have an account — sign in to accept your invitation." : "Drone inspections, AI estimates and insurance-ready reports — all in one place."}</p>
<div style={{ marginTop: 22 }}> <div style={{ marginTop: 22 }}>
<SocialButtons onPick={onSocial} /> <SocialButtons onPick={onSocial} />
@@ -435,7 +454,14 @@ function OtpVerify({ account, email, initialChannel = "email", remember, setReme
if (!PHONE_RE.test(phone)) { setError("Enter your phone in international format, e.g. +14155550100."); return; } if (!PHONE_RE.test(phone)) { setError("Enter your phone in international format, e.g. +14155550100."); return; }
await sendPhoneOtp(phone); setSent(true); await sendPhoneOtp(phone); setSent(true);
} }
} catch (e) { setError((e as Error).message); } } catch (e) {
// gotrue can throw an error whose message is an unhelpful "{}"/JSON blob (e.g. a
// 500 "Error sending magic link email" when SMTP isn't set up). Show something
// readable and actionable instead of the raw payload.
const raw = (e as { message?: unknown })?.message;
const readable = typeof raw === "string" && raw.trim() && !raw.trim().startsWith("{") ? raw.trim() : "";
setError(readable || "We couldn't send your sign-in code right now. Please try again shortly, or sign in with your password.");
}
} }
async function complete(code: string) { async function complete(code: string) {
+30 -69
View File
@@ -8,7 +8,7 @@ import {
PasswordStrength, LegalModal, PasswordStrength, LegalModal,
} from "./bits"; } from "./bits";
import { import {
countryCodes, relationshipOptions, addressCountries, countryCodes, addressCountries,
TERMS, PRIVACY, passwordStrength, type AddrCountry, TERMS, PRIVACY, passwordStrength, type AddrCountry,
} from "./data"; } from "./data";
import { useAuth, useAppShell } from "@abe-kap/appshell-sdk/react"; import { useAuth, useAppShell } from "@abe-kap/appshell-sdk/react";
@@ -48,15 +48,18 @@ export function RegisterFlow({ mode = "register" }: { mode?: "register" | "onboa
const [cc, setCc] = useState("+1"); const [cc, setCc] = useState("+1");
const [phone, setPhone] = useState(""); const [phone, setPhone] = useState("");
const [pw, setPw] = useState(""); const [pw, setPw] = useState("");
const [relationship, setRelationship] = useState("Customer");
const [alloeNo, setAlloeNo] = useState("");
const [alloeFirst, setAlloeFirst] = useState("");
const [alloeLast, setAlloeLast] = useState("");
const [termsOk, setTermsOk] = useState(false); const [termsOk, setTermsOk] = useState(false);
const [privacyOk, setPrivacyOk] = useState(false); const [privacyOk, setPrivacyOk] = useState(false);
// verify step (email is trusted without an OTP — see verifyValid below) // verify step (email is trusted without an OTP — see verifyValid below)
const [phoneVerified, setPhoneVerified] = useState(false); const [phoneVerified, setPhoneVerified] = useState(false);
// When arriving from a team invite, the email is fixed to the invited address.
const [invitedEmail, setInvitedEmail] = useState("");
useEffect(() => {
if (onboard) return;
try { const e = sessionStorage.getItem("invite_email"); if (e) { setEmail(e); setInvitedEmail(e); } } catch { /* ignore */ }
}, [onboard]);
// Onboarding: prefill the verified email — from the session-storage hint the login // Onboarding: prefill the verified email — from the session-storage hint the login
// page stashed at OAuth time, then confirmed via the live Supabase session. // page stashed at OAuth time, then confirmed via the live Supabase session.
@@ -69,16 +72,13 @@ export function RegisterFlow({ mode = "register" }: { mode?: "register" | "onboa
const STEP_LABELS = onboard ? ["Profile", "Verify", "Address"] : STEPS; const STEP_LABELS = onboard ? ["Profile", "Verify", "Address"] : STEPS;
const isSelf = relationship === "Customer" || relationship === "Owner";
const isEmployee = relationship === "Employee";
const country = countryCodes.find((c) => c.code === cc)!; const country = countryCodes.find((c) => c.code === cc)!;
const phoneOk = phone.replace(/\D/g, "").length === country.digits; const phoneOk = phone.replace(/\D/g, "").length === country.digits;
const pwOk = sso ? true : passwordStrength(pw).score >= 3; const pwOk = sso ? true : passwordStrength(pw).score >= 3;
const alloeIdOk = /^(?=.*[a-zA-Z])(?=.*\d).{4,}$/.test(alloeNo);
const step0Valid = const step0Valid =
first.trim() && last.trim() && EMAIL_RE.test(sso?.email || email) && phoneOk && pwOk && first.trim() && last.trim() && EMAIL_RE.test(sso?.email || email) && phoneOk && pwOk &&
termsOk && privacyOk && (isSelf || (alloeIdOk && (isEmployee || (alloeFirst.trim() && alloeLast.trim())))); termsOk && privacyOk;
// Email is already trusted in both flows (registration: Supabase auto-confirms on // Email is already trusted in both flows (registration: Supabase auto-confirms on
// signup; onboarding: Google-verified), so the Verify step only gates on the phone. // signup; onboarding: Google-verified), so the Verify step only gates on the phone.
@@ -107,8 +107,6 @@ export function RegisterFlow({ mode = "register" }: { mode?: "register" | "onboa
name: `${first} ${last}`.trim(), name: `${first} ${last}`.trim(),
initials: `${first[0] ?? ""}${last[0] ?? ""}`.toUpperCase(), initials: `${first[0] ?? ""}${last[0] ?? ""}`.toUpperCase(),
email: finalEmail, email: finalEmail,
isAllottee: isSelf,
allotteeNames: isSelf ? null : `${alloeFirst} ${alloeLast}`.trim(),
}; };
try { localStorage.setItem("lup_profile", JSON.stringify(profile)); } catch { /* ignore */ } try { localStorage.setItem("lup_profile", JSON.stringify(profile)); } catch { /* ignore */ }
@@ -121,17 +119,15 @@ export function RegisterFlow({ mode = "register" }: { mode?: "register" | "onboa
if (onboard && pw) { if (onboard && pw) {
try { await setPassword(pw); } catch { /* non-fatal — the profile still saves */ } try { await setPassword(pw); } catch { /* non-fatal — the profile still saves */ }
} }
// 2) Persist the full CRM registration payload to be-crm (name, phone, persona, // 2) Persist the CRM registration payload to be-crm (name, phone, addresses,
// allottee, both addresses, consent). Non-fatal: the auth account exists either way. // consent). No role/persona — a new user has no permissions until invited.
// Non-fatal: the auth account exists either way.
try { try {
const mailing = mailingSame ? regAddr : mailAddr; const mailing = mailingSame ? regAddr : mailAddr;
await sdk.command("crm.account.register", { await sdk.command("crm.account.register", {
email: finalEmail, email: finalEmail,
firstName: first, lastName: last, firstName: first, lastName: last,
phoneCc: cc, phoneNumber: phone.replace(/\D/g, ""), phoneCc: cc, phoneNumber: phone.replace(/\D/g, ""),
persona: relationship,
isAllottee: isSelf,
...(isSelf ? {} : { allotteeId: alloeNo, allotteeFirstName: alloeFirst, allotteeLastName: alloeLast }),
registeredAddress: regAddr, registeredAddress: regAddr,
mailingAddress: mailing, mailingAddress: mailing,
mailingSameAsRegistered: mailingSame, mailingSameAsRegistered: mailingSame,
@@ -141,6 +137,17 @@ export function RegisterFlow({ mode = "register" }: { mode?: "register" | "onboa
if (onboard) { setSubmitErr("Couldn't save your profile. Please try again."); return; } if (onboard) { setSubmitErr("Couldn't save your profile. Please try again."); return; }
// register mode: non-fatal — the auth account exists; the profile can be filled in later. // register mode: non-fatal — the auth account exists; the profile can be filled in later.
} }
// 3) If the user arrived from a team invitation link, redeem it now — this
// creates their membership with the invited role(s). Non-fatal.
try {
const inviteToken = sessionStorage.getItem("invite_token");
if (inviteToken) {
await sdk.command("crm.team.invitation.accept", { token: inviteToken });
sessionStorage.removeItem("invite_token");
sessionStorage.removeItem("invite_email");
}
} catch { /* invitation expired/used — they can still be invited again */ }
} }
// Consume the OAuth→onboarding handoff so a stale hint can't re-open onboarding. // Consume the OAuth→onboarding handoff so a stale hint can't re-open onboarding.
try { sessionStorage.removeItem("onboard_email"); } catch { /* ignore */ } try { sessionStorage.removeItem("onboard_email"); } catch { /* ignore */ }
@@ -155,14 +162,11 @@ export function RegisterFlow({ mode = "register" }: { mode?: "register" | "onboa
<> <>
{submitErr && <div style={{ marginBottom: 14 }}><FlashNote tone="error">{submitErr}</FlashNote></div>} {submitErr && <div style={{ marginBottom: 14 }}><FlashNote tone="error">{submitErr}</FlashNote></div>}
<StepAccount <StepAccount
onboard={onboard} creating={creating} onboard={onboard} creating={creating} invited={!!invitedEmail}
sso={sso} setSso={setSso} email={email} setEmail={setEmail} sso={sso} setSso={setSso} email={email} setEmail={setEmail}
first={first} setFirst={setFirst} last={last} setLast={setLast} first={first} setFirst={setFirst} last={last} setLast={setLast}
cc={cc} setCc={setCc} phone={phone} setPhone={setPhone} phoneOk={phoneOk} country={country} cc={cc} setCc={setCc} phone={phone} setPhone={setPhone} phoneOk={phoneOk} country={country}
pw={pw} setPw={setPw} pw={pw} setPw={setPw}
relationship={relationship} setRelationship={setRelationship} isSelf={isSelf}
alloeNo={alloeNo} setAlloeNo={setAlloeNo} alloeIdOk={alloeIdOk}
alloeFirst={alloeFirst} setAlloeFirst={setAlloeFirst} alloeLast={alloeLast} setAlloeLast={setAlloeLast}
termsOk={termsOk} setTermsOk={setTermsOk} privacyOk={privacyOk} setPrivacyOk={setPrivacyOk} termsOk={termsOk} setTermsOk={setTermsOk} privacyOk={privacyOk} setPrivacyOk={setPrivacyOk}
valid={!!step0Valid} valid={!!step0Valid}
onContinue={leaveAccountStep} toLogin={() => router.push("/portal/login")} onContinue={leaveAccountStep} toLogin={() => router.push("/portal/login")}
@@ -195,11 +199,8 @@ function StepAccount(p: {
first: string; setFirst: (v: string) => void; last: string; setLast: (v: string) => void; first: string; setFirst: (v: string) => void; last: string; setLast: (v: string) => void;
cc: string; setCc: (v: string) => void; phone: string; setPhone: (v: string) => void; phoneOk: boolean; country: typeof countryCodes[number]; cc: string; setCc: (v: string) => void; phone: string; setPhone: (v: string) => void; phoneOk: boolean; country: typeof countryCodes[number];
pw: string; setPw: (v: string) => void; pw: string; setPw: (v: string) => void;
relationship: string; setRelationship: (v: string) => void; isSelf: boolean;
alloeNo: string; setAlloeNo: (v: string) => void; alloeIdOk: boolean;
alloeFirst: string; setAlloeFirst: (v: string) => void; alloeLast: string; setAlloeLast: (v: string) => void;
termsOk: boolean; setTermsOk: (v: boolean) => void; privacyOk: boolean; setPrivacyOk: (v: boolean) => void; termsOk: boolean; setTermsOk: (v: boolean) => void; privacyOk: boolean; setPrivacyOk: (v: boolean) => void;
valid: boolean; onContinue: () => void; toLogin: () => void; onboard?: boolean; creating?: boolean; valid: boolean; onContinue: () => void; toLogin: () => void; onboard?: boolean; creating?: boolean; invited?: boolean;
}) { }) {
// Onboarding (OAuth) starts on the profile step — email is already known + verified. // Onboarding (OAuth) starts on the profile step — email is already known + verified.
const [phase, setPhase] = useState<"sso" | "profile">(p.onboard ? "profile" : "sso"); const [phase, setPhase] = useState<"sso" | "profile">(p.onboard ? "profile" : "sso");
@@ -210,21 +211,22 @@ function StepAccount(p: {
return ( return (
<div> <div>
<StepBack onClick={p.toLogin} /> <StepBack onClick={p.toLogin} />
<h1>Create your account</h1> <h1>{p.invited ? "Accept your invitation" : "Create your account"}</h1>
<p className="sub">Enter your email to get started.</p> <p className="sub">{p.invited ? "You've been invited to the team. Set up your account to join." : "Enter your email to get started."}</p>
<div style={{ marginTop: 20 }}> <div style={{ marginTop: 20 }}>
<form onSubmit={(e) => { e.preventDefault(); if (valid) { p.setSso(null); setPhase("profile"); } }}> <form onSubmit={(e) => { e.preventDefault(); if (valid) { p.setSso(null); setPhase("profile"); } }}>
<div className="field"> <div className="field">
<label className="label">Email address</label> <label className="label">Email address</label>
<div className="input-wrap"> <div className="input-wrap">
<span className="input-ico"><Icon name="mail" size={17} /></span> <span className="input-ico"><Icon name="mail" size={17} /></span>
<input className="input" type="email" value={p.email} onChange={(e) => p.setEmail(e.target.value)} placeholder="you@example.com" autoFocus /> <input className="input" type="email" value={p.email} onChange={(e) => p.setEmail(e.target.value)} placeholder="you@example.com" autoFocus={!p.invited} disabled={p.invited} readOnly={p.invited} />
</div> </div>
{p.invited && <span className="faint" style={{ fontSize: 12 }}>This is the address you were invited with.</span>}
</div> </div>
<button className="btn btn-primary" style={{ marginTop: 12 }} disabled={!valid}>Continue <Icon name="arrowR" size={16} /></button> <button className="btn btn-primary" style={{ marginTop: 12 }} disabled={!valid}>Continue <Icon name="arrowR" size={16} /></button>
</form> </form>
</div> </div>
<p className="foot-note">Already registered? <button className="link" onClick={p.toLogin}>Sign in</button></p> {!p.invited && <p className="foot-note">Already registered? <button className="link" onClick={p.toLogin}>Sign in</button></p>}
</div> </div>
); );
} }
@@ -287,47 +289,6 @@ function StepAccount(p: {
</div> </div>
)} )}
<div className="field" style={{ marginTop: 14 }}>
<label className="label">Your role</label>
<select className="input" value={p.relationship} onChange={(e) => p.setRelationship(e.target.value)}>
{relationshipOptions.map((r) => <option key={r}>{r}</option>)}
</select>
</div>
{p.isSelf ? (
<div style={{ marginTop: 12 }}><FlashNote tone="success">{p.relationship === "Owner" ? "Owner" : "Customer"} account you own this property.</FlashNote></div>
) : (() => {
const isEmployee = p.relationship === "Employee";
const cfg = ({
Employee: { banner: "Registering as a LynkedUp Pro team member.", title: "Employee details", idLabel: "Employee ID", idPh: "EMP-12345" },
Contractor:{ banner: "Registering on behalf of the property owner.", title: "Contractor details", idLabel: "Contractor ID", idPh: "Alphanumeric ID" },
"Sub-Con": { banner: "Registering on behalf of the property owner.", title: "Sub-contractor details", idLabel: "Sub-contractor ID", idPh: "Alphanumeric ID" },
Vendor: { banner: "Registering on behalf of the property owner.", title: "Vendor details", idLabel: "Vendor ID", idPh: "Alphanumeric ID" },
} as Record<string, { banner: string; title: string; idLabel: string; idPh: string }>)[p.relationship]
?? { banner: "Registering on behalf of the property owner.", title: "Property Owner Details", idLabel: "Owner / Property ID", idPh: "Alphanumeric ID" };
return (
<div style={{ marginTop: 12 }}>
<FlashNote tone="info">{cfg.banner}</FlashNote>
<div className="dashed-block" style={{ marginTop: 12 }}>
<div className="row between" style={{ marginBottom: 12 }}>
<strong style={{ fontSize: 13.5 }}>{cfg.title}</strong>
{p.alloeNo && (p.alloeIdOk ? <Badge tone="green"><Icon name="check" size={12} /> Valid</Badge> : <Badge tone="gray">Checking</Badge>)}
</div>
<div className="field">
<label className="label">{cfg.idLabel}</label>
<input className="input" value={p.alloeNo} onChange={(e) => p.setAlloeNo(e.target.value.toUpperCase())} placeholder={cfg.idPh} />
</div>
{!isEmployee && (
<div className="row gap-3" style={{ marginTop: 12 }}>
<div className="field grow"><label className="label">Owner first name</label><input className="input" value={p.alloeFirst} onChange={(e) => p.setAlloeFirst(e.target.value)} /></div>
<div className="field grow"><label className="label">Owner last name</label><input className="input" value={p.alloeLast} onChange={(e) => p.setAlloeLast(e.target.value)} /></div>
</div>
)}
</div>
</div>
);
})()}
<div className="col gap-2" style={{ marginTop: 16 }}> <div className="col gap-2" style={{ marginTop: 16 }}>
<label className="check-row"> <label className="check-row">
<input type="checkbox" checked={p.termsOk} disabled={!reviewed.terms} onChange={(e) => p.setTermsOk(e.target.checked)} /> <input type="checkbox" checked={p.termsOk} disabled={!reviewed.terms} onChange={(e) => p.setTermsOk(e.target.checked)} />
+66
View File
@@ -0,0 +1,66 @@
"use client";
import { useQuery } from "@abe-kap/appshell-sdk/react";
import { isShellConfigured } from "./appshell";
/**
* The signed-in user's effective CRM access, from crm.account.me. Drives navigation
* gating: a user with no membership/permissions sees only Dashboard + Profile; members
* see the areas their permissions allow.
*
* Every CRM permission id, granted to superadmins / owners. Used as the mock default
* when the Shell isn't configured (local demo shows everything).
*/
export const ALL_CRM_PERMISSIONS = [
"leads.manage", "pipeline.manage", "estimates.create", "dispatch.manage",
"reports.view", "billing.view", "team.manage", "roles.manage", "settings.manage",
] as const;
export interface MyAccess {
registered: boolean;
isMember: boolean;
roleSlugs: string[];
permissions: string[];
isSuperadmin: boolean;
/** True while the access query is still resolving (nav stays minimal until then). */
loading: boolean;
can: (permission: string) => boolean;
}
interface MeDTO {
registered: boolean;
isMember: boolean;
roleSlugs: string[];
permissions: string[];
isSuperadmin: boolean;
}
function useLiveAccess(): MyAccess {
const { data, loading } = useQuery<MeDTO>("crm.account.me");
const permissions = data?.permissions ?? [];
return {
registered: data?.registered ?? false,
isMember: data?.isMember ?? false,
roleSlugs: data?.roleSlugs ?? [],
permissions,
isSuperadmin: data?.isSuperadmin ?? false,
loading,
can: (p: string) => permissions.includes(p),
};
}
function useMockAccess(): MyAccess {
// No Shell (local demo): show everything so the mock UI is fully browsable.
const permissions = [...ALL_CRM_PERMISSIONS];
return {
registered: true,
isMember: true,
roleSlugs: ["superadmin"],
permissions,
isSuperadmin: true,
loading: false,
can: () => true,
};
}
export const useMyAccess: () => MyAccess = isShellConfigured() ? useLiveAccess : useMockAccess;
+113
View File
@@ -0,0 +1,113 @@
// 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, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
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 directory(): Promise<MailPerson[]> {
const rows = await this.sdk.query<DirectoryDTO[]>("crm.messenger.directory", { kind: "all", limit: 200 });
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 })) };
}
+303
View File
@@ -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: 200 });
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));
}
}
+50
View File
@@ -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]);
}
+78
View File
@@ -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();
}
+15 -7
View File
@@ -38,6 +38,8 @@ export interface UiMember {
} }
export interface UiInvite { export interface UiInvite {
id: string; email: string; roleIds: string[]; invitedBy: string; sentAt: string; id: string; email: string; roleIds: string[]; invitedBy: string; sentAt: string;
/** Accept token for the invite link (pending invites only; no email delivery yet). */
token?: string;
} }
export interface TeamData { export interface TeamData {
@@ -46,7 +48,9 @@ export interface TeamData {
setMemberRoles: (id: string, roleIds: string[]) => Promise<void>; setMemberRoles: (id: string, roleIds: string[]) => Promise<void>;
updateMember: (id: string, patch: { title?: string; roleIds?: string[] }) => Promise<void>; updateMember: (id: string, patch: { title?: string; roleIds?: string[] }) => Promise<void>;
removeMember: (id: string) => Promise<void>; removeMember: (id: string) => Promise<void>;
/** Create an invite. be-crm emails the invitee automatically. */
invite: (email: string, roleIds: string[]) => Promise<void>; invite: (email: string, roleIds: string[]) => Promise<void>;
/** Resend an invite (regenerates the token + re-emails it). */
resendInvite: (id: string) => Promise<void>; resendInvite: (id: string) => Promise<void>;
revokeInvite: (id: string) => Promise<void>; revokeInvite: (id: string) => Promise<void>;
setPermission: (roleId: string, permId: string, granted: boolean) => Promise<void>; setPermission: (roleId: string, permId: string, granted: boolean) => Promise<void>;
@@ -68,9 +72,9 @@ const initialsOf = (name: string) =>
/* ---- be-crm DTO types (subset used here) -------------------------------- */ /* ---- be-crm DTO types (subset used here) -------------------------------- */
interface RoleRef { id: string; slug: string; name: string; color: string | null; isSystem: boolean; isOwnerRole: boolean } interface RoleRef { id: string; slug: string; name: string; color: string | null; isSystem: boolean; isOwnerRole: boolean }
interface MemberDTO { id: string; principalId: string; jobTitle: string | null; joinedAt: string; status: "active" | "deactivated"; roles: RoleRef[]; openDeals: number } interface MemberDTO { id: string; principalId: string; jobTitle: string | null; joinedAt: string; status: "active" | "deactivated"; roles: RoleRef[]; openDeals: number; email?: string | null; firstName?: string | null; lastName?: string | null; displayName?: string | null }
interface RoleDTO { id: string; slug: string; name: string; description: string | null; color: string | null; isSystem: boolean; isOwnerRole: boolean; permissions: string[]; memberCount: number } interface RoleDTO { id: string; slug: string; name: string; description: string | null; color: string | null; isSystem: boolean; isOwnerRole: boolean; permissions: string[]; memberCount: number }
interface InvitationDTO { id: string; email: string; roles: RoleRef[]; invitedBy: string; createdAt: string } interface InvitationDTO { id: string; email: string; roles: RoleRef[]; invitedBy: string; createdAt: string; token?: string }
const relTime = (iso: string): string => { const relTime = (iso: string): string => {
const then = Date.parse(iso); const then = Date.parse(iso);
@@ -153,12 +157,16 @@ function useLiveTeam(): TeamData {
const members: UiMember[] = useMemo(() => (membersQ.data?.items ?? []).map((m) => { const members: UiMember[] = useMemo(() => (membersQ.data?.items ?? []).map((m) => {
const isYou = !!meId && m.principalId === meId; const isYou = !!meId && m.principalId === meId;
const name = isYou && user?.displayName // Prefer the member's real name/email from their CRM registration; fall back to the
? user.displayName // ACE (for the current user), then job title, then a short principal id.
: (m.jobTitle?.trim() || `Member ${m.principalId.replace(/^pp_/, "").slice(0, 6)}`); const name = m.displayName?.trim()
|| (isYou && user?.displayName)
|| m.jobTitle?.trim()
|| `Member ${m.principalId.replace(/^pp_/, "").slice(0, 6)}`;
const email = m.email || (isYou ? user?.email : undefined) || "";
return { return {
id: m.id, principalId: m.principalId, name, initials: initialsOf(name), id: m.id, principalId: m.principalId, name, initials: initialsOf(name),
email: isYou && user?.email ? user.email : m.principalId, email,
title: m.jobTitle ?? "", roleIds: m.roles.map((r) => r.id), gradient: gradientFor(m.id), title: m.jobTitle ?? "", roleIds: m.roles.map((r) => r.id), gradient: gradientFor(m.id),
status: (m.status === "active" ? "active" : "offline") as UiStatus, status: (m.status === "active" ? "active" : "offline") as UiStatus,
lastActive: m.status === "active" ? "Active" : "—", lastActive: m.status === "active" ? "Active" : "—",
@@ -169,7 +177,7 @@ function useLiveTeam(): TeamData {
const invites: UiInvite[] = useMemo(() => (invitesQ.data?.items ?? []).map((i) => ({ const invites: UiInvite[] = useMemo(() => (invitesQ.data?.items ?? []).map((i) => ({
id: i.id, email: i.email, roleIds: i.roles.map((r) => r.id), id: i.id, email: i.email, roleIds: i.roles.map((r) => r.id),
invitedBy: i.invitedBy, sentAt: relTime(i.createdAt), invitedBy: i.invitedBy, sentAt: relTime(i.createdAt), token: i.token,
})), [invitesQ.data]); })), [invitesQ.data]);
return { return {