Compare commits
19 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 49b04e9710 | |||
| e7c042fb1a | |||
| 9eb234935d | |||
| fa538355ae | |||
| 1a2043eaae | |||
| 70831e189d | |||
| eeded95940 | |||
| 0643b8c9b2 | |||
| be4bd5f41d | |||
| 75417cb4f1 | |||
| cc71516278 | |||
| 6606a55207 | |||
| 103f3ae3a1 | |||
| 661e291fae | |||
| 68bf137d11 | |||
| 2fa7ffc327 | |||
| 5f67c8fa85 | |||
| 4a53cb6353 | |||
| 5511ef4110 |
@@ -1,2 +1,6 @@
|
||||
@abe-kap:registry=https://npm.pkg.github.com
|
||||
//npm.pkg.github.com/:_authToken=${NODE_AUTH_TOKEN}
|
||||
# @insignia/* (iios-kernel-client — the MessageSocket live stream) resolve from the
|
||||
# self-hosted Gitea npm registry. Install needs a token with `read:package` in GITEA_TOKEN.
|
||||
@insignia:registry=https://git.lynkedup.cloud/api/packages/insignia/npm/
|
||||
//git.lynkedup.cloud/api/packages/insignia/npm/:_authToken=${GITEA_TOKEN}
|
||||
|
||||
Generated
+100
-1
@@ -9,6 +9,7 @@
|
||||
"version": "0.1.0",
|
||||
"dependencies": {
|
||||
"@abe-kap/appshell-sdk": "^0.2.6",
|
||||
"@insignia/iios-kernel-client": "^0.1.4",
|
||||
"clsx": "^2.1.1",
|
||||
"lucide-react": "^1.21.0",
|
||||
"next": "16.2.9",
|
||||
@@ -1011,6 +1012,20 @@
|
||||
"url": "https://opencollective.com/libvips"
|
||||
}
|
||||
},
|
||||
"node_modules/@insignia/iios-contracts": {
|
||||
"version": "0.1.0",
|
||||
"resolved": "https://git.lynkedup.cloud/api/packages/insignia/npm/%40insignia%2Fiios-contracts/-/0.1.0/iios-contracts-0.1.0.tgz",
|
||||
"integrity": "sha512-+ycbP8ORdwllMtn7dmxIL7lnDpDDkV+gHqT2OKJtMplMivjKU03gsuuEveQxnrE1CMvZ3fcSljmfMs10Cw131g=="
|
||||
},
|
||||
"node_modules/@insignia/iios-kernel-client": {
|
||||
"version": "0.1.4",
|
||||
"resolved": "https://git.lynkedup.cloud/api/packages/insignia/npm/%40insignia%2Fiios-kernel-client/-/0.1.4/iios-kernel-client-0.1.4.tgz",
|
||||
"integrity": "sha512-pYBHH21TvgOOm0kp3ogvZx/iEzXLwmU23jHpDzIolh5FrqxCrcpUjRwLDkeYRTTkRVdoJAPTmPES/pU66iNoiA==",
|
||||
"dependencies": {
|
||||
"@insignia/iios-contracts": "0.1.0",
|
||||
"socket.io-client": "^4.8.1"
|
||||
}
|
||||
},
|
||||
"node_modules/@jridgewell/gen-mapping": {
|
||||
"version": "0.3.13",
|
||||
"resolved": "https://registry.npmjs.org/@jridgewell/gen-mapping/-/gen-mapping-0.3.13.tgz",
|
||||
@@ -1279,6 +1294,12 @@
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@socket.io/component-emitter": {
|
||||
"version": "3.1.2",
|
||||
"resolved": "https://registry.npmjs.org/@socket.io/component-emitter/-/component-emitter-3.1.2.tgz",
|
||||
"integrity": "sha512-9BCxFwvbGg/RsZK9tjXd8s4UcwR0MWeFQ1XEKIQVVvAGJyINdrqKMcTRyLoK8Rse1GjzLV9cwjWV1olXRWEXVA==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@supabase/auth-js": {
|
||||
"version": "2.110.2",
|
||||
"resolved": "https://registry.npmjs.org/@supabase/auth-js/-/auth-js-2.110.2.tgz",
|
||||
@@ -3051,7 +3072,6 @@
|
||||
"version": "4.4.3",
|
||||
"resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz",
|
||||
"integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"ms": "^2.1.3"
|
||||
@@ -3205,6 +3225,28 @@
|
||||
"node": ">= 0.8"
|
||||
}
|
||||
},
|
||||
"node_modules/engine.io-client": {
|
||||
"version": "6.6.6",
|
||||
"resolved": "https://registry.npmjs.org/engine.io-client/-/engine.io-client-6.6.6.tgz",
|
||||
"integrity": "sha512-iY6QdftLQ9pyiPoX082bpf/u1UewnOaJrtJIF9T0++QB34lZrj0uP+Q/bj8AlUsAxqhnkTV2BS8SBZSxOmoV5Q==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@socket.io/component-emitter": "~3.1.0",
|
||||
"debug": "~4.4.1",
|
||||
"engine.io-parser": "~5.2.1",
|
||||
"ws": "~8.21.0",
|
||||
"xmlhttprequest-ssl": "~2.1.1"
|
||||
}
|
||||
},
|
||||
"node_modules/engine.io-parser": {
|
||||
"version": "5.2.3",
|
||||
"resolved": "https://registry.npmjs.org/engine.io-parser/-/engine.io-parser-5.2.3.tgz",
|
||||
"integrity": "sha512-HqD3yTBfnBxIrbnM1DoD6Pcq8NECnh8d4As1Qgh0z5Gg3jRRIqijury0CL3ghu/edArpUYiYqQiDUQBIs4np3Q==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=10.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/enhanced-resolve": {
|
||||
"version": "5.21.6",
|
||||
"resolved": "https://registry.npmjs.org/enhanced-resolve/-/enhanced-resolve-5.21.6.tgz",
|
||||
@@ -6688,6 +6730,34 @@
|
||||
"url": "https://github.com/sponsors/ljharb"
|
||||
}
|
||||
},
|
||||
"node_modules/socket.io-client": {
|
||||
"version": "4.8.3",
|
||||
"resolved": "https://registry.npmjs.org/socket.io-client/-/socket.io-client-4.8.3.tgz",
|
||||
"integrity": "sha512-uP0bpjWrjQmUt5DTHq9RuoCBdFJF10cdX9X+a368j/Ft0wmaVgxlrjvK3kjvgCODOMMOz9lcaRzxmso0bTWZ/g==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@socket.io/component-emitter": "~3.1.0",
|
||||
"debug": "~4.4.1",
|
||||
"engine.io-client": "~6.6.1",
|
||||
"socket.io-parser": "~4.2.4"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=10.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/socket.io-parser": {
|
||||
"version": "4.2.6",
|
||||
"resolved": "https://registry.npmjs.org/socket.io-parser/-/socket.io-parser-4.2.6.tgz",
|
||||
"integrity": "sha512-asJqbVBDsBCJx0pTqw3WfesSY0iRX+2xzWEWzrpcH7L6fLzrhyF8WPI8UaeM4YCuDfpwA/cgsdugMsmtz8EJeg==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@socket.io/component-emitter": "~3.1.0",
|
||||
"debug": "~4.4.1"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=10.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/source-map-js": {
|
||||
"version": "1.2.1",
|
||||
"resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.1.tgz",
|
||||
@@ -7448,6 +7518,35 @@
|
||||
"node": ">=0.10.0"
|
||||
}
|
||||
},
|
||||
"node_modules/ws": {
|
||||
"version": "8.21.1",
|
||||
"resolved": "https://registry.npmjs.org/ws/-/ws-8.21.1.tgz",
|
||||
"integrity": "sha512-+0NTnW77fFN/DjQi6k/Sq/Yvk4Sgajw7urW8V+asjXnRgDs9gyGkdb7EzgfhA4goXsRIZKE28fzIXBHEzhuiWw==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=10.0.0"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"bufferutil": "^4.0.1",
|
||||
"utf-8-validate": ">=5.0.2"
|
||||
},
|
||||
"peerDependenciesMeta": {
|
||||
"bufferutil": {
|
||||
"optional": true
|
||||
},
|
||||
"utf-8-validate": {
|
||||
"optional": true
|
||||
}
|
||||
}
|
||||
},
|
||||
"node_modules/xmlhttprequest-ssl": {
|
||||
"version": "2.1.2",
|
||||
"resolved": "https://registry.npmjs.org/xmlhttprequest-ssl/-/xmlhttprequest-ssl-2.1.2.tgz",
|
||||
"integrity": "sha512-TEU+nJVUUnA4CYJFLvK5X9AOeH4KvDvhIfm0vV1GaQRtchnG0hgK5p8hw/xjv8cunWYCsiPCSDzObPyhEwq3KQ==",
|
||||
"engines": {
|
||||
"node": ">=0.4.0"
|
||||
}
|
||||
},
|
||||
"node_modules/yallist": {
|
||||
"version": "3.1.1",
|
||||
"resolved": "https://registry.npmjs.org/yallist/-/yallist-3.1.1.tgz",
|
||||
|
||||
@@ -10,6 +10,7 @@
|
||||
},
|
||||
"dependencies": {
|
||||
"@abe-kap/appshell-sdk": "^0.2.6",
|
||||
"@insignia/iios-kernel-client": "^0.1.4",
|
||||
"clsx": "^2.1.1",
|
||||
"lucide-react": "^1.21.0",
|
||||
"next": "16.2.9",
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
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>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
/**
|
||||
* 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";
|
||||
@@ -0,0 +1,125 @@
|
||||
/* 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;
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
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>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,125 @@
|
||||
"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>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
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>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
import { NextResponse } from "next/server";
|
||||
|
||||
// Server-side proxy to be-crm's public invitation lookup, so the invite landing page
|
||||
// can learn the invited email + roles and whether an account exists — before the
|
||||
// invitee has a session. Server-to-server avoids CORS. No secrets involved (the token
|
||||
// is the only credential, and it was emailed to the invitee).
|
||||
|
||||
export const runtime = "nodejs";
|
||||
|
||||
const CRM_BASE_URL = (process.env.CRM_BASE_URL ?? "https://crm.lynkedup.cloud").replace(/\/$/, "");
|
||||
|
||||
export async function GET(request: Request) {
|
||||
const token = new URL(request.url).searchParams.get("token") ?? "";
|
||||
if (token.length < 16 || token.length > 256) {
|
||||
return NextResponse.json({ ok: false, status: "invalid" }, { status: 400 });
|
||||
}
|
||||
try {
|
||||
const res = await fetch(`${CRM_BASE_URL}/public/invitations/lookup?token=${encodeURIComponent(token)}`, {
|
||||
headers: { Accept: "application/json" },
|
||||
cache: "no-store",
|
||||
});
|
||||
if (!res.ok) return NextResponse.json({ ok: false, status: "unavailable" }, { status: 502 });
|
||||
const data = await res.json();
|
||||
return NextResponse.json(data);
|
||||
} catch {
|
||||
return NextResponse.json({ ok: false, status: "unavailable" }, { status: 502 });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,113 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useAuth, useAppShell } from "@abe-kap/appshell-sdk/react";
|
||||
import { PortalAside, PanelBrand } from "@/components/portal/parts";
|
||||
import { CookieBanner, Spinner } from "@/components/portal/bits";
|
||||
import { isShellConfigured } from "@/lib/appshell";
|
||||
|
||||
interface InviteInfo { ok: boolean; status?: string; email?: string; roleNames?: string[]; hasAccount?: boolean }
|
||||
|
||||
/**
|
||||
* Team invitation landing page (/portal/invite?token=…). It looks the token up
|
||||
* (public, pre-auth) to learn the invited email and whether an account exists, then:
|
||||
* - signed in + registered → accept now (creates the membership with the invited role);
|
||||
* - signed in, no CRM profile → onboarding, which redeems the token on finish;
|
||||
* - not signed in + email already has an account → sign in (email prefilled);
|
||||
* - not signed in + first-time invitee → register (email prefilled + locked).
|
||||
* The register/login/onboarding flows redeem the stashed token on completion.
|
||||
*/
|
||||
export default function InvitePage() {
|
||||
const router = useRouter();
|
||||
const { status, getUserEmail } = useAuth();
|
||||
const { ready, sdk } = useAppShell();
|
||||
const [error, setError] = useState("");
|
||||
const started = useRef(false);
|
||||
|
||||
useEffect(() => {
|
||||
let token = "";
|
||||
try { token = new URLSearchParams(window.location.search).get("token") ?? ""; } catch { /* ignore */ }
|
||||
if (!token) { setError("This invitation link is invalid or incomplete."); return; }
|
||||
if (!isShellConfigured()) { try { sessionStorage.setItem("invite_token", token); } catch { /* ignore */ } router.replace("/portal/register"); return; }
|
||||
if (!ready || started.current) return;
|
||||
started.current = true;
|
||||
|
||||
(async () => {
|
||||
try { sessionStorage.setItem("invite_token", token); } catch { /* ignore */ }
|
||||
|
||||
// Look the invitation up (pre-auth) to get the email + account state.
|
||||
let info: InviteInfo = { ok: false };
|
||||
try {
|
||||
const res = await fetch(`/api/invite/lookup?token=${encodeURIComponent(token)}`, { cache: "no-store" });
|
||||
info = await res.json();
|
||||
} catch { /* treat as unavailable below */ }
|
||||
|
||||
if (!info.ok) {
|
||||
const msg = info.status === "expired" ? "This invitation has expired. Ask for a new one."
|
||||
: info.status === "accepted" ? "This invitation has already been used."
|
||||
: info.status === "revoked" ? "This invitation was revoked."
|
||||
: "This invitation link is invalid.";
|
||||
setError(msg);
|
||||
try { sessionStorage.removeItem("invite_token"); } catch { /* ignore */ }
|
||||
return;
|
||||
}
|
||||
if (info.email) { try { sessionStorage.setItem("invite_email", info.email); } catch { /* ignore */ } }
|
||||
|
||||
// Signed in already: accept if registered, else finish onboarding first.
|
||||
if (status === "authenticated") {
|
||||
try {
|
||||
const st = await sdk.query<{ registered: boolean }>("crm.account.registrationStatus");
|
||||
if (!st?.registered) {
|
||||
try { const em = await getUserEmail(); if (em) sessionStorage.setItem("onboard_email", em); } catch { /* ignore */ }
|
||||
router.replace("/portal/onboarding");
|
||||
return;
|
||||
}
|
||||
} catch { /* fall through to accept */ }
|
||||
try {
|
||||
await sdk.command("crm.team.invitation.accept", { token });
|
||||
try { sessionStorage.removeItem("invite_token"); sessionStorage.removeItem("invite_email"); } catch { /* ignore */ }
|
||||
router.replace("/dashboard");
|
||||
} catch {
|
||||
setError("We couldn't accept this invitation — it may have expired or already been used.");
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
// Not signed in: existing account → sign in; first-time invitee → register.
|
||||
router.replace(info.hasAccount ? "/portal/login" : "/portal/register");
|
||||
})();
|
||||
}, [ready, status, router, sdk, getUserEmail]);
|
||||
|
||||
return (
|
||||
<main className="portal-main">
|
||||
<span className="portal-grid" />
|
||||
<div className="portal-split anim-in">
|
||||
<PortalAside />
|
||||
<section className="portal-panel">
|
||||
<div style={{ width: "100%", maxWidth: 420 }}>
|
||||
<PanelBrand />
|
||||
<div className="card anim-fade-up" style={{ textAlign: "center" }}>
|
||||
{error ? (
|
||||
<>
|
||||
<h1>Invitation problem</h1>
|
||||
<p className="sub">{error}</p>
|
||||
<button className="btn btn-primary" style={{ marginTop: 16 }} onClick={() => router.replace("/portal/login")}>
|
||||
Go to sign in
|
||||
</button>
|
||||
</>
|
||||
) : (
|
||||
<div className="interstitial">
|
||||
<Spinner lg />
|
||||
<h1 style={{ fontSize: 20, marginTop: 8 }}>Checking your invitation…</h1>
|
||||
<p className="sub">One moment while we set things up.</p>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
<CookieBanner />
|
||||
</main>
|
||||
);
|
||||
}
|
||||
@@ -15,6 +15,8 @@ import { Support } from "./support";
|
||||
import { Rules } from "./rules";
|
||||
import { AiAssistant } from "./ai-assistant";
|
||||
import { TeamManagement } from "./team-management";
|
||||
import { Messenger } from "./messenger";
|
||||
import { Inbox } from "./inbox";
|
||||
import "../../app/dashboard/dashboard.css";
|
||||
|
||||
export function Dashboard() {
|
||||
@@ -45,6 +47,8 @@ export function Dashboard() {
|
||||
: active === "support" ? <Support />
|
||||
: active === "rules" ? <Rules />
|
||||
: active === "ai" ? <AiAssistant />
|
||||
: active === "messenger" ? <Messenger />
|
||||
: active === "inbox" ? <Inbox />
|
||||
: active === "team" ? <TeamManagement />
|
||||
: <ComingSoon title={title} icon={item?.icon ?? "dashboard"} onGo={setActive} />}
|
||||
</ToastProvider>
|
||||
|
||||
@@ -0,0 +1,85 @@
|
||||
"use client";
|
||||
|
||||
// ============================================================
|
||||
// Inbox — a personalized work/awareness feed IIOS projects from
|
||||
// events (mentions, needs-reply, support updates, …), surfaced via
|
||||
// the be-crm data door (crm.inbox.*). List + filter by state, and
|
||||
// mark items done / snoozed / archived. Items are created by IIOS's
|
||||
// projector, never here. Mock when the Shell isn't configured.
|
||||
// ============================================================
|
||||
|
||||
import { useState } from "react";
|
||||
import { Btn, Icon, PageHead, Pill } from "./ui";
|
||||
import { useInboxData, type InboxState, type UiInboxItem } from "@/lib/inbox-api";
|
||||
|
||||
const KIND_LABEL: Record<string, string> = {
|
||||
MENTION: "Mention", NEEDS_REPLY: "Needs reply", NEEDS_REVIEW: "Needs review", NEEDS_APPROVAL: "Needs approval",
|
||||
SUPPORT_UPDATE: "Support", MEETING_FOLLOWUP: "Meeting", DIGEST: "Digest", SYSTEM_ALERT: "Alert", CRM_OWNER_INTEREST: "Owner",
|
||||
};
|
||||
const FILTERS: { value: InboxState; label: string }[] = [
|
||||
{ value: "OPEN", label: "Open" }, { value: "SNOOZED", label: "Snoozed" }, { value: "DONE", label: "Done" }, { value: "ARCHIVED", label: "Archived" },
|
||||
];
|
||||
|
||||
export function Inbox() {
|
||||
const [filter, setFilter] = useState<InboxState>("OPEN");
|
||||
const inbox = useInboxData(filter);
|
||||
|
||||
return (
|
||||
<div className="view">
|
||||
<PageHead eyebrow="Communication" title="Inbox" subtitle="Mentions, replies and updates that need your attention" icon="bell" />
|
||||
{!inbox.live && (
|
||||
<div style={{ margin: "0 0 14px", padding: "8px 14px", borderRadius: 10, background: "var(--panel-2)", color: "var(--muted)", fontSize: 13, border: "1px solid var(--border)" }}>
|
||||
Demo mode — running on mock data. It goes live once the Shell + be-crm are connected.
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div style={{ display: "flex", gap: 6, marginBottom: 14, flexWrap: "wrap" }}>
|
||||
{FILTERS.map((f) => (
|
||||
<Btn key={f.value} variant={filter === f.value ? "primary" : "outline"} onClick={() => setFilter(f.value)}>{f.label}</Btn>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<div className="card" style={{ padding: 0, overflow: "hidden" }}>
|
||||
{inbox.loading && <div style={{ padding: 20, color: "var(--muted)" }}>Loading…</div>}
|
||||
{!inbox.loading && inbox.items.length === 0 && (
|
||||
<div style={{ padding: 28, color: "var(--muted)", textAlign: "center" }}>Nothing here — you're all caught up 🎉</div>
|
||||
)}
|
||||
{inbox.items.map((it) => (
|
||||
<InboxRow
|
||||
key={it.id} it={it}
|
||||
onDone={() => inbox.transition(it.id, "DONE")}
|
||||
onSnooze={() => inbox.transition(it.id, "SNOOZED")}
|
||||
onArchive={() => inbox.transition(it.id, "ARCHIVED")}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function InboxRow({ it, onDone, onSnooze, onArchive }: { it: UiInboxItem; onDone: () => void; onSnooze: () => void; onArchive: () => void }) {
|
||||
const isMention = it.kind === "MENTION";
|
||||
return (
|
||||
<div style={{ display: "flex", gap: 12, alignItems: "flex-start", padding: "14px 18px", borderBottom: "1px solid var(--border)" }}>
|
||||
<span style={{ marginTop: 2, color: isMention ? "var(--orange)" : "var(--text-2)" }}>
|
||||
<Icon name={isMention ? "chat" : "bell"} size={18} />
|
||||
</span>
|
||||
<div style={{ flex: 1, minWidth: 0 }}>
|
||||
<div style={{ display: "flex", gap: 8, alignItems: "center", flexWrap: "wrap" }}>
|
||||
<Pill tone={isMention ? "warn" : "muted"}>{KIND_LABEL[it.kind] ?? it.kind}</Pill>
|
||||
<span style={{ fontWeight: 600 }}>{it.title}</span>
|
||||
</div>
|
||||
{it.summary && <div style={{ color: "var(--muted)", fontSize: 13, marginTop: 3 }}>{it.summary}</div>}
|
||||
</div>
|
||||
{it.state === "OPEN" ? (
|
||||
<div style={{ display: "flex", gap: 6, flexShrink: 0 }}>
|
||||
<Btn variant="ghost" icon="clock" onClick={onSnooze}>Snooze</Btn>
|
||||
<Btn variant="outline" icon="check" onClick={onDone}>Done</Btn>
|
||||
<Btn variant="ghost" icon="x" onClick={onArchive}>Archive</Btn>
|
||||
</div>
|
||||
) : (
|
||||
<Pill tone="muted">{it.state.toLowerCase()}</Pill>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,248 @@
|
||||
"use client";
|
||||
|
||||
// ============================================================
|
||||
// Messenger — internal team + client chat, powered by IIOS via
|
||||
// the be-crm data door (crm.messenger.*). Conversation list ⇄
|
||||
// thread view + composer, with a "new chat" people picker that
|
||||
// creates a DM (1 person) or group (2+). DM-vs-group and who-can-
|
||||
// chat are enforced server-side by IIOS/OPA; this is just UI.
|
||||
// Data comes from useMessengerData()/useThread(): local mock when
|
||||
// the Shell isn't configured, live be-crm when it is.
|
||||
// ============================================================
|
||||
|
||||
import { type CSSProperties, useEffect, useRef, useState } from "react";
|
||||
import { Avatar, Btn, Field, Icon, Modal, PageHead, Pill, useToast } from "./ui";
|
||||
import { useMessengerData, useThread, type Membership, type UiConversation, type UiPerson } from "@/lib/messenger-api";
|
||||
import { MessengerSocketProvider } from "@/lib/messenger-socket";
|
||||
|
||||
const initialsOf = (name: string) =>
|
||||
name.split(/\s+/).filter(Boolean).slice(0, 2).map((p) => p[0]).join("").toUpperCase() || "?";
|
||||
const timeOf = (iso?: string) => {
|
||||
if (!iso) return "";
|
||||
const d = new Date(iso);
|
||||
return Number.isNaN(+d) ? "" : d.toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" });
|
||||
};
|
||||
const GROUP_GRAD = "linear-gradient(135deg,#6366f1,#8b5cf6)";
|
||||
const CUSTOMER_GRAD = "linear-gradient(135deg,#10b981,#059669)";
|
||||
const inputStyle: CSSProperties = {
|
||||
width: "100%", padding: "9px 12px", borderRadius: 10, border: "1px solid var(--border)",
|
||||
background: "var(--panel)", color: "var(--text)", fontSize: 14, outline: "none",
|
||||
};
|
||||
|
||||
export function Messenger() {
|
||||
// One shared IIOS socket for the whole panel (live in Shell mode; no-op in mock).
|
||||
return (
|
||||
<MessengerSocketProvider>
|
||||
<MessengerPanel />
|
||||
</MessengerSocketProvider>
|
||||
);
|
||||
}
|
||||
|
||||
function MessengerPanel() {
|
||||
const m = useMessengerData();
|
||||
const toast = useToast();
|
||||
const [selected, setSelected] = useState<string | null>(null);
|
||||
const [newOpen, setNewOpen] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
if ((!selected || !m.conversations.some((c) => c.threadId === selected)) && m.conversations[0]) {
|
||||
setSelected(m.conversations[0].threadId);
|
||||
}
|
||||
}, [m.conversations, selected]);
|
||||
|
||||
const current = m.conversations.find((c) => c.threadId === selected) ?? null;
|
||||
|
||||
return (
|
||||
<div className="view">
|
||||
<PageHead
|
||||
eyebrow="Communication" title="Messenger" subtitle="Chat with your team and clients — direct or in groups" icon="send"
|
||||
actions={<Btn icon="plus" onClick={() => setNewOpen(true)}>New chat</Btn>}
|
||||
/>
|
||||
{!m.live && (
|
||||
<div style={{ margin: "0 0 14px", padding: "8px 14px", borderRadius: 10, background: "var(--panel-2)", color: "var(--muted)", fontSize: 13, border: "1px solid var(--border)" }}>
|
||||
Demo mode — running on mock data. It goes live once the Shell + be-crm are connected.
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="card" style={{ display: "flex", height: 620, padding: 0, overflow: "hidden" }}>
|
||||
<aside style={{ width: 296, borderRight: "1px solid var(--border)", overflowY: "auto", background: "var(--panel)" }}>
|
||||
{m.loading && <div style={{ padding: 16, color: "var(--muted)" }}>Loading…</div>}
|
||||
{!m.loading && m.conversations.length === 0 && (
|
||||
<div style={{ padding: 16, color: "var(--muted)" }}>No conversations yet. Start a new chat.</div>
|
||||
)}
|
||||
{m.conversations.map((c) => (
|
||||
<ConversationRow key={c.threadId} c={c} active={c.threadId === selected} onClick={() => setSelected(c.threadId)} />
|
||||
))}
|
||||
</aside>
|
||||
|
||||
<section style={{ flex: 1, display: "flex", flexDirection: "column", minWidth: 0 }}>
|
||||
{current ? (
|
||||
<ThreadView key={current.threadId} conv={current} onError={(msg) => toast.push({ tone: "error", title: "Message failed", desc: msg })} />
|
||||
) : (
|
||||
<div style={{ margin: "auto", color: "var(--muted)", textAlign: "center" }}>
|
||||
<Icon name="send" size={38} />
|
||||
<p>Select or start a conversation</p>
|
||||
</div>
|
||||
)}
|
||||
</section>
|
||||
</div>
|
||||
|
||||
<NewChatModal
|
||||
open={newOpen} onClose={() => setNewOpen(false)} directory={m.directory}
|
||||
onCreate={async (ids, opts) => {
|
||||
try {
|
||||
const id = await m.openConversation(ids, opts);
|
||||
setSelected(id);
|
||||
setNewOpen(false);
|
||||
} catch (e) {
|
||||
toast.push({ tone: "error", title: "Couldn't start chat", desc: (e as Error).message });
|
||||
}
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function ConversationRow({ c, active, onClick }: { c: UiConversation; active: boolean; onClick: () => void }) {
|
||||
return (
|
||||
<button
|
||||
onClick={onClick}
|
||||
style={{
|
||||
display: "flex", gap: 10, alignItems: "center", width: "100%", textAlign: "left",
|
||||
padding: "10px 14px", border: "none", borderBottom: "1px solid var(--border)", cursor: "pointer",
|
||||
background: active ? "var(--panel-2)" : "transparent", color: "var(--text)",
|
||||
}}
|
||||
>
|
||||
<Avatar initials={initialsOf(c.title)} size={38} gradient={c.membership === "group" ? GROUP_GRAD : undefined} />
|
||||
<div style={{ flex: 1, minWidth: 0 }}>
|
||||
<div style={{ display: "flex", justifyContent: "space-between", gap: 8, alignItems: "center" }}>
|
||||
<span style={{ fontWeight: 600, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{c.title}</span>
|
||||
{c.membership === "group" && <Pill tone="muted">group</Pill>}
|
||||
</div>
|
||||
<div style={{ color: "var(--muted)", fontSize: 12.5, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>
|
||||
{c.lastMessage ?? "No messages yet"}
|
||||
</div>
|
||||
</div>
|
||||
{c.unread > 0 && (
|
||||
<span style={{ background: "var(--orange)", color: "#fff", borderRadius: 999, fontSize: 11, padding: "1px 7px" }}>{c.unread}</span>
|
||||
)}
|
||||
</button>
|
||||
);
|
||||
}
|
||||
|
||||
function ThreadView({ conv, onError }: { conv: UiConversation; onError: (m: string) => void }) {
|
||||
const t = useThread(conv.threadId);
|
||||
const [draft, setDraft] = useState("");
|
||||
const [sending, setSending] = useState(false);
|
||||
const endRef = useRef<HTMLDivElement>(null);
|
||||
|
||||
useEffect(() => { endRef.current?.scrollIntoView({ behavior: "smooth" }); }, [t.messages.length]);
|
||||
|
||||
async function submit() {
|
||||
const text = draft.trim();
|
||||
if (!text || sending) return;
|
||||
setDraft(""); setSending(true);
|
||||
try { await t.send(text); }
|
||||
catch (e) { setDraft(text); onError((e as Error).message); }
|
||||
finally { setSending(false); }
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<header style={{ display: "flex", alignItems: "center", gap: 10, padding: "12px 18px", borderBottom: "1px solid var(--border)" }}>
|
||||
<Avatar initials={initialsOf(conv.title)} size={34} gradient={conv.membership === "group" ? GROUP_GRAD : undefined} />
|
||||
<div>
|
||||
<div style={{ fontWeight: 600 }}>{conv.title}</div>
|
||||
<div style={{ color: "var(--muted)", fontSize: 12 }}>
|
||||
{conv.membership === "group" ? `${conv.participants.length} people` : "Direct message"}
|
||||
</div>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<div style={{ flex: 1, overflowY: "auto", padding: 18, display: "flex", flexDirection: "column", gap: 8, background: "var(--bg)" }}>
|
||||
{t.loading && t.messages.length === 0 && <div style={{ margin: "auto", color: "var(--muted)" }}>Loading messages…</div>}
|
||||
{!t.loading && t.messages.length === 0 && <div style={{ margin: "auto", color: "var(--muted)" }}>No messages yet — say hello 👋</div>}
|
||||
{t.messages.map((msg) => (
|
||||
<div key={msg.id} style={{ alignSelf: msg.mine ? "flex-end" : "flex-start", maxWidth: "72%" }}>
|
||||
<div style={{
|
||||
background: msg.mine ? "var(--grad-brand)" : "var(--panel-2)", color: msg.mine ? "#fff" : "var(--text)",
|
||||
padding: "8px 12px", borderRadius: 14,
|
||||
borderBottomRightRadius: msg.mine ? 4 : 14, borderBottomLeftRadius: msg.mine ? 14 : 4,
|
||||
whiteSpace: "pre-wrap", wordBreak: "break-word", fontSize: 14,
|
||||
}}>
|
||||
{msg.text}
|
||||
</div>
|
||||
<div style={{ fontSize: 10.5, color: "var(--muted)", textAlign: msg.mine ? "right" : "left", marginTop: 2 }}>{timeOf(msg.at)}</div>
|
||||
</div>
|
||||
))}
|
||||
<div ref={endRef} />
|
||||
</div>
|
||||
|
||||
<footer style={{ display: "flex", gap: 8, padding: 14, borderTop: "1px solid var(--border)" }}>
|
||||
<input
|
||||
value={draft} onChange={(e) => setDraft(e.target.value)}
|
||||
onKeyDown={(e) => { if (e.key === "Enter" && !e.shiftKey) { e.preventDefault(); void submit(); } }}
|
||||
placeholder="Type a message…" style={inputStyle}
|
||||
/>
|
||||
<Btn icon="send" onClick={() => void submit()} disabled={sending || !draft.trim()}>Send</Btn>
|
||||
</footer>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
function NewChatModal({
|
||||
open, onClose, directory, onCreate,
|
||||
}: {
|
||||
open: boolean; onClose: () => void; directory: UiPerson[];
|
||||
onCreate: (ids: string[], opts: { membership: Membership; subject?: string }) => Promise<void>;
|
||||
}) {
|
||||
const [picked, setPicked] = useState<string[]>([]);
|
||||
const [subject, setSubject] = useState("");
|
||||
const [q, setQ] = useState("");
|
||||
const [busy, setBusy] = useState(false);
|
||||
|
||||
useEffect(() => { if (!open) { setPicked([]); setSubject(""); setQ(""); setBusy(false); } }, [open]);
|
||||
|
||||
const membership: Membership = picked.length > 1 ? "group" : "dm";
|
||||
const filtered = directory.filter((p) => p.name.toLowerCase().includes(q.trim().toLowerCase()));
|
||||
const toggle = (id: string) => setPicked((l) => (l.includes(id) ? l.filter((x) => x !== id) : [...l, id]));
|
||||
|
||||
async function create() {
|
||||
if (!picked.length || busy) return;
|
||||
setBusy(true);
|
||||
await onCreate(picked, { membership, ...(membership === "group" && subject.trim() ? { subject: subject.trim() } : {}) });
|
||||
setBusy(false);
|
||||
}
|
||||
|
||||
return (
|
||||
<Modal
|
||||
open={open} onClose={onClose} title="New conversation"
|
||||
subtitle={membership === "group" ? "Group chat" : "Direct message"} icon="send"
|
||||
footer={<>
|
||||
<Btn variant="ghost" onClick={onClose}>Cancel</Btn>
|
||||
<Btn icon="send" onClick={() => void create()} disabled={!picked.length || busy}>{busy ? "Starting…" : "Start chat"}</Btn>
|
||||
</>}
|
||||
>
|
||||
<input value={q} onChange={(e) => setQ(e.target.value)} placeholder="Search people…" style={{ ...inputStyle, marginBottom: 10 }} />
|
||||
{membership === "group" && (
|
||||
<Field label="Group name (optional)">
|
||||
<input value={subject} onChange={(e) => setSubject(e.target.value)} placeholder="e.g. Storm response" style={inputStyle} />
|
||||
</Field>
|
||||
)}
|
||||
<div style={{ maxHeight: 320, overflowY: "auto", marginTop: 8, display: "flex", flexDirection: "column", gap: 2 }}>
|
||||
{filtered.length === 0 && <div style={{ color: "var(--muted)", padding: 10 }}>No people found.</div>}
|
||||
{filtered.map((p) => (
|
||||
<label key={p.id} style={{
|
||||
display: "flex", alignItems: "center", gap: 10, padding: "8px 10px", borderRadius: 10, cursor: "pointer",
|
||||
background: picked.includes(p.id) ? "var(--panel-2)" : "transparent",
|
||||
}}>
|
||||
<input type="checkbox" checked={picked.includes(p.id)} onChange={() => toggle(p.id)} />
|
||||
<Avatar initials={initialsOf(p.name)} size={30} gradient={p.kind === "customer" ? CUSTOMER_GRAD : undefined} />
|
||||
<span style={{ flex: 1 }}>{p.name}</span>
|
||||
<Pill tone="muted">{p.kind}</Pill>
|
||||
</label>
|
||||
))}
|
||||
</div>
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
@@ -6,6 +6,7 @@ import { ChevronsUpDown, LogOut } from "lucide-react";
|
||||
import { useAuth } from "@abe-kap/appshell-sdk/react";
|
||||
import { Icon } from "./ui";
|
||||
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() || "?";
|
||||
@@ -28,6 +29,13 @@ export const NAV_GROUPS: NavGroup[] = [
|
||||
{ key: "pipeline", label: "Pipeline", icon: "pipeline" },
|
||||
],
|
||||
},
|
||||
{
|
||||
title: "Communication",
|
||||
items: [
|
||||
{ key: "messenger", label: "Messenger", icon: "send", subtitle: "Chat with your team and clients" },
|
||||
{ key: "inbox", label: "Inbox", icon: "bell", subtitle: "Mentions, replies and updates for you" },
|
||||
],
|
||||
},
|
||||
{
|
||||
title: "Workspace",
|
||||
items: [
|
||||
@@ -67,10 +75,45 @@ export const NAV_GROUPS: NavGroup[] = [
|
||||
|
||||
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 }) {
|
||||
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) : "";
|
||||
@@ -92,7 +135,7 @@ export function Sidebar({ active, onSelect }: { active: string; onSelect: (k: st
|
||||
</div>
|
||||
|
||||
<nav className="dash-nav">
|
||||
{NAV_GROUPS.map((g, gi) => (
|
||||
{visibleGroups.map((g, gi) => (
|
||||
<div className="nav-section" key={gi}>
|
||||
<div className="nav-group">{g.title}</div>
|
||||
{g.items.map((it) => (
|
||||
|
||||
@@ -301,8 +301,15 @@ export function TeamManagement() {
|
||||
</div>
|
||||
<RoleChips roleIds={inv.roleIds} roleById={roleById} />
|
||||
<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 () => {
|
||||
try { await team.resendInvite(inv.id); toast.push({ tone: "success", title: "Invite resent", desc: `A fresh link was sent to ${inv.email}.` }); }
|
||||
try { await team.resendInvite(inv.id); toast.push({ tone: "success", title: "Invite resent", desc: `A fresh link was emailed to ${inv.email}.` }); }
|
||||
catch (e) { toast.push({ tone: "error", title: "Couldn't resend", desc: (e as Error).message }); }
|
||||
}}>Resend</Btn>
|
||||
<Btn variant="ghost" size="sm" icon="x" onClick={async () => {
|
||||
@@ -326,7 +333,7 @@ export function TeamManagement() {
|
||||
try {
|
||||
await team.invite(email, roleIds);
|
||||
setTab("invites");
|
||||
toast.push({ tone: "success", title: "Invitation sent", desc: `${email} was invited with ${roleIds.length} role${roleIds.length === 1 ? "" : "s"}.` });
|
||||
toast.push({ tone: "success", title: "Invitation sent", desc: `We emailed an invite to ${email}. You can also copy the link.` });
|
||||
} catch (e) { toast.push({ tone: "error", title: "Couldn't send invite", desc: (e as Error).message }); }
|
||||
}}
|
||||
/>
|
||||
|
||||
@@ -34,6 +34,25 @@ export function LoginFlow() {
|
||||
const [remember, setRemember] = useState(false);
|
||||
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 {
|
||||
@@ -87,7 +106,7 @@ export function LoginFlow() {
|
||||
registered = !!st?.registered;
|
||||
} catch { registered = false; }
|
||||
window.history.replaceState({}, "", "/portal/login");
|
||||
if (registered) { router.replace("/dashboard"); return; }
|
||||
if (registered) { await acceptPendingInviteThenDashboard(); return; }
|
||||
// Capture the verified email now (session is fresh) so onboarding prefills it.
|
||||
try { const em = await getUserEmail(); if (em) sessionStorage.setItem("onboard_email", em); } catch { /* ignore */ }
|
||||
router.replace("/portal/onboarding");
|
||||
@@ -154,7 +173,7 @@ export function LoginFlow() {
|
||||
{step === "identify" && (
|
||||
<>
|
||||
{flash && <div style={{ marginBottom: 16 }}><FlashNote tone="error">{flash}</FlashNote></div>}
|
||||
<Identify email={email} setEmail={setEmail} onSocial={onSocial} onEmail={identifyEmail} onPhone={startPhoneLogin} toRegister={() => router.push("/portal/register")} />
|
||||
<Identify email={email} setEmail={setEmail} onSocial={onSocial} onEmail={identifyEmail} onPhone={startPhoneLogin} toRegister={() => router.push("/portal/register")} invited={invited} />
|
||||
</>
|
||||
)}
|
||||
|
||||
@@ -201,11 +220,11 @@ export function LoginFlow() {
|
||||
)}
|
||||
|
||||
{step === "password" && account && (
|
||||
<Password account={account} email={email} login={login} onAuthenticated={() => router.replace("/dashboard")} flash={flash} onBack={back} onForgot={() => push("fp_confirm")} onOtp={() => { setOtpChannel("email"); replace("otp"); }} onLocked={() => setFlash("This account is temporarily locked.")} onOk={() => afterAuth("password")} />
|
||||
<Password account={account} email={email} login={login} onAuthenticated={acceptPendingInviteThenDashboard} flash={flash} onBack={back} onForgot={() => push("fp_confirm")} onOtp={() => { setOtpChannel("email"); replace("otp"); }} onLocked={() => setFlash("This account is temporarily locked.")} onOk={() => afterAuth("password")} />
|
||||
)}
|
||||
|
||||
{step === "otp" && account && (
|
||||
<OtpVerify account={account} email={email} initialChannel={otpChannel} remember={remember} setRemember={setRemember} onBack={back} onVerified={() => afterAuth("otp")} onAuthenticated={() => router.replace("/dashboard")} />
|
||||
<OtpVerify account={account} email={email} initialChannel={otpChannel} remember={remember} setRemember={setRemember} onBack={back} onVerified={() => afterAuth("otp")} onAuthenticated={acceptPendingInviteThenDashboard} />
|
||||
)}
|
||||
|
||||
{step === "another" && account && (
|
||||
@@ -269,17 +288,17 @@ export function LoginFlow() {
|
||||
|
||||
/* ============================ screens ============================ */
|
||||
|
||||
function Identify({ email, setEmail, onSocial, onEmail, onPhone, toRegister }: {
|
||||
function Identify({ email, setEmail, onSocial, onEmail, onPhone, toRegister, invited }: {
|
||||
email: string; setEmail: (v: string) => void;
|
||||
onSocial: (p: "google") => void; onEmail: () => void; onPhone: () => void; toRegister: () => void;
|
||||
onSocial: (p: "google") => void; onEmail: () => void; onPhone: () => void; toRegister: () => void; invited?: boolean;
|
||||
}) {
|
||||
const [showEmail, setShowEmail] = useState(false);
|
||||
const [showEmail, setShowEmail] = useState(!!invited);
|
||||
const valid = EMAIL_RE.test(email);
|
||||
return (
|
||||
<div>
|
||||
<div className="kicker">Welcome back</div>
|
||||
<h1>Sign in to LynkedUp</h1>
|
||||
<p className="sub">Drone inspections, AI estimates and insurance-ready reports — all in one place.</p>
|
||||
<div className="kicker">{invited ? "You're invited" : "Welcome back"}</div>
|
||||
<h1>{invited ? "Sign in to join the team" : "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>
|
||||
|
||||
<div style={{ marginTop: 22 }}>
|
||||
<SocialButtons onPick={onSocial} />
|
||||
@@ -435,7 +454,14 @@ function OtpVerify({ account, email, initialChannel = "email", remember, setReme
|
||||
if (!PHONE_RE.test(phone)) { setError("Enter your phone in international format, e.g. +14155550100."); return; }
|
||||
await sendPhoneOtp(phone); setSent(true);
|
||||
}
|
||||
} catch (e) { setError((e as Error).message); }
|
||||
} catch (e) {
|
||||
// gotrue can throw an error whose message is an unhelpful "{}"/JSON blob (e.g. a
|
||||
// 500 "Error sending magic link email" when SMTP isn't set up). Show something
|
||||
// readable and actionable instead of the raw payload.
|
||||
const raw = (e as { message?: unknown })?.message;
|
||||
const readable = typeof raw === "string" && raw.trim() && !raw.trim().startsWith("{") ? raw.trim() : "";
|
||||
setError(readable || "We couldn't send your sign-in code right now. Please try again shortly, or sign in with your password.");
|
||||
}
|
||||
}
|
||||
|
||||
async function complete(code: string) {
|
||||
|
||||
@@ -8,7 +8,7 @@ import {
|
||||
PasswordStrength, LegalModal,
|
||||
} from "./bits";
|
||||
import {
|
||||
countryCodes, relationshipOptions, addressCountries,
|
||||
countryCodes, addressCountries,
|
||||
TERMS, PRIVACY, passwordStrength, type AddrCountry,
|
||||
} from "./data";
|
||||
import { useAuth, useAppShell } from "@abe-kap/appshell-sdk/react";
|
||||
@@ -48,15 +48,18 @@ export function RegisterFlow({ mode = "register" }: { mode?: "register" | "onboa
|
||||
const [cc, setCc] = useState("+1");
|
||||
const [phone, setPhone] = 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 [privacyOk, setPrivacyOk] = useState(false);
|
||||
|
||||
// verify step (email is trusted without an OTP — see verifyValid below)
|
||||
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.
|
||||
@@ -69,16 +72,13 @@ export function RegisterFlow({ mode = "register" }: { mode?: "register" | "onboa
|
||||
|
||||
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 phoneOk = phone.replace(/\D/g, "").length === country.digits;
|
||||
const pwOk = sso ? true : passwordStrength(pw).score >= 3;
|
||||
const alloeIdOk = /^(?=.*[a-zA-Z])(?=.*\d).{4,}$/.test(alloeNo);
|
||||
|
||||
const step0Valid =
|
||||
first.trim() && last.trim() && EMAIL_RE.test(sso?.email || email) && phoneOk && pwOk &&
|
||||
termsOk && privacyOk && (isSelf || (alloeIdOk && (isEmployee || (alloeFirst.trim() && alloeLast.trim()))));
|
||||
termsOk && privacyOk;
|
||||
|
||||
// Email is already trusted in both flows (registration: Supabase auto-confirms on
|
||||
// signup; onboarding: Google-verified), so the Verify step only gates on the phone.
|
||||
@@ -107,8 +107,6 @@ export function RegisterFlow({ mode = "register" }: { mode?: "register" | "onboa
|
||||
name: `${first} ${last}`.trim(),
|
||||
initials: `${first[0] ?? ""}${last[0] ?? ""}`.toUpperCase(),
|
||||
email: finalEmail,
|
||||
isAllottee: isSelf,
|
||||
allotteeNames: isSelf ? null : `${alloeFirst} ${alloeLast}`.trim(),
|
||||
};
|
||||
try { localStorage.setItem("lup_profile", JSON.stringify(profile)); } catch { /* ignore */ }
|
||||
|
||||
@@ -121,17 +119,15 @@ export function RegisterFlow({ mode = "register" }: { mode?: "register" | "onboa
|
||||
if (onboard && pw) {
|
||||
try { await setPassword(pw); } catch { /* non-fatal — the profile still saves */ }
|
||||
}
|
||||
// 2) Persist the full CRM registration payload to be-crm (name, phone, persona,
|
||||
// allottee, both addresses, consent). Non-fatal: the auth account exists either way.
|
||||
// 2) Persist the CRM registration payload to be-crm (name, phone, addresses,
|
||||
// consent). No role/persona — a new user has no permissions until invited.
|
||||
// Non-fatal: the auth account exists either way.
|
||||
try {
|
||||
const mailing = mailingSame ? regAddr : mailAddr;
|
||||
await sdk.command("crm.account.register", {
|
||||
email: finalEmail,
|
||||
firstName: first, lastName: last,
|
||||
phoneCc: cc, phoneNumber: phone.replace(/\D/g, ""),
|
||||
persona: relationship,
|
||||
isAllottee: isSelf,
|
||||
...(isSelf ? {} : { allotteeId: alloeNo, allotteeFirstName: alloeFirst, allotteeLastName: alloeLast }),
|
||||
registeredAddress: regAddr,
|
||||
mailingAddress: mailing,
|
||||
mailingSameAsRegistered: mailingSame,
|
||||
@@ -141,6 +137,17 @@ export function RegisterFlow({ mode = "register" }: { mode?: "register" | "onboa
|
||||
if (onboard) { setSubmitErr("Couldn't save your profile. Please try again."); return; }
|
||||
// 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 */ }
|
||||
@@ -155,14 +162,11 @@ export function RegisterFlow({ mode = "register" }: { mode?: "register" | "onboa
|
||||
<>
|
||||
{submitErr && <div style={{ marginBottom: 14 }}><FlashNote tone="error">{submitErr}</FlashNote></div>}
|
||||
<StepAccount
|
||||
onboard={onboard} creating={creating}
|
||||
onboard={onboard} creating={creating} invited={!!invitedEmail}
|
||||
sso={sso} setSso={setSso} email={email} setEmail={setEmail}
|
||||
first={first} setFirst={setFirst} last={last} setLast={setLast}
|
||||
cc={cc} setCc={setCc} phone={phone} setPhone={setPhone} phoneOk={phoneOk} country={country}
|
||||
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}
|
||||
valid={!!step0Valid}
|
||||
onContinue={leaveAccountStep} toLogin={() => router.push("/portal/login")}
|
||||
@@ -195,11 +199,8 @@ function StepAccount(p: {
|
||||
first: string; setFirst: (v: string) => void; last: string; setLast: (v: string) => void;
|
||||
cc: string; setCc: (v: string) => void; phone: string; setPhone: (v: string) => void; phoneOk: boolean; country: typeof countryCodes[number];
|
||||
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;
|
||||
valid: boolean; onContinue: () => void; toLogin: () => void; onboard?: boolean; creating?: boolean;
|
||||
valid: boolean; onContinue: () => void; toLogin: () => void; onboard?: boolean; creating?: boolean; invited?: boolean;
|
||||
}) {
|
||||
// Onboarding (OAuth) starts on the profile step — email is already known + verified.
|
||||
const [phase, setPhase] = useState<"sso" | "profile">(p.onboard ? "profile" : "sso");
|
||||
@@ -210,21 +211,22 @@ function StepAccount(p: {
|
||||
return (
|
||||
<div>
|
||||
<StepBack onClick={p.toLogin} />
|
||||
<h1>Create your account</h1>
|
||||
<p className="sub">Enter your email to get started.</p>
|
||||
<h1>{p.invited ? "Accept your invitation" : "Create your account"}</h1>
|
||||
<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 }}>
|
||||
<form onSubmit={(e) => { e.preventDefault(); if (valid) { p.setSso(null); setPhase("profile"); } }}>
|
||||
<div className="field">
|
||||
<label className="label">Email address</label>
|
||||
<div className="input-wrap">
|
||||
<span className="input-ico"><Icon name="mail" size={17} /></span>
|
||||
<input className="input" type="email" value={p.email} onChange={(e) => p.setEmail(e.target.value)} placeholder="you@example.com" autoFocus />
|
||||
<input className="input" type="email" value={p.email} onChange={(e) => p.setEmail(e.target.value)} placeholder="you@example.com" autoFocus={!p.invited} disabled={p.invited} readOnly={p.invited} />
|
||||
</div>
|
||||
{p.invited && <span className="faint" style={{ fontSize: 12 }}>This is the address you were invited with.</span>}
|
||||
</div>
|
||||
<button className="btn btn-primary" style={{ marginTop: 12 }} disabled={!valid}>Continue <Icon name="arrowR" size={16} /></button>
|
||||
</form>
|
||||
</div>
|
||||
<p className="foot-note">Already registered? <button className="link" onClick={p.toLogin}>Sign in</button></p>
|
||||
{!p.invited && <p className="foot-note">Already registered? <button className="link" onClick={p.toLogin}>Sign in</button></p>}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -287,47 +289,6 @@ function StepAccount(p: {
|
||||
</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 }}>
|
||||
<label className="check-row">
|
||||
<input type="checkbox" checked={p.termsOk} disabled={!reviewed.terms} onChange={(e) => p.setTermsOk(e.target.checked)} />
|
||||
|
||||
@@ -0,0 +1,66 @@
|
||||
"use client";
|
||||
|
||||
import { useQuery } from "@abe-kap/appshell-sdk/react";
|
||||
import { isShellConfigured } from "./appshell";
|
||||
|
||||
/**
|
||||
* The signed-in user's effective CRM access, from crm.account.me. Drives navigation
|
||||
* gating: a user with no membership/permissions sees only Dashboard + Profile; members
|
||||
* see the areas their permissions allow.
|
||||
*
|
||||
* Every CRM permission id, granted to superadmins / owners. Used as the mock default
|
||||
* when the Shell isn't configured (local demo shows everything).
|
||||
*/
|
||||
export const ALL_CRM_PERMISSIONS = [
|
||||
"leads.manage", "pipeline.manage", "estimates.create", "dispatch.manage",
|
||||
"reports.view", "billing.view", "team.manage", "roles.manage", "settings.manage",
|
||||
] as const;
|
||||
|
||||
export interface MyAccess {
|
||||
registered: boolean;
|
||||
isMember: boolean;
|
||||
roleSlugs: string[];
|
||||
permissions: string[];
|
||||
isSuperadmin: boolean;
|
||||
/** True while the access query is still resolving (nav stays minimal until then). */
|
||||
loading: boolean;
|
||||
can: (permission: string) => boolean;
|
||||
}
|
||||
|
||||
interface MeDTO {
|
||||
registered: boolean;
|
||||
isMember: boolean;
|
||||
roleSlugs: string[];
|
||||
permissions: string[];
|
||||
isSuperadmin: boolean;
|
||||
}
|
||||
|
||||
function useLiveAccess(): MyAccess {
|
||||
const { data, loading } = useQuery<MeDTO>("crm.account.me");
|
||||
const permissions = data?.permissions ?? [];
|
||||
return {
|
||||
registered: data?.registered ?? false,
|
||||
isMember: data?.isMember ?? false,
|
||||
roleSlugs: data?.roleSlugs ?? [],
|
||||
permissions,
|
||||
isSuperadmin: data?.isSuperadmin ?? false,
|
||||
loading,
|
||||
can: (p: string) => permissions.includes(p),
|
||||
};
|
||||
}
|
||||
|
||||
function useMockAccess(): MyAccess {
|
||||
// No Shell (local demo): show everything so the mock UI is fully browsable.
|
||||
const permissions = [...ALL_CRM_PERMISSIONS];
|
||||
return {
|
||||
registered: true,
|
||||
isMember: true,
|
||||
roleSlugs: ["superadmin"],
|
||||
permissions,
|
||||
isSuperadmin: true,
|
||||
loading: false,
|
||||
can: () => true,
|
||||
};
|
||||
}
|
||||
|
||||
export const useMyAccess: () => MyAccess = isShellConfigured() ? useLiveAccess : useMockAccess;
|
||||
@@ -0,0 +1,57 @@
|
||||
"use client";
|
||||
|
||||
// Inbox data layer. The inbox is a personalized work/awareness feed IIOS projects from events
|
||||
// (NEEDS_REPLY, MENTION, …). The CRM lists it and transitions item state; items are never created
|
||||
// here. Mock when the Shell isn't configured; live via the be-crm data door (crm.inbox.*) otherwise.
|
||||
//
|
||||
// Live contract (be-crm):
|
||||
// query crm.inbox.list { state? } -> InboxItem[]
|
||||
// cmd crm.inbox.transition { id, state, reason? } -> InboxItem
|
||||
|
||||
import { useCallback, useMemo, useState } from "react";
|
||||
import { useAppShell, useQuery } from "@abe-kap/appshell-sdk/react";
|
||||
import { isShellConfigured } from "./appshell";
|
||||
|
||||
export type InboxState = "OPEN" | "SNOOZED" | "DONE" | "ARCHIVED" | "CANCELLED" | "STALE";
|
||||
export interface UiInboxItem {
|
||||
id: string; kind: string; state: InboxState; title: string; summary?: string;
|
||||
priority: string; threadId?: string; createdAt: string;
|
||||
}
|
||||
|
||||
const SHELL = isShellConfigured();
|
||||
|
||||
export interface InboxData {
|
||||
live: boolean; loading: boolean; error: string | null;
|
||||
items: UiInboxItem[];
|
||||
transition: (id: string, state: InboxState) => Promise<void>;
|
||||
refetch: () => void;
|
||||
}
|
||||
|
||||
export function useInboxData(state?: InboxState): InboxData {
|
||||
return SHELL ? useLiveInbox(state) : useMockInbox(state);
|
||||
}
|
||||
|
||||
function useLiveInbox(state?: InboxState): InboxData {
|
||||
const { sdk } = useAppShell();
|
||||
const q = useQuery<UiInboxItem[]>("crm.inbox.list", state ? { state } : {});
|
||||
const transition = useCallback(async (id: string, next: InboxState) => {
|
||||
await sdk.command("crm.inbox.transition", { id, state: next });
|
||||
q.refetch();
|
||||
}, [sdk, q]);
|
||||
return { live: true, loading: q.loading, error: q.error?.message ?? null, items: q.data ?? [], transition, refetch: q.refetch };
|
||||
}
|
||||
|
||||
const MOCK_ITEMS: UiInboxItem[] = [
|
||||
{ id: "in_1", kind: "MENTION", state: "OPEN", title: "Sofia mentioned you", summary: "@you — can you confirm the Henderson scope?", priority: "HIGH", threadId: "th_mock_1", createdAt: new Date().toISOString() },
|
||||
{ id: "in_2", kind: "NEEDS_REPLY", state: "OPEN", title: "Reply needed — Storm response", summary: "Dan: Crew is rolling out at 7.", priority: "MEDIUM", threadId: "th_mock_2", createdAt: new Date().toISOString() },
|
||||
{ id: "in_3", kind: "SUPPORT_UPDATE", state: "OPEN", title: "Ticket TK-204 updated", summary: "Customer replied on the roof-leak case.", priority: "LOW", createdAt: new Date().toISOString() },
|
||||
];
|
||||
|
||||
function useMockInbox(state?: InboxState): InboxData {
|
||||
const [items, setItems] = useState<UiInboxItem[]>(MOCK_ITEMS);
|
||||
const filtered = useMemo(() => (state ? items.filter((i) => i.state === state) : items), [items, state]);
|
||||
const transition = useCallback(async (id: string, next: InboxState) => {
|
||||
setItems((l) => l.map((i) => (i.id === id ? { ...i, state: next } : i)));
|
||||
}, []);
|
||||
return { live: false, loading: false, error: null, items: filtered, transition, refetch: () => {} };
|
||||
}
|
||||
@@ -0,0 +1,238 @@
|
||||
"use client";
|
||||
|
||||
// Messenger data layer. Serves EITHER a local mock (when the Shell isn't configured — the demo
|
||||
// keeps working) OR the live be-crm data door (crm.messenger.*), behind one interface so the UI is
|
||||
// mode-agnostic. DM-vs-group + who-can-chat are enforced server-side by IIOS/OPA; this is just glue.
|
||||
//
|
||||
// Live contract (be-crm):
|
||||
// query crm.messenger.directory { kind, query?, limit } -> DirectoryEntry[]
|
||||
// query crm.messenger.conversation.list {} -> ConversationSummary[]
|
||||
// cmd crm.messenger.conversation.open { participantIds[], membership?, subject? } -> { threadId, ... }
|
||||
// query crm.messenger.history { threadId } -> MessengerMessage[]
|
||||
// cmd crm.messenger.send { threadId, content } -> MessengerMessage
|
||||
// cmd crm.messenger.participant.add { threadId, userId }
|
||||
//
|
||||
// v1 uses REST + polling for the live stream; v2 swaps in the IIOS MessageSocket (see messenger-socket.ts).
|
||||
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||
import { useAppShell, useQuery } from "@abe-kap/appshell-sdk/react";
|
||||
import { isShellConfigured } from "./appshell";
|
||||
import { useMessengerSocket } from "./messenger-socket";
|
||||
|
||||
export type Membership = "dm" | "group";
|
||||
export interface UiPerson { id: string; name: string; kind: "staff" | "customer" }
|
||||
export interface UiConversation {
|
||||
threadId: string; title: string; subject: string | null; membership: Membership | null;
|
||||
participants: string[]; unread: number; lastMessage?: string; lastAt?: string;
|
||||
}
|
||||
export interface UiMessage { id: string; actorId: string | null; text: string; at: string; mine: boolean }
|
||||
|
||||
interface DirectoryDTO { id: string; displayName: string; kind: "staff" | "customer" }
|
||||
interface ConversationDTO {
|
||||
threadId: string; subject: string | null; membership: Membership | null;
|
||||
participants: string[]; unread: number; lastMessage?: string; lastAt?: string;
|
||||
}
|
||||
interface MessageDTO { interactionId: string; actorId: string | null; kind: string; occurredAt: string; text: string | null }
|
||||
|
||||
const SHELL = isShellConfigured();
|
||||
const POLL_MS = 4000;
|
||||
|
||||
const shortId = (id: string) => id.replace(/^(pp_|cust_)/, "").slice(0, 6);
|
||||
|
||||
/* ======================================================================== */
|
||||
/* Public hooks */
|
||||
/* ======================================================================== */
|
||||
|
||||
export interface MessengerData {
|
||||
live: boolean; loading: boolean; error: string | null;
|
||||
directory: UiPerson[];
|
||||
conversations: UiConversation[];
|
||||
nameOf: (id: string) => string;
|
||||
openConversation: (participantIds: string[], opts?: { membership?: Membership; subject?: string }) => Promise<string>;
|
||||
refetch: () => void;
|
||||
}
|
||||
|
||||
export interface ThreadData {
|
||||
loading: boolean; error: string | null;
|
||||
messages: UiMessage[];
|
||||
send: (content: string) => Promise<void>;
|
||||
refetch: () => void;
|
||||
}
|
||||
|
||||
export function useMessengerData(): MessengerData {
|
||||
return SHELL ? useLiveMessenger() : useMockMessenger();
|
||||
}
|
||||
export function useThread(threadId: string): ThreadData {
|
||||
return SHELL ? useLiveThread(threadId) : useMockThread(threadId);
|
||||
}
|
||||
|
||||
/* ======================================================================== */
|
||||
/* Live implementation (be-crm data door) */
|
||||
/* ======================================================================== */
|
||||
|
||||
function useLiveMessenger(): MessengerData {
|
||||
const { sdk } = useAppShell();
|
||||
const dirQ = useQuery<DirectoryDTO[]>("crm.messenger.directory", { kind: "all", limit: 100 });
|
||||
const convQ = useQuery<ConversationDTO[]>("crm.messenger.conversation.list", {});
|
||||
|
||||
const directory: UiPerson[] = useMemo(
|
||||
() => (dirQ.data ?? []).map((d) => ({ id: d.id, name: d.displayName, kind: d.kind })),
|
||||
[dirQ.data],
|
||||
);
|
||||
const nameById = useMemo(() => Object.fromEntries(directory.map((p) => [p.id, p.name])), [directory]);
|
||||
const nameOf = useCallback((id: string) => nameById[id] ?? `User ${shortId(id)}`, [nameById]);
|
||||
|
||||
const conversations: UiConversation[] = useMemo(
|
||||
() => (convQ.data ?? []).map((c) => shape(c, nameOf)),
|
||||
[convQ.data, nameOf],
|
||||
);
|
||||
|
||||
const refetch = useCallback(() => { dirQ.refetch(); convQ.refetch(); }, [dirQ, convQ]);
|
||||
const openConversation = useCallback(async (participantIds: string[], opts?: { membership?: Membership; subject?: string }) => {
|
||||
const res = (await sdk.command("crm.messenger.conversation.open", {
|
||||
participantIds, ...(opts?.membership ? { membership: opts.membership } : {}), ...(opts?.subject ? { subject: opts.subject } : {}),
|
||||
})) as { threadId: string };
|
||||
convQ.refetch();
|
||||
return res.threadId;
|
||||
}, [sdk, convQ]);
|
||||
|
||||
return {
|
||||
live: true,
|
||||
loading: dirQ.loading || convQ.loading,
|
||||
error: (dirQ.error ?? convQ.error)?.message ?? null,
|
||||
directory, conversations, nameOf, openConversation, refetch,
|
||||
};
|
||||
}
|
||||
|
||||
function useLiveThread(threadId: string): ThreadData {
|
||||
const { sdk } = useAppShell();
|
||||
const socket = useMessengerSocket();
|
||||
const socketReady = socket?.ready ?? false;
|
||||
const q = useQuery<MessageDTO[]>("crm.messenger.history", { threadId });
|
||||
const [socketMsgs, setSocketMsgs] = useState<UiMessage[]>([]);
|
||||
const [myActorId, setMyActorId] = useState<string | null>(null);
|
||||
|
||||
// REST poll — the fallback whenever the live socket isn't connected.
|
||||
const refetchRef = useRef(q.refetch);
|
||||
refetchRef.current = q.refetch;
|
||||
useEffect(() => {
|
||||
if (socketReady) return;
|
||||
const t = setInterval(() => refetchRef.current(), POLL_MS);
|
||||
return () => clearInterval(t);
|
||||
}, [socketReady, threadId]);
|
||||
|
||||
// Socket (primary): load history + subscribe to live messages once connected.
|
||||
useEffect(() => {
|
||||
if (!socket || !socketReady) return;
|
||||
let alive = true;
|
||||
setSocketMsgs([]);
|
||||
void socket.openThread(threadId).then((hist) => { if (alive) setSocketMsgs(hist); }).catch(() => {});
|
||||
const unsub = socket.subscribe(threadId, (m) => setSocketMsgs((l) => (l.some((x) => x.id === m.id) ? l : [...l, m])));
|
||||
return () => { alive = false; unsub(); };
|
||||
}, [socket, socketReady, threadId]);
|
||||
|
||||
const restMsgs: UiMessage[] = useMemo(
|
||||
() => (q.data ?? []).map((m) => ({
|
||||
id: m.interactionId, actorId: m.actorId, text: m.text ?? "", at: m.occurredAt,
|
||||
mine: !!myActorId && m.actorId === myActorId,
|
||||
})),
|
||||
[q.data, myActorId],
|
||||
);
|
||||
|
||||
const messages = socketReady ? socketMsgs : restMsgs;
|
||||
|
||||
const send = useCallback(async (content: string) => {
|
||||
if (socket && socketReady) {
|
||||
await socket.send(threadId, content); // echoes back over the socket as a 'message' event
|
||||
} else {
|
||||
const m = (await sdk.command("crm.messenger.send", { threadId, content })) as MessageDTO;
|
||||
if (m.actorId) setMyActorId(m.actorId);
|
||||
q.refetch();
|
||||
}
|
||||
}, [socket, socketReady, threadId, sdk, q]);
|
||||
|
||||
return { loading: q.loading && !socketReady, error: q.error?.message ?? null, messages, send, refetch: q.refetch };
|
||||
}
|
||||
|
||||
function shape(c: ConversationDTO, nameOf: (id: string) => string): UiConversation {
|
||||
const title = c.subject?.trim()
|
||||
|| (c.membership === "group"
|
||||
? "Group"
|
||||
: c.participants.map(nameOf).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 } : {}) };
|
||||
}
|
||||
|
||||
/* ======================================================================== */
|
||||
/* Mock implementation (no Shell configured — the demo keeps working) */
|
||||
/* ======================================================================== */
|
||||
|
||||
const MOCK_PEOPLE: UiPerson[] = [
|
||||
{ id: "pp_sofia", name: "Sofia Ramirez", kind: "staff" },
|
||||
{ id: "pp_dan", name: "Dan Whitaker", kind: "staff" },
|
||||
{ id: "pp_priya", name: "Priya Nair", kind: "staff" },
|
||||
{ id: "cust_acme", name: "Acme Roofing (Client)", kind: "customer" },
|
||||
{ id: "cust_globex", name: "Globex Homes (Client)", kind: "customer" },
|
||||
];
|
||||
|
||||
interface MockThread { threadId: string; membership: Membership; subject: string | null; participants: string[]; messages: UiMessage[] }
|
||||
const now = () => new Date().toISOString();
|
||||
let MOCK_SEQ = 100;
|
||||
|
||||
// A tiny module-level store both mock hooks share, with a subscribe-on-change so the
|
||||
// conversation list and the open thread stay in sync (no globalThis, no render writes).
|
||||
const MOCK_STORE = new Map<string, MockThread>([
|
||||
["th_mock_1", { threadId: "th_mock_1", membership: "dm", subject: null, participants: ["me", "pp_sofia"],
|
||||
messages: [{ id: "m1", actorId: "pp_sofia", text: "Can you review the Henderson estimate?", at: now(), mine: false }] }],
|
||||
["th_mock_2", { threadId: "th_mock_2", membership: "group", subject: "Storm response — East side", participants: ["me", "pp_dan", "pp_priya"],
|
||||
messages: [{ id: "m2", actorId: "pp_dan", text: "Crew is rolling out at 7.", at: now(), mine: false }] }],
|
||||
]);
|
||||
const mockListeners = new Set<() => void>();
|
||||
const notifyMock = () => mockListeners.forEach((l) => l());
|
||||
function useMockSubscription(): void {
|
||||
const [, setV] = useState(0);
|
||||
useEffect(() => {
|
||||
const l = () => setV((n) => n + 1);
|
||||
mockListeners.add(l);
|
||||
return () => { mockListeners.delete(l); };
|
||||
}, []);
|
||||
}
|
||||
|
||||
function useMockMessenger(): MessengerData {
|
||||
useMockSubscription();
|
||||
const nameById = useMemo(() => Object.fromEntries(MOCK_PEOPLE.map((p) => [p.id, p.name])), []);
|
||||
const nameOf = useCallback((id: string) => nameById[id] ?? `User ${shortId(id)}`, [nameById]);
|
||||
|
||||
const conversations: UiConversation[] = [...MOCK_STORE.values()].map((t) => {
|
||||
const last = t.messages[t.messages.length - 1];
|
||||
return {
|
||||
threadId: t.threadId,
|
||||
title: t.subject || t.participants.filter((p) => p !== "me").map(nameOf).join(", ") || "Conversation",
|
||||
subject: t.subject, membership: t.membership, participants: t.participants, unread: 0,
|
||||
...(last ? { lastMessage: last.text, lastAt: last.at } : {}),
|
||||
};
|
||||
});
|
||||
|
||||
const openConversation = useCallback(async (participantIds: string[], opts?: { membership?: Membership; subject?: string }) => {
|
||||
const membership = opts?.membership ?? (participantIds.length === 1 ? "dm" : "group");
|
||||
const threadId = `th_mock_${MOCK_SEQ++}`;
|
||||
MOCK_STORE.set(threadId, { threadId, membership, subject: opts?.subject ?? null, participants: ["me", ...participantIds], messages: [] });
|
||||
notifyMock();
|
||||
return threadId;
|
||||
}, []);
|
||||
|
||||
return { live: false, loading: false, error: null, directory: MOCK_PEOPLE, conversations, nameOf, openConversation, refetch: () => {} };
|
||||
}
|
||||
|
||||
function useMockThread(threadId: string): ThreadData {
|
||||
useMockSubscription();
|
||||
const thread = MOCK_STORE.get(threadId);
|
||||
const send = useCallback(async (content: string) => {
|
||||
const t = MOCK_STORE.get(threadId);
|
||||
if (t) {
|
||||
t.messages = [...t.messages, { id: `m_${MOCK_SEQ++}`, actorId: "me", text: content, at: now(), mine: true }];
|
||||
notifyMock();
|
||||
}
|
||||
}, [threadId]);
|
||||
return { loading: false, error: null, messages: thread?.messages ?? [], send, refetch: notifyMock };
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
"use client";
|
||||
|
||||
// v2 live stream: one IIOS MessageSocket for the whole Messenger panel, using the SDK
|
||||
// (@insignia/iios-kernel-client) — not raw socket.io. The delegated realtime token comes from
|
||||
// the be-crm data door (crm.messenger.realtime). Threads subscribe through a context; the socket
|
||||
// re-opens every joined thread on reconnect (handled inside the SDK). In mock mode this is a no-op
|
||||
// passthrough and the thread hook falls back to the REST poll.
|
||||
|
||||
import { createContext, useCallback, useContext, useEffect, useRef, useState, type ReactNode } from "react";
|
||||
import { MessageSocket, type Message } from "@insignia/iios-kernel-client";
|
||||
import { useAuth, useQuery } from "@abe-kap/appshell-sdk/react";
|
||||
import { isShellConfigured } from "./appshell";
|
||||
import type { UiMessage } from "./messenger-api";
|
||||
|
||||
interface RealtimeDTO { url: string; audience: string; token?: string }
|
||||
|
||||
export interface MessengerSocket {
|
||||
ready: boolean;
|
||||
openThread: (threadId: string) => Promise<UiMessage[]>;
|
||||
send: (threadId: string, content: string) => Promise<void>;
|
||||
subscribe: (threadId: string, cb: (m: UiMessage) => void) => () => void;
|
||||
}
|
||||
|
||||
const Ctx = createContext<MessengerSocket | null>(null);
|
||||
export function useMessengerSocket(): MessengerSocket | null { return useContext(Ctx); }
|
||||
|
||||
const SHELL = isShellConfigured();
|
||||
|
||||
const toUi = (m: Message, myUserId?: string): UiMessage => ({
|
||||
id: m.id, actorId: m.senderActorId ?? null, text: m.content ?? "", at: m.createdAt,
|
||||
mine: !!myUserId && m.senderId === myUserId,
|
||||
});
|
||||
|
||||
export function MessengerSocketProvider({ children }: { children: ReactNode }) {
|
||||
// SHELL is a build-time constant, so the branch is stable across renders (Rules-of-Hooks safe).
|
||||
if (!SHELL) return <>{children}</>;
|
||||
return <LiveSocketProvider>{children}</LiveSocketProvider>;
|
||||
}
|
||||
|
||||
function LiveSocketProvider({ children }: { children: ReactNode }) {
|
||||
const { user } = useAuth();
|
||||
const rt = useQuery<RealtimeDTO>("crm.messenger.realtime", {});
|
||||
const [ready, setReady] = useState(false);
|
||||
const socketRef = useRef<MessageSocket | null>(null);
|
||||
const listeners = useRef<Map<string, Set<(m: UiMessage) => void>>>(new Map());
|
||||
const myRef = useRef<string | undefined>(user?.id);
|
||||
myRef.current = user?.id;
|
||||
|
||||
const url = rt.data?.url;
|
||||
const token = rt.data?.token;
|
||||
|
||||
useEffect(() => {
|
||||
if (!url || !token) return;
|
||||
const socket = new MessageSocket({ serviceUrl: url, token, autoConnect: false });
|
||||
socketRef.current = socket;
|
||||
const offConnected = socket.onConnected(() => setReady(true));
|
||||
const offMessage = socket.on("message", (m) => {
|
||||
const cbs = listeners.current.get(m.threadId);
|
||||
if (cbs && cbs.size) { const ui = toUi(m, myRef.current); cbs.forEach((cb) => cb(ui)); }
|
||||
});
|
||||
socket.connect();
|
||||
return () => { offConnected(); offMessage(); socket.disconnect(); socketRef.current = null; setReady(false); };
|
||||
}, [url, token]);
|
||||
|
||||
const openThread = useCallback(async (threadId: string): Promise<UiMessage[]> => {
|
||||
const s = socketRef.current;
|
||||
if (!s) return [];
|
||||
const res = await s.openThread(threadId);
|
||||
return res.history.map((m) => toUi(m, myRef.current));
|
||||
}, []);
|
||||
|
||||
const send = useCallback(async (threadId: string, content: string) => {
|
||||
const s = socketRef.current;
|
||||
if (!s) throw new Error("Not connected");
|
||||
await s.sendMessage(threadId, content);
|
||||
}, []);
|
||||
|
||||
const subscribe = useCallback((threadId: string, cb: (m: UiMessage) => void) => {
|
||||
const map = listeners.current;
|
||||
if (!map.has(threadId)) map.set(threadId, new Set());
|
||||
map.get(threadId)!.add(cb);
|
||||
return () => { map.get(threadId)?.delete(cb); };
|
||||
}, []);
|
||||
|
||||
return <Ctx.Provider value={{ ready, openThread, send, subscribe }}>{children}</Ctx.Provider>;
|
||||
}
|
||||
+15
-7
@@ -38,6 +38,8 @@ export interface UiMember {
|
||||
}
|
||||
export interface UiInvite {
|
||||
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 {
|
||||
@@ -46,7 +48,9 @@ export interface TeamData {
|
||||
setMemberRoles: (id: string, roleIds: string[]) => Promise<void>;
|
||||
updateMember: (id: string, patch: { title?: string; roleIds?: string[] }) => Promise<void>;
|
||||
removeMember: (id: string) => Promise<void>;
|
||||
/** Create an invite. be-crm emails the invitee automatically. */
|
||||
invite: (email: string, roleIds: string[]) => Promise<void>;
|
||||
/** Resend an invite (regenerates the token + re-emails it). */
|
||||
resendInvite: (id: string) => Promise<void>;
|
||||
revokeInvite: (id: string) => Promise<void>;
|
||||
setPermission: (roleId: string, permId: string, granted: boolean) => Promise<void>;
|
||||
@@ -68,9 +72,9 @@ const initialsOf = (name: string) =>
|
||||
/* ---- be-crm DTO types (subset used here) -------------------------------- */
|
||||
|
||||
interface RoleRef { id: string; slug: string; name: string; color: string | null; isSystem: boolean; isOwnerRole: boolean }
|
||||
interface MemberDTO { id: string; principalId: string; jobTitle: string | null; joinedAt: string; status: "active" | "deactivated"; roles: RoleRef[]; openDeals: number }
|
||||
interface MemberDTO { id: string; principalId: string; jobTitle: string | null; joinedAt: string; status: "active" | "deactivated"; roles: RoleRef[]; openDeals: number; email?: string | null; firstName?: string | null; lastName?: string | null; displayName?: string | null }
|
||||
interface RoleDTO { id: string; slug: string; name: string; description: string | null; color: string | null; isSystem: boolean; isOwnerRole: boolean; permissions: string[]; memberCount: number }
|
||||
interface InvitationDTO { id: string; email: string; roles: RoleRef[]; invitedBy: string; createdAt: string }
|
||||
interface InvitationDTO { id: string; email: string; roles: RoleRef[]; invitedBy: string; createdAt: string; token?: string }
|
||||
|
||||
const relTime = (iso: string): string => {
|
||||
const then = Date.parse(iso);
|
||||
@@ -153,12 +157,16 @@ function useLiveTeam(): TeamData {
|
||||
|
||||
const members: UiMember[] = useMemo(() => (membersQ.data?.items ?? []).map((m) => {
|
||||
const isYou = !!meId && m.principalId === meId;
|
||||
const name = isYou && user?.displayName
|
||||
? user.displayName
|
||||
: (m.jobTitle?.trim() || `Member ${m.principalId.replace(/^pp_/, "").slice(0, 6)}`);
|
||||
// Prefer the member's real name/email from their CRM registration; fall back to the
|
||||
// ACE (for the current user), then job title, then a short principal id.
|
||||
const name = m.displayName?.trim()
|
||||
|| (isYou && user?.displayName)
|
||||
|| m.jobTitle?.trim()
|
||||
|| `Member ${m.principalId.replace(/^pp_/, "").slice(0, 6)}`;
|
||||
const email = m.email || (isYou ? user?.email : undefined) || "";
|
||||
return {
|
||||
id: m.id, principalId: m.principalId, name, initials: initialsOf(name),
|
||||
email: isYou && user?.email ? user.email : m.principalId,
|
||||
email,
|
||||
title: m.jobTitle ?? "", roleIds: m.roles.map((r) => r.id), gradient: gradientFor(m.id),
|
||||
status: (m.status === "active" ? "active" : "offline") as UiStatus,
|
||||
lastActive: m.status === "active" ? "Active" : "—",
|
||||
@@ -169,7 +177,7 @@ function useLiveTeam(): TeamData {
|
||||
|
||||
const invites: UiInvite[] = useMemo(() => (invitesQ.data?.items ?? []).map((i) => ({
|
||||
id: i.id, email: i.email, roleIds: i.roles.map((r) => r.id),
|
||||
invitedBy: i.invitedBy, sentAt: relTime(i.createdAt),
|
||||
invitedBy: i.invitedBy, sentAt: relTime(i.createdAt), token: i.token,
|
||||
})), [invitesQ.data]);
|
||||
|
||||
return {
|
||||
|
||||
Reference in New Issue
Block a user