forked from Goutam/lynkeduppro-crm
feat(dashboard): offline web push — service worker, subscribe flow, deep-link
Notifications phase 2: a /push-sw.js service worker shows a system notification on push and, on click, focuses an open CRM tab (or opens one) and deep-links to the thread. usePushNotifications registers the SW, requests permission, subscribes with IIOS's VAPID key, and stores the subscription via the be-crm door. The topbar bell becomes a real enable/disable control (hidden when push is unsupported/demo). Dashboard listens for the SW's notif-click message + a ?thread= deep link. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,50 @@
|
|||||||
|
/* Web Push service worker for CRM offline notifications.
|
||||||
|
*
|
||||||
|
* Receives push payloads from IIOS (WebPushDelivery), shows a system notification, and on click
|
||||||
|
* focuses an open CRM tab (or opens one) and posts the thread to deep-link to. The payload shape is
|
||||||
|
* IIOS's NotificationPayload: { title, body, data: { threadId, interactionId? } }.
|
||||||
|
*
|
||||||
|
* Served from /public at /push-sw.js → root scope ('/'), so it controls the whole app.
|
||||||
|
*/
|
||||||
|
|
||||||
|
self.addEventListener("push", (event) => {
|
||||||
|
let payload = {};
|
||||||
|
try {
|
||||||
|
payload = event.data ? event.data.json() : {};
|
||||||
|
} catch {
|
||||||
|
payload = { title: "New notification", body: event.data ? event.data.text() : "" };
|
||||||
|
}
|
||||||
|
const title = payload.title || "New message";
|
||||||
|
const threadId = payload.data && payload.data.threadId;
|
||||||
|
event.waitUntil(
|
||||||
|
self.registration.showNotification(title, {
|
||||||
|
body: payload.body || "",
|
||||||
|
// Coalesce repeated pings for the same thread into one notification.
|
||||||
|
tag: threadId ? `thread:${threadId}` : undefined,
|
||||||
|
renotify: Boolean(threadId),
|
||||||
|
data: payload.data || {},
|
||||||
|
icon: "/icons/i_bell.svg",
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
self.addEventListener("notificationclick", (event) => {
|
||||||
|
event.notification.close();
|
||||||
|
const threadId = event.notification.data && event.notification.data.threadId;
|
||||||
|
event.waitUntil(
|
||||||
|
(async () => {
|
||||||
|
const all = await self.clients.matchAll({ type: "window", includeUncontrolled: true });
|
||||||
|
// Prefer an already-open CRM tab: focus it and tell the app which thread to open.
|
||||||
|
for (const client of all) {
|
||||||
|
if ("focus" in client) {
|
||||||
|
await client.focus();
|
||||||
|
client.postMessage({ type: "notif-click", threadId: threadId || null });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// No tab open — launch one deep-linked via the query string.
|
||||||
|
const url = threadId ? `/dashboard?thread=${encodeURIComponent(threadId)}` : "/dashboard";
|
||||||
|
if (self.clients.openWindow) await self.clients.openWindow(url);
|
||||||
|
})(),
|
||||||
|
);
|
||||||
|
});
|
||||||
@@ -39,6 +39,25 @@ export function Dashboard() {
|
|||||||
// eslint-disable-next-line react-hooks/set-state-in-effect
|
// eslint-disable-next-line react-hooks/set-state-in-effect
|
||||||
try { const t = localStorage.getItem("lup_dash_theme"); if (t === "light" || t === "dark") setTheme(t); } catch {}
|
try { const t = localStorage.getItem("lup_dash_theme"); if (t === "light" || t === "dark") setTheme(t); } catch {}
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
|
// Deep-link from a clicked push notification. Two paths from the service worker:
|
||||||
|
// - a tab was already open → it postMessages { type: 'notif-click', threadId } to focus here
|
||||||
|
// - no tab was open → it opens /dashboard?thread=<id>, which we read once on mount
|
||||||
|
useEffect(() => {
|
||||||
|
try {
|
||||||
|
const t = new URLSearchParams(window.location.search).get("thread");
|
||||||
|
if (t) {
|
||||||
|
navigateToConversation("messenger", t);
|
||||||
|
window.history.replaceState({}, "", window.location.pathname);
|
||||||
|
}
|
||||||
|
} catch {}
|
||||||
|
if (!("serviceWorker" in navigator)) return;
|
||||||
|
const onMessage = (e: MessageEvent) => {
|
||||||
|
if (e.data?.type === "notif-click" && e.data.threadId) navigateToConversation("messenger", e.data.threadId);
|
||||||
|
};
|
||||||
|
navigator.serviceWorker.addEventListener("message", onMessage);
|
||||||
|
return () => navigator.serviceWorker.removeEventListener("message", onMessage);
|
||||||
|
}, []);
|
||||||
function toggle() {
|
function toggle() {
|
||||||
setTheme((t) => { const n = t === "dark" ? "light" : "dark"; try { localStorage.setItem("lup_dash_theme", n); } catch {} return n; });
|
setTheme((t) => { const n = t === "dark" ? "light" : "dark"; try { localStorage.setItem("lup_dash_theme", n); } catch {} return n; });
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,74 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
// Topbar bell → offline-notification control. Click opens a small popover to enable/disable Web Push
|
||||||
|
// for this browser. The dot is lit when this browser is subscribed. Hidden entirely when push isn't
|
||||||
|
// available (demo mode, or a browser without ServiceWorker/PushManager).
|
||||||
|
|
||||||
|
import { useState } from "react";
|
||||||
|
import { Icon } from "./ui";
|
||||||
|
import { usePushNotifications } from "@/lib/push-notifications";
|
||||||
|
|
||||||
|
export function NotificationBell() {
|
||||||
|
const push = usePushNotifications();
|
||||||
|
const [open, setOpen] = useState(false);
|
||||||
|
|
||||||
|
if (!push.supported) return null;
|
||||||
|
|
||||||
|
const denied = push.permission === "denied";
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div style={{ position: "relative" }}>
|
||||||
|
<button
|
||||||
|
className="ic-btn"
|
||||||
|
aria-label="Notifications"
|
||||||
|
aria-haspopup="menu"
|
||||||
|
aria-expanded={open}
|
||||||
|
style={{ position: "relative" }}
|
||||||
|
onClick={() => setOpen((o) => !o)}
|
||||||
|
>
|
||||||
|
<Icon name="bell" size={18} />
|
||||||
|
<span
|
||||||
|
style={{
|
||||||
|
position: "absolute",
|
||||||
|
top: 9,
|
||||||
|
right: 10,
|
||||||
|
width: 7,
|
||||||
|
height: 7,
|
||||||
|
borderRadius: 99,
|
||||||
|
background: push.subscribed ? "var(--orange)" : "var(--border)",
|
||||||
|
border: "2px solid var(--panel)",
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
</button>
|
||||||
|
{open && (
|
||||||
|
<>
|
||||||
|
<div className="tm-menu-scrim" onClick={() => setOpen(false)} />
|
||||||
|
<div className="tm-menu-pop" role="menu" style={{ width: 260, padding: 14 }}>
|
||||||
|
<div style={{ fontWeight: 700, fontSize: 13, marginBottom: 4 }}>Offline notifications</div>
|
||||||
|
<p style={{ fontSize: 12, color: "var(--muted)", margin: "0 0 12px", lineHeight: 1.4 }}>
|
||||||
|
{push.subscribed
|
||||||
|
? "You'll get push notifications for new direct messages and mentions, even when this tab is closed."
|
||||||
|
: "Get notified about direct messages and mentions when the CRM isn't open."}
|
||||||
|
</p>
|
||||||
|
|
||||||
|
{denied ? (
|
||||||
|
<p style={{ fontSize: 12, color: "var(--danger, #c0392b)", margin: 0 }}>
|
||||||
|
Notifications are blocked in your browser settings. Allow them for this site, then try again.
|
||||||
|
</p>
|
||||||
|
) : push.subscribed ? (
|
||||||
|
<button className="ds-btn v-ghost full" disabled={push.busy} onClick={() => push.disable()}>
|
||||||
|
{push.busy ? "Turning off…" : "Turn off notifications"}
|
||||||
|
</button>
|
||||||
|
) : (
|
||||||
|
<button className="ds-btn v-primary full" disabled={push.busy} onClick={() => push.enable()}>
|
||||||
|
{push.busy ? "Enabling…" : "Enable notifications"}
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{push.error && <p style={{ fontSize: 11.5, color: "var(--danger, #c0392b)", margin: "10px 0 0" }}>{push.error}</p>}
|
||||||
|
</div>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -4,8 +4,8 @@ import { useState } from "react";
|
|||||||
import { useRouter } from "next/navigation";
|
import { useRouter } from "next/navigation";
|
||||||
import { Sun, Moon, ChevronDown, LogOut } from "lucide-react";
|
import { Sun, Moon, ChevronDown, LogOut } from "lucide-react";
|
||||||
import { useAuth } from "@abe-kap/appshell-sdk/react";
|
import { useAuth } from "@abe-kap/appshell-sdk/react";
|
||||||
import { Icon } from "./ui";
|
|
||||||
import { GlobalSearch } from "./global-search";
|
import { GlobalSearch } from "./global-search";
|
||||||
|
import { NotificationBell } from "./notification-bell";
|
||||||
import { user } from "./account-data";
|
import { user } from "./account-data";
|
||||||
|
|
||||||
function initialsOf(name: string): string {
|
function initialsOf(name: string): string {
|
||||||
@@ -40,10 +40,7 @@ export function Topbar({ theme, onToggle, title, subtitle, onNavigate }: { theme
|
|||||||
<button className="ic-btn" aria-label="Toggle theme" onClick={onToggle}>
|
<button className="ic-btn" aria-label="Toggle theme" onClick={onToggle}>
|
||||||
{theme === "dark" ? <Moon size={18} /> : <Sun size={18} />}
|
{theme === "dark" ? <Moon size={18} /> : <Sun size={18} />}
|
||||||
</button>
|
</button>
|
||||||
<button className="ic-btn" aria-label="Notifications" style={{ position: "relative" }}>
|
<NotificationBell />
|
||||||
<Icon name="bell" size={18} />
|
|
||||||
<span style={{ position: "absolute", top: 9, right: 10, width: 7, height: 7, borderRadius: 99, background: "var(--orange)", border: "2px solid var(--panel)" }} />
|
|
||||||
</button>
|
|
||||||
<div className="top-user-wrap" style={{ position: "relative" }}>
|
<div className="top-user-wrap" style={{ position: "relative" }}>
|
||||||
<button className="top-user" onClick={() => setMenuOpen((o) => !o)} aria-haspopup="menu" aria-expanded={menuOpen}>
|
<button className="top-user" onClick={() => setMenuOpen((o) => !o)} aria-haspopup="menu" aria-expanded={menuOpen}>
|
||||||
<span className="av" style={{ background: user.avatarGradient, display: "grid", placeItems: "center", color: "#fff", fontWeight: 700, fontSize: 12 }}>{initials}</span>
|
<span className="av" style={{ background: user.avatarGradient, display: "grid", placeItems: "center", color: "#fff", fontWeight: 700, fontSize: 12 }}>{initials}</span>
|
||||||
|
|||||||
@@ -0,0 +1,138 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
// Offline notifications data layer (Web Push). Registers the service worker, subscribes the browser
|
||||||
|
// with IIOS's VAPID key, and hands the subscription to the be-crm door so IIOS can reach this user
|
||||||
|
// while no CRM tab is open. Push needs a real backend (VAPID key + delivery), so it is only offered
|
||||||
|
// when the Shell is configured (live); demo mode reports it unsupported.
|
||||||
|
//
|
||||||
|
// Live contract (be-crm data door → IIOS /v1/notifications/*):
|
||||||
|
// query crm.messenger.push.vapidKey {} -> { key } ('' = push disabled server-side)
|
||||||
|
// cmd crm.messenger.push.subscribe { endpoint, keys, userAgent } -> { ok }
|
||||||
|
// cmd crm.messenger.push.unsubscribe { endpoint } -> { ok }
|
||||||
|
|
||||||
|
import { useCallback, useEffect, useState } from "react";
|
||||||
|
import { useAppShell } from "@abe-kap/appshell-sdk/react";
|
||||||
|
import { isShellConfigured } from "./appshell";
|
||||||
|
|
||||||
|
const SHELL = isShellConfigured();
|
||||||
|
const SW_URL = "/push-sw.js";
|
||||||
|
|
||||||
|
export type PushPermission = "default" | "granted" | "denied";
|
||||||
|
|
||||||
|
export interface PushState {
|
||||||
|
/** Browser can do Web Push AND we have a live backend to deliver it. */
|
||||||
|
supported: boolean;
|
||||||
|
/** OS/browser permission for notifications. */
|
||||||
|
permission: PushPermission;
|
||||||
|
/** This browser currently has an active push subscription registered with the backend. */
|
||||||
|
subscribed: boolean;
|
||||||
|
/** A subscribe/unsubscribe round-trip is in flight. */
|
||||||
|
busy: boolean;
|
||||||
|
error: string | null;
|
||||||
|
enable: () => Promise<void>;
|
||||||
|
disable: () => Promise<void>;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** VAPID keys travel as URL-safe base64; PushManager wants raw bytes. */
|
||||||
|
function urlBase64ToUint8Array(base64: string): Uint8Array {
|
||||||
|
const padding = "=".repeat((4 - (base64.length % 4)) % 4);
|
||||||
|
const normalized = (base64 + padding).replace(/-/g, "+").replace(/_/g, "/");
|
||||||
|
const raw = atob(normalized);
|
||||||
|
const out = new Uint8Array(raw.length);
|
||||||
|
for (let i = 0; i < raw.length; i++) out[i] = raw.charCodeAt(i);
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
function browserSupportsPush(): boolean {
|
||||||
|
return typeof window !== "undefined" && "serviceWorker" in navigator && "PushManager" in window && "Notification" in window;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Serialize a PushSubscription into the door's { endpoint, keys } shape. */
|
||||||
|
function toSubscribeBody(sub: PushSubscription): { endpoint: string; keys: { p256dh: string; auth: string }; userAgent: string } {
|
||||||
|
const json = sub.toJSON();
|
||||||
|
return {
|
||||||
|
endpoint: sub.endpoint,
|
||||||
|
keys: { p256dh: json.keys?.p256dh ?? "", auth: json.keys?.auth ?? "" },
|
||||||
|
userAgent: typeof navigator !== "undefined" ? navigator.userAgent.slice(0, 400) : "",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export function usePushNotifications(): PushState {
|
||||||
|
const { sdk } = useAppShell();
|
||||||
|
const [supported] = useState<boolean>(() => SHELL && browserSupportsPush());
|
||||||
|
const [permission, setPermission] = useState<PushPermission>("default");
|
||||||
|
const [subscribed, setSubscribed] = useState(false);
|
||||||
|
const [busy, setBusy] = useState(false);
|
||||||
|
const [error, setError] = useState<string | null>(null);
|
||||||
|
|
||||||
|
// Reflect the current OS permission + whether a subscription already exists (e.g. across reloads).
|
||||||
|
useEffect(() => {
|
||||||
|
if (!supported) return;
|
||||||
|
setPermission(Notification.permission as PushPermission);
|
||||||
|
let cancelled = false;
|
||||||
|
navigator.serviceWorker.ready
|
||||||
|
.then((reg) => reg.pushManager.getSubscription())
|
||||||
|
.then((sub) => {
|
||||||
|
if (!cancelled) setSubscribed(Boolean(sub));
|
||||||
|
})
|
||||||
|
.catch(() => {});
|
||||||
|
return () => {
|
||||||
|
cancelled = true;
|
||||||
|
};
|
||||||
|
}, [supported]);
|
||||||
|
|
||||||
|
const enable = useCallback(async () => {
|
||||||
|
if (!supported) return;
|
||||||
|
setBusy(true);
|
||||||
|
setError(null);
|
||||||
|
try {
|
||||||
|
const perm = await Notification.requestPermission();
|
||||||
|
setPermission(perm as PushPermission);
|
||||||
|
if (perm !== "granted") throw new Error("Notifications permission was not granted.");
|
||||||
|
|
||||||
|
const reg = await navigator.serviceWorker.register(SW_URL);
|
||||||
|
await navigator.serviceWorker.ready;
|
||||||
|
|
||||||
|
const { key } = await sdk.query<{ key: string }>("crm.messenger.push.vapidKey", {});
|
||||||
|
if (!key) throw new Error("Push is not enabled on the server (no VAPID key).");
|
||||||
|
|
||||||
|
const existing = await reg.pushManager.getSubscription();
|
||||||
|
const sub =
|
||||||
|
existing ??
|
||||||
|
(await reg.pushManager.subscribe({
|
||||||
|
userVisibleOnly: true,
|
||||||
|
// Cast: this lib's BufferSource type pins ArrayBuffer, but a plain Uint8Array is valid here.
|
||||||
|
applicationServerKey: urlBase64ToUint8Array(key) as BufferSource,
|
||||||
|
}));
|
||||||
|
|
||||||
|
await sdk.command("crm.messenger.push.subscribe", toSubscribeBody(sub));
|
||||||
|
setSubscribed(true);
|
||||||
|
} catch (e) {
|
||||||
|
setError(e instanceof Error ? e.message : "Could not enable notifications.");
|
||||||
|
} finally {
|
||||||
|
setBusy(false);
|
||||||
|
}
|
||||||
|
}, [supported, sdk]);
|
||||||
|
|
||||||
|
const disable = useCallback(async () => {
|
||||||
|
if (!supported) return;
|
||||||
|
setBusy(true);
|
||||||
|
setError(null);
|
||||||
|
try {
|
||||||
|
const reg = await navigator.serviceWorker.ready;
|
||||||
|
const sub = await reg.pushManager.getSubscription();
|
||||||
|
if (sub) {
|
||||||
|
// Tell the backend first (still has the endpoint), then drop the local subscription.
|
||||||
|
await sdk.command("crm.messenger.push.unsubscribe", { endpoint: sub.endpoint }).catch(() => {});
|
||||||
|
await sub.unsubscribe();
|
||||||
|
}
|
||||||
|
setSubscribed(false);
|
||||||
|
} catch (e) {
|
||||||
|
setError(e instanceof Error ? e.message : "Could not disable notifications.");
|
||||||
|
} finally {
|
||||||
|
setBusy(false);
|
||||||
|
}
|
||||||
|
}, [supported, sdk]);
|
||||||
|
|
||||||
|
return { supported, permission, subscribed, busy, error, enable, disable };
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user