Deferred backlog: attachments, canned responses, tags, search, notifications, password change

Attachments: file storage on the same data volume, serving route with
dual auth (session or portal/widget token, internal-note attachments
never token-servable), inbound ingestion from email (mailparser) and
Telegram (photo/document handlers), outbound delivery via SMTP
attachments and Telegram sendDocument/sendPhoto, upload UI (paperclip +
pending-file chip) on all three reply surfaces. Extracted
lib/tickets/delivery.ts so the text-only and attachment-upload admin
routes share one channel-delivery code path instead of duplicating it.

Canned responses: CRUD + a popover picker in the reply box that inserts
a saved template into the draft.

Tags: fixed 6-color palette reusing existing soft-badge tokens, a picker
on the ticket page, colored chips + a filter row on the dashboard.

Search: LIKE-based (not FTS5 — simpler and sufficient at this volume)
across ticket subject, customer name, and message bodies; a debounced
search box on the dashboard.

Desktop notifications: permission toggle + a background subscriber that
fires for new tickets and customer messages while the tab is hidden,
clicking one navigates to the ticket.

Password change: new account settings page, verifies the current
password before updating.

Nav: gear-menu settings list now includes Шаблоны ответов/Теги/Аккаунт.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01QcXH24ky6zjk2UyK5oZUPH
This commit is contained in:
ogrechkoandClaude Sonnet 5 committed 2026-07-26 17:32:12 +00:00
1 parent 7947633709
commit 89b9c5eaac
40 files changed
+2758 -113

No files matched your search

