Add embeddable chat widget for websites
Reuses the existing portal-token/SSE mechanism (customers.portalToken, /api/portal/events) for anonymous widget visitors instead of building a parallel auth system. Public API: session bootstrap + messages endpoint, both scoped by a non-secret siteKey with optional origin allowlist. Embeddable script (public/widget.js) is a small self-contained vanilla JS file: floating button + iframe kept mounted for a live SSE connection, with a postMessage bridge for the unread badge. Admin UI at Settings -> Виджет manages sites and shows the embed snippet. Also generalized recordTelegramInboundMessage -> recordChatInboundMessage (channel param) since Telegram and the widget need the identical find-or-create-open-ticket heuristic. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01QcXH24ky6zjk2UyK5oZUPH
This commit is contained in:
1 parent
59e6c32d79
commit
4efce5f307
19 files changed
+1267
-14
No files matched your search
@@ -3,7 +3,7 @@
|
||||
import { useMemo, useState } from "react";
|
||||
import Link from "next/link";
|
||||
import { AnimatePresence, motion } from "framer-motion";
|
||||
import { Send, Globe, UserRound, Mail, Plus } from "lucide-react";
|
||||
import { Send, Globe, UserRound, Mail, MessageSquare, Plus } from "lucide-react";
|
||||
import { useTicketEvents } from "@/lib/events/use-ticket-events";
|
||||
import { formatRelativeTime } from "@/lib/format";
|
||||
import type { TicketDTO, TicketStatus } from "@/lib/tickets/types";
|
||||
@@ -16,7 +16,13 @@ const COLUMNS: { status: TicketStatus; label: string }[] = [
|
||||
{ status: "closed", label: "Закрытые" },
|
||||
];
|
||||
|
||||
const CHANNEL_ICON = { telegram: Send, portal: Globe, manual: UserRound, email: Mail } as const;
|
||||
const CHANNEL_ICON = {
|
||||
telegram: Send,
|
||||
portal: Globe,
|
||||
manual: UserRound,
|
||||
email: Mail,
|
||||
widget: MessageSquare,
|
||||
} as const;
|
||||
|
||||
const PRIORITY_COLOR: Record<TicketDTO["priority"], string> = {
|
||||
low: "var(--text-faint)",
|
||||
|
||||
@@ -2,12 +2,13 @@
|
||||
|
||||
import Link from "next/link";
|
||||
import { usePathname } from "next/navigation";
|
||||
import { LayoutDashboard, Send, Mail } from "lucide-react";
|
||||
import { LayoutDashboard, Send, Mail, Code2 } from "lucide-react";
|
||||
|
||||
const links = [
|
||||
{ href: "/dashboard", label: "Дашборд", icon: LayoutDashboard },
|
||||
{ href: "/settings/telegram", label: "Telegram", icon: Send },
|
||||
{ href: "/settings/email", label: "Почта", icon: Mail },
|
||||
{ href: "/settings/widget", label: "Виджет", icon: Code2 },
|
||||
];
|
||||
|
||||
export function NavLinks() {
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
import { listWidgetSites } from "@/lib/tickets/service";
|
||||
import { WidgetSitesManager } from "./widget-sites-manager";
|
||||
|
||||
export default async function WidgetSettingsPage() {
|
||||
const sites = await listWidgetSites();
|
||||
return (
|
||||
<div className="max-w-2xl">
|
||||
<h1 className="mb-1 text-xl font-bold tracking-tight">Виджет для сайтов</h1>
|
||||
<p className="mb-6 text-sm text-text-muted">
|
||||
Встройте чат на любой сайт — сообщения посетителей превращаются в заявки.
|
||||
</p>
|
||||
<WidgetSitesManager
|
||||
initialSites={sites.map((s) => ({
|
||||
id: s.id,
|
||||
name: s.name,
|
||||
siteKey: s.siteKey,
|
||||
allowedOrigin: s.allowedOrigin,
|
||||
enabled: s.enabled,
|
||||
}))}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,129 @@
|
||||
"use client";
|
||||
|
||||
import { useState } from "react";
|
||||
import { Plus, Copy, Check } from "lucide-react";
|
||||
|
||||
interface Site {
|
||||
id: string;
|
||||
name: string;
|
||||
siteKey: string;
|
||||
allowedOrigin: string | null;
|
||||
enabled: boolean;
|
||||
}
|
||||
|
||||
export function WidgetSitesManager({ initialSites }: { initialSites: Site[] }) {
|
||||
const [sites, setSites] = useState(initialSites);
|
||||
const [name, setName] = useState("");
|
||||
const [allowedOrigin, setAllowedOrigin] = useState("");
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
async function handleCreate(e: React.FormEvent) {
|
||||
e.preventDefault();
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
|
||||
const res = await fetch("/api/widget/sites", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ name, allowedOrigin: allowedOrigin || undefined }),
|
||||
});
|
||||
|
||||
setLoading(false);
|
||||
if (!res.ok) {
|
||||
const data = await res.json().catch(() => null);
|
||||
setError(data?.error ?? "Не удалось создать сайт");
|
||||
return;
|
||||
}
|
||||
|
||||
const { site } = await res.json();
|
||||
setSites((prev) => [site, ...prev]);
|
||||
setName("");
|
||||
setAllowedOrigin("");
|
||||
}
|
||||
|
||||
async function toggleEnabled(site: Site) {
|
||||
const res = await fetch("/api/widget/sites", {
|
||||
method: "PATCH",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ id: site.id, enabled: !site.enabled }),
|
||||
});
|
||||
if (res.ok) {
|
||||
const { site: updated } = await res.json();
|
||||
setSites((prev) => prev.map((s) => (s.id === site.id ? updated : s)));
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-4">
|
||||
<form onSubmit={handleCreate} className="card flex flex-col gap-3 p-4 sm:flex-row sm:items-end">
|
||||
<label className="flex-1 text-sm">
|
||||
<span className="mb-1 block font-medium text-text-muted">Название сайта</span>
|
||||
<input
|
||||
required
|
||||
value={name}
|
||||
onChange={(e) => setName(e.target.value)}
|
||||
placeholder="top-sysops.ru"
|
||||
className="w-full rounded-md border border-border bg-surface px-3 py-2 text-sm outline-none focus:border-accent"
|
||||
/>
|
||||
</label>
|
||||
<label className="flex-1 text-sm">
|
||||
<span className="mb-1 block font-medium text-text-muted">Домен (необязательно)</span>
|
||||
<input
|
||||
value={allowedOrigin}
|
||||
onChange={(e) => setAllowedOrigin(e.target.value)}
|
||||
placeholder="https://top-sysops.ru"
|
||||
className="w-full rounded-md border border-border bg-surface px-3 py-2 text-sm outline-none focus:border-accent"
|
||||
/>
|
||||
</label>
|
||||
<button type="submit" disabled={loading} className="btn btn-primary shrink-0">
|
||||
<Plus size={15} />
|
||||
Добавить
|
||||
</button>
|
||||
</form>
|
||||
|
||||
{error && <p className="rounded-md bg-danger-soft px-3 py-2 text-sm text-danger-soft-text">{error}</p>}
|
||||
|
||||
{sites.length === 0 && <p className="text-sm text-text-muted">Сайтов пока нет.</p>}
|
||||
|
||||
<div className="flex flex-col gap-3">
|
||||
{sites.map((site) => (
|
||||
<SiteCard key={site.id} site={site} onToggle={() => toggleEnabled(site)} />
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function SiteCard({ site, onToggle }: { site: Site; onToggle: () => void }) {
|
||||
const [copied, setCopied] = useState(false);
|
||||
const origin = typeof window !== "undefined" ? window.location.origin : "";
|
||||
const snippet = `<script src="${origin}/widget.js" data-key="${site.siteKey}" async></script>`;
|
||||
|
||||
async function copySnippet() {
|
||||
await navigator.clipboard.writeText(snippet);
|
||||
setCopied(true);
|
||||
setTimeout(() => setCopied(false), 1500);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="card p-4">
|
||||
<div className="mb-2 flex items-center justify-between">
|
||||
<div>
|
||||
<p className="text-sm font-medium">{site.name}</p>
|
||||
{site.allowedOrigin && <p className="text-xs text-text-faint">{site.allowedOrigin}</p>}
|
||||
</div>
|
||||
<label className="flex items-center gap-2 text-xs text-text-muted">
|
||||
<input type="checkbox" checked={site.enabled} onChange={onToggle} />
|
||||
{site.enabled ? "Включён" : "Выключен"}
|
||||
</label>
|
||||
</div>
|
||||
<div className="flex items-center gap-2 rounded-md bg-surface-hover px-3 py-2">
|
||||
<code className="flex-1 overflow-x-auto whitespace-nowrap text-xs">{snippet}</code>
|
||||
<button onClick={copySnippet} className="btn btn-ghost shrink-0 px-2 py-1">
|
||||
{copied ? <Check size={13} /> : <Copy size={13} />}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
export const runtime = "nodejs";
|
||||
|
||||
import { NextResponse } from "next/server";
|
||||
import { z } from "zod";
|
||||
import {
|
||||
getWidgetSiteByKey,
|
||||
getCustomerByPortalToken,
|
||||
renameCustomerIfGuest,
|
||||
recordChatInboundMessage,
|
||||
} from "@/lib/tickets/service";
|
||||
|
||||
// Simple in-memory per-visitor rate limit — this is a public, unauthenticated
|
||||
// endpoint. Good enough at MVP scale; resets on restart.
|
||||
const attempts = new Map<string, { count: number; resetAt: number }>();
|
||||
const MAX_ATTEMPTS = 20;
|
||||
const WINDOW_MS = 5 * 60 * 1000;
|
||||
|
||||
function isRateLimited(key: string): boolean {
|
||||
const now = Date.now();
|
||||
const entry = attempts.get(key);
|
||||
if (!entry || entry.resetAt < now) {
|
||||
attempts.set(key, { count: 1, resetAt: now + WINDOW_MS });
|
||||
return false;
|
||||
}
|
||||
entry.count += 1;
|
||||
return entry.count > MAX_ATTEMPTS;
|
||||
}
|
||||
|
||||
const schema = z.object({
|
||||
siteKey: z.string().min(1),
|
||||
token: z.string().min(1),
|
||||
body: z.string().min(1).max(4_000),
|
||||
name: z.string().max(100).optional(),
|
||||
});
|
||||
|
||||
export async function POST(request: Request) {
|
||||
const body = await request.json().catch(() => null);
|
||||
const parsed = schema.safeParse(body);
|
||||
if (!parsed.success) {
|
||||
return NextResponse.json({ error: "Invalid input" }, { status: 400 });
|
||||
}
|
||||
|
||||
if (isRateLimited(parsed.data.token)) {
|
||||
return NextResponse.json({ error: "Слишком много сообщений — подождите немного" }, { status: 429 });
|
||||
}
|
||||
|
||||
const site = await getWidgetSiteByKey(parsed.data.siteKey);
|
||||
if (!site || !site.enabled) {
|
||||
return NextResponse.json({ error: "Unknown or disabled widget" }, { status: 404 });
|
||||
}
|
||||
|
||||
const customer = await getCustomerByPortalToken(parsed.data.token);
|
||||
if (!customer) {
|
||||
return NextResponse.json({ error: "Invalid token" }, { status: 404 });
|
||||
}
|
||||
|
||||
const name = parsed.data.name?.trim();
|
||||
if (name) {
|
||||
await renameCustomerIfGuest(customer.id, name);
|
||||
}
|
||||
|
||||
const result = await recordChatInboundMessage({
|
||||
customerId: customer.id,
|
||||
channel: "widget",
|
||||
body: parsed.data.body,
|
||||
authorName: name || customer.displayName,
|
||||
subjectForNewTicket: `Чат (${site.name}): ${parsed.data.body.slice(0, 60)}`,
|
||||
});
|
||||
|
||||
return NextResponse.json(result, { status: 201 });
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
export const runtime = "nodejs";
|
||||
|
||||
import { NextResponse } from "next/server";
|
||||
import { z } from "zod";
|
||||
import {
|
||||
getWidgetSiteByKey,
|
||||
getCustomerByPortalToken,
|
||||
createGuestCustomer,
|
||||
listTicketsForCustomer,
|
||||
getTicketForCustomer,
|
||||
} from "@/lib/tickets/service";
|
||||
|
||||
const schema = z.object({
|
||||
siteKey: z.string().min(1),
|
||||
token: z.string().optional(),
|
||||
});
|
||||
|
||||
function originAllowed(request: Request, allowedOrigin: string | null): boolean {
|
||||
if (!allowedOrigin) return true;
|
||||
return request.headers.get("origin") === allowedOrigin;
|
||||
}
|
||||
|
||||
/** Bootstraps (or resumes) a widget visitor's session and their current conversation, in one call. */
|
||||
export async function POST(request: Request) {
|
||||
const body = await request.json().catch(() => null);
|
||||
const parsed = schema.safeParse(body);
|
||||
if (!parsed.success) {
|
||||
return NextResponse.json({ error: "Invalid input" }, { status: 400 });
|
||||
}
|
||||
|
||||
const site = await getWidgetSiteByKey(parsed.data.siteKey);
|
||||
if (!site || !site.enabled) {
|
||||
return NextResponse.json({ error: "Unknown or disabled widget" }, { status: 404 });
|
||||
}
|
||||
if (!originAllowed(request, site.allowedOrigin)) {
|
||||
return NextResponse.json({ error: "Origin not allowed" }, { status: 403 });
|
||||
}
|
||||
|
||||
const customer =
|
||||
(parsed.data.token ? await getCustomerByPortalToken(parsed.data.token) : null) ??
|
||||
(await createGuestCustomer());
|
||||
|
||||
const tickets = await listTicketsForCustomer(customer.id);
|
||||
const openTicket = tickets.find((t) => t.status !== "closed") ?? null;
|
||||
const result = openTicket ? await getTicketForCustomer(customer.id, openTicket.id) : null;
|
||||
|
||||
return NextResponse.json({
|
||||
token: customer.portalToken,
|
||||
ticket: result?.ticket ?? null,
|
||||
messages: result?.messages ?? [],
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
export const runtime = "nodejs";
|
||||
|
||||
import { NextResponse } from "next/server";
|
||||
import { z } from "zod";
|
||||
import { requireSession } from "@/lib/auth/require";
|
||||
import { listWidgetSites, createWidgetSite, setWidgetSiteEnabled } from "@/lib/tickets/service";
|
||||
|
||||
export async function GET() {
|
||||
const { session, response } = await requireSession();
|
||||
if (!session) return response;
|
||||
|
||||
return NextResponse.json({ sites: await listWidgetSites() });
|
||||
}
|
||||
|
||||
const createSchema = z.object({
|
||||
name: z.string().min(1).max(100),
|
||||
allowedOrigin: z.string().url().optional(),
|
||||
});
|
||||
|
||||
export async function POST(request: Request) {
|
||||
const { session, response } = await requireSession();
|
||||
if (!session) return response;
|
||||
|
||||
const body = await request.json().catch(() => null);
|
||||
const parsed = createSchema.safeParse(body);
|
||||
if (!parsed.success) {
|
||||
return NextResponse.json({ error: "Invalid input" }, { status: 400 });
|
||||
}
|
||||
|
||||
const site = await createWidgetSite(parsed.data.name, parsed.data.allowedOrigin);
|
||||
return NextResponse.json({ site }, { status: 201 });
|
||||
}
|
||||
|
||||
const patchSchema = z.object({
|
||||
id: z.string().min(1),
|
||||
enabled: z.boolean(),
|
||||
});
|
||||
|
||||
export async function PATCH(request: Request) {
|
||||
const { session, response } = await requireSession();
|
||||
if (!session) return response;
|
||||
|
||||
const body = await request.json().catch(() => null);
|
||||
const parsed = patchSchema.safeParse(body);
|
||||
if (!parsed.success) {
|
||||
return NextResponse.json({ error: "Invalid input" }, { status: 400 });
|
||||
}
|
||||
|
||||
const site = await setWidgetSiteEnabled(parsed.data.id, parsed.data.enabled);
|
||||
return NextResponse.json({ site });
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
import { Suspense } from "react";
|
||||
import { WidgetChat } from "./widget-chat";
|
||||
|
||||
export default function WidgetChatPage() {
|
||||
return (
|
||||
<Suspense fallback={null}>
|
||||
<WidgetChat />
|
||||
</Suspense>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,143 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import { useSearchParams } from "next/navigation";
|
||||
import { AnimatePresence, motion } from "framer-motion";
|
||||
import { Send } from "lucide-react";
|
||||
import { useTicketEvents } from "@/lib/events/use-ticket-events";
|
||||
import { formatRelativeTime } from "@/lib/format";
|
||||
import type { MessageDTO } from "@/lib/tickets/types";
|
||||
|
||||
const STORAGE_KEY = "top-tickets-widget-token";
|
||||
|
||||
export function WidgetChat() {
|
||||
const siteKey = useSearchParams().get("key") ?? "";
|
||||
|
||||
const [token, setToken] = useState<string | null>(null);
|
||||
const [messages, setMessages] = useState<MessageDTO[]>([]);
|
||||
const [name, setName] = useState("");
|
||||
const [draft, setDraft] = useState("");
|
||||
const [ready, setReady] = useState(false);
|
||||
const [sending, setSending] = useState(false);
|
||||
const bottomRef = useRef<HTMLDivElement>(null);
|
||||
|
||||
useEffect(() => {
|
||||
const stored = localStorage.getItem(STORAGE_KEY) ?? undefined;
|
||||
fetch("/api/widget/session", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ siteKey, token: stored }),
|
||||
})
|
||||
.then((res) => res.json())
|
||||
.then((data) => {
|
||||
localStorage.setItem(STORAGE_KEY, data.token);
|
||||
setToken(data.token);
|
||||
setMessages(data.messages ?? []);
|
||||
setReady(true);
|
||||
});
|
||||
}, [siteKey]);
|
||||
|
||||
useTicketEvents(token ? `/api/portal/events?token=${encodeURIComponent(token)}` : "", (event) => {
|
||||
if (event.type !== "message.created") return;
|
||||
setMessages((prev) => (prev.some((m) => m.id === event.message.id) ? prev : [...prev, event.message]));
|
||||
if (event.message.authorType === "agent") {
|
||||
window.parent.postMessage({ type: "top-tickets:new-message" }, "*");
|
||||
}
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
bottomRef.current?.scrollIntoView({ behavior: "smooth" });
|
||||
}, [messages.length]);
|
||||
|
||||
async function sendMessage() {
|
||||
if (!draft.trim() || !token) return;
|
||||
setSending(true);
|
||||
const res = await fetch("/api/widget/messages", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ siteKey, token, body: draft, name: name.trim() || undefined }),
|
||||
});
|
||||
setSending(false);
|
||||
if (res.ok) {
|
||||
setDraft("");
|
||||
}
|
||||
}
|
||||
|
||||
if (!ready) {
|
||||
return <div style={{ height: "100%" }} />;
|
||||
}
|
||||
|
||||
const isFirstMessage = messages.length === 0;
|
||||
|
||||
return (
|
||||
<div className="flex h-full flex-col p-3">
|
||||
{isFirstMessage && (
|
||||
<label className="mb-2 block text-xs">
|
||||
<span className="mb-1 block text-text-muted">Ваше имя (необязательно)</span>
|
||||
<input
|
||||
value={name}
|
||||
onChange={(e) => setName(e.target.value)}
|
||||
placeholder="Как к вам обращаться?"
|
||||
className="w-full rounded-md border border-border bg-surface px-2 py-1.5 text-sm outline-none focus:border-accent"
|
||||
/>
|
||||
</label>
|
||||
)}
|
||||
|
||||
<div className="flex-1 overflow-y-auto">
|
||||
<AnimatePresence initial={false}>
|
||||
{messages.map((message) => (
|
||||
<MessageBubble key={message.id} message={message} />
|
||||
))}
|
||||
</AnimatePresence>
|
||||
{isFirstMessage && (
|
||||
<p className="mt-6 text-center text-sm text-text-muted">Напишите нам — обычно отвечаем быстро.</p>
|
||||
)}
|
||||
<div ref={bottomRef} />
|
||||
</div>
|
||||
|
||||
<div className="mt-2 flex gap-2">
|
||||
<textarea
|
||||
rows={1}
|
||||
value={draft}
|
||||
onChange={(e) => setDraft(e.target.value)}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === "Enter" && !e.shiftKey) {
|
||||
e.preventDefault();
|
||||
sendMessage();
|
||||
}
|
||||
}}
|
||||
placeholder="Напишите сообщение…"
|
||||
className="flex-1 resize-none rounded-md border border-border bg-surface px-3 py-2 text-sm outline-none focus:border-accent"
|
||||
/>
|
||||
<button onClick={sendMessage} disabled={sending || !draft.trim()} className="btn btn-primary">
|
||||
<Send size={15} />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function MessageBubble({ message }: { message: MessageDTO }) {
|
||||
const isMine = message.authorType === "customer";
|
||||
|
||||
if (message.authorType === "system") {
|
||||
return <p className="my-2 text-center text-xs text-text-faint">{message.body}</p>;
|
||||
}
|
||||
|
||||
return (
|
||||
<motion.div
|
||||
layout
|
||||
initial={{ opacity: 0, y: 8 }}
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
transition={{ duration: 0.18 }}
|
||||
className={`mb-3 flex ${isMine ? "justify-end" : "justify-start"}`}
|
||||
>
|
||||
<div className={`max-w-[85%] rounded-lg px-3 py-2 text-sm ${isMine ? "bg-accent text-white" : "bg-surface-hover"}`}>
|
||||
<p className="mb-1 whitespace-pre-wrap">{message.body}</p>
|
||||
<p className={`text-[11px] ${isMine ? "text-white/70" : "text-text-faint"}`}>
|
||||
{formatRelativeTime(message.createdAt)}
|
||||
</p>
|
||||
</div>
|
||||
</motion.div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
export default function WidgetLayout({ children }: { children: React.ReactNode }) {
|
||||
return <div style={{ height: "100vh", width: "100%" }}>{children}</div>;
|
||||
}
|
||||
Reference in new issue
Block a user