Compare commits
2 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| e43c35af4d | |||
| c05aa0641c |
@@ -41,4 +41,3 @@ yarn-error.log*
|
|||||||
next-env.d.ts
|
next-env.d.ts
|
||||||
|
|
||||||
.vercel
|
.vercel
|
||||||
.env*.local
|
|
||||||
|
|||||||
@@ -1,6 +1,2 @@
|
|||||||
@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}
|
|
||||||
|
|||||||
@@ -1,240 +0,0 @@
|
|||||||
# Messaging UI SDK — Design
|
|
||||||
|
|
||||||
**Date:** 2026-07-17
|
|
||||||
**Status:** Approved, pending implementation plan
|
|
||||||
|
|
||||||
## Problem
|
|
||||||
|
|
||||||
Messaging UI is rewritten from scratch in every app that needs it. `lynkeduppro-crm`
|
|
||||||
has a rich, working messenger — conversation list, thread view, bubbles, reactions,
|
|
||||||
reply threading, typing, read receipts — built as 352 lines in
|
|
||||||
`src/components/dashboard/messenger.tsx` over 371 lines in `src/lib/messenger-api.ts`.
|
|
||||||
None of it is reusable.
|
|
||||||
|
|
||||||
### Why not just use `@insignia/iios-message-web`?
|
|
||||||
|
|
||||||
Because it does not solve this problem, and the CRM already rejected it.
|
|
||||||
|
|
||||||
`iios-message-web` is 109 lines across 2 files. It is fully headless: its only JSX is
|
|
||||||
the context provider element itself. It exports `MessageProvider`, `useThread`,
|
|
||||||
`useMessages` and a `Message` type — nothing more. It ships no components, no CSS, no
|
|
||||||
theming.
|
|
||||||
|
|
||||||
It also guessed its API wrong. `useMessages.send` narrows the options bag to
|
|
||||||
`{ contentRef? }`, while the underlying `MessageSocket.sendMessage` accepts
|
|
||||||
`parentInteractionId`, `mentions`, and `attachment`. Threading, mentions and
|
|
||||||
attachments are unreachable through its public API. The socket is held in a
|
|
||||||
module-private context with no escape hatch. It has zero consumers outside the iios
|
|
||||||
repo, and its own docs reference a `useSendMessage` hook that does not exist.
|
|
||||||
|
|
||||||
The CRM consequently bypassed it and depends on `@insignia/iios-kernel-client`
|
|
||||||
directly.
|
|
||||||
|
|
||||||
**The lesson drives this design:** the headless layer is already an SDK
|
|
||||||
(`iios-kernel-client` — sockets, threads, receipts, typing, published, consumed). A
|
|
||||||
second headless package saves no app any work. The unsolved part is the UI.
|
|
||||||
|
|
||||||
### Why tower is not a consumer
|
|
||||||
|
|
||||||
Tower's messaging is a WhatsApp group ingest → moderate → forward pipeline, not chat.
|
|
||||||
There is no `Conversation` model; `Message` is a captured group post keyed by
|
|
||||||
`senderJid` + `sourceGroupId` with a moderation `status` enum
|
|
||||||
(`RAW/PENDING/APPROVED/...`) — no recipient, no delivery state. "Send" is a BullMQ job
|
|
||||||
rate-limited to 20 forwards/minute to avoid WhatsApp bans. There is no
|
|
||||||
socket.io/websocket/SSE in the browser anywhere in the repo. Its `threads` and
|
|
||||||
`drafts` mean different things than a chat SDK's would.
|
|
||||||
|
|
||||||
Tower would pay the abstraction cost for realtime machinery it never turns on. It is
|
|
||||||
explicitly out of scope.
|
|
||||||
|
|
||||||
## Constraint: one real consumer
|
|
||||||
|
|
||||||
`lynkeduppro-crm` is the only consumer. Genericity is not achievable by intent — it is
|
|
||||||
forced by a second consumer. This design therefore ports only what is already proven
|
|
||||||
in production and refuses to invent abstraction for imagined needs. `iios-message-web`
|
|
||||||
is the cautionary example of the opposite approach.
|
|
||||||
|
|
||||||
## Architecture
|
|
||||||
|
|
||||||
One package, `@insignia/messaging-ui`, published to the existing Gitea registry
|
|
||||||
(`https://git.lynkedup.cloud/api/packages/insignia/npm/`). React as a peer dependency.
|
|
||||||
|
|
||||||
```
|
|
||||||
@insignia/messaging-ui
|
|
||||||
. → components + provider + hooks
|
|
||||||
./styles.css → structural CSS + token defaults
|
|
||||||
./adapters/kernel → optional iios-kernel-client adapter
|
|
||||||
./adapters/mock → in-memory adapter for demos/tests
|
|
||||||
```
|
|
||||||
|
|
||||||
**The core has zero transport knowledge.** `iios-kernel-client` is reachable only via
|
|
||||||
the optional `./adapters/kernel` subpath, so an app on a different backend never pulls
|
|
||||||
socket code. This is the specific mistake `iios-message-web` made by welding itself to
|
|
||||||
`MessageSocket`.
|
|
||||||
|
|
||||||
This boundary is load-bearing for the actual consumer: the CRM does **not** talk to
|
|
||||||
iios directly. It routes messaging through be-crm's data door (`crm.messenger.*`) via
|
|
||||||
`@abe-kap/appshell-sdk`, socket-primary with a 4s REST poll fallback. An SDK that
|
|
||||||
hardcoded `iios-kernel-client` could not be adopted by the only app that wants it.
|
|
||||||
|
|
||||||
## The adapter contract
|
|
||||||
|
|
||||||
Lifted from the existing `MessengerData`/`ThreadData` interfaces in
|
|
||||||
`src/lib/messenger-api.ts`, which already survived two implementations (live + mock).
|
|
||||||
Two implementations is the minimum real evidence that a seam is genuine rather than
|
|
||||||
imagined. This contract was not designed for an SDK — it earned its shape.
|
|
||||||
|
|
||||||
```ts
|
|
||||||
interface MessagingAdapter {
|
|
||||||
listConversations(): Promise<Conversation[]>;
|
|
||||||
openThread(p: { participantIds: string[]; subject?: string }): Promise<{ threadId: string }>;
|
|
||||||
history(threadId: string): Promise<Message[]>;
|
|
||||||
send(threadId: string, content: string, opts?: SendOpts): Promise<Message>;
|
|
||||||
subscribe(threadId: string, cb: (e: MessageEvent) => void): Unsubscribe;
|
|
||||||
sendTyping(threadId: string): void;
|
|
||||||
markRead(threadId: string, messageId: string): Promise<void>;
|
|
||||||
react?(messageId: string, emoji: string): Promise<void>;
|
|
||||||
upload?(file: File): Promise<{ url: string; mime: string; name: string }>;
|
|
||||||
currentActorId(): string | null;
|
|
||||||
}
|
|
||||||
|
|
||||||
interface SendOpts {
|
|
||||||
parentInteractionId?: string;
|
|
||||||
attachment?: { url: string; mime: string; name: string };
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
### Graceful degradation
|
|
||||||
|
|
||||||
`react` and `upload` are optional. When an adapter omits them the UI hides the
|
|
||||||
reaction picker or the attach button respectively. This is how one component set
|
|
||||||
serves both a full CRM messenger and a stripped-down widget without a `mode` prop.
|
|
||||||
|
|
||||||
### `currentActorId` fixes a live bug
|
|
||||||
|
|
||||||
Today the CRM infers the current actor id by scanning for a message you sent:
|
|
||||||
|
|
||||||
```ts
|
|
||||||
// src/lib/messenger-socket.tsx — current behaviour
|
|
||||||
const mine = socketMsgs.find((m) => m.mine && m.actorId);
|
|
||||||
if (mine?.actorId && mine.actorId !== myActorId) setMyActorId(mine.actorId);
|
|
||||||
```
|
|
||||||
|
|
||||||
Until you have sent a message in a thread, `myActorId` is `null`. Because the REST
|
|
||||||
poll fallback computes `mine: !!myActorId && m.actorId === myActorId`, **every message
|
|
||||||
renders as not-yours** in that state. The root cause is that the kernel's receipt
|
|
||||||
event carries no `threadId`, making it a global stream the CRM compensates for.
|
|
||||||
|
|
||||||
Making identity an explicit adapter responsibility eliminates this class of bug rather
|
|
||||||
than porting it. The two-tier socket/poll fallback stays in the adapter, not the SDK —
|
|
||||||
the CRM's adapter keeps its 4s poll; a socket-only app implements `subscribe` and
|
|
||||||
never polls.
|
|
||||||
|
|
||||||
## Components
|
|
||||||
|
|
||||||
Composable primitives plus one all-in-one for drop-in use:
|
|
||||||
|
|
||||||
```tsx
|
|
||||||
<MessagingProvider adapter={adapter}>
|
|
||||||
<Messenger onNewChat={openPicker} /> {/* all-in-one: list + thread */}
|
|
||||||
|
|
||||||
{/* ...or compose: */}
|
|
||||||
<ConversationList onSelect={setId} renderRow={custom} />
|
|
||||||
<ThreadView threadId={id} />
|
|
||||||
<Composer threadId={id} />
|
|
||||||
</MessagingProvider>
|
|
||||||
```
|
|
||||||
|
|
||||||
Hooks remain exported (`useConversations`, `useThread`, `useMessages`) so a host
|
|
||||||
wanting entirely custom UI can use the SDK headlessly. This makes `iios-message-web`'s
|
|
||||||
use case a strict subset of this package rather than a competitor.
|
|
||||||
|
|
||||||
### Explicitly out of scope
|
|
||||||
|
|
||||||
- **Inbox.** Coupled to iios semantics, not chat transport. Items are projected
|
|
||||||
server-side by iios from domain events (`MENTION`, `NEEDS_REPLY`, `SUPPORT_UPDATE`,
|
|
||||||
`CRM_OWNER_INTEREST`); authz is OPA policy. A chat SDK cannot own this.
|
|
||||||
- **People picker / directory.** Fed by `crm.messenger.directory`. "Who exists and who
|
|
||||||
may I message" is host and tenant territory. `<Messenger>` takes an `onNewChat`
|
|
||||||
callback; the host renders its own picker.
|
|
||||||
- **Presence.** No consumer needs it.
|
|
||||||
|
|
||||||
## Theming
|
|
||||||
|
|
||||||
Structural CSS with token defaults, overridden by the host. No Tailwind, no CSS-in-JS,
|
|
||||||
no build coupling — the CRM has no shadcn and near-zero Tailwind (its real styling is
|
|
||||||
1142 lines of hand-rolled `dashboard.css` plus inline style objects), so a
|
|
||||||
Tailwind-based SDK would force a restyle of the only consumer.
|
|
||||||
|
|
||||||
```css
|
|
||||||
:root {
|
|
||||||
--msg-font; --msg-radius; --msg-gap;
|
|
||||||
--msg-bubble-own-bg; --msg-bubble-other-bg;
|
|
||||||
--msg-accent; --msg-muted; --msg-surface; --msg-border;
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
Every component accepts `className`; `<Messenger>` accepts a `classNames` slot map for
|
|
||||||
per-part overrides. The CRM's existing `#6366f1 → #8b5cf6` group-avatar gradient
|
|
||||||
becomes a token value rather than a hardcode.
|
|
||||||
|
|
||||||
## Attachments
|
|
||||||
|
|
||||||
The SDK renders attachments (image thumbnail, file chip, download) and calls
|
|
||||||
`adapter.upload(file)`, passing the result into `send`. **Storage, auth, and
|
|
||||||
size/mime limits are host concerns** — baking in an upload target would break the next
|
|
||||||
app. The attach button is hidden when `upload` is absent.
|
|
||||||
|
|
||||||
`MessageSocket.sendMessage` already accepts an `attachment` field, so this exercises
|
|
||||||
an existing wire contract rather than inventing one. No consumer has exercised it yet;
|
|
||||||
the CRM has no file upload anywhere today.
|
|
||||||
|
|
||||||
## Data flow
|
|
||||||
|
|
||||||
1. Host constructs an adapter (CRM: wrapping appshell data door + socket).
|
|
||||||
2. `MessagingProvider` holds the adapter in context.
|
|
||||||
3. `useConversations` calls `listConversations`; `useMessages(threadId)` calls
|
|
||||||
`history` then `subscribe`.
|
|
||||||
4. `Composer` calls `send` with optimistic append; on rejection the optimistic message
|
|
||||||
is rolled back and the input text restored (matching current CRM behaviour).
|
|
||||||
5. `subscribe` events reconcile against optimistic state by message id.
|
|
||||||
|
|
||||||
## Error handling
|
|
||||||
|
|
||||||
- Adapter method rejection surfaces via hook `error` state; components render an
|
|
||||||
inline error affordance, never throw.
|
|
||||||
- Optimistic send failure restores composer text — the CRM's current behaviour, kept.
|
|
||||||
- `subscribe` disconnect is the adapter's problem, not the SDK's. The SDK renders a
|
|
||||||
`connected: boolean` from the adapter as a banner (the CRM's existing "Demo mode"
|
|
||||||
banner generalises to this).
|
|
||||||
|
|
||||||
## Validation
|
|
||||||
|
|
||||||
The migration is the validation. There is no second app, so the honest bar is:
|
|
||||||
|
|
||||||
1. Rewrite the CRM's `messenger.tsx` to consume the SDK; its data-door implementation
|
|
||||||
becomes `CrmMessagingAdapter`. **Success = identical behaviour with the 352-line
|
|
||||||
component deleted**, and the mock adapter preserving demo-mode fallback.
|
|
||||||
2. Then `support.tsx`'s `MessageCenter` — currently pure `setTimeout` theatre with no
|
|
||||||
backend — becomes a zero-risk second surface.
|
|
||||||
|
|
||||||
Two surfaces in one app is not a true second consumer. It is the best honest test
|
|
||||||
available of the adapter boundary, and it should be understood as such. **The design
|
|
||||||
should be revisited when a genuine second app appears** rather than treated as settled.
|
|
||||||
|
|
||||||
## Testing
|
|
||||||
|
|
||||||
- **Component tests against the mock adapter** — no network. This is the payoff of the
|
|
||||||
injected seam.
|
|
||||||
- **`CrmMessagingAdapter` tested against the contract** independently of UI.
|
|
||||||
- **A shared adapter conformance suite** any adapter can run, so the kernel and CRM
|
|
||||||
adapters are verified against one definition of correct.
|
|
||||||
- Explicit regression test for the `currentActorId` bug: messages render as own before
|
|
||||||
the user has sent anything in the thread.
|
|
||||||
|
|
||||||
## Open questions
|
|
||||||
|
|
||||||
- Package name: `@insignia/messaging-ui` assumed, not confirmed.
|
|
||||||
- Whether `CrmMessagingAdapter` lives in the CRM repo or ships as
|
|
||||||
`./adapters/crm`. Preference: the CRM repo — it depends on appshell-sdk, which the
|
|
||||||
SDK must not.
|
|
||||||
+2
-2
@@ -1,8 +1,8 @@
|
|||||||
import type { NextConfig } from "next";
|
import type { NextConfig } from "next";
|
||||||
|
|
||||||
const nextConfig: NextConfig = {
|
const nextConfig: NextConfig = {
|
||||||
// The SDKs ship ESM; let Next transpile them.
|
// The SDK ships ESM/TS; let Next transpile it.
|
||||||
transpilePackages: ["@abe-kap/appshell-sdk", "@insignia/iios-messaging-ui"],
|
transpilePackages: ["@abe-kap/appshell-sdk"],
|
||||||
// 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.
|
||||||
|
|||||||
Generated
+21
-896
File diff suppressed because it is too large
Load Diff
+1
-3
@@ -9,9 +9,7 @@
|
|||||||
"lint": "eslint"
|
"lint": "eslint"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@abe-kap/appshell-sdk": "^0.2.6",
|
"@abe-kap/appshell-sdk": "^0.2.0",
|
||||||
"@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",
|
||||||
|
|||||||
@@ -1,45 +0,0 @@
|
|||||||
import type { Metadata } from "next";
|
|
||||||
import Link from "next/link";
|
|
||||||
import "@/components/portal/portal.css";
|
|
||||||
import "./legal.css";
|
|
||||||
import { COMPANY } from "./legal-config";
|
|
||||||
|
|
||||||
export const metadata: Metadata = {
|
|
||||||
title: `${COMPANY} — Legal & SMS`,
|
|
||||||
description: `${COMPANY} SMS program opt-in, Privacy Policy and Terms of Service.`,
|
|
||||||
};
|
|
||||||
|
|
||||||
export default function LegalLayout({ children }: { children: React.ReactNode }) {
|
|
||||||
return (
|
|
||||||
<>
|
|
||||||
<link rel="preconnect" href="https://fonts.googleapis.com" />
|
|
||||||
<link rel="preconnect" href="https://fonts.gstatic.com" crossOrigin="anonymous" />
|
|
||||||
<link
|
|
||||||
href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800&display=swap"
|
|
||||||
rel="stylesheet"
|
|
||||||
/>
|
|
||||||
<div className="legal-root">
|
|
||||||
<header className="legal-bar">
|
|
||||||
<Link href="/portal/login" aria-label={`${COMPANY} home`}>
|
|
||||||
{/* eslint-disable-next-line @next/next/no-img-element */}
|
|
||||||
<img src="/image/logo.png" alt={`${COMPANY} logo`} />
|
|
||||||
</Link>
|
|
||||||
<nav>
|
|
||||||
<Link href="/sms-opt-in">SMS Alerts</Link>
|
|
||||||
<Link href="/privacy">Privacy</Link>
|
|
||||||
<Link href="/terms">Terms</Link>
|
|
||||||
</nav>
|
|
||||||
</header>
|
|
||||||
{children}
|
|
||||||
<footer className="legal-foot">
|
|
||||||
<div>© {new Date().getFullYear()} {COMPANY}. All rights reserved.</div>
|
|
||||||
<div style={{ marginTop: 8 }}>
|
|
||||||
<Link href="/sms-opt-in">SMS Alerts</Link>
|
|
||||||
<Link href="/privacy">Privacy Policy</Link>
|
|
||||||
<Link href="/terms">Terms of Service</Link>
|
|
||||||
</div>
|
|
||||||
</footer>
|
|
||||||
</div>
|
|
||||||
</>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -1,11 +0,0 @@
|
|||||||
/**
|
|
||||||
* Shared business details for the public compliance pages (SMS opt-in, Privacy,
|
|
||||||
* Terms). Edit these in one place to keep every page and disclosure consistent.
|
|
||||||
* Replace SMS_SENDER with your live Twilio number once the campaign is approved.
|
|
||||||
*/
|
|
||||||
export const COMPANY = "LynkedUp Pro";
|
|
||||||
export const SUPPORT_EMAIL = "support@lynkeduppro.com";
|
|
||||||
export const PRIVACY_EMAIL = "privacy@lynkeduppro.com";
|
|
||||||
export const SMS_SENDER = "(555) 010-0100"; // TODO: replace with your Twilio A2P number
|
|
||||||
export const SITE_URL = "https://lynkeduppro-crmnew.vercel.app";
|
|
||||||
export const LAST_UPDATED = "July 13, 2026";
|
|
||||||
@@ -1,125 +0,0 @@
|
|||||||
/* Public compliance pages (SMS opt-in, Privacy, Terms). Reuses the portal design
|
|
||||||
tokens (--bg, --text, --primary…) from portal.css for a consistent look, with
|
|
||||||
prose styling tuned for long-form legal copy. */
|
|
||||||
|
|
||||||
.legal-root {
|
|
||||||
min-height: 100vh;
|
|
||||||
background: var(--bg, #0b0c11);
|
|
||||||
color: var(--text, #f3f4f8);
|
|
||||||
font-family: var(--font-ui, "Inter", system-ui, sans-serif);
|
|
||||||
display: flex;
|
|
||||||
flex-direction: column;
|
|
||||||
}
|
|
||||||
|
|
||||||
.legal-bar {
|
|
||||||
display: flex;
|
|
||||||
align-items: center;
|
|
||||||
justify-content: space-between;
|
|
||||||
gap: 16px;
|
|
||||||
padding: 18px 24px;
|
|
||||||
border-bottom: 1px solid var(--line, rgba(255, 255, 255, 0.09));
|
|
||||||
position: sticky;
|
|
||||||
top: 0;
|
|
||||||
background: color-mix(in srgb, var(--bg, #0b0c11) 88%, transparent);
|
|
||||||
backdrop-filter: blur(10px);
|
|
||||||
z-index: 5;
|
|
||||||
}
|
|
||||||
.legal-bar img { height: 30px; width: auto; }
|
|
||||||
.legal-bar nav { display: flex; gap: 20px; flex-wrap: wrap; }
|
|
||||||
.legal-bar nav a {
|
|
||||||
color: var(--muted, #a3a8b5);
|
|
||||||
text-decoration: none;
|
|
||||||
font-size: 14px;
|
|
||||||
font-weight: 600;
|
|
||||||
}
|
|
||||||
.legal-bar nav a:hover { color: var(--text, #f3f4f8); }
|
|
||||||
.legal-bar nav a.on { color: var(--primary-2, #fb923c); }
|
|
||||||
|
|
||||||
.legal-wrap { flex: 1; width: 100%; max-width: 820px; margin: 0 auto; padding: 44px 24px 80px; }
|
|
||||||
|
|
||||||
.legal-wrap h1 { font-size: 32px; font-weight: 800; letter-spacing: -0.02em; margin: 0 0 6px; }
|
|
||||||
.legal-wrap .updated { color: var(--faint, #6c7280); font-size: 13px; margin: 0 0 30px; }
|
|
||||||
.legal-wrap h2 {
|
|
||||||
font-size: 19px; font-weight: 700; margin: 34px 0 10px;
|
|
||||||
padding-top: 20px; border-top: 1px solid var(--line, rgba(255, 255, 255, 0.09));
|
|
||||||
}
|
|
||||||
.legal-wrap h2:first-of-type { border-top: none; padding-top: 0; }
|
|
||||||
.legal-wrap p, .legal-wrap li { color: var(--muted, #a3a8b5); font-size: 15px; line-height: 1.7; }
|
|
||||||
.legal-wrap p { margin: 0 0 12px; }
|
|
||||||
.legal-wrap ul { margin: 0 0 12px; padding-left: 20px; }
|
|
||||||
.legal-wrap li { margin: 0 0 6px; }
|
|
||||||
.legal-wrap strong { color: var(--text, #f3f4f8); font-weight: 600; }
|
|
||||||
.legal-wrap a { color: var(--primary-2, #fb923c); }
|
|
||||||
|
|
||||||
/* Callout box for the mandatory SMS disclosures — makes them easy for a reviewer to find. */
|
|
||||||
.legal-callout {
|
|
||||||
border: 1px solid var(--line-2, rgba(255, 255, 255, 0.15));
|
|
||||||
background: var(--surface, rgba(255, 255, 255, 0.04));
|
|
||||||
border-radius: var(--radius-sm, 13px);
|
|
||||||
padding: 16px 18px;
|
|
||||||
margin: 8px 0 18px;
|
|
||||||
}
|
|
||||||
.legal-callout p:last-child { margin-bottom: 0; }
|
|
||||||
|
|
||||||
.legal-foot {
|
|
||||||
border-top: 1px solid var(--line, rgba(255, 255, 255, 0.09));
|
|
||||||
padding: 22px 24px;
|
|
||||||
text-align: center;
|
|
||||||
color: var(--faint, #6c7280);
|
|
||||||
font-size: 13px;
|
|
||||||
}
|
|
||||||
.legal-foot a { color: var(--muted, #a3a8b5); text-decoration: none; margin: 0 10px; }
|
|
||||||
.legal-foot a:hover { color: var(--text, #f3f4f8); }
|
|
||||||
|
|
||||||
/* SMS opt-in form */
|
|
||||||
.optin-card {
|
|
||||||
border: 1px solid var(--line, rgba(255, 255, 255, 0.09));
|
|
||||||
background: var(--surface, rgba(255, 255, 255, 0.04));
|
|
||||||
border-radius: var(--radius-sm, 13px);
|
|
||||||
padding: 22px;
|
|
||||||
margin-top: 22px;
|
|
||||||
}
|
|
||||||
.optin-field { margin-bottom: 16px; }
|
|
||||||
.optin-field label { display: block; font-weight: 600; font-size: 14px; margin-bottom: 7px; color: var(--text, #f3f4f8); }
|
|
||||||
.optin-input {
|
|
||||||
width: 100%;
|
|
||||||
background: var(--ink, #121319);
|
|
||||||
border: 1px solid var(--line-2, rgba(255, 255, 255, 0.15));
|
|
||||||
border-radius: 10px;
|
|
||||||
padding: 13px 14px;
|
|
||||||
color: var(--text, #f3f4f8);
|
|
||||||
font-size: 15px;
|
|
||||||
font-family: inherit;
|
|
||||||
}
|
|
||||||
.optin-input:focus { outline: 2px solid var(--primary, #f97316); outline-offset: 1px; border-color: transparent; }
|
|
||||||
|
|
||||||
.optin-consent { display: flex; gap: 11px; align-items: flex-start; margin: 6px 0 4px; }
|
|
||||||
.optin-consent input { margin-top: 3px; width: 18px; height: 18px; flex: none; accent-color: var(--primary, #f97316); }
|
|
||||||
.optin-consent label { font-size: 13.5px; line-height: 1.6; color: var(--muted, #a3a8b5); }
|
|
||||||
|
|
||||||
.optin-submit {
|
|
||||||
width: 100%;
|
|
||||||
margin-top: 18px;
|
|
||||||
background: var(--primary, #f97316);
|
|
||||||
color: #fff;
|
|
||||||
border: none;
|
|
||||||
border-radius: 10px;
|
|
||||||
padding: 14px;
|
|
||||||
font-size: 15px;
|
|
||||||
font-weight: 700;
|
|
||||||
cursor: pointer;
|
|
||||||
font-family: inherit;
|
|
||||||
}
|
|
||||||
.optin-submit:disabled { opacity: 0.5; cursor: not-allowed; }
|
|
||||||
|
|
||||||
.optin-fine { font-size: 12.5px; color: var(--faint, #6c7280); line-height: 1.6; margin-top: 14px; }
|
|
||||||
.optin-done {
|
|
||||||
border: 1px solid color-mix(in srgb, var(--green, #34d399) 45%, transparent);
|
|
||||||
background: color-mix(in srgb, var(--green, #34d399) 12%, transparent);
|
|
||||||
color: #a7f3d0;
|
|
||||||
border-radius: var(--radius-sm, 13px);
|
|
||||||
padding: 18px 20px;
|
|
||||||
margin-top: 22px;
|
|
||||||
font-size: 14.5px;
|
|
||||||
line-height: 1.6;
|
|
||||||
}
|
|
||||||
@@ -1,98 +0,0 @@
|
|||||||
import type { Metadata } from "next";
|
|
||||||
import Link from "next/link";
|
|
||||||
import { COMPANY, SUPPORT_EMAIL, PRIVACY_EMAIL, LAST_UPDATED } from "../legal-config";
|
|
||||||
|
|
||||||
export const metadata: Metadata = {
|
|
||||||
title: `Privacy Policy — ${COMPANY}`,
|
|
||||||
description: `How ${COMPANY} collects, uses, and protects your information, including SMS/text messaging.`,
|
|
||||||
};
|
|
||||||
|
|
||||||
export default function PrivacyPage() {
|
|
||||||
return (
|
|
||||||
<main className="legal-wrap">
|
|
||||||
<h1>Privacy Policy</h1>
|
|
||||||
<p className="updated">Last updated: {LAST_UPDATED}</p>
|
|
||||||
|
|
||||||
<p>
|
|
||||||
This Privacy Policy explains how {COMPANY} ("{COMPANY}," "we,"
|
|
||||||
"us") collects, uses, and protects your information when you use our
|
|
||||||
website, portal, and services, including our text message (SMS) program.
|
|
||||||
</p>
|
|
||||||
|
|
||||||
<h2>Information we collect</h2>
|
|
||||||
<ul>
|
|
||||||
<li><strong>Account information</strong> — name, email address, and mobile phone number you provide when registering or signing in.</li>
|
|
||||||
<li><strong>Property and service information</strong> — details you share to request roof inspections, estimates, and reports.</li>
|
|
||||||
<li><strong>Usage and device information</strong> — log data, device and browser type, and similar technical information collected automatically.</li>
|
|
||||||
</ul>
|
|
||||||
|
|
||||||
<h2>How we use your information</h2>
|
|
||||||
<ul>
|
|
||||||
<li>To create and secure your account, including sending one-time verification codes (OTP).</li>
|
|
||||||
<li>To provide, maintain, and improve our services.</li>
|
|
||||||
<li>To communicate with you about your account, appointments, estimates, and support requests.</li>
|
|
||||||
<li>To comply with legal obligations and protect against fraud and abuse.</li>
|
|
||||||
</ul>
|
|
||||||
|
|
||||||
<h2>SMS / text messaging</h2>
|
|
||||||
<div className="legal-callout">
|
|
||||||
<p>
|
|
||||||
<strong>
|
|
||||||
We do not sell, rent, or share your mobile phone number, or your SMS opt-in
|
|
||||||
consent, with any third parties or affiliates for their marketing or
|
|
||||||
promotional purposes.
|
|
||||||
</strong>
|
|
||||||
</p>
|
|
||||||
<p>
|
|
||||||
Mobile information collected for the purpose of sending text messages is used
|
|
||||||
only to deliver the messages you opted into and is not shared with third parties
|
|
||||||
for marketing. We may share your number only with service providers (such as our
|
|
||||||
messaging platform) strictly to deliver the messages, and as required by law.
|
|
||||||
</p>
|
|
||||||
<p>
|
|
||||||
<strong>Message frequency varies</strong> — verification codes are sent when you
|
|
||||||
request them (for example, each time you sign in or register), and account or
|
|
||||||
service notifications are occasional. <strong>Message and data rates may
|
|
||||||
apply</strong>, depending on your mobile carrier and plan.
|
|
||||||
</p>
|
|
||||||
<p>
|
|
||||||
You can opt out at any time by replying <strong>STOP</strong> to any message, and
|
|
||||||
get help by replying <strong>HELP</strong>. See our{" "}
|
|
||||||
<Link href="/terms">Terms of Service</Link> and the{" "}
|
|
||||||
<Link href="/sms-opt-in">SMS opt-in page</Link> for full program details.
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<h2>How we share information</h2>
|
|
||||||
<p>
|
|
||||||
We do not sell your personal information. We share information only with service
|
|
||||||
providers who help us operate the service (for example, cloud hosting,
|
|
||||||
authentication, and messaging providers), and when required by law or to protect
|
|
||||||
our rights. As stated above, mobile phone numbers and SMS consent are never shared
|
|
||||||
with third parties or affiliates for marketing purposes.
|
|
||||||
</p>
|
|
||||||
|
|
||||||
<h2>Data retention and security</h2>
|
|
||||||
<p>
|
|
||||||
We retain personal information for as long as your account is active or as needed to
|
|
||||||
provide the service and meet legal obligations. We use administrative, technical,
|
|
||||||
and physical safeguards designed to protect your information; no method of
|
|
||||||
transmission or storage is completely secure.
|
|
||||||
</p>
|
|
||||||
|
|
||||||
<h2>Your choices and rights</h2>
|
|
||||||
<p>
|
|
||||||
You may access or update your account information at any time, opt out of SMS by
|
|
||||||
replying STOP, and request deletion of your account by contacting us. Depending on
|
|
||||||
your location, you may have additional rights under applicable privacy laws.
|
|
||||||
</p>
|
|
||||||
|
|
||||||
<h2>Contact us</h2>
|
|
||||||
<p>
|
|
||||||
Questions about this Privacy Policy? Email us at{" "}
|
|
||||||
<a href={`mailto:${PRIVACY_EMAIL}`}>{PRIVACY_EMAIL}</a> or{" "}
|
|
||||||
<a href={`mailto:${SUPPORT_EMAIL}`}>{SUPPORT_EMAIL}</a>.
|
|
||||||
</p>
|
|
||||||
</main>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -1,125 +0,0 @@
|
|||||||
"use client";
|
|
||||||
|
|
||||||
import { useState } from "react";
|
|
||||||
import Link from "next/link";
|
|
||||||
import { COMPANY, SMS_SENDER, SUPPORT_EMAIL } from "../legal-config";
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Public SMS opt-in web form for A2P 10DLC campaign verification. Contains every
|
|
||||||
* element Twilio/CTIA require: phone field, an un-pre-checked consent checkbox, a
|
|
||||||
* description of the messages, frequency, rates disclaimer, HELP/STOP instructions,
|
|
||||||
* and links to the Terms and Privacy Policy.
|
|
||||||
*/
|
|
||||||
export default function SmsOptInPage() {
|
|
||||||
const [phone, setPhone] = useState("");
|
|
||||||
const [consent, setConsent] = useState(false);
|
|
||||||
const [done, setDone] = useState(false);
|
|
||||||
|
|
||||||
const digits = phone.replace(/\D/g, "");
|
|
||||||
const valid = digits.length >= 10 && consent;
|
|
||||||
|
|
||||||
function onSubmit(e: React.FormEvent) {
|
|
||||||
e.preventDefault();
|
|
||||||
if (!valid) return;
|
|
||||||
// Records the opt-in. Consent + timestamp should be persisted server-side for your
|
|
||||||
// records; this confirmation is the user-facing acknowledgement.
|
|
||||||
setDone(true);
|
|
||||||
}
|
|
||||||
|
|
||||||
return (
|
|
||||||
<main className="legal-wrap">
|
|
||||||
<h1>{COMPANY} SMS Alerts</h1>
|
|
||||||
<p className="updated">Sign up to receive text messages from {COMPANY}.</p>
|
|
||||||
|
|
||||||
<p>
|
|
||||||
At {COMPANY}, we send text messages to help you use and secure your account. By
|
|
||||||
opting in below you'll receive <strong>account and service messages</strong>,
|
|
||||||
including:
|
|
||||||
</p>
|
|
||||||
<ul>
|
|
||||||
<li>One-time verification codes (OTP) when you sign in or register</li>
|
|
||||||
<li>Sign-in and security alerts</li>
|
|
||||||
<li>Roof inspection scheduling and status updates</li>
|
|
||||||
<li>Estimate and report notifications</li>
|
|
||||||
</ul>
|
|
||||||
|
|
||||||
{done ? (
|
|
||||||
<div className="optin-done" role="status">
|
|
||||||
<strong>You're signed up.</strong>{" "}We'll text account and service
|
|
||||||
messages to {phone}. Reply <strong>STOP</strong>{" "}at any time to unsubscribe,
|
|
||||||
or <strong>HELP</strong>{" "}for help.
|
|
||||||
</div>
|
|
||||||
) : (
|
|
||||||
<form className="optin-card" onSubmit={onSubmit}>
|
|
||||||
<div className="optin-field">
|
|
||||||
<label htmlFor="sms-phone">Mobile phone number</label>
|
|
||||||
<input
|
|
||||||
id="sms-phone"
|
|
||||||
className="optin-input"
|
|
||||||
type="tel"
|
|
||||||
inputMode="tel"
|
|
||||||
autoComplete="tel"
|
|
||||||
placeholder="+1 (555) 010-0100"
|
|
||||||
value={phone}
|
|
||||||
onChange={(e) => setPhone(e.target.value)}
|
|
||||||
required
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Consent checkbox — MUST NOT be pre-checked (starts false). */}
|
|
||||||
<div className="optin-consent">
|
|
||||||
<input
|
|
||||||
id="sms-consent"
|
|
||||||
type="checkbox"
|
|
||||||
checked={consent}
|
|
||||||
onChange={(e) => setConsent(e.target.checked)}
|
|
||||||
/>
|
|
||||||
<label htmlFor="sms-consent">
|
|
||||||
I agree to receive account and service text messages (including one-time
|
|
||||||
verification codes) from {COMPANY} at the number provided. Consent is not a
|
|
||||||
condition of purchase. Message frequency varies. Message and data rates may
|
|
||||||
apply. Reply HELP for help and STOP to unsubscribe. See our{" "}
|
|
||||||
<Link href="/terms">Terms of Service</Link> and{" "}
|
|
||||||
<Link href="/privacy">Privacy Policy</Link>.
|
|
||||||
</label>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<button className="optin-submit" type="submit" disabled={!valid}>
|
|
||||||
Yes, sign me up!
|
|
||||||
</button>
|
|
||||||
|
|
||||||
<p className="optin-fine">
|
|
||||||
Message frequency varies. Message and data rates may apply. Reply{" "}
|
|
||||||
<strong>HELP</strong>{" "}for help or <strong>STOP</strong>{" "}to cancel at any
|
|
||||||
time. Carriers are not liable for delayed or undelivered messages.
|
|
||||||
</p>
|
|
||||||
</form>
|
|
||||||
)}
|
|
||||||
|
|
||||||
<h2>Program details</h2>
|
|
||||||
<ul>
|
|
||||||
<li><strong>Program name:</strong> {COMPANY} Account & Service Alerts</li>
|
|
||||||
<li><strong>Message types:</strong> verification codes (OTP), security alerts, appointment and inspection updates, estimate notifications</li>
|
|
||||||
<li><strong>Message frequency:</strong> varies — codes are sent when you request them (e.g. each sign-in or registration); notifications are occasional</li>
|
|
||||||
<li><strong>Cost:</strong> Message and data rates may apply, per your mobile plan</li>
|
|
||||||
</ul>
|
|
||||||
|
|
||||||
<h2>How to opt out or get help</h2>
|
|
||||||
<p>
|
|
||||||
Reply <strong>STOP</strong>{" "}to any message to unsubscribe — you'll get one
|
|
||||||
confirmation and no further texts. Reply <strong>HELP</strong>{" "}for help, or
|
|
||||||
contact us at <a href={`mailto:${SUPPORT_EMAIL}`}>{SUPPORT_EMAIL}</a>
|
|
||||||
{SMS_SENDER ? <> or {SMS_SENDER}</> : null}. Messages are sent from {COMPANY}.
|
|
||||||
</p>
|
|
||||||
|
|
||||||
<h2>Your privacy</h2>
|
|
||||||
<p>
|
|
||||||
<strong>
|
|
||||||
We do not sell, rent, or share your mobile phone number or your SMS opt-in
|
|
||||||
consent with any third parties or affiliates for their marketing purposes.
|
|
||||||
</strong>{" "}
|
|
||||||
See our <Link href="/privacy">Privacy Policy</Link>{" "}for full details.
|
|
||||||
</p>
|
|
||||||
</main>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -1,85 +0,0 @@
|
|||||||
import type { Metadata } from "next";
|
|
||||||
import Link from "next/link";
|
|
||||||
import { COMPANY, SUPPORT_EMAIL, LAST_UPDATED } from "../legal-config";
|
|
||||||
|
|
||||||
export const metadata: Metadata = {
|
|
||||||
title: `Terms of Service — ${COMPANY}`,
|
|
||||||
description: `The terms governing your use of ${COMPANY}, including the SMS/text messaging program.`,
|
|
||||||
};
|
|
||||||
|
|
||||||
export default function TermsPage() {
|
|
||||||
return (
|
|
||||||
<main className="legal-wrap">
|
|
||||||
<h1>Terms of Service</h1>
|
|
||||||
<p className="updated">Last updated: {LAST_UPDATED}</p>
|
|
||||||
|
|
||||||
<p>
|
|
||||||
These Terms of Service ("Terms") govern your access to and use of the {COMPANY}{" "}
|
|
||||||
website, portal, and services (the "Service"). By using the
|
|
||||||
Service you agree to these Terms.
|
|
||||||
</p>
|
|
||||||
|
|
||||||
<h2>Use of the Service</h2>
|
|
||||||
<p>
|
|
||||||
You must provide accurate information, keep your credentials secure, and use the
|
|
||||||
Service only for lawful purposes and in accordance with these Terms. You are
|
|
||||||
responsible for activity that occurs under your account.
|
|
||||||
</p>
|
|
||||||
|
|
||||||
<h2>Accounts and verification</h2>
|
|
||||||
<p>
|
|
||||||
To protect your account we may verify your identity, including by sending one-time
|
|
||||||
codes to your email or mobile number. You agree to receive these verification
|
|
||||||
messages as part of using the Service.
|
|
||||||
</p>
|
|
||||||
|
|
||||||
<h2>SMS / text messaging program</h2>
|
|
||||||
<div className="legal-callout">
|
|
||||||
<p>
|
|
||||||
By opting in on our <Link href="/sms-opt-in">SMS opt-in page</Link> or by
|
|
||||||
providing your mobile number and agreeing to receive texts, you consent to
|
|
||||||
receive <strong>account and service text messages</strong> from {COMPANY},
|
|
||||||
including one-time verification codes (OTP), security alerts, appointment and
|
|
||||||
inspection updates, and estimate notifications.
|
|
||||||
</p>
|
|
||||||
<p>
|
|
||||||
<strong>Message frequency varies.</strong> <strong>Message and data rates may
|
|
||||||
apply.</strong> Reply <strong>HELP</strong> for help or <strong>STOP</strong> to
|
|
||||||
unsubscribe at any time; after you send STOP we will send one confirmation and no
|
|
||||||
further messages. Carriers are not liable for delayed or undelivered messages.
|
|
||||||
</p>
|
|
||||||
<p>
|
|
||||||
We do not sell, rent, or share your mobile number or SMS consent with third
|
|
||||||
parties or affiliates for marketing. See our{" "}
|
|
||||||
<Link href="/privacy">Privacy Policy</Link> for details.
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<h2>Acceptable use</h2>
|
|
||||||
<p>
|
|
||||||
You may not misuse the Service, attempt to access accounts or data you are not
|
|
||||||
authorized to access, interfere with the Service's operation, or use it to
|
|
||||||
send unlawful, harmful, or infringing content.
|
|
||||||
</p>
|
|
||||||
|
|
||||||
<h2>Disclaimers and limitation of liability</h2>
|
|
||||||
<p>
|
|
||||||
The Service is provided "as is" without warranties of any kind. To the
|
|
||||||
fullest extent permitted by law, {COMPANY} is not liable for any indirect,
|
|
||||||
incidental, or consequential damages arising from your use of the Service.
|
|
||||||
</p>
|
|
||||||
|
|
||||||
<h2>Changes to these Terms</h2>
|
|
||||||
<p>
|
|
||||||
We may update these Terms from time to time. Continued use of the Service after
|
|
||||||
changes take effect constitutes acceptance of the updated Terms.
|
|
||||||
</p>
|
|
||||||
|
|
||||||
<h2>Contact us</h2>
|
|
||||||
<p>
|
|
||||||
Questions about these Terms? Email us at{" "}
|
|
||||||
<a href={`mailto:${SUPPORT_EMAIL}`}>{SUPPORT_EMAIL}</a>.
|
|
||||||
</p>
|
|
||||||
</main>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -1,28 +0,0 @@
|
|||||||
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 });
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -106,11 +106,6 @@
|
|||||||
.sb-user .av { width: 30px; height: 30px; border-radius: 8px; object-fit: cover; flex: 0 0 30px; }
|
.sb-user .av { width: 30px; height: 30px; border-radius: 8px; object-fit: cover; flex: 0 0 30px; }
|
||||||
.sb-user .nm { font-size: 12.5px; font-weight: 600; }
|
.sb-user .nm { font-size: 12.5px; font-weight: 600; }
|
||||||
.sb-user .rl { font-size: 11px; color: var(--faint); }
|
.sb-user .rl { font-size: 11px; color: var(--faint); }
|
||||||
.sb-user .nm, .sb-user .rl { max-width: 130px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
|
|
||||||
.sb-user-menu { position: absolute; bottom: 56px; left: 12px; right: 12px; z-index: 30; padding: 6px; border-radius: 12px; border: 1px solid var(--border-2); background: var(--panel); box-shadow: var(--shadow), 0 8px 30px -12px rgba(0,0,0,0.55); animation: ds-rise 0.14s ease; }
|
|
||||||
.sb-user-menu button { display: flex; align-items: center; gap: 9px; width: 100%; padding: 9px 10px; border: 0; border-radius: 9px; background: none; color: var(--text-2); font-family: inherit; font-size: 12.5px; font-weight: 600; cursor: pointer; text-align: left; }
|
|
||||||
.sb-user-menu button:hover { background: var(--panel-2); }
|
|
||||||
.sb-user-menu button.danger { color: var(--red, #ef4444); }
|
|
||||||
|
|
||||||
/* ---- main ---- */
|
/* ---- main ---- */
|
||||||
.dash-main { flex: 1; min-width: 0; display: flex; flex-direction: column; }
|
.dash-main { flex: 1; min-width: 0; display: flex; flex-direction: column; }
|
||||||
@@ -134,21 +129,6 @@
|
|||||||
.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; }
|
||||||
@@ -452,7 +432,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; flex: 1 1 auto; min-height: 0; }
|
.dash-root .ds-modal-body { padding: 18px 20px; overflow-y: auto; }
|
||||||
.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 ---- */
|
||||||
@@ -1156,23 +1136,3 @@
|
|||||||
.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; }
|
|
||||||
|
|||||||
@@ -1,113 +0,0 @@
|
|||||||
"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>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -1,56 +0,0 @@
|
|||||||
"use client";
|
|
||||||
|
|
||||||
import { useEffect, 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 { RegisterFlow } from "@/components/portal/register-flow";
|
|
||||||
import { CookieBanner } from "@/components/portal/bits";
|
|
||||||
import { isShellConfigured } from "@/lib/appshell";
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Post-OAuth onboarding — a first-time Google user completes their CRM profile
|
|
||||||
* (everything except email, which Google already verified).
|
|
||||||
*
|
|
||||||
* This screen is ONLY a step in the OAuth → onboarding handoff: the login page
|
|
||||||
* stashes the verified email in `sessionStorage` right before routing here. Any
|
|
||||||
* other way in — a typed URL, a fresh tab, a lost session — has no handoff hint
|
|
||||||
* (and possibly no session), so we bounce back to sign in rather than showing an
|
|
||||||
* empty form.
|
|
||||||
*/
|
|
||||||
export default function OnboardingPage() {
|
|
||||||
const router = useRouter();
|
|
||||||
const { status } = useAuth();
|
|
||||||
const { ready } = useAppShell();
|
|
||||||
const [allowed, setAllowed] = useState(false);
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
if (!isShellConfigured()) { setAllowed(true); return; } // local dev without the Shell
|
|
||||||
if (!ready) return; // wait for session restore
|
|
||||||
let hasHandoff = false;
|
|
||||||
try { hasHandoff = !!sessionStorage.getItem("onboard_email"); } catch { /* ignore */ }
|
|
||||||
if (status === "unauthenticated" || !hasHandoff) {
|
|
||||||
router.replace("/portal/login");
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
setAllowed(true);
|
|
||||||
}, [ready, status, router]);
|
|
||||||
|
|
||||||
if (!allowed) return <main className="portal-main"><span className="portal-grid" /></main>;
|
|
||||||
|
|
||||||
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 />
|
|
||||||
<RegisterFlow mode="onboard" />
|
|
||||||
</div>
|
|
||||||
</section>
|
|
||||||
</div>
|
|
||||||
<CookieBanner />
|
|
||||||
</main>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -2,7 +2,7 @@
|
|||||||
|
|
||||||
import { useEffect } from "react";
|
import { useEffect } from "react";
|
||||||
import { useRouter } from "next/navigation";
|
import { useRouter } from "next/navigation";
|
||||||
import { useAuth, useAppShell } from "@abe-kap/appshell-sdk/react";
|
import { useAuth } from "@abe-kap/appshell-sdk/react";
|
||||||
import { isShellConfigured } from "@/lib/appshell";
|
import { isShellConfigured } from "@/lib/appshell";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -14,21 +14,16 @@ import { isShellConfigured } from "@/lib/appshell";
|
|||||||
export function AuthGate({ children }: { children: React.ReactNode }) {
|
export function AuthGate({ children }: { children: React.ReactNode }) {
|
||||||
const router = useRouter();
|
const router = useRouter();
|
||||||
const { status } = useAuth();
|
const { status } = useAuth();
|
||||||
const { ready } = useAppShell();
|
|
||||||
const shell = isShellConfigured();
|
const shell = isShellConfigured();
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
// Only bounce to login once the SDK has finished booting AND restore() has
|
if (shell && status === "unauthenticated") router.replace("/portal/login");
|
||||||
// resolved to unauthenticated. Redirecting while boot is still in flight would
|
}, [shell, status, router]);
|
||||||
// drop a perfectly valid session on reload (the status is transiently not-yet
|
|
||||||
// "authenticated" during boot).
|
|
||||||
if (shell && ready && status === "unauthenticated") router.replace("/portal/login");
|
|
||||||
}, [shell, ready, status, router]);
|
|
||||||
|
|
||||||
if (shell && (!ready || status !== "authenticated")) {
|
if (shell && status !== "authenticated") {
|
||||||
return (
|
return (
|
||||||
<div style={{ minHeight: "60vh", display: "grid", placeItems: "center", color: "var(--muted, #888)" }}>
|
<div style={{ minHeight: "60vh", display: "grid", placeItems: "center", color: "var(--muted, #888)" }}>
|
||||||
{ready && status === "unauthenticated" ? "Redirecting to sign in…" : "Loading your workspace…"}
|
{status === "loading" ? "Loading your workspace…" : "Redirecting to sign in…"}
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -15,9 +15,6 @@ 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() {
|
||||||
@@ -48,9 +45,6 @@ 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>
|
||||||
|
|||||||
@@ -1,48 +0,0 @@
|
|||||||
"use client";
|
|
||||||
|
|
||||||
// The CRM Inbox, rendered by @insignia/iios-messaging-ui instead of the bespoke in-CRM inbox.
|
|
||||||
// Live = the be-crm data door (CrmInboxAdapter over crm.inbox.* + crm.mail.*); demo = the SDK's
|
|
||||||
// MockInboxAdapter.
|
|
||||||
|
|
||||||
import { useMemo } from "react";
|
|
||||||
import { useAppShell } from "@abe-kap/appshell-sdk/react";
|
|
||||||
import { InboxProvider, Inbox as SdkInbox, type InboxAdapter } from "@insignia/iios-messaging-ui";
|
|
||||||
import { MockInboxAdapter } from "@insignia/iios-messaging-ui/adapters/mock-inbox";
|
|
||||||
import "@insignia/iios-messaging-ui/styles.css";
|
|
||||||
import { isShellConfigured } from "@/lib/appshell";
|
|
||||||
import { CrmInboxAdapter } from "@/lib/crm-inbox-adapter";
|
|
||||||
import type { DataDoor } from "@/lib/crm-messaging-adapter";
|
|
||||||
|
|
||||||
const SHELL = isShellConfigured();
|
|
||||||
|
|
||||||
export function InboxSdk() {
|
|
||||||
return (
|
|
||||||
<div className="view">
|
|
||||||
{!SHELL && (
|
|
||||||
<div style={{ margin: "0 0 14px", padding: "8px 14px", borderRadius: 10, background: "var(--panel-2)", color: "var(--muted)", fontSize: 13, border: "1px solid var(--border)" }}>
|
|
||||||
Demo mode — running on the SDK's mock inbox adapter.
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
<div className="miu-host miu-host-inbox">{SHELL ? <LiveInbox /> : <DemoInbox />}</div>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
function DemoInbox() {
|
|
||||||
const adapter = useMemo<InboxAdapter>(() => new MockInboxAdapter(), []);
|
|
||||||
return (
|
|
||||||
<InboxProvider adapter={adapter}>
|
|
||||||
<SdkInbox />
|
|
||||||
</InboxProvider>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
function LiveInbox() {
|
|
||||||
const { sdk } = useAppShell();
|
|
||||||
const adapter = useMemo<InboxAdapter>(() => new CrmInboxAdapter(sdk as unknown as DataDoor), [sdk]);
|
|
||||||
return (
|
|
||||||
<InboxProvider adapter={adapter}>
|
|
||||||
<SdkInbox />
|
|
||||||
</InboxProvider>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -1,89 +0,0 @@
|
|||||||
"use client";
|
|
||||||
|
|
||||||
// The CRM messenger, now rendered by the shared @insignia/iios-messaging-ui SDK instead of a
|
|
||||||
// bespoke in-CRM implementation. The CRM only supplies an adapter (transport) + theming; all the
|
|
||||||
// UI + messaging logic lives in the SDK. Live path = the be-crm data door (CrmMessagingAdapter);
|
|
||||||
// demo path = the SDK's own MockAdapter.
|
|
||||||
|
|
||||||
import { useEffect, useMemo, useState } from "react";
|
|
||||||
import { useAppShell, useAuth, useQuery } from "@abe-kap/appshell-sdk/react";
|
|
||||||
import { MessageSocket } from "@insignia/iios-kernel-client";
|
|
||||||
import { MessagingProvider, Messenger as SdkMessenger, type MessagingAdapter } from "@insignia/iios-messaging-ui";
|
|
||||||
import { MockAdapter } from "@insignia/iios-messaging-ui/adapters/mock";
|
|
||||||
import "@insignia/iios-messaging-ui/styles.css";
|
|
||||||
import { isShellConfigured } from "@/lib/appshell";
|
|
||||||
import { CrmMessagingAdapter, type DataDoor } from "@/lib/crm-messaging-adapter";
|
|
||||||
|
|
||||||
interface RealtimeDTO { url: string; audience: string; token?: string }
|
|
||||||
|
|
||||||
/** Open the IIOS message socket with the delegated token the BFF mints (crm.messenger.realtime). */
|
|
||||||
function useRealtimeSocket(): MessageSocket | null {
|
|
||||||
const rt = useQuery<RealtimeDTO>("crm.messenger.realtime", {});
|
|
||||||
const [socket, setSocket] = useState<MessageSocket | null>(null);
|
|
||||||
const url = rt.data?.url;
|
|
||||||
const token = rt.data?.token;
|
|
||||||
useEffect(() => {
|
|
||||||
if (!url || !token) return;
|
|
||||||
const s = new MessageSocket({ serviceUrl: url, token, autoConnect: false });
|
|
||||||
s.connect();
|
|
||||||
setSocket(s);
|
|
||||||
return () => {
|
|
||||||
s.disconnect();
|
|
||||||
setSocket(null);
|
|
||||||
};
|
|
||||||
}, [url, token]);
|
|
||||||
return socket;
|
|
||||||
}
|
|
||||||
|
|
||||||
const SHELL = isShellConfigured();
|
|
||||||
|
|
||||||
export function MessengerSdk() {
|
|
||||||
return (
|
|
||||||
<div className="view">
|
|
||||||
{!SHELL && (
|
|
||||||
<div
|
|
||||||
style={{
|
|
||||||
margin: "0 0 14px",
|
|
||||||
padding: "8px 14px",
|
|
||||||
borderRadius: 10,
|
|
||||||
background: "var(--panel-2)",
|
|
||||||
color: "var(--muted)",
|
|
||||||
fontSize: 13,
|
|
||||||
border: "1px solid var(--border)",
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
Demo mode — running on the SDK's mock adapter.
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
<div className="miu-host">{SHELL ? <LiveHost /> : <DemoHost />}</div>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
// SHELL is a build-time constant, so exactly one of these mounts for the life of the app
|
|
||||||
// (Rules-of-Hooks safe — the other branch never renders).
|
|
||||||
function DemoHost() {
|
|
||||||
const adapter = useMemo<MessagingAdapter>(() => new MockAdapter(), []);
|
|
||||||
return (
|
|
||||||
<MessagingProvider adapter={adapter}>
|
|
||||||
<SdkMessenger />
|
|
||||||
</MessagingProvider>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
function LiveHost() {
|
|
||||||
const { sdk } = useAppShell();
|
|
||||||
const { user } = useAuth();
|
|
||||||
const socket = useRealtimeSocket();
|
|
||||||
// Rebuilds once the socket connects: the first adapter (no socket) polls; the second runs live.
|
|
||||||
const adapter = useMemo<MessagingAdapter | null>(
|
|
||||||
() => (user?.id ? new CrmMessagingAdapter(sdk as unknown as DataDoor, user.id, socket ?? undefined) : null),
|
|
||||||
[sdk, user?.id, socket],
|
|
||||||
);
|
|
||||||
if (!adapter) return <div className="miu-empty">Loading…</div>;
|
|
||||||
return (
|
|
||||||
<MessagingProvider adapter={adapter}>
|
|
||||||
<SdkMessenger />
|
|
||||||
</MessagingProvider>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -1,136 +0,0 @@
|
|||||||
"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>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -1,16 +1,8 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
import { useState } from "react";
|
import { ChevronsUpDown } from "lucide-react";
|
||||||
import { useRouter } from "next/navigation";
|
|
||||||
import { ChevronsUpDown, LogOut } from "lucide-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 {
|
|
||||||
return name.split(/\s+/).filter(Boolean).slice(0, 2).map((p) => p[0]).join("").toUpperCase() || "?";
|
|
||||||
}
|
|
||||||
|
|
||||||
export type NavItem = { key: string; label: string; icon: string; subtitle?: string };
|
export type NavItem = { key: string; label: string; icon: string; subtitle?: string };
|
||||||
export type NavGroup = { title: string; items: NavItem[] };
|
export type NavGroup = { title: string; items: NavItem[] };
|
||||||
@@ -29,13 +21,6 @@ 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: [
|
||||||
@@ -75,58 +60,7 @@ 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 { user: me, logout, context } = useAuth();
|
|
||||||
const access = useMyAccess();
|
|
||||||
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
|
|
||||||
// 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 name = me?.displayName || user.name;
|
|
||||||
const initials = me ? initialsOf(me.displayName) : user.initials;
|
|
||||||
const secondary = me?.email || roleLabel || user.role;
|
|
||||||
|
|
||||||
async function signOut() {
|
|
||||||
setMenuOpen(false);
|
|
||||||
try { await logout(); } catch { /* ignore — proceed to portal either way */ }
|
|
||||||
router.replace("/portal/login");
|
|
||||||
}
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<aside className="dash-sidebar">
|
<aside className="dash-sidebar">
|
||||||
<div className="dash-brand">
|
<div className="dash-brand">
|
||||||
@@ -135,7 +69,7 @@ export function Sidebar({ active, onSelect }: { active: string; onSelect: (k: st
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
<nav className="dash-nav">
|
<nav className="dash-nav">
|
||||||
{visibleGroups.map((g, gi) => (
|
{NAV_GROUPS.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) => (
|
||||||
@@ -148,20 +82,12 @@ export function Sidebar({ active, onSelect }: { active: string; onSelect: (k: st
|
|||||||
))}
|
))}
|
||||||
</nav>
|
</nav>
|
||||||
|
|
||||||
<div className="sb-foot" style={{ position: "relative" }}>
|
<div className="sb-foot">
|
||||||
{menuOpen && (
|
<button className="sb-user">
|
||||||
<>
|
<span className="av" style={{ background: user.avatarGradient, display: "grid", placeItems: "center", color: "#fff", fontWeight: 700, fontSize: 12 }}>{user.initials}</span>
|
||||||
<div className="tm-menu-scrim" onClick={() => setMenuOpen(false)} />
|
<div style={{ flex: 1, textAlign: "left" }}>
|
||||||
<div className="sb-user-menu" role="menu">
|
<div className="nm">{user.name}</div>
|
||||||
<button className="danger" onClick={signOut}><LogOut size={15} /> Sign out</button>
|
<div className="rl">{user.role}</div>
|
||||||
</div>
|
|
||||||
</>
|
|
||||||
)}
|
|
||||||
<button className="sb-user" onClick={() => setMenuOpen((o) => !o)} aria-haspopup="menu" aria-expanded={menuOpen}>
|
|
||||||
<span className="av" style={{ background: user.avatarGradient, display: "grid", placeItems: "center", color: "#fff", fontWeight: 700, fontSize: 12 }}>{initials}</span>
|
|
||||||
<div style={{ flex: 1, textAlign: "left", minWidth: 0 }}>
|
|
||||||
<div className="nm">{name}</div>
|
|
||||||
<div className="rl" style={{ overflow: "hidden", textOverflow: "ellipsis" }}>{secondary}</div>
|
|
||||||
</div>
|
</div>
|
||||||
<ChevronsUpDown size={15} />
|
<ChevronsUpDown size={15} />
|
||||||
</button>
|
</button>
|
||||||
|
|||||||
@@ -301,15 +301,8 @@ 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 emailed to ${inv.email}.` }); }
|
try { await team.resendInvite(inv.id); toast.push({ tone: "success", title: "Invite resent", desc: `A fresh link was sent 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 () => {
|
||||||
@@ -333,7 +326,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: `We emailed an invite to ${email}. You can also copy the link.` });
|
toast.push({ tone: "success", title: "Invitation sent", desc: `${email} was invited with ${roleIds.length} role${roleIds.length === 1 ? "" : "s"}.` });
|
||||||
} 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 }); }
|
||||||
}}
|
}}
|
||||||
/>
|
/>
|
||||||
|
|||||||
@@ -1,33 +1,20 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
import { useState } from "react";
|
import { Sun, Moon, ChevronDown } from "lucide-react";
|
||||||
import { useRouter } from "next/navigation";
|
|
||||||
import { Sun, Moon, ChevronDown, LogOut } from "lucide-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 { useAuth } from "@abe-kap/appshell-sdk/react";
|
||||||
|
|
||||||
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();
|
||||||
}
|
}
|
||||||
|
|
||||||
export function Topbar({ theme, onToggle, title, subtitle }: { theme: "dark" | "light"; onToggle: () => void; title: string; subtitle: string }) {
|
export function Topbar({ theme, onToggle, title, subtitle }: { theme: "dark" | "light"; onToggle: () => void; title: string; subtitle: string }) {
|
||||||
// When signed in through the Shell, show the real identity from the App Context
|
// When signed in through the Shell, show the real identity from the App Context
|
||||||
// Envelope; otherwise fall back to the static demo user.
|
// Envelope; otherwise fall back to the static demo user.
|
||||||
const router = useRouter();
|
const { user: me } = useAuth();
|
||||||
const { user: me, logout, context } = useAuth();
|
|
||||||
const [menuOpen, setMenuOpen] = useState(false);
|
|
||||||
const roleLabel = context?.scope?.role ? context.scope.role.charAt(0).toUpperCase() + context.scope.role.slice(1) : "";
|
|
||||||
const name = me?.displayName || user.name;
|
const name = me?.displayName || user.name;
|
||||||
const initials = me ? initialsOf(me.displayName) : user.initials;
|
const initials = me ? initialsOf(me.displayName) : user.initials;
|
||||||
const secondary = me?.email || roleLabel || user.role;
|
|
||||||
|
|
||||||
async function signOut() {
|
|
||||||
setMenuOpen(false);
|
|
||||||
try { await logout(); } catch { /* ignore */ }
|
|
||||||
router.replace("/portal/login");
|
|
||||||
}
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<header className="dash-topbar">
|
<header className="dash-topbar">
|
||||||
<div className="dash-title">
|
<div className="dash-title">
|
||||||
@@ -43,24 +30,14 @@ export function Topbar({ theme, onToggle, title, subtitle }: { theme: "dark" | "
|
|||||||
<Icon name="bell" size={18} />
|
<Icon name="bell" size={18} />
|
||||||
<span style={{ position: "absolute", top: 9, right: 10, width: 7, height: 7, borderRadius: 99, background: "var(--orange)", border: "2px solid var(--panel)" }} />
|
<span style={{ position: "absolute", top: 9, right: 10, width: 7, height: 7, borderRadius: 99, background: "var(--orange)", border: "2px solid var(--panel)" }} />
|
||||||
</button>
|
</button>
|
||||||
<div className="top-user-wrap" style={{ position: "relative" }}>
|
<button className="top-user">
|
||||||
<button className="top-user" onClick={() => setMenuOpen((o) => !o)} aria-haspopup="menu" aria-expanded={menuOpen}>
|
|
||||||
<span className="av" style={{ background: user.avatarGradient, display: "grid", placeItems: "center", color: "#fff", fontWeight: 700, fontSize: 12 }}>{initials}</span>
|
<span className="av" style={{ background: user.avatarGradient, display: "grid", placeItems: "center", color: "#fff", fontWeight: 700, fontSize: 12 }}>{initials}</span>
|
||||||
<div style={{ textAlign: "left", minWidth: 0 }}>
|
<div style={{ textAlign: "left" }}>
|
||||||
<div className="nm">{name}</div>
|
<div className="nm">{name}</div>
|
||||||
<div className="rl" style={{ overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap", maxWidth: 150 }}>{secondary}</div>
|
<div className="rl">{user.role}</div>
|
||||||
</div>
|
</div>
|
||||||
<ChevronDown size={16} />
|
<ChevronDown size={16} />
|
||||||
</button>
|
</button>
|
||||||
{menuOpen && (
|
|
||||||
<>
|
|
||||||
<div className="tm-menu-scrim" onClick={() => setMenuOpen(false)} />
|
|
||||||
<div className="tm-menu-pop" role="menu">
|
|
||||||
<button className="danger" onClick={signOut}><LogOut size={15} /> Sign out</button>
|
|
||||||
</div>
|
|
||||||
</>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
</div>
|
</div>
|
||||||
</header>
|
</header>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -14,7 +14,6 @@ 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,
|
||||||
@@ -222,11 +221,6 @@ 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(); };
|
||||||
@@ -234,8 +228,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 || !mounted) return null;
|
if (!open) return null;
|
||||||
const overlay = (
|
return (
|
||||||
<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">
|
||||||
@@ -253,7 +247,6 @@ export function Modal({ open, onClose, title, subtitle, icon, children, footer,
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
return host ? createPortal(overlay, host) : overlay;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/* ---------------------------------------------------------- */
|
/* ---------------------------------------------------------- */
|
||||||
|
|||||||
@@ -145,13 +145,18 @@ export function startSocial(provider: "google" | "microsoft" | "apple"): boolean
|
|||||||
if (url) { window.location.href = url; return true; }
|
if (url) { window.location.href = url; return true; }
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
export function SocialButtons({ onPick, verb = "Continue" }: { onPick: (p: "google") => void; verb?: string }) {
|
export function SocialButtons({ onPick, verb = "Continue" }: { onPick: (p: "google" | "microsoft" | "apple") => void; verb?: string }) {
|
||||||
// Only Google is offered (Microsoft/Apple intentionally hidden).
|
|
||||||
return (
|
return (
|
||||||
<div className="col gap-3">
|
<div className="col gap-3">
|
||||||
<button className="btn btn-oauth" type="button" onClick={() => onPick("google")}>
|
<button className="btn btn-oauth" type="button" onClick={() => onPick("google")}>
|
||||||
<GoogleMark /> {verb} with Google
|
<GoogleMark /> {verb} with Google
|
||||||
</button>
|
</button>
|
||||||
|
<button className="btn btn-oauth" type="button" onClick={() => onPick("microsoft")}>
|
||||||
|
<MicrosoftMark /> {verb} with Microsoft / Outlook
|
||||||
|
</button>
|
||||||
|
<button className="btn btn-oauth" type="button" onClick={() => onPick("apple")}>
|
||||||
|
<AppleMark /> {verb} with Apple
|
||||||
|
</button>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -9,9 +9,8 @@ import {
|
|||||||
PasswordStrength,
|
PasswordStrength,
|
||||||
} from "./bits";
|
} from "./bits";
|
||||||
import { lookupAccount, maskEmail, type Account } from "./data";
|
import { lookupAccount, maskEmail, type Account } from "./data";
|
||||||
import { useAuth, useAppShell } from "@abe-kap/appshell-sdk/react";
|
import { useAuth } from "@abe-kap/appshell-sdk/react";
|
||||||
import { isShellConfigured } from "@/lib/appshell";
|
import { isShellConfigured } from "@/lib/appshell";
|
||||||
import { MOCK_OTP } from "@/lib/otp";
|
|
||||||
|
|
||||||
// Map the portal's social button ids to Supabase OAuth provider ids.
|
// Map the portal's social button ids to Supabase OAuth provider ids.
|
||||||
const OAUTH_PROVIDER: Record<string, string> = { google: "google", microsoft: "azure", apple: "apple" };
|
const OAUTH_PROVIDER: Record<string, string> = { google: "google", microsoft: "azure", apple: "apple" };
|
||||||
@@ -25,45 +24,13 @@ const EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
|
|||||||
|
|
||||||
export function LoginFlow() {
|
export function LoginFlow() {
|
||||||
const router = useRouter();
|
const router = useRouter();
|
||||||
const { login, loginWithOAuth, completeOAuthLogin, getUserEmail } = useAuth();
|
const { login, loginWithOAuth, completeOAuthLogin } = useAuth();
|
||||||
const { ready, sdk } = useAppShell();
|
|
||||||
const [step, setStep] = useState<Step>("identify");
|
const [step, setStep] = useState<Step>("identify");
|
||||||
const [email, setEmail] = useState("");
|
const [email, setEmail] = useState("");
|
||||||
const [account, setAccount] = useState<Account | null>(null);
|
const [account, setAccount] = useState<Account | null>(null);
|
||||||
const [provider, setProvider] = useState<string>("");
|
const [provider, setProvider] = useState<string>("");
|
||||||
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 [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).
|
|
||||||
function blankAccount(): Account {
|
|
||||||
return { firstName: "", name: "", initials: "", hasPasskey: false, hasTotp: false, hasPush: false, maskedEmail: maskEmail(email || ""), maskedPhone: "", maskedWa: "" };
|
|
||||||
}
|
|
||||||
// Direct "sign in with phone" → the one-time-code screen, SMS preselected.
|
|
||||||
function startPhoneLogin() {
|
|
||||||
setAccount(blankAccount());
|
|
||||||
setOtpChannel("sms");
|
|
||||||
push("otp"); // push (not replace) so Back returns to the identify screen
|
|
||||||
}
|
|
||||||
|
|
||||||
/* ---- history hash sync ---- */
|
/* ---- history hash sync ---- */
|
||||||
function push(s: Step) {
|
function push(s: Step) {
|
||||||
@@ -91,31 +58,11 @@ export function LoginFlow() {
|
|||||||
if (!isShellConfigured()) return;
|
if (!isShellConfigured()) return;
|
||||||
const code = new URLSearchParams(window.location.search).get("code");
|
const code = new URLSearchParams(window.location.search).get("code");
|
||||||
if (!code) return;
|
if (!code) return;
|
||||||
// Wait until the SDK has booted — completeOAuthLogin no-ops (returns null) if
|
|
||||||
// sdk.auth isn't ready yet, and this effect only re-runs when `ready` flips.
|
|
||||||
if (!ready) { setStep("connecting"); return; }
|
|
||||||
setStep("connecting");
|
setStep("connecting");
|
||||||
completeOAuthLogin(code)
|
completeOAuthLogin(code)
|
||||||
.then(async (ace) => {
|
.then((ace) => { if (ace) router.replace("/dashboard"); else replace("identify"); })
|
||||||
if (!ace) { replace("identify"); return; }
|
.catch(() => { setFlash("Sign-in with that provider didn't complete. Try again."); replace("identify"); });
|
||||||
// First-time Google user (no CRM profile yet) → complete onboarding; an
|
}, [completeOAuthLogin, router]);
|
||||||
// existing profile → straight to the dashboard.
|
|
||||||
let registered = false;
|
|
||||||
try {
|
|
||||||
const st = await sdk.query<{ registered: boolean }>("crm.account.registrationStatus");
|
|
||||||
registered = !!st?.registered;
|
|
||||||
} catch { registered = false; }
|
|
||||||
window.history.replaceState({}, "", "/portal/login");
|
|
||||||
if (registered) { await acceptPendingInviteThenDashboard(); return; }
|
|
||||||
// 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 */ }
|
|
||||||
router.replace("/portal/onboarding");
|
|
||||||
})
|
|
||||||
.catch(() => {
|
|
||||||
setFlash("Google sign-in didn't complete. Please try again.");
|
|
||||||
replace("identify");
|
|
||||||
});
|
|
||||||
}, [ready, completeOAuthLogin, router, sdk, getUserEmail]);
|
|
||||||
|
|
||||||
/* ---- auth resolution ---- */
|
/* ---- auth resolution ---- */
|
||||||
function afterAuth(factor: "password" | "passkey" | "otp" | "totp" | "push" | "social") {
|
function afterAuth(factor: "password" | "passkey" | "otp" | "totp" | "push" | "social") {
|
||||||
@@ -153,8 +100,7 @@ export function LoginFlow() {
|
|||||||
hasPasskey: false, hasTotp: false, hasPush: false,
|
hasPasskey: false, hasTotp: false, hasPush: false,
|
||||||
maskedEmail: maskEmail(email), maskedPhone: "", maskedWa: "",
|
maskedEmail: maskEmail(email), maskedPhone: "", maskedWa: "",
|
||||||
});
|
});
|
||||||
setOtpChannel("email");
|
replace("password");
|
||||||
push("password"); // push (not replace) so Back returns to the email screen, not off-page
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
push("connecting");
|
push("connecting");
|
||||||
@@ -170,18 +116,14 @@ export function LoginFlow() {
|
|||||||
/* =================================================================== */
|
/* =================================================================== */
|
||||||
return (
|
return (
|
||||||
<div className="card anim-fade-up" key={step}>
|
<div className="card anim-fade-up" key={step}>
|
||||||
{step === "identify" && (
|
{step === "identify" && <Identify email={email} setEmail={setEmail} onSocial={onSocial} onEmail={identifyEmail} toRegister={() => router.push("/portal/register")} />}
|
||||||
<>
|
|
||||||
{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")} invited={invited} />
|
|
||||||
</>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{step === "connecting" && (
|
{step === "connecting" && (
|
||||||
<div className="interstitial">
|
<div className="interstitial">
|
||||||
<Spinner lg />
|
<Spinner lg />
|
||||||
<div>
|
<div>
|
||||||
<h1 style={{ fontSize: 20 }}>{provider ? `Connecting to ${cap(provider)}…` : "Looking up your account…"}</h1>
|
<h1 style={{ fontSize: 20 }}>{provider ? `Connecting to ${cap(provider)}…` : "Looking up your account…"}</h1>
|
||||||
|
{provider && <p className="sub" style={{ marginTop: 6 }}>Demo mode — no provider keys configured.</p>}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
@@ -220,11 +162,11 @@ export function LoginFlow() {
|
|||||||
)}
|
)}
|
||||||
|
|
||||||
{step === "password" && account && (
|
{step === "password" && account && (
|
||||||
<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")} />
|
<Password account={account} email={email} login={login} onAuthenticated={() => router.replace("/dashboard")} flash={flash} onBack={back} onForgot={() => push("fp_confirm")} onOtp={() => 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={acceptPendingInviteThenDashboard} />
|
<OtpVerify account={account} email={email} remember={remember} setRemember={setRemember} onBack={back} onVerified={() => afterAuth("otp")} onAuthenticated={() => router.replace("/dashboard")} />
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{step === "another" && account && (
|
{step === "another" && account && (
|
||||||
@@ -288,17 +230,17 @@ export function LoginFlow() {
|
|||||||
|
|
||||||
/* ============================ screens ============================ */
|
/* ============================ screens ============================ */
|
||||||
|
|
||||||
function Identify({ email, setEmail, onSocial, onEmail, onPhone, toRegister, invited }: {
|
function Identify({ email, setEmail, onSocial, onEmail, toRegister }: {
|
||||||
email: string; setEmail: (v: string) => void;
|
email: string; setEmail: (v: string) => void;
|
||||||
onSocial: (p: "google") => void; onEmail: () => void; onPhone: () => void; toRegister: () => void; invited?: boolean;
|
onSocial: (p: "google" | "microsoft" | "apple") => void; onEmail: () => void; toRegister: () => void;
|
||||||
}) {
|
}) {
|
||||||
const [showEmail, setShowEmail] = useState(!!invited);
|
const [showEmail, setShowEmail] = useState(false);
|
||||||
const valid = EMAIL_RE.test(email);
|
const valid = EMAIL_RE.test(email);
|
||||||
return (
|
return (
|
||||||
<div>
|
<div>
|
||||||
<div className="kicker">{invited ? "You're invited" : "Welcome back"}</div>
|
<div className="kicker">Welcome back</div>
|
||||||
<h1>{invited ? "Sign in to join the team" : "Sign in to LynkedUp"}</h1>
|
<h1>Sign in to LynkedUp</h1>
|
||||||
<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>
|
<p className="sub">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} />
|
||||||
@@ -321,12 +263,6 @@ function Identify({ email, setEmail, onSocial, onEmail, onPhone, toRegister, inv
|
|||||||
</button>
|
</button>
|
||||||
</form>
|
</form>
|
||||||
)}
|
)}
|
||||||
{/* Phone (SMS) sign-in needs a deliverable one-time code — hidden while SMS is
|
|
||||||
mocked, since a faked code can't mint a real session. Email + password + Google
|
|
||||||
all work without SMS. */}
|
|
||||||
{isShellConfigured() && !MOCK_OTP && (
|
|
||||||
<button className="link" style={{ marginTop: 14, display: "block" }} onClick={onPhone}><Icon name="sms" size={15} /> Sign in with a phone number instead</button>
|
|
||||||
)}
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<p className="foot-note">New homeowner or contractor? <button className="link" onClick={toRegister}>Register here</button></p>
|
<p className="foot-note">New homeowner or contractor? <button className="link" onClick={toRegister}>Register here</button></p>
|
||||||
@@ -335,6 +271,7 @@ function Identify({ email, setEmail, onSocial, onEmail, onPhone, toRegister, inv
|
|||||||
<span><Icon name="shield" size={13} /> Licensed & Insured</span>
|
<span><Icon name="shield" size={13} /> Licensed & Insured</span>
|
||||||
<span><Icon name="check" size={13} /> Drone-Powered</span>
|
<span><Icon name="check" size={13} /> Drone-Powered</span>
|
||||||
</div>
|
</div>
|
||||||
|
<p className="demo-hint">Demo: any email signs in; an email starting with “new” shows “not found”.</p>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -369,6 +306,7 @@ function Passkey({ account, onBack, onPassword, onAnother, onSuccess, onFail }:
|
|||||||
<button className="link" onClick={onPassword}>Use your password instead</button>
|
<button className="link" onClick={onPassword}>Use your password instead</button>
|
||||||
<button className="link" onClick={onAnother}>Try another way</button>
|
<button className="link" onClick={onAnother}>Try another way</button>
|
||||||
</div>
|
</div>
|
||||||
|
<p className="demo-hint">Demo: passkey always succeeds here.</p>
|
||||||
<button hidden onClick={onFail} />
|
<button hidden onClick={onFail} />
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
@@ -419,19 +357,20 @@ function Password({ account, email, login, onAuthenticated, flash, onBack, onFor
|
|||||||
</form>
|
</form>
|
||||||
<div className="row between" style={{ marginTop: 16 }}>
|
<div className="row between" style={{ marginTop: 16 }}>
|
||||||
<button className="link" onClick={onForgot}>Forgot password?</button>
|
<button className="link" onClick={onForgot}>Forgot password?</button>
|
||||||
<button className="link" onClick={onOtp}>Sign in with a one-time code</button>
|
<button className="link" onClick={onOtp}>Sign in using email OTP</button>
|
||||||
</div>
|
</div>
|
||||||
|
{!isShellConfigured() && <p className="demo-hint">Demo: any password works; type “wrong” to see the lockout. Password always needs 2-step next.</p>}
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
function OtpVerify({ account, email, initialChannel = "email", remember, setRemember, onBack, onVerified, onAuthenticated }: {
|
function OtpVerify({ account, email, remember, setRemember, onBack, onVerified, onAuthenticated }: {
|
||||||
account: Account; email: string; initialChannel?: "email" | "sms"; remember: boolean; setRemember: (v: boolean) => void; onBack: () => void; onVerified: () => void; onAuthenticated: () => void;
|
account: Account; email: string; remember: boolean; setRemember: (v: boolean) => void; onBack: () => void; onVerified: () => void; onAuthenticated: () => void;
|
||||||
}) {
|
}) {
|
||||||
const { sendEmailOtp, verifyEmailOtp, sendPhoneOtp, verifyPhoneOtp } = useAuth();
|
const { sendEmailOtp, verifyEmailOtp, sendPhoneOtp, verifyPhoneOtp } = useAuth();
|
||||||
const shell = isShellConfigured();
|
const shell = isShellConfigured();
|
||||||
// In Shell mode only email + SMS are real Supabase OTP channels; hide WhatsApp.
|
// In Shell mode only email + SMS are real Supabase OTP channels; hide WhatsApp.
|
||||||
const [channel, setChannel] = useState<"email" | "sms" | "wa">(initialChannel);
|
const [channel, setChannel] = useState<"email" | "sms" | "wa">("email");
|
||||||
const [phone, setPhone] = useState("");
|
const [phone, setPhone] = useState("");
|
||||||
const [sent, setSent] = useState(false);
|
const [sent, setSent] = useState(false);
|
||||||
const [busy, setBusy] = useState(false);
|
const [busy, setBusy] = useState(false);
|
||||||
@@ -454,14 +393,7 @@ 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) {
|
} catch (e) { setError((e as Error).message); }
|
||||||
// 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) {
|
||||||
@@ -480,22 +412,12 @@ function OtpVerify({ account, email, initialChannel = "email", remember, setReme
|
|||||||
<div>
|
<div>
|
||||||
<StepBack onClick={onBack} />
|
<StepBack onClick={onBack} />
|
||||||
<h1>{shell ? "One-time passcode" : "2-step verification"}</h1>
|
<h1>{shell ? "One-time passcode" : "2-step verification"}</h1>
|
||||||
<p className="sub">
|
<p className="sub">{shell ? "We'll text or email you a 6-digit code to sign in." : "Enter the 6-digit code we sent you to finish signing in."}</p>
|
||||||
{!shell
|
|
||||||
? "Enter the 6-digit code we sent you to finish signing in."
|
|
||||||
: channel === "sms"
|
|
||||||
? "We'll text a 6-digit code to sign in."
|
|
||||||
: "We'll email you a 6-digit code to sign in."}
|
|
||||||
</p>
|
|
||||||
{/* In Shell mode the channel is fixed by how you signed in (email vs phone) —
|
|
||||||
no toggle, so an email sign-in never shows a stray SMS option. */}
|
|
||||||
{!shell && (
|
|
||||||
<div className="seg" style={{ margin: "16px 0 14px" }}>
|
<div className="seg" style={{ margin: "16px 0 14px" }}>
|
||||||
<button className={channel === "email" ? "on" : ""} onClick={() => { setChannel("email"); setError(""); setSent(false); }}><Icon name="mail" size={15} /> Email</button>
|
<button className={channel === "email" ? "on" : ""} onClick={() => { setChannel("email"); setError(""); setSent(false); }}><Icon name="mail" size={15} /> Email</button>
|
||||||
<button className={channel === "sms" ? "on" : ""} onClick={() => { setChannel("sms"); setError(""); setSent(false); }}><Icon name="sms" size={15} /> SMS</button>
|
<button className={channel === "sms" ? "on" : ""} onClick={() => { setChannel("sms"); setError(""); setSent(false); }}><Icon name="sms" size={15} /> SMS</button>
|
||||||
<button className={channel === "wa" ? "on" : ""} onClick={() => { setChannel("wa"); setError(""); }}><Icon name="whatsapp" size={15} /> WhatsApp</button>
|
{!shell && <button className={channel === "wa" ? "on" : ""} onClick={() => { setChannel("wa"); setError(""); }}><Icon name="whatsapp" size={15} /> WhatsApp</button>}
|
||||||
</div>
|
</div>
|
||||||
)}
|
|
||||||
|
|
||||||
{shell && channel === "sms" && !sent ? (
|
{shell && channel === "sms" && !sent ? (
|
||||||
<form onSubmit={(e) => { e.preventDefault(); void send(); }}>
|
<form onSubmit={(e) => { e.preventDefault(); void send(); }}>
|
||||||
@@ -518,6 +440,7 @@ function OtpVerify({ account, email, initialChannel = "email", remember, setReme
|
|||||||
<span />
|
<span />
|
||||||
</div>
|
</div>
|
||||||
<RememberDevice checked={remember} onChange={setRemember} note="2-step is still required at each sign-in." />
|
<RememberDevice checked={remember} onChange={setRemember} note="2-step is still required at each sign-in." />
|
||||||
|
{!shell && <p className="demo-hint">Demo: any 6 digits verify; “000000” shows an error.</p>}
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -572,6 +495,7 @@ function Totp({ remember, setRemember, onBack, onVerified }: { remember: boolean
|
|||||||
{setupKey ? "Enter a 6-digit code instead" : "Enter setup key instead"}
|
{setupKey ? "Enter a 6-digit code instead" : "Enter setup key instead"}
|
||||||
</button>
|
</button>
|
||||||
<RememberDevice checked={remember} onChange={setRemember} />
|
<RememberDevice checked={remember} onChange={setRemember} />
|
||||||
|
<p className="demo-hint">Demo: any 6 digits verify; “000000” fails.</p>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -590,6 +514,7 @@ function PushApprove({ onBack, onApproved, onCancel }: { onBack: () => void; onA
|
|||||||
<p className="sub" style={{ textAlign: "center" }}>{approved ? "Your sign-in was approved." : "We sent a notification to your mobile app. Approve it to continue."}</p>
|
<p className="sub" style={{ textAlign: "center" }}>{approved ? "Your sign-in was approved." : "We sent a notification to your mobile app. Approve it to continue."}</p>
|
||||||
<div className="interstitial">{approved ? <Icon name="check" size={30} /> : <Spinner lg />}</div>
|
<div className="interstitial">{approved ? <Icon name="check" size={30} /> : <Spinner lg />}</div>
|
||||||
{!approved && <button className="btn" onClick={onCancel}>Cancel</button>}
|
{!approved && <button className="btn" onClick={onCancel}>Cancel</button>}
|
||||||
|
<p className="demo-hint">Demo: auto-approves after ~3 seconds.</p>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -673,6 +598,7 @@ function ForgotCode({ onBack, onOk }: { onBack: () => void; onOk: () => void })
|
|||||||
<div style={{ marginTop: 18 }}><OtpBoxes onComplete={(c) => (c === "000000" ? setError(true) : onOk())} error={error} /></div>
|
<div style={{ marginTop: 18 }}><OtpBoxes onComplete={(c) => (c === "000000" ? setError(true) : onOk())} error={error} /></div>
|
||||||
{error && <div style={{ marginTop: 12 }}><FlashNote tone="error">Incorrect code.</FlashNote></div>}
|
{error && <div style={{ marginTop: 12 }}><FlashNote tone="error">Incorrect code.</FlashNote></div>}
|
||||||
<div style={{ marginTop: 14 }}><ResendLink seconds={30} /></div>
|
<div style={{ marginTop: 14 }}><ResendLink seconds={30} /></div>
|
||||||
|
<p className="demo-hint">Demo: any 6 digits work; “000000” fails.</p>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -5,35 +5,26 @@ import { useRouter } from "next/navigation";
|
|||||||
import { Icon, Avatar } from "./icons";
|
import { Icon, Avatar } from "./icons";
|
||||||
import {
|
import {
|
||||||
StepBack, FlashNote, Badge, OtpBoxes, ResendLink, RememberDevice,
|
StepBack, FlashNote, Badge, OtpBoxes, ResendLink, RememberDevice,
|
||||||
PasswordStrength, LegalModal,
|
SocialButtons, startSocial, PasswordStrength, LegalModal,
|
||||||
} from "./bits";
|
} from "./bits";
|
||||||
import {
|
import {
|
||||||
countryCodes, addressCountries,
|
countryCodes, relationshipOptions, 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";
|
||||||
import { isShellConfigured } from "@/lib/appshell";
|
import { isShellConfigured } from "@/lib/appshell";
|
||||||
import { MOCK_OTP, DEMO_OTP } from "@/lib/otp";
|
|
||||||
|
|
||||||
type Addr = { line1?: string; line2?: string; city?: string; state?: string; postalCode?: string; country?: string; locality?: string };
|
type Addr = { line1?: string; line2?: string; city?: string; state?: string; postalCode?: string; country?: string; locality?: string };
|
||||||
|
|
||||||
const STEPS = ["Account", "Verify", "Address"];
|
const STEPS = ["Account", "Verify", "Address"];
|
||||||
const EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
|
const EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
|
||||||
|
|
||||||
export function RegisterFlow({ mode = "register" }: { mode?: "register" | "onboard" }) {
|
export function RegisterFlow() {
|
||||||
// "onboard" = an already-authenticated OAuth (Google) user completing their CRM
|
|
||||||
// profile: email is skipped (Google-verified), the auth account already exists so
|
|
||||||
// we only SET a password + persist the profile, and the OTP-verify step is skipped.
|
|
||||||
const onboard = mode === "onboard";
|
|
||||||
const router = useRouter();
|
const router = useRouter();
|
||||||
const { register, setPassword, getUserEmail, addPhone, verifyPhone } = useAuth();
|
const { register } = useAuth();
|
||||||
const { sdk } = useAppShell();
|
const { sdk } = useAppShell();
|
||||||
const [step, setStep] = useState(0);
|
const [step, setStep] = useState(0);
|
||||||
const [submitErr, setSubmitErr] = useState("");
|
const [submitErr, setSubmitErr] = useState("");
|
||||||
// Verifying a phone via Supabase needs a live session. Onboarding already has one
|
|
||||||
// (Google OAuth); registration creates the account when leaving the Account step,
|
|
||||||
// then attaches + verifies the phone on it. `creating` guards the Account button.
|
|
||||||
const [creating, setCreating] = useState(false);
|
|
||||||
|
|
||||||
// address (lifted from StepAddress/AddressBlock so finish() can persist it)
|
// address (lifted from StepAddress/AddressBlock so finish() can persist it)
|
||||||
const [regAddr, setRegAddr] = useState<Addr>({});
|
const [regAddr, setRegAddr] = useState<Addr>({});
|
||||||
@@ -48,58 +39,29 @@ 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
|
||||||
|
const [emailVerified, setEmailVerified] = useState(false);
|
||||||
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
|
|
||||||
// page stashed at OAuth time, then confirmed via the live Supabase session.
|
|
||||||
useEffect(() => {
|
|
||||||
if (!onboard) return;
|
|
||||||
try { const cached = sessionStorage.getItem("onboard_email"); if (cached) setEmail(cached); } catch { /* ignore */ }
|
|
||||||
getUserEmail().then((e) => { if (e) setEmail(e); }).catch(() => { /* ignore */ });
|
|
||||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
||||||
}, [onboard]);
|
|
||||||
|
|
||||||
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;
|
termsOk && privacyOk && (isSelf || (alloeIdOk && (isEmployee || (alloeFirst.trim() && alloeLast.trim()))));
|
||||||
|
|
||||||
// Email is already trusted in both flows (registration: Supabase auto-confirms on
|
const step2Valid = emailVerified && phoneVerified;
|
||||||
// signup; onboarding: Google-verified), so the Verify step only gates on the phone.
|
|
||||||
const verifyValid = phoneVerified;
|
|
||||||
|
|
||||||
// Registration: create the auth account when leaving the Account step, so the phone
|
|
||||||
// can be attached + verified against a live session at the Verify step. Onboarding
|
|
||||||
// is already authenticated, so it just advances.
|
|
||||||
async function leaveAccountStep() {
|
|
||||||
if (onboard || !isShellConfigured() || sso) { setStep(1); return; }
|
|
||||||
setSubmitErr("");
|
|
||||||
setCreating(true);
|
|
||||||
try {
|
|
||||||
await register(email, pw);
|
|
||||||
setStep(1);
|
|
||||||
} catch {
|
|
||||||
setSubmitErr("We couldn't create that account. The email may already be registered.");
|
|
||||||
} finally {
|
|
||||||
setCreating(false);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async function finish() {
|
async function finish() {
|
||||||
const finalEmail = sso?.email || email;
|
const finalEmail = sso?.email || email;
|
||||||
@@ -107,78 +69,66 @@ 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 */ }
|
||||||
|
|
||||||
if (isShellConfigured()) {
|
if (isShellConfigured()) {
|
||||||
setSubmitErr("");
|
setSubmitErr("");
|
||||||
// 1) Auth account already exists at this point — registration created it when
|
// 1) Auth account — appshell → Supabase (SSO users already have a session).
|
||||||
// leaving the Account step; onboarding users signed in via Google. Onboarding
|
if (!sso) {
|
||||||
// additionally sets a password so email+password login works too (the phone was
|
try { await register(finalEmail, pw); }
|
||||||
// just verified against the same live session).
|
catch { setSubmitErr("We couldn't create that account. The email may already be registered."); return; }
|
||||||
if (onboard && pw) {
|
|
||||||
try { await setPassword(pw); } catch { /* non-fatal — the profile still saves */ }
|
|
||||||
}
|
}
|
||||||
// 2) Persist the CRM registration payload to be-crm (name, phone, addresses,
|
// 2) Persist the full CRM registration payload to be-crm (name, phone, persona,
|
||||||
// consent). No role/persona — a new user has no permissions until invited.
|
// allottee, both addresses, consent). Non-fatal: the auth account exists either way.
|
||||||
// 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,
|
||||||
consentTerms: termsOk, consentPrivacy: privacyOk,
|
consentTerms: termsOk, consentPrivacy: privacyOk,
|
||||||
});
|
});
|
||||||
} catch {
|
} catch (e) {
|
||||||
if (onboard) { setSubmitErr("Couldn't save your profile. Please try again."); return; }
|
console.warn("crm.account.register failed (continuing):", e);
|
||||||
// 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.
|
|
||||||
try { sessionStorage.removeItem("onboard_email"); } catch { /* ignore */ }
|
|
||||||
router.push("/dashboard");
|
router.push("/dashboard");
|
||||||
}
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="card anim-fade-up">
|
<div className="card anim-fade-up">
|
||||||
<Stepper current={step} labels={STEP_LABELS} />
|
<Stepper current={step} />
|
||||||
|
|
||||||
{step === 0 && (
|
{step === 0 && (
|
||||||
<>
|
|
||||||
{submitErr && <div style={{ marginBottom: 14 }}><FlashNote tone="error">{submitErr}</FlashNote></div>}
|
|
||||||
<StepAccount
|
<StepAccount
|
||||||
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={() => setStep(1)} toLogin={() => router.push("/portal/login")}
|
||||||
/>
|
/>
|
||||||
</>
|
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{step === 1 && (
|
{step === 1 && (
|
||||||
<StepVerify
|
<StepVerify
|
||||||
cc={cc} phone={phone} country={country}
|
emailValue={sso?.email || email} cc={cc} phone={phone} country={country}
|
||||||
|
emailVerified={emailVerified} setEmailVerified={setEmailVerified}
|
||||||
phoneVerified={phoneVerified} setPhoneVerified={setPhoneVerified}
|
phoneVerified={phoneVerified} setPhoneVerified={setPhoneVerified}
|
||||||
valid={verifyValid} onBack={() => setStep(0)} onContinue={() => setStep(2)}
|
valid={step2Valid} onBack={() => setStep(0)} onContinue={() => setStep(2)}
|
||||||
/>
|
/>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
@@ -199,53 +149,59 @@ 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; invited?: boolean;
|
valid: boolean; onContinue: () => void; toLogin: () => void;
|
||||||
}) {
|
}) {
|
||||||
// Onboarding (OAuth) starts on the profile step — email is already known + verified.
|
const [phase, setPhase] = useState<"sso" | "profile">("sso");
|
||||||
const [phase, setPhase] = useState<"sso" | "profile">(p.onboard ? "profile" : "sso");
|
|
||||||
const [modal, setModal] = useState<null | "terms" | "privacy">(null);
|
const [modal, setModal] = useState<null | "terms" | "privacy">(null);
|
||||||
|
|
||||||
|
function pickSso(provider: "google" | "microsoft" | "apple") {
|
||||||
|
if (startSocial(provider)) return;
|
||||||
|
const mockEmail = `you@${provider === "microsoft" ? "outlook.com" : provider + ".com"}`;
|
||||||
|
p.setSso({ provider, email: mockEmail });
|
||||||
|
p.setEmail(mockEmail);
|
||||||
|
setPhase("profile");
|
||||||
|
}
|
||||||
|
|
||||||
if (phase === "sso") {
|
if (phase === "sso") {
|
||||||
const valid = EMAIL_RE.test(p.email);
|
const valid = EMAIL_RE.test(p.email);
|
||||||
return (
|
return (
|
||||||
<div>
|
<div>
|
||||||
<StepBack onClick={p.toLogin} />
|
<h1>Create your account</h1>
|
||||||
<h1>{p.invited ? "Accept your invitation" : "Create your account"}</h1>
|
<p className="sub">Sign up with a provider or 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 }}>
|
||||||
|
<SocialButtons onPick={pickSso} verb="Sign up" />
|
||||||
|
<div className="divider">or continue with email</div>
|
||||||
<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={!p.invited} disabled={p.invited} readOnly={p.invited} />
|
<input className="input" type="email" value={p.email} onChange={(e) => p.setEmail(e.target.value)} placeholder="you@example.com" autoFocus />
|
||||||
</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.invited && <p className="foot-note">Already registered? <button className="link" onClick={p.toLogin}>Sign in</button></p>}
|
<p className="foot-note">Already registered? <button className="link" onClick={p.toLogin}>Sign in</button></p>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div>
|
<div>
|
||||||
{/* Non-onboarding users can step back to the email screen; onboarding starts
|
|
||||||
here (email came from Google), so there's nothing to go back to. */}
|
|
||||||
{!p.onboard && <StepBack onClick={() => setPhase("sso")} />}
|
|
||||||
<h1>Complete your profile</h1>
|
<h1>Complete your profile</h1>
|
||||||
<p className="sub">Tell us a bit about you to set up your account.</p>
|
<p className="sub">Tell us a bit about you to set up your account.</p>
|
||||||
|
|
||||||
<div className="field" style={{ marginTop: 16 }}>
|
<div style={{ marginTop: 16 }}>
|
||||||
<label className="label">Email address</label>
|
{p.sso ? (
|
||||||
<div className="input-wrap">
|
<div className="conn-banner conn-green"><Icon name="check" size={16} /> Connected with {cap(p.sso.provider)} · {p.sso.email}</div>
|
||||||
<span className="input-ico"><Icon name="mail" size={17} /></span>
|
) : (
|
||||||
<input className="input" type="email" value={p.email} disabled readOnly aria-label="Email address" />
|
<div className="conn-banner conn-blue"><Icon name="mail" size={16} /> Creating account for {p.email}</div>
|
||||||
</div>
|
)}
|
||||||
<span className="faint" style={{ fontSize: 12 }}>{p.onboard ? "Verified with Google — this can't be changed." : "The email you're registering with."}</span>
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="row gap-3" style={{ marginTop: 18, alignItems: "center" }}>
|
<div className="row gap-3" style={{ marginTop: 18, alignItems: "center" }}>
|
||||||
@@ -289,6 +245,47 @@ 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)} />
|
||||||
@@ -302,9 +299,7 @@ function StepAccount(p: {
|
|||||||
|
|
||||||
{!p.valid && <p className="hint-line">Fill all required fields and accept both documents to continue.</p>}
|
{!p.valid && <p className="hint-line">Fill all required fields and accept both documents to continue.</p>}
|
||||||
|
|
||||||
<button className="btn btn-primary" style={{ marginTop: 14 }} disabled={!p.valid || p.creating} onClick={p.onContinue}>
|
<button className="btn btn-primary" style={{ marginTop: 14 }} disabled={!p.valid} onClick={p.onContinue}>Create Account & Verify <Icon name="arrowR" size={16} /></button>
|
||||||
{p.creating ? "Creating account…" : p.onboard ? "Continue" : "Create Account & Verify"} {!p.creating && <Icon name="arrowR" size={16} />}
|
|
||||||
</button>
|
|
||||||
|
|
||||||
{modal === "terms" && <LegalModal doc={TERMS} onClose={() => setModal(null)} onReviewed={() => { reviewed.terms = true; setModal(null); }} />}
|
{modal === "terms" && <LegalModal doc={TERMS} onClose={() => setModal(null)} onReviewed={() => { reviewed.terms = true; setModal(null); }} />}
|
||||||
{modal === "privacy" && <LegalModal doc={PRIVACY} onClose={() => setModal(null)} onReviewed={() => { reviewed.privacy = true; setModal(null); }} />}
|
{modal === "privacy" && <LegalModal doc={PRIVACY} onClose={() => setModal(null)} onReviewed={() => { reviewed.privacy = true; setModal(null); }} />}
|
||||||
@@ -314,13 +309,10 @@ function StepAccount(p: {
|
|||||||
// module-level reviewed flags (per mount lifetime) — enables the checkboxes after a doc is read
|
// module-level reviewed flags (per mount lifetime) — enables the checkboxes after a doc is read
|
||||||
const reviewed = { terms: false, privacy: false };
|
const reviewed = { terms: false, privacy: false };
|
||||||
|
|
||||||
/* ====================== STEP 1 — VERIFY PHONE ======================
|
/* ====================== STEP 1 — VERIFY ====================== */
|
||||||
Email is already trusted (registration: Supabase auto-confirms on signup;
|
|
||||||
onboarding: Google-verified), so this step only verifies the phone via a real
|
|
||||||
SMS OTP: addPhone() → Twilio texts a code → verifyPhone() confirms it. Both
|
|
||||||
run against the live Supabase session established in the previous step. */
|
|
||||||
function StepVerify(p: {
|
function StepVerify(p: {
|
||||||
cc: string; phone: string; country: typeof countryCodes[number];
|
emailValue: string; cc: string; phone: string; country: typeof countryCodes[number];
|
||||||
|
emailVerified: boolean; setEmailVerified: (v: boolean) => void;
|
||||||
phoneVerified: boolean; setPhoneVerified: (v: boolean) => void;
|
phoneVerified: boolean; setPhoneVerified: (v: boolean) => void;
|
||||||
valid: boolean; onBack: () => void; onContinue: () => void;
|
valid: boolean; onBack: () => void; onContinue: () => void;
|
||||||
}) {
|
}) {
|
||||||
@@ -328,11 +320,12 @@ function StepVerify(p: {
|
|||||||
return (
|
return (
|
||||||
<div>
|
<div>
|
||||||
<StepBack onClick={p.onBack} />
|
<StepBack onClick={p.onBack} />
|
||||||
<h1>Verify your phone</h1>
|
<h1>Verify email & phone</h1>
|
||||||
<p className="sub">We'll text a one-time code to confirm your number. Your email is already verified.</p>
|
<p className="sub">Confirm both so we can secure your account.</p>
|
||||||
|
|
||||||
<div className="col gap-4" style={{ marginTop: 16 }}>
|
<div className="col gap-4" style={{ marginTop: 16 }}>
|
||||||
<PhoneVerify cc={p.cc} country={p.country} initialPhone={p.phone} verified={p.phoneVerified} onVerified={() => p.setPhoneVerified(true)} />
|
<VerifyChannel kind="email" initial={p.emailValue} country={p.country} cc={p.cc} initialPhone={p.phone} verified={p.emailVerified} onVerified={() => p.setEmailVerified(true)} />
|
||||||
|
<VerifyChannel kind="phone" initial={p.emailValue} country={p.country} cc={p.cc} initialPhone={p.phone} verified={p.phoneVerified} onVerified={() => p.setPhoneVerified(true)} />
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div style={{ marginTop: 14 }}><RememberDevice checked={remember} onChange={setRemember} /></div>
|
<div style={{ marginTop: 14 }}><RememberDevice checked={remember} onChange={setRemember} /></div>
|
||||||
@@ -341,53 +334,40 @@ function StepVerify(p: {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
type SendState = "idle" | "sending" | "sent" | "invalid_mobile" | "send_error";
|
type SendState = "idle" | "sending" | "ok" | "invalid_email" | "mailbox_full" | "bounce_risk" | "invalid_mobile";
|
||||||
function PhoneVerify({ cc, country, initialPhone, verified, onVerified }: {
|
function VerifyChannel({ kind, initial, country, cc, initialPhone, verified, onVerified }: {
|
||||||
cc: string; country: typeof countryCodes[number]; initialPhone: string;
|
kind: "email" | "phone"; initial: string; country: typeof countryCodes[number]; cc: string; initialPhone: string;
|
||||||
verified: boolean; onVerified: () => void;
|
verified: boolean; onVerified: () => void;
|
||||||
}) {
|
}) {
|
||||||
const { addPhone, verifyPhone } = useAuth();
|
const [value, setValue] = useState(kind === "email" ? initial : initialPhone);
|
||||||
const [value, setValue] = useState(initialPhone);
|
const [via, setVia] = useState<"primary" | "wa">("primary");
|
||||||
const [state, setState] = useState<SendState>("idle");
|
const [state, setState] = useState<SendState>("idle");
|
||||||
const [otpError, setOtpError] = useState("");
|
const [otpError, setOtpError] = useState(false);
|
||||||
const e164 = `${cc}${value.replace(/\D/g, "")}`;
|
const primaryLabel = kind === "email" ? "Email" : "SMS";
|
||||||
|
|
||||||
async function send() {
|
function send() {
|
||||||
if (value.replace(/\D/g, "").length !== country.digits) { setState("invalid_mobile"); return; }
|
|
||||||
setState("sending");
|
setState("sending");
|
||||||
setOtpError("");
|
setTimeout(() => {
|
||||||
if (MOCK_OTP) { setState("sent"); return; } // demo: skip Twilio entirely
|
if (kind === "email") {
|
||||||
try {
|
if (!EMAIL_RE.test(value)) return setState("invalid_email");
|
||||||
await addPhone(e164); // Supabase → Twilio sends the SMS OTP
|
if (value.includes("full")) return setState("mailbox_full");
|
||||||
setState("sent");
|
if (value.includes("bo")) return setState("bounce_risk");
|
||||||
} catch {
|
return setState("ok");
|
||||||
setState("send_error");
|
} else {
|
||||||
}
|
if (value.replace(/\D/g, "").length !== country.digits) return setState("invalid_mobile");
|
||||||
}
|
return setState("ok");
|
||||||
|
|
||||||
async function submit(code: string) {
|
|
||||||
setOtpError("");
|
|
||||||
if (MOCK_OTP) {
|
|
||||||
if (code === DEMO_OTP) onVerified();
|
|
||||||
else setOtpError(`Demo mode — enter ${DEMO_OTP} to verify.`);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
try {
|
|
||||||
await verifyPhone(e164, code); // confirm the OTP (phone_change)
|
|
||||||
onVerified();
|
|
||||||
} catch {
|
|
||||||
setOtpError("That code didn't match. Check the SMS and try again.");
|
|
||||||
}
|
}
|
||||||
|
}, 700);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (verified) {
|
if (verified) {
|
||||||
return (
|
return (
|
||||||
<div className="vchannel verified">
|
<div className="vchannel verified">
|
||||||
<div className="row between">
|
<div className="row between">
|
||||||
<span className="row gap-2" style={{ fontWeight: 600, fontSize: 14 }}><Icon name="phone" size={16} /> Mobile</span>
|
<span className="row gap-2" style={{ fontWeight: 600, fontSize: 14 }}><Icon name={kind === "email" ? "mail" : "phone"} size={16} /> {kind === "email" ? "Email" : "Mobile"}</span>
|
||||||
<Badge tone="green"><Icon name="check" size={12} /> Verified</Badge>
|
<Badge tone="green"><Icon name="check" size={12} /> Verified</Badge>
|
||||||
</div>
|
</div>
|
||||||
<p className="faint" style={{ fontSize: 12.5, marginTop: 8 }}>{cc} {value}</p>
|
<p className="faint" style={{ fontSize: 12.5, marginTop: 8 }}>{kind === "email" ? value : `${cc} ${value}`}</p>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -395,36 +375,46 @@ function PhoneVerify({ cc, country, initialPhone, verified, onVerified }: {
|
|||||||
return (
|
return (
|
||||||
<div className="vchannel">
|
<div className="vchannel">
|
||||||
<div className="row between" style={{ marginBottom: 12 }}>
|
<div className="row between" style={{ marginBottom: 12 }}>
|
||||||
<span className="row gap-2" style={{ fontWeight: 600, fontSize: 14 }}><Icon name="phone" size={16} /> Mobile number</span>
|
<span className="row gap-2" style={{ fontWeight: 600, fontSize: 14 }}><Icon name={kind === "email" ? "mail" : "phone"} size={16} /> {kind === "email" ? "Email address" : "Mobile number"}</span>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
{kind === "email" ? (
|
||||||
|
<input className="input" value={value} onChange={(e) => { setValue(e.target.value); setState("idle"); }} placeholder="you@example.com" />
|
||||||
|
) : (
|
||||||
<div className="phone-row">
|
<div className="phone-row">
|
||||||
<span className="input cc-select" style={{ display: "flex", alignItems: "center", justifyContent: "center", gap: 7 }}>
|
<span className="input cc-select" style={{ display: "flex", alignItems: "center", justifyContent: "center", gap: 7 }}>
|
||||||
{/* eslint-disable-next-line @next/next/no-img-element */}
|
{/* eslint-disable-next-line @next/next/no-img-element */}
|
||||||
<img className="cc-flag-img static" src={flagUrl(country.flag)} alt={country.name} width={22} height={16} />
|
<img className="cc-flag-img static" src={flagUrl(country.flag)} alt={country.name} width={22} height={16} />
|
||||||
{cc}
|
{cc}
|
||||||
</span>
|
</span>
|
||||||
<input className="input grow" inputMode="numeric" value={value} disabled={state === "sent"} onChange={(e) => { setValue(e.target.value.replace(/\D/g, "")); setState("idle"); }} placeholder={country.example} />
|
<input className="input grow" inputMode="numeric" value={value} onChange={(e) => { setValue(e.target.value.replace(/\D/g, "")); setState("idle"); }} placeholder={country.example} />
|
||||||
</div>
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
<div className="row between" style={{ marginTop: 12 }}>
|
<div className="row between" style={{ marginTop: 12 }}>
|
||||||
<span className="faint" style={{ fontSize: 12 }}>{MOCK_OTP ? "Demo verification (no SMS sent)." : "Standard SMS rates may apply."}</span>
|
<div className="seg">
|
||||||
<button className="btn btn-sm" style={{ width: "auto" }} disabled={state === "sending" || state === "sent"} onClick={send}>
|
<button className={via === "primary" ? "on" : ""} onClick={() => setVia("primary")}>{primaryLabel}</button>
|
||||||
{state === "sending" ? "Sending…" : state === "sent" ? "Sent" : "Send code"}
|
<button className={via === "wa" ? "on" : ""} onClick={() => setVia("wa")}><Icon name="whatsapp" size={14} /> WhatsApp</button>
|
||||||
|
</div>
|
||||||
|
<button className="btn btn-sm" style={{ width: "auto" }} disabled={state === "sending" || state === "ok"} onClick={send}>
|
||||||
|
{state === "sending" ? "Sending…" : "Send code"}
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{state === "sent" && <p className="faint" style={{ fontSize: 12, marginTop: 10 }}>{MOCK_OTP ? `Demo mode — enter ${DEMO_OTP} to verify (SMS temporarily disabled).` : `Code sent to ${cc} ${value} by SMS.`}</p>}
|
{state === "ok" && <p className="faint" style={{ fontSize: 12, marginTop: 10 }}>OTP sent via {via === "wa" ? "WhatsApp" : primaryLabel}.</p>}
|
||||||
|
{state === "invalid_email" && <div style={{ marginTop: 10 }}><FlashNote tone="error">That email address looks invalid.</FlashNote></div>}
|
||||||
|
{state === "mailbox_full" && <div style={{ marginTop: 10 }}><FlashNote tone="warn">This mailbox appears full — try another email.</FlashNote></div>}
|
||||||
|
{state === "bounce_risk" && <div style={{ marginTop: 10 }}><FlashNote tone="warn">High bounce risk for this address.</FlashNote></div>}
|
||||||
{state === "invalid_mobile" && <div style={{ marginTop: 10 }}><FlashNote tone="error">Enter a valid {country.digits}-digit mobile number.</FlashNote></div>}
|
{state === "invalid_mobile" && <div style={{ marginTop: 10 }}><FlashNote tone="error">Enter a valid {country.digits}-digit mobile number.</FlashNote></div>}
|
||||||
{state === "send_error" && <div style={{ marginTop: 10 }}><FlashNote tone="error">Couldn't send the code. Check the number and try again.</FlashNote></div>}
|
|
||||||
|
|
||||||
{state === "sent" && (
|
{state === "ok" && (
|
||||||
<div style={{ marginTop: 14 }}>
|
<div style={{ marginTop: 14 }}>
|
||||||
<OtpBoxes onComplete={submit} error={!!otpError} />
|
<OtpBoxes onComplete={(c) => { if (c === "000000") setOtpError(true); else { setOtpError(false); onVerified(); } }} error={otpError} />
|
||||||
{otpError && <div style={{ marginTop: 10 }}><FlashNote tone="error">{otpError}</FlashNote></div>}
|
{otpError && <div style={{ marginTop: 10 }}><FlashNote tone="error">Incorrect code.</FlashNote></div>}
|
||||||
<div style={{ marginTop: 12 }}><ResendLink seconds={60} onResend={send} /></div>
|
<div style={{ marginTop: 12 }}><ResendLink seconds={60} /></div>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
<p className="demo-hint">Demo: any 6 digits verify; “000000” fails. Email with “full”/“bo” shows send errors.</p>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -602,10 +592,10 @@ function AddressBlock({ idPrefix, onChange }: { idPrefix: string; onChange?: (a:
|
|||||||
}
|
}
|
||||||
|
|
||||||
/* ====================== stepper ====================== */
|
/* ====================== stepper ====================== */
|
||||||
function Stepper({ current, labels = STEPS }: { current: number; labels?: string[] }) {
|
function Stepper({ current }: { current: number }) {
|
||||||
return (
|
return (
|
||||||
<div className="steps">
|
<div className="steps">
|
||||||
{labels.map((label, i) => {
|
{STEPS.map((label, i) => {
|
||||||
const done = i < current, on = i === current;
|
const done = i < current, on = i === current;
|
||||||
return (
|
return (
|
||||||
<div key={label} style={{ display: "contents" }}>
|
<div key={label} style={{ display: "contents" }}>
|
||||||
|
|||||||
@@ -1,66 +0,0 @@
|
|||||||
"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;
|
|
||||||
@@ -1,113 +0,0 @@
|
|||||||
// The CRM's InboxAdapter — the SDK <Inbox> rendered over the be-crm data door
|
|
||||||
// (crm.inbox.* + crm.mail.*). Folds mail threads into the unified inbox exactly as the old
|
|
||||||
// inbox-api did; the CRM keeps auth/tenancy server-side.
|
|
||||||
|
|
||||||
import type {
|
|
||||||
InboxAdapter,
|
|
||||||
InboxItem,
|
|
||||||
InboxState,
|
|
||||||
MailAttachment,
|
|
||||||
MailMessage,
|
|
||||||
MailPerson,
|
|
||||||
} from "@insignia/iios-messaging-ui";
|
|
||||||
import type { DataDoor } from "./crm-messaging-adapter";
|
|
||||||
|
|
||||||
const MAX_ATTACHMENT_BYTES = 26 * 1024 * 1024; // matches IIOS's cap
|
|
||||||
|
|
||||||
// Some types (notably .md) have no OS-registered MIME, so the browser reports an empty file.type.
|
|
||||||
const EXT_MIME: Record<string, string> = {
|
|
||||||
md: "text/markdown", markdown: "text/markdown", html: "text/html", htm: "text/html", txt: "text/plain", csv: "text/csv",
|
|
||||||
};
|
|
||||||
function mimeForFile(file: File): string {
|
|
||||||
if (file.type) return file.type;
|
|
||||||
const ext = file.name.toLowerCase().split(".").pop() ?? "";
|
|
||||||
return EXT_MIME[ext] ?? "application/octet-stream";
|
|
||||||
}
|
|
||||||
|
|
||||||
interface InboxItemDTO {
|
|
||||||
id: string; kind: string; state: InboxState; title: string; summary?: string; priority: string; threadId?: string; createdAt: string;
|
|
||||||
}
|
|
||||||
interface MailThreadDTO { threadId: string; subject: string | null; participants: string[]; unread: number; lastMessage?: string; lastAt?: string }
|
|
||||||
interface MailMessageDTO {
|
|
||||||
interactionId: string; actorId: string | null; kind: string; occurredAt: string;
|
|
||||||
html: string | null; text: string | null;
|
|
||||||
attachment: { contentRef: string; mimeType: string; sizeBytes: number; filename: string | null } | null;
|
|
||||||
}
|
|
||||||
interface DirectoryDTO { id: string; displayName: string; kind: "staff" | "customer" }
|
|
||||||
|
|
||||||
const escapeHtml = (s: string): string => s.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">");
|
|
||||||
|
|
||||||
export class CrmInboxAdapter implements InboxAdapter {
|
|
||||||
constructor(private readonly sdk: DataDoor) {}
|
|
||||||
|
|
||||||
async listInbox(state?: InboxState): Promise<InboxItem[]> {
|
|
||||||
const showMail = !state || state === "OPEN";
|
|
||||||
const [items, mail] = await Promise.all([
|
|
||||||
this.sdk.query<InboxItemDTO[]>("crm.inbox.list", state ? { state } : {}),
|
|
||||||
showMail ? this.sdk.query<MailThreadDTO[]>("crm.mail.list", {}) : Promise.resolve([] as MailThreadDTO[]),
|
|
||||||
]);
|
|
||||||
const mailItems: InboxItem[] = mail.map((t) => ({
|
|
||||||
id: `mail:${t.threadId}`,
|
|
||||||
kind: "MAIL",
|
|
||||||
state: "OPEN",
|
|
||||||
title: t.subject || "(no subject)",
|
|
||||||
...(t.lastMessage ? { summary: t.lastMessage } : {}),
|
|
||||||
priority: t.unread > 0 ? "HIGH" : "LOW",
|
|
||||||
threadId: t.threadId,
|
|
||||||
createdAt: t.lastAt ?? "",
|
|
||||||
}));
|
|
||||||
return [...mailItems, ...items].sort((a, b) => (b.createdAt ?? "").localeCompare(a.createdAt ?? ""));
|
|
||||||
}
|
|
||||||
|
|
||||||
async transition(id: string, state: InboxState): Promise<void> {
|
|
||||||
await this.sdk.command("crm.inbox.transition", { id, state });
|
|
||||||
}
|
|
||||||
|
|
||||||
async mailHistory(threadId: string): Promise<MailMessage[]> {
|
|
||||||
const rows = await this.sdk.query<MailMessageDTO[]>("crm.mail.history", { threadId });
|
|
||||||
return rows.map((m) => ({
|
|
||||||
id: m.interactionId,
|
|
||||||
actorId: m.actorId,
|
|
||||||
kind: m.kind,
|
|
||||||
at: m.occurredAt,
|
|
||||||
html: m.html,
|
|
||||||
text: m.text,
|
|
||||||
attachment: m.attachment,
|
|
||||||
}));
|
|
||||||
}
|
|
||||||
|
|
||||||
async mailReply(threadId: string, content: string, attachment?: MailAttachment): Promise<void> {
|
|
||||||
await this.sdk.command("crm.mail.reply", {
|
|
||||||
threadId,
|
|
||||||
content,
|
|
||||||
...(attachment ? { attachment: { filename: attachment.filename ?? "attachment", contentRef: attachment.contentRef, mimeType: attachment.mimeType, sizeBytes: attachment.sizeBytes } } : {}),
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
async uploadAttachment(file: File): Promise<MailAttachment> {
|
|
||||||
if (file.size > MAX_ATTACHMENT_BYTES) throw new Error("File is too large (max 25 MB).");
|
|
||||||
const mime = mimeForFile(file);
|
|
||||||
const { objectKey, uploadUrl } = await this.sdk.command<{ objectKey: string; uploadUrl: string }>("crm.media.presignUpload", { mime, sizeBytes: file.size });
|
|
||||||
const res = await fetch(uploadUrl, { method: "PUT", body: file });
|
|
||||||
if (!res.ok) throw new Error(`Upload failed (${res.status}).`);
|
|
||||||
return { contentRef: objectKey, mimeType: mime, sizeBytes: file.size, filename: file.name };
|
|
||||||
}
|
|
||||||
|
|
||||||
async 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 })) };
|
|
||||||
}
|
|
||||||
@@ -1,303 +0,0 @@
|
|||||||
// 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));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,50 +0,0 @@
|
|||||||
"use client";
|
|
||||||
|
|
||||||
// Media (attachment) helpers over the be-crm data door (crm.media.*). The browser transfers bytes
|
|
||||||
// DIRECTLY to IIOS storage via the signed URLs — be-crm only mints them. Used by Messenger + Mail.
|
|
||||||
|
|
||||||
import { useCallback } from "react";
|
|
||||||
import { useAppShell } from "@abe-kap/appshell-sdk/react";
|
|
||||||
|
|
||||||
export interface UploadedAttachment { contentRef: string; mimeType: string; sizeBytes: number; filename: string }
|
|
||||||
|
|
||||||
export const MAX_ATTACHMENT_BYTES = 26 * 1024 * 1024; // matches IIOS's cap
|
|
||||||
|
|
||||||
export function isImage(mime?: string | null): boolean {
|
|
||||||
return !!mime && mime.startsWith("image/");
|
|
||||||
}
|
|
||||||
|
|
||||||
// Some types (notably .md) have no OS-registered MIME, so the browser reports an empty file.type.
|
|
||||||
// Fall back to the extension for the text types IIOS allows, else a generic binary.
|
|
||||||
const EXT_MIME: Record<string, string> = {
|
|
||||||
md: "text/markdown", markdown: "text/markdown",
|
|
||||||
html: "text/html", htm: "text/html",
|
|
||||||
txt: "text/plain", csv: "text/csv",
|
|
||||||
};
|
|
||||||
function mimeForFile(file: File): string {
|
|
||||||
if (file.type) return file.type;
|
|
||||||
const ext = file.name.toLowerCase().split(".").pop() ?? "";
|
|
||||||
return EXT_MIME[ext] ?? "application/octet-stream";
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Upload a File → { contentRef, mimeType, sizeBytes, filename }. Throws on oversize / failure. */
|
|
||||||
export function useUploadAttachment() {
|
|
||||||
const { sdk } = useAppShell();
|
|
||||||
return useCallback(async (file: File): Promise<UploadedAttachment> => {
|
|
||||||
if (file.size > MAX_ATTACHMENT_BYTES) throw new Error("File is too large (max 25 MB).");
|
|
||||||
const mime = mimeForFile(file);
|
|
||||||
const { objectKey, uploadUrl } = (await sdk.command("crm.media.presignUpload", { mime, sizeBytes: file.size })) as { objectKey: string; uploadUrl: string };
|
|
||||||
const res = await fetch(uploadUrl, { method: "PUT", body: file });
|
|
||||||
if (!res.ok) throw new Error(`Upload failed (${res.status}).`);
|
|
||||||
return { contentRef: objectKey, mimeType: mime, sizeBytes: file.size, filename: file.name };
|
|
||||||
}, [sdk]);
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Mint a short-lived signed URL to display/download an attachment by its contentRef. */
|
|
||||||
export function useDownloadUrl() {
|
|
||||||
const { sdk } = useAppShell();
|
|
||||||
return useCallback(async (contentRef: string, mime?: string): Promise<string> => {
|
|
||||||
const { url } = (await sdk.command("crm.media.presignDownload", { contentRef, ...(mime ? { mime } : {}) })) as { url: string };
|
|
||||||
return url;
|
|
||||||
}, [sdk]);
|
|
||||||
}
|
|
||||||
@@ -1,16 +0,0 @@
|
|||||||
/**
|
|
||||||
* Demo OTP fallback, shared by the login and registration flows.
|
|
||||||
*
|
|
||||||
* While the Twilio SMS sender is down we can't deliver real one-time codes. When
|
|
||||||
* MOCK_OTP is on, phone verification steps skip Supabase/Twilio and accept a fixed
|
|
||||||
* DEMO_OTP instead. Flip NEXT_PUBLIC_MOCK_OTP to "false" (or remove it) to restore
|
|
||||||
* real SMS — no other change needed.
|
|
||||||
*
|
|
||||||
* IMPORTANT: this only substitutes for a *secondary* verification (e.g. confirming a
|
|
||||||
* phone during registration/onboarding, where the session already exists). It cannot
|
|
||||||
* mock a *login* whose sole credential is the OTP — there the OTP verification is what
|
|
||||||
* mints the session, and a faked code produces no session (the dashboard's AuthGate
|
|
||||||
* would bounce the user straight back). Passwordless login therefore stays real.
|
|
||||||
*/
|
|
||||||
export const MOCK_OTP = process.env.NEXT_PUBLIC_MOCK_OTP === "true";
|
|
||||||
export const DEMO_OTP = "123456";
|
|
||||||
@@ -1,78 +0,0 @@
|
|||||||
"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();
|
|
||||||
}
|
|
||||||
+7
-15
@@ -38,8 +38,6 @@ 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 {
|
||||||
@@ -48,9 +46,7 @@ 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>;
|
||||||
@@ -72,9 +68,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; email?: string | null; firstName?: string | null; lastName?: string | null; displayName?: string | null }
|
interface MemberDTO { id: string; principalId: string; jobTitle: string | null; joinedAt: string; status: "active" | "deactivated"; roles: RoleRef[]; openDeals: number }
|
||||||
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; token?: string }
|
interface InvitationDTO { id: string; email: string; roles: RoleRef[]; invitedBy: string; createdAt: string }
|
||||||
|
|
||||||
const relTime = (iso: string): string => {
|
const relTime = (iso: string): string => {
|
||||||
const then = Date.parse(iso);
|
const then = Date.parse(iso);
|
||||||
@@ -157,16 +153,12 @@ 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;
|
||||||
// Prefer the member's real name/email from their CRM registration; fall back to the
|
const name = isYou && user?.displayName
|
||||||
// ACE (for the current user), then job title, then a short principal id.
|
? user.displayName
|
||||||
const name = m.displayName?.trim()
|
: (m.jobTitle?.trim() || `Member ${m.principalId.replace(/^pp_/, "").slice(0, 6)}`);
|
||||||
|| (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,
|
email: isYou && user?.email ? user.email : m.principalId,
|
||||||
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" : "—",
|
||||||
@@ -177,7 +169,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), token: i.token,
|
invitedBy: i.invitedBy, sentAt: relTime(i.createdAt),
|
||||||
})), [invitesQ.data]);
|
})), [invitesQ.data]);
|
||||||
|
|
||||||
return {
|
return {
|
||||||
|
|||||||
Reference in New Issue
Block a user