+90 -6
View File
@@ -1,14 +1,15 @@
"use client";
import { useMemo, useState } from "react";
import { useEffect, useMemo, useState } from "react";
import Link from "next/link";
import { AnimatePresence, motion } from "framer-motion";
import { Send, Globe, UserRound, Mail, MessageSquare, Plus, Inbox } from "lucide-react";
import { Send, Globe, UserRound, Mail, MessageSquare, Plus, Inbox, Search, X } from "lucide-react";
import { useTicketEvents } from "@/lib/events/use-ticket-events";
import { formatRelativeTime } from "@/lib/format";
import type { TicketDTO, TicketStatus } from "@/lib/tickets/types";
import { NewTicketModal } from "./new-ticket-modal";
import { Avatar } from "@/components/avatar";
import { TAG_COLOR_CLASSES } from "@/lib/tags/colors";
const COLUMNS: { status: TicketStatus; label: string; empty: string }[] = [
{ status: "new", label: "Новые", empty: "Новых заявок нет" },
@@ -44,6 +45,10 @@ const PRIORITY_COLOR: Record<TicketDTO["priority"], string> = {
export function TicketBoard({ initialTickets }: { initialTickets: TicketDTO[] }) {
const [tickets, setTickets] = useState<TicketDTO[]>(initialTickets);
const [modalOpen, setModalOpen] = useState(false);
const [activeTagId, setActiveTagId] = useState<string | null>(null);
const [query, setQuery] = useState("");
const [searchResults, setSearchResults] = useState<TicketDTO[] | null>(null);
const [searching, setSearching] = useState(false);
useTicketEvents("/api/events", (event) => {
if (event.type === "ticket.created" || event.type === "ticket.updated") {
@@ -54,20 +59,50 @@ export function TicketBoard({ initialTickets }: { initialTickets: TicketDTO[] })
}
});
// Search hits the server (message bodies aren't loaded client-side),
// debounced. An empty query needs no fetch — baseTickets below just falls
// back to the live SSE-backed list, so there's nothing to reset here.
useEffect(() => {
if (!query.trim()) return;
const handle = setTimeout(() => {
setSearching(true);
fetch(`/api/tickets?q=${encodeURIComponent(query)}`)
.then((res) => res.json())
.then((data) => setSearchResults(data.tickets ?? []))
.finally(() => setSearching(false));
}, 300);
return () => clearTimeout(handle);
}, [query]);
const baseTickets = query.trim() ? (searchResults ?? tickets) : tickets;
const availableTags = useMemo(() => {
const map = new Map<string, TicketDTO["tags"][number]>();
for (const ticket of baseTickets) {
for (const tag of ticket.tags) map.set(tag.id, tag);
}
return [...map.values()].sort((a, b) => a.name.localeCompare(b.name));
}, [baseTickets]);
const filteredTickets = useMemo(() => {
if (!activeTagId) return baseTickets;
return baseTickets.filter((t) => t.tags.some((tag) => tag.id === activeTagId));
}, [baseTickets, activeTagId]);
const byStatus = useMemo(() => {
const grouped: Record<TicketStatus, TicketDTO[]> = { new: [], open: [], pending: [], closed: [] };
for (const ticket of tickets) {
for (const ticket of filteredTickets) {
grouped[ticket.status].push(ticket);
}
for (const list of Object.values(grouped)) {
list.sort((a, b) => b.lastMessageAt - a.lastMessageAt);
}
return grouped;
}, [tickets]);
}, [filteredTickets]);
return (
<div>
<div className="mb-5 flex items-center justify-between">
<div className="mb-4 flex flex-wrap items-center justify-between gap-3">
<h1 className="font-display text-xl font-bold tracking-tight">Заявки</h1>
<button className="btn btn-primary" onClick={() => setModalOpen(true)}>
<Plus size={16} />
@@ -75,6 +110,46 @@ export function TicketBoard({ initialTickets }: { initialTickets: TicketDTO[] })
</button>
</div>
<div className="relative mb-4 max-w-sm">
<Search size={14} className="pointer-events-none absolute left-3 top-1/2 -translate-y-1/2 text-text-faint" />
<input
value={query}
onChange={(e) => setQuery(e.target.value)}
placeholder="Поиск по заявкам…"
className="w-full rounded-md border border-border bg-surface py-2 pl-9 pr-8 text-sm outline-none focus:border-accent"
/>
{query && (
<button
onClick={() => setQuery("")}
className="absolute right-2.5 top-1/2 -translate-y-1/2 text-text-faint hover:text-text"
>
<X size={14} />
</button>
)}
</div>
{query.trim() && searchResults && (
<p className="mb-4 text-xs text-text-faint">
{searching ? "Ищем…" : `Найдено: ${searchResults.length}`}
</p>
)}
{availableTags.length > 0 && (
<div className="mb-4 flex flex-wrap gap-1.5">
{availableTags.map((tag) => (
<button
key={tag.id}
onClick={() => setActiveTagId((prev) => (prev === tag.id ? null : tag.id))}
className={`rounded-full px-2.5 py-1 text-xs font-medium transition-opacity ${TAG_COLOR_CLASSES[tag.color]} ${
activeTagId && activeTagId !== tag.id ? "opacity-40" : ""
}`}
>
{tag.name}
</button>
))}
</div>
)}
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-4">
{COLUMNS.map((col) => (
<div key={col.status} className="min-w-0">
@@ -122,7 +197,16 @@ function TicketCard({ ticket }: { ticket: TicketDTO }) {
className="card block p-3 shadow-sm transition-shadow hover:shadow-md"
style={{ borderLeft: `3px solid ${PRIORITY_COLOR[ticket.priority]}` }}
>
<p className="mb-2 line-clamp-2 text-sm font-medium">{ticket.subject}</p>
<p className="mb-1 line-clamp-2 text-sm font-medium">{ticket.subject}</p>
{ticket.tags.length > 0 && (
<div className="mb-2 flex flex-wrap gap-1">
{ticket.tags.map((tag) => (
<span key={tag.id} className={`rounded-full px-1.5 py-0.5 text-[10px] font-medium ${TAG_COLOR_CLASSES[tag.color]}`}>
{tag.name}
</span>
))}
</div>
)}
<div className="flex items-center justify-between">
<span className="flex min-w-0 items-center gap-1.5">
<Avatar name={ticket.customerName} size={20} />
+38
View File
@@ -0,0 +1,38 @@
"use client";
import { useRouter } from "next/navigation";
import { useTicketEvents } from "@/lib/events/use-ticket-events";
/**
* No visible UI — just a permanently-mounted subscriber (in the admin
* layout, so it's alive regardless of which admin page is open) that fires
* a desktop notification for events that mean "a customer needs a
* response," while the tab is in the background. Agent-authored messages
* are deliberately skipped — that's the agent's own action, not a signal.
*/
export function DesktopNotifications() {
const router = useRouter();
useTicketEvents("/api/events", (event) => {
if (typeof window === "undefined" || !("Notification" in window)) return;
if (Notification.permission !== "granted" || !document.hidden) return;
if (event.type === "ticket.created") {
const notification = new Notification("Новая заявка", { body: event.ticket.subject });
notification.onclick = () => {
window.focus();
router.push(`/tickets/${event.ticket.id}`);
};
} else if (event.type === "message.created" && event.message.authorType === "customer") {
const notification = new Notification(`Сообщение от ${event.message.authorName}`, {
body: event.message.body.slice(0, 120),
});
notification.onclick = () => {
window.focus();
router.push(`/tickets/${event.ticketId}`);
};
}
});
return null;
}
+4
View File
@@ -5,6 +5,8 @@ import { LogoutButton } from "./logout-button";
import { NavLinks } from "./nav-links";
import { ThemeToggle } from "./theme-toggle";
import { SettingsMenu } from "./settings-menu";
import { NotificationToggle } from "./notification-toggle";
import { DesktopNotifications } from "./desktop-notifications";
export default async function AdminLayout({ children }: { children: React.ReactNode }) {
const session = await getCurrentSession();
@@ -24,6 +26,7 @@ export default async function AdminLayout({ children }: { children: React.ReactN
</div>
<div className="ml-auto flex items-center gap-2 sm:gap-3">
<span className="hidden text-sm text-text-muted sm:inline">{session.user.name}</span>
<NotificationToggle />
<SettingsMenu />
<ThemeToggle />
<LogoutButton />
@@ -34,6 +37,7 @@ export default async function AdminLayout({ children }: { children: React.ReactN
</div>
</header>
<main className="mx-auto w-full max-w-7xl flex-1 px-4 py-6 sm:px-6">{children}</main>
<DesktopNotifications />
</div>
);
}
+30
View File
@@ -0,0 +1,30 @@
"use client";
import { useState } from "react";
import { Bell, BellOff } from "lucide-react";
function initialPermission(): NotificationPermission | "unsupported" {
if (typeof window === "undefined" || !("Notification" in window)) return "unsupported";
return Notification.permission;
}
export function NotificationToggle() {
const [permission, setPermission] = useState(initialPermission);
if (permission === "unsupported") return null;
async function requestPermission() {
if (permission === "granted") return; // no API to revoke it programmatically — only the browser's own site settings can
setPermission(await Notification.requestPermission());
}
return (
<button
onClick={requestPermission}
className="btn btn-ghost"
title={permission === "granted" ? "Уведомления включены" : "Включить уведомления о новых заявках"}
>
{permission === "granted" ? <Bell size={15} /> : <BellOff size={15} />}
</button>
);
}
+5 -2
View File
@@ -3,12 +3,15 @@
import { useEffect, useRef, useState } from "react";
import Link from "next/link";
import { usePathname } from "next/navigation";
import { Settings, Send, Mail, Code2 } from "lucide-react";
import { Settings, Send, Mail, Code2, MessageSquareText, Tags, UserCog } from "lucide-react";
const items = [
{ href: "/settings/telegram", label: "Telegram", icon: Send },
{ href: "/settings/email", label: "Почта", icon: Mail },
{ href: "/settings/widget", label: "Виджет", icon: Code2 },
{ href: "/settings/canned", label: "Шаблоны ответов", icon: MessageSquareText },
{ href: "/settings/tags", label: "Теги", icon: Tags },
{ href: "/settings/account", label: "Аккаунт", icon: UserCog },
];
export function SettingsMenu() {
@@ -39,7 +42,7 @@ export function SettingsMenu() {
<Settings size={15} />
</button>
{open && (
<div className="card absolute right-0 top-full z-20 mt-2 w-44 overflow-hidden p-1">
<div className="card absolute right-0 top-full z-20 mt-2 w-52 overflow-hidden p-1">
{items.map(({ href, label, icon: Icon }) => {
const active = pathname.startsWith(href);
return (
@@ -0,0 +1,90 @@
"use client";
import { useState } from "react";
import { KeyRound } from "lucide-react";
export function ChangePasswordForm() {
const [currentPassword, setCurrentPassword] = useState("");
const [newPassword, setNewPassword] = useState("");
const [confirmPassword, setConfirmPassword] = useState("");
const [error, setError] = useState<string | null>(null);
const [success, setSuccess] = useState(false);
const [loading, setLoading] = useState(false);
async function handleSubmit(e: React.FormEvent) {
e.preventDefault();
setError(null);
setSuccess(false);
if (newPassword !== confirmPassword) {
setError("Пароли не совпадают");
return;
}
setLoading(true);
const res = await fetch("/api/auth/change-password", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ currentPassword, newPassword }),
});
setLoading(false);
if (!res.ok) {
const data = await res.json().catch(() => null);
setError(data?.error ?? "Не удалось сменить пароль");
return;
}
setSuccess(true);
setCurrentPassword("");
setNewPassword("");
setConfirmPassword("");
}
return (
<form onSubmit={handleSubmit} className="card p-4">
<label className="mb-3 block text-sm">
<span className="mb-1 block font-medium text-text-muted">Текущий пароль</span>
<input
required
type="password"
value={currentPassword}
onChange={(e) => setCurrentPassword(e.target.value)}
className="w-full rounded-md border border-border bg-surface px-3 py-2 text-sm outline-none focus:border-accent"
/>
</label>
<label className="mb-3 block text-sm">
<span className="mb-1 block font-medium text-text-muted">Новый пароль</span>
<input
required
type="password"
minLength={8}
value={newPassword}
onChange={(e) => setNewPassword(e.target.value)}
className="w-full rounded-md border border-border bg-surface px-3 py-2 text-sm outline-none focus:border-accent"
/>
</label>
<label className="mb-4 block text-sm">
<span className="mb-1 block font-medium text-text-muted">Повторите новый пароль</span>
<input
required
type="password"
minLength={8}
value={confirmPassword}
onChange={(e) => setConfirmPassword(e.target.value)}
className="w-full rounded-md border border-border bg-surface px-3 py-2 text-sm outline-none focus:border-accent"
/>
</label>
{error && <p className="mb-3 rounded-md bg-danger-soft px-3 py-2 text-sm text-danger-soft-text">{error}</p>}
{success && (
<p className="mb-3 rounded-md bg-success-soft px-3 py-2 text-sm text-success-soft-text">Пароль изменён</p>
)}
<button type="submit" disabled={loading} className="btn btn-primary w-full justify-center">
<KeyRound size={15} />
Сменить пароль
</button>
</form>
);
}
+14
View File
@@ -0,0 +1,14 @@
import { getCurrentSession } from "@/lib/auth/session";
import { ChangePasswordForm } from "./change-password-form";
export default async function AccountSettingsPage() {
const session = await getCurrentSession();
return (
<div className="max-w-sm">
<h1 className="mb-1 font-display text-xl font-bold tracking-tight">Аккаунт</h1>
<p className="mb-6 text-sm text-text-muted">{session?.user.email}</p>
<ChangePasswordForm />
</div>
);
}
@@ -0,0 +1,161 @@
"use client";
import { useState } from "react";
import { Plus, Pencil, Trash2, X, Check } from "lucide-react";
interface CannedResponse {
id: string;
title: string;
body: string;
}
export function CannedResponsesManager({ initialResponses }: { initialResponses: CannedResponse[] }) {
const [responses, setResponses] = useState(initialResponses);
const [title, setTitle] = useState("");
const [body, setBody] = useState("");
const [loading, setLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
const [editingId, setEditingId] = useState<string | null>(null);
async function handleCreate(e: React.FormEvent) {
e.preventDefault();
setLoading(true);
setError(null);
const res = await fetch("/api/canned-responses", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ title, body }),
});
setLoading(false);
if (!res.ok) {
const data = await res.json().catch(() => null);
setError(data?.error ?? "Не удалось создать шаблон");
return;
}
const { response } = await res.json();
setResponses((prev) => [...prev, response].sort((a, b) => a.title.localeCompare(b.title)));
setTitle("");
setBody("");
}
async function handleDelete(id: string) {
await fetch(`/api/canned-responses/${id}`, { method: "DELETE" });
setResponses((prev) => prev.filter((r) => r.id !== id));
}
async function handleUpdate(id: string, newTitle: string, newBody: string) {
const res = await fetch(`/api/canned-responses/${id}`, {
method: "PATCH",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ title: newTitle, body: newBody }),
});
if (res.ok) {
const { response } = await res.json();
setResponses((prev) => prev.map((r) => (r.id === id ? response : r)));
setEditingId(null);
}
}
return (
<div className="flex flex-col gap-4">
<form onSubmit={handleCreate} className="card flex flex-col gap-3 p-4">
<label className="text-sm">
<span className="mb-1 block font-medium text-text-muted">Название</span>
<input
required
value={title}
onChange={(e) => setTitle(e.target.value)}
placeholder="Например: Просим больше информации"
className="w-full rounded-md border border-border bg-surface px-3 py-2 text-sm outline-none focus:border-accent"
/>
</label>
<label className="text-sm">
<span className="mb-1 block font-medium text-text-muted">Текст</span>
<textarea
required
rows={3}
value={body}
onChange={(e) => setBody(e.target.value)}
className="w-full resize-none 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 self-start">
<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>}
{responses.length === 0 && <p className="text-sm text-text-muted">Шаблонов пока нет.</p>}
<div className="flex flex-col gap-3">
{responses.map((response) =>
editingId === response.id ? (
<EditForm
key={response.id}
response={response}
onCancel={() => setEditingId(null)}
onSave={(t, b) => handleUpdate(response.id, t, b)}
/>
) : (
<div key={response.id} className="card p-4">
<div className="mb-1 flex items-center justify-between gap-2">
<p className="text-sm font-medium">{response.title}</p>
<div className="flex shrink-0 gap-1">
<button onClick={() => setEditingId(response.id)} className="btn btn-ghost px-2 py-1">
<Pencil size={13} />
</button>
<button onClick={() => handleDelete(response.id)} className="btn btn-ghost px-2 py-1">
<Trash2 size={13} />
</button>
</div>
</div>
<p className="whitespace-pre-wrap text-sm text-text-muted">{response.body}</p>
</div>
),
)}
</div>
</div>
);
}
function EditForm({
response,
onCancel,
onSave,
}: {
response: CannedResponse;
onCancel: () => void;
onSave: (title: string, body: string) => void;
}) {
const [title, setTitle] = useState(response.title);
const [body, setBody] = useState(response.body);
return (
<div className="card p-4">
<input
value={title}
onChange={(e) => setTitle(e.target.value)}
className="mb-2 w-full rounded-md border border-border bg-surface px-3 py-2 text-sm outline-none focus:border-accent"
/>
<textarea
rows={3}
value={body}
onChange={(e) => setBody(e.target.value)}
className="mb-2 w-full resize-none rounded-md border border-border bg-surface px-3 py-2 text-sm outline-none focus:border-accent"
/>
<div className="flex gap-2">
<button onClick={() => onSave(title, body)} className="btn btn-primary px-2 py-1">
<Check size={13} />
</button>
<button onClick={onCancel} className="btn btn-ghost px-2 py-1">
<X size={13} />
</button>
</div>
</div>
);
}
+15
View File
@@ -0,0 +1,15 @@
import { listCannedResponses } from "@/lib/tickets/service";
import { CannedResponsesManager } from "./canned-responses-manager";
export default async function CannedResponsesPage() {
const responses = await listCannedResponses();
return (
<div className="max-w-2xl">
<h1 className="mb-1 font-display text-xl font-bold tracking-tight">Шаблоны ответов</h1>
<p className="mb-6 text-sm text-text-muted">
Готовые тексты, которые можно вставить в ответ клиенту одним кликом.
</p>
<CannedResponsesManager initialResponses={responses} />
</div>
);
}
+13
View File
@@ -0,0 +1,13 @@
import { listTags } from "@/lib/tickets/service";
import { TagsManager } from "./tags-manager";
export default async function TagsSettingsPage() {
const tags = await listTags();
return (
<div className="max-w-lg">
<h1 className="mb-1 font-display text-xl font-bold tracking-tight">Теги</h1>
<p className="mb-6 text-sm text-text-muted">Метки для категоризации заявок.</p>
<TagsManager initialTags={tags} />
</div>
);
}
@@ -0,0 +1,95 @@
"use client";
import { useState } from "react";
import { Plus, Trash2 } from "lucide-react";
import { TAG_COLOR_CLASSES, TAG_COLORS, TAG_COLOR_LABELS } from "@/lib/tags/colors";
import type { TagDTO, TagColor } from "@/lib/tickets/types";
export function TagsManager({ initialTags }: { initialTags: TagDTO[] }) {
const [tags, setTags] = useState(initialTags);
const [name, setName] = useState("");
const [color, setColor] = useState<TagColor>("accent");
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/tags", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ name, color }),
});
setLoading(false);
if (!res.ok) {
const data = await res.json().catch(() => null);
setError(data?.error ?? "Не удалось создать тег");
return;
}
const { tag } = await res.json();
setTags((prev) => [...prev, tag]);
setName("");
}
async function handleDelete(id: string) {
await fetch(`/api/tags/${id}`, { method: "DELETE" });
setTags((prev) => prev.filter((t) => t.id !== id));
}
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="Срочно"
className="w-full rounded-md border border-border bg-surface px-3 py-2 text-sm outline-none focus:border-accent"
/>
</label>
<label className="text-sm">
<span className="mb-1 block font-medium text-text-muted">Цвет</span>
<select
value={color}
onChange={(e) => setColor(e.target.value as TagColor)}
className="rounded-md border border-border bg-surface px-3 py-2 text-sm outline-none focus:border-accent"
>
{TAG_COLORS.map((c) => (
<option key={c} value={c}>
{TAG_COLOR_LABELS[c]}
</option>
))}
</select>
</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>}
{tags.length === 0 && <p className="text-sm text-text-muted">Тегов пока нет.</p>}
<div className="flex flex-wrap gap-2">
{tags.map((tag) => (
<span
key={tag.id}
className={`flex items-center gap-1.5 rounded-full px-3 py-1 text-sm font-medium ${TAG_COLOR_CLASSES[tag.color]}`}
>
{tag.name}
<button onClick={() => handleDelete(tag.id)} className="opacity-60 hover:opacity-100">
<Trash2 size={12} />
</button>
</span>
))}
</div>
</div>
);
}
@@ -0,0 +1,87 @@
"use client";
import { useEffect, useRef, useState } from "react";
import { Tags as TagsIcon, Check } from "lucide-react";
import { TAG_COLOR_CLASSES } from "@/lib/tags/colors";
import type { TagDTO } from "@/lib/tickets/types";
export function TagPicker({
ticketId,
selectedTags,
onChange,
}: {
ticketId: string;
selectedTags: TagDTO[];
onChange: (tags: TagDTO[]) => void;
}) {
const [allTags, setAllTags] = useState<TagDTO[]>([]);
const [open, setOpen] = useState(false);
const rootRef = useRef<HTMLDivElement>(null);
useEffect(() => {
fetch("/api/tags")
.then((res) => res.json())
.then((data) => setAllTags(data.tags ?? []));
}, []);
useEffect(() => {
function onClickOutside(e: MouseEvent) {
if (rootRef.current && !rootRef.current.contains(e.target as Node)) setOpen(false);
}
document.addEventListener("mousedown", onClickOutside);
return () => document.removeEventListener("mousedown", onClickOutside);
}, []);
async function toggle(tagId: string) {
const selectedIds = selectedTags.map((t) => t.id);
const nextIds = selectedIds.includes(tagId)
? selectedIds.filter((id) => id !== tagId)
: [...selectedIds, tagId];
const res = await fetch(`/api/tickets/${ticketId}/tags`, {
method: "PUT",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ tagIds: nextIds }),
});
if (res.ok) {
const { tags } = await res.json();
onChange(tags);
}
}
return (
<div ref={rootRef} className="relative flex flex-wrap items-center gap-1.5">
{selectedTags.map((tag) => (
<span key={tag.id} className={`rounded-full px-2 py-0.5 text-xs font-medium ${TAG_COLOR_CLASSES[tag.color]}`}>
{tag.name}
</span>
))}
<button type="button" onClick={() => setOpen((v) => !v)} className="btn btn-ghost px-1.5 py-1" title="Теги">
<TagsIcon size={13} />
</button>
{open && (
<div className="card absolute left-0 top-full z-20 mt-2 w-56 p-1">
{allTags.length === 0 && (
<p className="p-2 text-xs text-text-faint">Тегов пока нет — добавьте в настройках</p>
)}
{allTags.map((tag) => {
const active = selectedTags.some((t) => t.id === tag.id);
return (
<button
key={tag.id}
type="button"
onClick={() => toggle(tag.id)}
className="flex w-full items-center justify-between rounded-md px-2 py-1.5 text-left hover:bg-surface-hover"
>
<span className={`rounded-full px-2 py-0.5 text-xs font-medium ${TAG_COLOR_CLASSES[tag.color]}`}>
{tag.name}
</span>
{active && <Check size={13} className="text-accent" />}
</button>
);
})}
</div>
)}
</div>
);
}
+113 -10
View File
@@ -3,10 +3,12 @@
import { useEffect, useRef, useState } from "react";
import Link from "next/link";
import { AnimatePresence, motion } from "framer-motion";
import { ArrowLeft, Send, StickyNote } from "lucide-react";
import { ArrowLeft, Send, StickyNote, Paperclip, X, MessageSquareText } from "lucide-react";
import { useTicketEvents } from "@/lib/events/use-ticket-events";
import { formatRelativeTime } from "@/lib/format";
import { Avatar } from "@/components/avatar";
import { AttachmentChip } from "@/components/attachment-chip";
import { TagPicker } from "./tag-picker";
import type { TicketDTO, MessageDTO, TicketStatus } from "@/lib/tickets/types";
const STATUS_LABEL: Record<TicketStatus, string> = {
@@ -29,8 +31,32 @@ export function TicketThread({
const [messages, setMessages] = useState(initialMessages);
const [draft, setDraft] = useState("");
const [visibility, setVisibility] = useState<"public" | "internal">("public");
const [pendingFile, setPendingFile] = useState<File | null>(null);
const [sending, setSending] = useState(false);
const [cannedResponses, setCannedResponses] = useState<{ id: string; title: string; body: string }[]>([]);
const [cannedOpen, setCannedOpen] = useState(false);
const bottomRef = useRef<HTMLDivElement>(null);
const fileInputRef = useRef<HTMLInputElement>(null);
const cannedRef = useRef<HTMLDivElement>(null);
useEffect(() => {
fetch("/api/canned-responses")
.then((res) => res.json())
.then((data) => setCannedResponses(data.responses ?? []));
}, []);
useEffect(() => {
function onClickOutside(e: MouseEvent) {
if (cannedRef.current && !cannedRef.current.contains(e.target as Node)) setCannedOpen(false);
}
document.addEventListener("mousedown", onClickOutside);
return () => document.removeEventListener("mousedown", onClickOutside);
}, []);
function insertCanned(body: string) {
setDraft((prev) => (prev.trim() ? `${prev}\n${body}` : body));
setCannedOpen(false);
}
useTicketEvents("/api/events", (event) => {
if (event.type === "ticket.updated" && event.ticket.id === ticket.id) {
@@ -46,15 +72,30 @@ export function TicketThread({
}, [messages.length]);
async function sendReply() {
if (!draft.trim()) return;
if (!draft.trim() && !pendingFile) return;
setSending(true);
const res = await fetch(`/api/tickets/${ticket.id}/messages`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ body: draft, visibility }),
});
let res: Response;
if (pendingFile) {
const formData = new FormData();
formData.append("file", pendingFile);
formData.append("caption", draft);
formData.append("visibility", visibility);
res = await fetch(`/api/tickets/${ticket.id}/attachments`, { method: "POST", body: formData });
} else {
res = await fetch(`/api/tickets/${ticket.id}/messages`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ body: draft, visibility }),
});
}
setSending(false);
if (res.ok) setDraft("");
if (res.ok) {
setDraft("");
setPendingFile(null);
if (fileInputRef.current) fileInputRef.current.value = "";
}
}
async function updateStatus(status: TicketStatus) {
@@ -90,10 +131,15 @@ export function TicketThread({
Дашборд
</Link>
<h1 className="truncate font-display text-lg font-bold">{ticket.subject}</h1>
<span className="flex items-center gap-1.5">
<span className="mb-2 flex items-center gap-1.5">
<Avatar name={ticket.customerName} size={18} />
<span className="text-sm text-text-muted">{ticket.customerName}</span>
</span>
<TagPicker
ticketId={ticket.id}
selectedTags={ticket.tags}
onChange={(tags) => setTicket((t) => ({ ...t, tags }))}
/>
</div>
<div className="flex w-full shrink-0 items-center gap-2 sm:w-auto">
@@ -153,7 +199,22 @@ export function TicketThread({
Заметка для команды
</button>
</div>
{pendingFile && (
<div className="mb-1.5 flex items-center gap-2 rounded-md border border-border bg-surface-hover px-2.5 py-1.5 text-xs">
<Paperclip size={12} />
<span className="flex-1 truncate">{pendingFile.name}</span>
<button type="button" onClick={() => setPendingFile(null)} className="text-text-muted hover:text-text">
<X size={13} />
</button>
</div>
)}
<div className="flex gap-2">
<input
ref={fileInputRef}
type="file"
className="hidden"
onChange={(e) => setPendingFile(e.target.files?.[0] ?? null)}
/>
<textarea
value={draft}
onChange={(e) => setDraft(e.target.value)}
@@ -171,9 +232,45 @@ export function TicketThread({
: "border-border bg-surface focus:border-accent"
}`}
/>
<div ref={cannedRef} className="relative self-end">
<button
type="button"
onClick={() => setCannedOpen((v) => !v)}
className="btn btn-ghost"
title="Шаблоны ответов"
>
<MessageSquareText size={15} />
</button>
{cannedOpen && (
<div className="card absolute bottom-full right-0 z-20 mb-2 max-h-64 w-72 overflow-y-auto p-1">
{cannedResponses.length === 0 && (
<p className="p-2 text-xs text-text-faint">Шаблонов пока нет</p>
)}
{cannedResponses.map((c) => (
<button
key={c.id}
type="button"
onClick={() => insertCanned(c.body)}
className="block w-full rounded-md px-3 py-2 text-left text-sm hover:bg-surface-hover"
>
<p className="font-medium">{c.title}</p>
<p className="truncate text-xs text-text-faint">{c.body}</p>
</button>
))}
</div>
)}
</div>
<button
type="button"
onClick={() => fileInputRef.current?.click()}
className="btn btn-ghost self-end"
title="Прикрепить файл"
>
<Paperclip size={15} />
</button>
<button
onClick={sendReply}
disabled={sending || !draft.trim()}
disabled={sending || (!draft.trim() && !pendingFile)}
className={visibility === "internal" ? "btn self-end bg-warning text-white hover:brightness-95" : "btn btn-primary self-end"}
>
{visibility === "internal" ? <StickyNote size={15} /> : <Send size={15} />}
@@ -208,6 +305,9 @@ function MessageBubble({ message }: { message: MessageDTO }) {
Внутренняя заметка
</p>
<p className="mb-1 whitespace-pre-wrap text-sm">{message.body}</p>
{message.attachments.map((a) => (
<AttachmentChip key={a.id} attachment={a} />
))}
<p className="text-[11px] text-warning-soft-text/80">
{message.authorName} · {formatRelativeTime(message.createdAt)}
</p>
@@ -225,6 +325,9 @@ function MessageBubble({ message }: { message: MessageDTO }) {
>
<div className={`max-w-[75%] rounded-lg px-3 py-2 text-sm ${isAgent ? "bg-accent text-white" : "bg-surface-hover"}`}>
<p className="mb-1 whitespace-pre-wrap">{message.body}</p>
{message.attachments.map((a) => (
<AttachmentChip key={a.id} attachment={a} />
))}
<p className={`text-[11px] ${isAgent ? "text-white/70" : "text-text-faint"}`}>
{message.authorName} · {formatRelativeTime(message.createdAt)}
</p>
@@ -3,9 +3,10 @@
import { useEffect, useRef, useState } from "react";
import Link from "next/link";
import { AnimatePresence, motion } from "framer-motion";
import { ArrowLeft, Send } from "lucide-react";
import { ArrowLeft, Send, Paperclip, X } from "lucide-react";
import { useTicketEvents } from "@/lib/events/use-ticket-events";
import { formatRelativeTime } from "@/lib/format";
import { AttachmentChip } from "@/components/attachment-chip";
import type { TicketDTO, MessageDTO } from "@/lib/tickets/types";
export function PortalThread({
@@ -21,8 +22,10 @@ export function PortalThread({
}) {
const [messages, setMessages] = useState(initialMessages);
const [draft, setDraft] = useState("");
const [pendingFile, setPendingFile] = useState<File | null>(null);
const [sending, setSending] = useState(false);
const bottomRef = useRef<HTMLDivElement>(null);
const fileInputRef = useRef<HTMLInputElement>(null);
useTicketEvents(`/api/portal/events?token=${encodeURIComponent(token)}`, (event) => {
if (event.type === "message.created" && event.ticketId === ticket.id) {
@@ -35,15 +38,30 @@ export function PortalThread({
}, [messages.length]);
async function sendReply() {
if (!draft.trim()) return;
if (!draft.trim() && !pendingFile) return;
setSending(true);
const res = await fetch(`/api/portal/tickets/${ticket.id}/messages`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ token, body: draft }),
});
let res: Response;
if (pendingFile) {
const formData = new FormData();
formData.append("token", token);
formData.append("file", pendingFile);
formData.append("caption", draft);
res = await fetch(`/api/portal/tickets/${ticket.id}/attachments`, { method: "POST", body: formData });
} else {
res = await fetch(`/api/portal/tickets/${ticket.id}/messages`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ token, body: draft }),
});
}
setSending(false);
if (res.ok) setDraft("");
if (res.ok) {
setDraft("");
setPendingFile(null);
if (fileInputRef.current) fileInputRef.current.value = "";
}
}
return (
@@ -57,13 +75,29 @@ export function PortalThread({
<div className="card flex-1 overflow-y-auto p-4">
<AnimatePresence initial={false}>
{messages.map((message) => (
<MessageBubble key={message.id} message={message} isMine={message.authorType === "customer"} />
<MessageBubble key={message.id} message={message} isMine={message.authorType === "customer"} token={token} />
))}
</AnimatePresence>
<div ref={bottomRef} />
</div>
{pendingFile && (
<div className="mt-3 flex items-center gap-2 rounded-md border border-border bg-surface-hover px-2.5 py-1.5 text-xs">
<Paperclip size={12} />
<span className="flex-1 truncate">{pendingFile.name}</span>
<button type="button" onClick={() => setPendingFile(null)} className="text-text-muted hover:text-text">
<X size={13} />
</button>
</div>
)}
<div className="mt-3 flex gap-2">
<input
ref={fileInputRef}
type="file"
className="hidden"
onChange={(e) => setPendingFile(e.target.files?.[0] ?? null)}
/>
<textarea
value={draft}
onChange={(e) => setDraft(e.target.value)}
@@ -77,7 +111,19 @@ export function PortalThread({
placeholder={`Ответить как ${customerName}…`}
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={sendReply} disabled={sending || !draft.trim()} className="btn btn-primary self-end">
<button
type="button"
onClick={() => fileInputRef.current?.click()}
className="btn btn-ghost self-end"
title="Прикрепить файл"
>
<Paperclip size={15} />
</button>
<button
onClick={sendReply}
disabled={sending || (!draft.trim() && !pendingFile)}
className="btn btn-primary self-end"
>
<Send size={15} />
</button>
</div>
@@ -85,7 +131,15 @@ export function PortalThread({
);
}
function MessageBubble({ message, isMine }: { message: MessageDTO; isMine: boolean }) {
function MessageBubble({
message,
isMine,
token,
}: {
message: MessageDTO;
isMine: boolean;
token: string;
}) {
if (message.authorType === "system") {
return <p className="my-2 text-center text-xs text-text-faint">{message.body}</p>;
}
@@ -100,6 +154,9 @@ function MessageBubble({ message, isMine }: { message: MessageDTO; isMine: boole
>
<div className={`max-w-[75%] 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>
{message.attachments.map((a) => (
<AttachmentChip key={a.id} attachment={a} token={token} />
))}
<p className={`text-[11px] ${isMine ? "text-white/70" : "text-text-faint"}`}>
{message.authorName} · {formatRelativeTime(message.createdAt)}
</p>
+48
View File
@@ -0,0 +1,48 @@
export const runtime = "nodejs";
import { NextResponse } from "next/server";
import { getCurrentSession } from "@/lib/auth/session";
import { getAttachmentContext, getCustomerByPortalToken } from "@/lib/tickets/service";
import { readAttachmentBuffer } from "@/lib/attachments/storage";
function contentDisposition(type: "inline" | "attachment", filename: string): string {
const asciiFallback = filename.replace(/[^\x20-\x7E]/g, "_");
return `${type}; filename="${asciiFallback}"; filename*=UTF-8''${encodeURIComponent(filename)}`;
}
export async function GET(request: Request, { params }: { params: Promise<{ id: string }> }) {
const { id } = await params;
const context = await getAttachmentContext(id);
if (!context) {
return NextResponse.json({ error: "Not found" }, { status: 404 });
}
const session = await getCurrentSession();
let authorized = Boolean(session);
// Internal-note attachments are never servable via a customer token, only
// an agent session — same rule getTicketForCustomer applies to messages.
if (!authorized && context.message.visibility === "public") {
const token = new URL(request.url).searchParams.get("token");
if (token) {
const customer = await getCustomerByPortalToken(token);
authorized = Boolean(customer && customer.id === context.ticket.customerId);
}
}
if (!authorized) {
return NextResponse.json({ error: "Not found" }, { status: 404 });
}
const buffer = await readAttachmentBuffer(context.attachment.storageKey);
const isImage = context.attachment.mimeType.startsWith("image/");
return new Response(new Uint8Array(buffer), {
headers: {
"Content-Type": context.attachment.mimeType,
"Content-Disposition": contentDisposition(isImage ? "inline" : "attachment", context.attachment.filename),
"Content-Length": String(context.attachment.sizeBytes),
"Cache-Control": "private, max-age=31536000, immutable",
},
});
}
+40
View File
@@ -0,0 +1,40 @@
export const runtime = "nodejs";
import { NextResponse } from "next/server";
import { z } from "zod";
import { eq } from "drizzle-orm";
import { requireSession } from "@/lib/auth/require";
import { verifyPassword, hashPassword } from "@/lib/auth/password";
import { db } from "@/lib/db/client";
import { users } from "@/lib/db/schema";
const schema = z.object({
currentPassword: z.string().min(1),
newPassword: z.string().min(8, "Пароль должен быть не короче 8 символов"),
});
export async function POST(request: Request) {
const { session, response } = await requireSession();
if (!session) return response;
const body = await request.json().catch(() => null);
const parsed = schema.safeParse(body);
if (!parsed.success) {
return NextResponse.json({ error: parsed.error.issues[0]?.message ?? "Invalid input" }, { status: 400 });
}
const user = await db.query.users.findFirst({ where: eq(users.id, session.user.id) });
if (!user) {
return NextResponse.json({ error: "User not found" }, { status: 404 });
}
const ok = await verifyPassword(user.passwordHash, parsed.data.currentPassword);
if (!ok) {
return NextResponse.json({ error: "Текущий пароль неверен" }, { status: 401 });
}
const newHash = await hashPassword(parsed.data.newPassword);
await db.update(users).set({ passwordHash: newHash }).where(eq(users.id, user.id));
return NextResponse.json({ ok: true });
}
@@ -0,0 +1,35 @@
export const runtime = "nodejs";
import { NextResponse } from "next/server";
import { z } from "zod";
import { requireSession } from "@/lib/auth/require";
import { updateCannedResponse, deleteCannedResponse } from "@/lib/tickets/service";
const updateSchema = z.object({
title: z.string().min(1).max(100),
body: z.string().min(1).max(5_000),
});
export async function PATCH(request: Request, { params }: { params: Promise<{ id: string }> }) {
const { session, response } = await requireSession();
if (!session) return response;
const { id } = await params;
const body = await request.json().catch(() => null);
const parsed = updateSchema.safeParse(body);
if (!parsed.success) {
return NextResponse.json({ error: "Invalid input" }, { status: 400 });
}
const canned = await updateCannedResponse(id, parsed.data.title, parsed.data.body);
return NextResponse.json({ response: canned });
}
export async function DELETE(_request: Request, { params }: { params: Promise<{ id: string }> }) {
const { session, response } = await requireSession();
if (!session) return response;
const { id } = await params;
await deleteCannedResponse(id);
return NextResponse.json({ ok: true });
}
+32
View File
@@ -0,0 +1,32 @@
export const runtime = "nodejs";
import { NextResponse } from "next/server";
import { z } from "zod";
import { requireSession } from "@/lib/auth/require";
import { listCannedResponses, createCannedResponse } from "@/lib/tickets/service";
export async function GET() {
const { session, response } = await requireSession();
if (!session) return response;
return NextResponse.json({ responses: await listCannedResponses() });
}
const createSchema = z.object({
title: z.string().min(1).max(100),
body: z.string().min(1).max(5_000),
});
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 canned = await createCannedResponse(parsed.data.title, parsed.data.body);
return NextResponse.json({ response: canned }, { status: 201 });
}
@@ -0,0 +1,65 @@
export const runtime = "nodejs";
import { NextResponse } from "next/server";
import { getCustomerByPortalToken, appendCustomerReply } from "@/lib/tickets/service";
import { saveAttachment, AttachmentTooLargeError, MAX_ATTACHMENT_BYTES } from "@/lib/attachments/storage";
export async function POST(
request: Request,
{ params }: { params: Promise<{ ticketId: string }> },
) {
const { ticketId } = await params;
const formData = await request.formData().catch(() => null);
const token = formData?.get("token");
if (typeof token !== "string" || !token) {
return NextResponse.json({ error: "Missing token" }, { status: 400 });
}
const file = formData?.get("file");
if (!(file instanceof File)) {
return NextResponse.json({ error: "Missing file" }, { status: 400 });
}
if (file.size > MAX_ATTACHMENT_BYTES) {
return NextResponse.json({ error: "File too large" }, { status: 413 });
}
const customer = await getCustomerByPortalToken(token);
if (!customer) {
return NextResponse.json({ error: "Invalid token" }, { status: 404 });
}
const captionRaw = formData?.get("caption");
const caption = typeof captionRaw === "string" ? captionRaw.trim() : "";
const buffer = Buffer.from(await file.arrayBuffer());
let saved;
try {
saved = await saveAttachment(buffer);
} catch (err) {
if (err instanceof AttachmentTooLargeError) {
return NextResponse.json({ error: "File too large" }, { status: 413 });
}
throw err;
}
try {
const result = await appendCustomerReply({
ticketId,
customerId: customer.id,
authorName: customer.displayName,
body: caption || file.name || "Вложение",
attachments: [
{
filename: file.name || "file",
mimeType: file.type || "application/octet-stream",
sizeBytes: saved.sizeBytes,
storageKey: saved.storageKey,
},
],
});
return NextResponse.json(result, { status: 201 });
} catch {
return NextResponse.json({ error: "Ticket not found" }, { status: 404 });
}
}
+14
View File
@@ -0,0 +1,14 @@
export const runtime = "nodejs";
import { NextResponse } from "next/server";
import { requireSession } from "@/lib/auth/require";
import { deleteTag } from "@/lib/tickets/service";
export async function DELETE(_request: Request, { params }: { params: Promise<{ id: string }> }) {
const { session, response } = await requireSession();
if (!session) return response;
const { id } = await params;
await deleteTag(id);
return NextResponse.json({ ok: true });
}
+32
View File
@@ -0,0 +1,32 @@
export const runtime = "nodejs";
import { NextResponse } from "next/server";
import { z } from "zod";
import { requireSession } from "@/lib/auth/require";
import { listTags, createTag } from "@/lib/tickets/service";
export async function GET() {
const { session, response } = await requireSession();
if (!session) return response;
return NextResponse.json({ tags: await listTags() });
}
const createSchema = z.object({
name: z.string().min(1).max(50),
color: z.enum(["accent", "success", "warning", "info", "rose", "danger"]),
});
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 tag = await createTag(parsed.data.name, parsed.data.color);
return NextResponse.json({ tag }, { status: 201 });
}
@@ -0,0 +1,56 @@
export const runtime = "nodejs";
import { NextResponse } from "next/server";
import { requireSession } from "@/lib/auth/require";
import { deliverAgentMessage } from "@/lib/tickets/delivery";
import { saveAttachment, AttachmentTooLargeError, MAX_ATTACHMENT_BYTES } from "@/lib/attachments/storage";
export async function POST(request: Request, { params }: { params: Promise<{ id: string }> }) {
const { session, response } = await requireSession();
if (!session) return response;
const { id } = await params;
const formData = await request.formData().catch(() => null);
const file = formData?.get("file");
if (!(file instanceof File)) {
return NextResponse.json({ error: "Missing file" }, { status: 400 });
}
if (file.size > MAX_ATTACHMENT_BYTES) {
return NextResponse.json({ error: "File too large" }, { status: 413 });
}
const captionRaw = formData?.get("caption");
const caption = typeof captionRaw === "string" ? captionRaw.trim() : "";
const visibility = formData?.get("visibility") === "internal" ? "internal" : "public";
const buffer = Buffer.from(await file.arrayBuffer());
let saved;
try {
saved = await saveAttachment(buffer);
} catch (err) {
if (err instanceof AttachmentTooLargeError) {
return NextResponse.json({ error: "File too large" }, { status: 413 });
}
throw err;
}
try {
const result = await deliverAgentMessage({
ticketId: id,
agentId: session.user.id,
agentName: session.user.name,
body: caption || file.name || "Вложение",
visibility,
attachment: {
filename: file.name || "file",
mimeType: file.type || "application/octet-stream",
sizeBytes: saved.sizeBytes,
storageKey: saved.storageKey,
buffer,
},
});
return NextResponse.json(result, { status: 201 });
} catch {
return NextResponse.json({ error: "Ticket not found" }, { status: 404 });
}
}
+6 -45
View File
@@ -3,12 +3,7 @@ export const runtime = "nodejs";
import { NextResponse } from "next/server";
import { z } from "zod";
import { requireSession } from "@/lib/auth/require";
import { recordAgentReply, recordInternalNote, getEmailThreadContext } from "@/lib/tickets/service";
import { sendTelegramMessage } from "@/lib/telegram/bot";
import { sendTicketReplyEmail } from "@/lib/mail/smtp";
import { db } from "@/lib/db/client";
import { customers } from "@/lib/db/schema";
import { eq } from "drizzle-orm";
import { deliverAgentMessage } from "@/lib/tickets/delivery";
const messageSchema = z.object({
body: z.string().min(1).max(10_000),
@@ -26,50 +21,16 @@ export async function POST(request: Request, { params }: { params: Promise<{ id:
return NextResponse.json({ error: "Invalid input" }, { status: 400 });
}
const ticket = await db.query.tickets.findFirst({ where: (t, { eq: eqOp }) => eqOp(t.id, id) });
if (!ticket) {
return NextResponse.json({ error: "Ticket not found" }, { status: 404 });
}
if (parsed.data.visibility === "internal") {
const result = await recordInternalNote({
try {
const result = await deliverAgentMessage({
ticketId: id,
agentId: session.user.id,
agentName: session.user.name,
body: parsed.data.body,
visibility: parsed.data.visibility,
});
return NextResponse.json(result, { status: 201 });
} catch {
return NextResponse.json({ error: "Ticket not found" }, { status: 404 });
}
let emailMessageId: string | undefined;
if (ticket.channel === "email") {
const context = await getEmailThreadContext(id);
if (context) {
emailMessageId = await sendTicketReplyEmail({
to: context.customerEmail,
subject: context.subject,
body: parsed.data.body,
inReplyTo: context.inReplyTo,
});
}
}
const result = await recordAgentReply({
ticketId: id,
agentId: session.user.id,
agentName: session.user.name,
body: parsed.data.body,
emailMessageId,
});
if (result.ticket.channel === "telegram") {
const customer = await db.query.customers.findFirst({
where: eq(customers.id, result.ticket.customerId),
});
if (customer?.telegramChatId) {
await sendTelegramMessage(customer.telegramChatId, parsed.data.body);
}
}
return NextResponse.json(result, { status: 201 });
}
+23
View File
@@ -0,0 +1,23 @@
export const runtime = "nodejs";
import { NextResponse } from "next/server";
import { z } from "zod";
import { requireSession } from "@/lib/auth/require";
import { setTicketTags } from "@/lib/tickets/service";
const schema = z.object({ tagIds: z.array(z.string()) });
export async function PUT(request: Request, { params }: { params: Promise<{ id: string }> }) {
const { session, response } = await requireSession();
if (!session) return response;
const { id } = await params;
const body = await request.json().catch(() => null);
const parsed = schema.safeParse(body);
if (!parsed.success) {
return NextResponse.json({ error: "Invalid input" }, { status: 400 });
}
const tags = await setTicketTags(id, parsed.data.tagIds);
return NextResponse.json({ tags });
}
+3 -2
View File
@@ -5,11 +5,12 @@ import { z } from "zod";
import { requireSession } from "@/lib/auth/require";
import { listTickets, createManualTicket } from "@/lib/tickets/service";
export async function GET() {
export async function GET(request: Request) {
const { session, response } = await requireSession();
if (!session) return response;
const tickets = await listTickets();
const query = new URL(request.url).searchParams.get("q") ?? undefined;
const tickets = await listTickets(query);
return NextResponse.json({ tickets });
}
+98
View File
@@ -0,0 +1,98 @@
export const runtime = "nodejs";
import { NextResponse } from "next/server";
import {
getWidgetSiteByKey,
getCustomerByPortalToken,
renameCustomerIfGuest,
recordChatInboundMessage,
} from "@/lib/tickets/service";
import { saveAttachment, AttachmentTooLargeError, MAX_ATTACHMENT_BYTES } from "@/lib/attachments/storage";
// Same shape as /api/widget/messages' limiter — kept separate rather than
// shared since each route's rate budget is independent.
const attempts = new Map<string, { count: number; resetAt: number }>();
const MAX_ATTEMPTS = 10;
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;
}
export async function POST(request: Request) {
const formData = await request.formData().catch(() => null);
const siteKey = formData?.get("siteKey");
const token = formData?.get("token");
if (typeof siteKey !== "string" || !siteKey || typeof token !== "string" || !token) {
return NextResponse.json({ error: "Invalid input" }, { status: 400 });
}
if (isRateLimited(token)) {
return NextResponse.json({ error: "Слишком много сообщений — подождите немного" }, { status: 429 });
}
const file = formData?.get("file");
if (!(file instanceof File)) {
return NextResponse.json({ error: "Missing file" }, { status: 400 });
}
if (file.size > MAX_ATTACHMENT_BYTES) {
return NextResponse.json({ error: "File too large" }, { status: 413 });
}
const site = await getWidgetSiteByKey(siteKey);
if (!site || !site.enabled) {
return NextResponse.json({ error: "Unknown or disabled widget" }, { status: 404 });
}
const customer = await getCustomerByPortalToken(token);
if (!customer) {
return NextResponse.json({ error: "Invalid token" }, { status: 404 });
}
const nameRaw = formData?.get("name");
const name = typeof nameRaw === "string" ? nameRaw.trim() : "";
if (name) {
await renameCustomerIfGuest(customer.id, name);
}
const captionRaw = formData?.get("caption");
const caption = typeof captionRaw === "string" ? captionRaw.trim() : "";
const buffer = Buffer.from(await file.arrayBuffer());
let saved;
try {
saved = await saveAttachment(buffer);
} catch (err) {
if (err instanceof AttachmentTooLargeError) {
return NextResponse.json({ error: "File too large" }, { status: 413 });
}
throw err;
}
const body = caption || file.name || "Вложение";
const result = await recordChatInboundMessage({
customerId: customer.id,
channel: "widget",
body,
authorName: name || customer.displayName,
subjectForNewTicket: `Чат (${site.name}): ${body.slice(0, 60)}`,
attachments: [
{
filename: file.name || "file",
mimeType: file.type || "application/octet-stream",
sizeBytes: saved.sizeBytes,
storageKey: saved.storageKey,
},
],
});
return NextResponse.json(result, { status: 201 });
}
+55 -10
View File
@@ -3,9 +3,10 @@
import { useEffect, useRef, useState } from "react";
import { useSearchParams } from "next/navigation";
import { AnimatePresence, motion } from "framer-motion";
import { Send } from "lucide-react";
import { Send, Paperclip, X } from "lucide-react";
import { useTicketEvents } from "@/lib/events/use-ticket-events";
import { formatRelativeTime } from "@/lib/format";
import { AttachmentChip } from "@/components/attachment-chip";
import type { MessageDTO } from "@/lib/tickets/types";
const STORAGE_KEY = "top-tickets-widget-token";
@@ -17,9 +18,11 @@ export function WidgetChat() {
const [messages, setMessages] = useState<MessageDTO[]>([]);
const [name, setName] = useState("");
const [draft, setDraft] = useState("");
const [pendingFile, setPendingFile] = useState<File | null>(null);
const [ready, setReady] = useState(false);
const [sending, setSending] = useState(false);
const bottomRef = useRef<HTMLDivElement>(null);
const fileInputRef = useRef<HTMLInputElement>(null);
useEffect(() => {
const stored = localStorage.getItem(STORAGE_KEY) ?? undefined;
@@ -50,16 +53,31 @@ export function WidgetChat() {
}, [messages.length]);
async function sendMessage() {
if (!draft.trim() || !token) return;
if ((!draft.trim() && !pendingFile) || !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 }),
});
let res: Response;
if (pendingFile) {
const formData = new FormData();
formData.append("siteKey", siteKey);
formData.append("token", token);
formData.append("file", pendingFile);
formData.append("caption", draft);
if (name.trim()) formData.append("name", name.trim());
res = await fetch("/api/widget/attachments", { method: "POST", body: formData });
} else {
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("");
setPendingFile(null);
if (fileInputRef.current) fileInputRef.current.value = "";
}
}
@@ -86,7 +104,7 @@ export function WidgetChat() {
<div className="flex-1 overflow-y-auto">
<AnimatePresence initial={false}>
{messages.map((message) => (
<MessageBubble key={message.id} message={message} />
<MessageBubble key={message.id} message={message} token={token ?? ""} />
))}
</AnimatePresence>
{isFirstMessage && (
@@ -95,7 +113,23 @@ export function WidgetChat() {
<div ref={bottomRef} />
</div>
{pendingFile && (
<div className="mt-2 flex items-center gap-2 rounded-md border border-border bg-surface-hover px-2.5 py-1.5 text-xs">
<Paperclip size={12} />
<span className="flex-1 truncate">{pendingFile.name}</span>
<button type="button" onClick={() => setPendingFile(null)} className="text-text-muted hover:text-text">
<X size={13} />
</button>
</div>
)}
<div className="mt-2 flex gap-2">
<input
ref={fileInputRef}
type="file"
className="hidden"
onChange={(e) => setPendingFile(e.target.files?.[0] ?? null)}
/>
<textarea
rows={1}
value={draft}
@@ -109,7 +143,15 @@ export function WidgetChat() {
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">
<button
type="button"
onClick={() => fileInputRef.current?.click()}
className="btn btn-ghost"
title="Прикрепить файл"
>
<Paperclip size={15} />
</button>
<button onClick={sendMessage} disabled={sending || (!draft.trim() && !pendingFile)} className="btn btn-primary">
<Send size={15} />
</button>
</div>
@@ -117,7 +159,7 @@ export function WidgetChat() {
);
}
function MessageBubble({ message }: { message: MessageDTO }) {
function MessageBubble({ message, token }: { message: MessageDTO; token: string }) {
const isMine = message.authorType === "customer";
if (message.authorType === "system") {
@@ -134,6 +176,9 @@ function MessageBubble({ message }: { message: MessageDTO }) {
>
<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>
{message.attachments.map((a) => (
<AttachmentChip key={a.id} attachment={a} token={token} />
))}
<p className={`text-[11px] ${isMine ? "text-white/70" : "text-text-faint"}`}>
{formatRelativeTime(message.createdAt)}
</p>