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:
1 parent
7947633709
commit
89b9c5eaac
40 files changed
+2751
-106
No files matched your search
@@ -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} />
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
@@ -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`, {
|
||||
|
||||
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`, {
|
||||
|
||||
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>
|
||||
|
||||
@@ -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",
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -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 });
|
||||
}
|
||||
@@ -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 });
|
||||
}
|
||||
}
|
||||
@@ -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 });
|
||||
}
|
||||
@@ -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 });
|
||||
}
|
||||
}
|
||||
@@ -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) {
|
||||
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 });
|
||||
}
|
||||
|
||||
if (parsed.data.visibility === "internal") {
|
||||
const result = await recordInternalNote({
|
||||
ticketId: id,
|
||||
agentId: session.user.id,
|
||||
agentName: session.user.name,
|
||||
body: parsed.data.body,
|
||||
});
|
||||
return NextResponse.json(result, { status: 201 });
|
||||
}
|
||||
|
||||
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 });
|
||||
}
|
||||
@@ -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 });
|
||||
}
|
||||
@@ -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 });
|
||||
}
|
||||
|
||||
|
||||
@@ -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 });
|
||||
}
|
||||
@@ -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", {
|
||||
|
||||
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>
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
import { Paperclip } from "lucide-react";
|
||||
import type { AttachmentDTO } from "@/lib/tickets/types";
|
||||
|
||||
function formatSize(bytes: number): string {
|
||||
if (bytes < 1024) return `${bytes} B`;
|
||||
if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
|
||||
return `${(bytes / 1024 / 1024).toFixed(1)} MB`;
|
||||
}
|
||||
|
||||
export function AttachmentChip({ attachment, token }: { attachment: AttachmentDTO; token?: string }) {
|
||||
const url = `/api/attachments/${attachment.id}${token ? `?token=${encodeURIComponent(token)}` : ""}`;
|
||||
const isImage = attachment.mimeType.startsWith("image/");
|
||||
|
||||
if (isImage) {
|
||||
return (
|
||||
<a
|
||||
href={url}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="mt-1.5 block max-w-[220px] overflow-hidden rounded-md border border-border"
|
||||
>
|
||||
{/* eslint-disable-next-line @next/next/no-img-element -- serves from our own auth-gated API route, not next/image-optimizable */}
|
||||
<img src={url} alt={attachment.filename} className="block max-h-48 w-full object-cover" />
|
||||
</a>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<a
|
||||
href={url}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="mt-1.5 flex max-w-[220px] items-center gap-2 rounded-md border border-border bg-surface px-2.5 py-1.5 text-xs hover:bg-surface-hover"
|
||||
>
|
||||
<Paperclip size={13} className="shrink-0" />
|
||||
<span className="truncate">{attachment.filename}</span>
|
||||
<span className="shrink-0 text-text-faint">{formatSize(attachment.sizeBytes)}</span>
|
||||
</a>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
import fs from "node:fs/promises";
|
||||
import path from "node:path";
|
||||
import crypto from "node:crypto";
|
||||
|
||||
export const MAX_ATTACHMENT_BYTES = 15 * 1024 * 1024;
|
||||
|
||||
export class AttachmentTooLargeError extends Error {}
|
||||
|
||||
function attachmentsDir(): string {
|
||||
const dataDir = process.env.DATA_DIR ?? path.join(process.cwd(), "data");
|
||||
return path.join(dataDir, "attachments");
|
||||
}
|
||||
|
||||
/** storageKey is always a freshly generated UUID here — never derived from user input, so no path-traversal risk. */
|
||||
export async function saveAttachment(buffer: Buffer): Promise<{ storageKey: string; sizeBytes: number }> {
|
||||
if (buffer.byteLength > MAX_ATTACHMENT_BYTES) {
|
||||
throw new AttachmentTooLargeError(`File exceeds ${MAX_ATTACHMENT_BYTES} bytes`);
|
||||
}
|
||||
const dir = attachmentsDir();
|
||||
await fs.mkdir(dir, { recursive: true });
|
||||
const storageKey = crypto.randomUUID();
|
||||
await fs.writeFile(path.join(dir, storageKey), buffer);
|
||||
return { storageKey, sizeBytes: buffer.byteLength };
|
||||
}
|
||||
|
||||
export async function readAttachmentBuffer(storageKey: string): Promise<Buffer> {
|
||||
return fs.readFile(path.join(attachmentsDir(), storageKey));
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
CREATE TABLE `attachments` (
|
||||
`id` text PRIMARY KEY NOT NULL,
|
||||
`message_id` text NOT NULL,
|
||||
`filename` text NOT NULL,
|
||||
`mime_type` text NOT NULL,
|
||||
`size_bytes` integer NOT NULL,
|
||||
`storage_key` text NOT NULL,
|
||||
`created_at` integer DEFAULT (unixepoch('subsec') * 1000) NOT NULL,
|
||||
FOREIGN KEY (`message_id`) REFERENCES `messages`(`id`) ON UPDATE no action ON DELETE cascade
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE `canned_responses` (
|
||||
`id` text PRIMARY KEY NOT NULL,
|
||||
`title` text NOT NULL,
|
||||
`body` text NOT NULL,
|
||||
`created_at` integer DEFAULT (unixepoch('subsec') * 1000) NOT NULL
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE `tags` (
|
||||
`id` text PRIMARY KEY NOT NULL,
|
||||
`name` text NOT NULL,
|
||||
`color` text DEFAULT 'accent' NOT NULL,
|
||||
`created_at` integer DEFAULT (unixepoch('subsec') * 1000) NOT NULL
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE UNIQUE INDEX `tags_name_unique` ON `tags` (`name`);--> statement-breakpoint
|
||||
CREATE TABLE `ticket_tags` (
|
||||
`ticket_id` text NOT NULL,
|
||||
`tag_id` text NOT NULL,
|
||||
PRIMARY KEY(`ticket_id`, `tag_id`),
|
||||
FOREIGN KEY (`ticket_id`) REFERENCES `tickets`(`id`) ON UPDATE no action ON DELETE cascade,
|
||||
FOREIGN KEY (`tag_id`) REFERENCES `tags`(`id`) ON UPDATE no action ON DELETE cascade
|
||||
);
|
||||
@@ -0,0 +1,837 @@
|
||||
{
|
||||
"version": "6",
|
||||
"dialect": "sqlite",
|
||||
"id": "c974991b-5c77-4525-a20c-91b3b31a7a70",
|
||||
"prevId": "727e15bd-5319-45d7-9cc5-52683fe1dc2e",
|
||||
"tables": {
|
||||
"attachments": {
|
||||
"name": "attachments",
|
||||
"columns": {
|
||||
"id": {
|
||||
"name": "id",
|
||||
"type": "text",
|
||||
"primaryKey": true,
|
||||
"notNull": true,
|
||||
"autoincrement": false
|
||||
},
|
||||
"message_id": {
|
||||
"name": "message_id",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false
|
||||
},
|
||||
"filename": {
|
||||
"name": "filename",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false
|
||||
},
|
||||
"mime_type": {
|
||||
"name": "mime_type",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false
|
||||
},
|
||||
"size_bytes": {
|
||||
"name": "size_bytes",
|
||||
"type": "integer",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false
|
||||
},
|
||||
"storage_key": {
|
||||
"name": "storage_key",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false
|
||||
},
|
||||
"created_at": {
|
||||
"name": "created_at",
|
||||
"type": "integer",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false,
|
||||
"default": "(unixepoch('subsec') * 1000)"
|
||||
}
|
||||
},
|
||||
"indexes": {},
|
||||
"foreignKeys": {
|
||||
"attachments_message_id_messages_id_fk": {
|
||||
"name": "attachments_message_id_messages_id_fk",
|
||||
"tableFrom": "attachments",
|
||||
"tableTo": "messages",
|
||||
"columnsFrom": [
|
||||
"message_id"
|
||||
],
|
||||
"columnsTo": [
|
||||
"id"
|
||||
],
|
||||
"onDelete": "cascade",
|
||||
"onUpdate": "no action"
|
||||
}
|
||||
},
|
||||
"compositePrimaryKeys": {},
|
||||
"uniqueConstraints": {},
|
||||
"checkConstraints": {}
|
||||
},
|
||||
"canned_responses": {
|
||||
"name": "canned_responses",
|
||||
"columns": {
|
||||
"id": {
|
||||
"name": "id",
|
||||
"type": "text",
|
||||
"primaryKey": true,
|
||||
"notNull": true,
|
||||
"autoincrement": false
|
||||
},
|
||||
"title": {
|
||||
"name": "title",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false
|
||||
},
|
||||
"body": {
|
||||
"name": "body",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false
|
||||
},
|
||||
"created_at": {
|
||||
"name": "created_at",
|
||||
"type": "integer",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false,
|
||||
"default": "(unixepoch('subsec') * 1000)"
|
||||
}
|
||||
},
|
||||
"indexes": {},
|
||||
"foreignKeys": {},
|
||||
"compositePrimaryKeys": {},
|
||||
"uniqueConstraints": {},
|
||||
"checkConstraints": {}
|
||||
},
|
||||
"customers": {
|
||||
"name": "customers",
|
||||
"columns": {
|
||||
"id": {
|
||||
"name": "id",
|
||||
"type": "text",
|
||||
"primaryKey": true,
|
||||
"notNull": true,
|
||||
"autoincrement": false
|
||||
},
|
||||
"display_name": {
|
||||
"name": "display_name",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false
|
||||
},
|
||||
"email": {
|
||||
"name": "email",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": false,
|
||||
"autoincrement": false
|
||||
},
|
||||
"telegram_chat_id": {
|
||||
"name": "telegram_chat_id",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": false,
|
||||
"autoincrement": false
|
||||
},
|
||||
"portal_token": {
|
||||
"name": "portal_token",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false
|
||||
},
|
||||
"created_at": {
|
||||
"name": "created_at",
|
||||
"type": "integer",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false,
|
||||
"default": "(unixepoch('subsec') * 1000)"
|
||||
}
|
||||
},
|
||||
"indexes": {
|
||||
"customers_telegram_chat_id_unique": {
|
||||
"name": "customers_telegram_chat_id_unique",
|
||||
"columns": [
|
||||
"telegram_chat_id"
|
||||
],
|
||||
"isUnique": true
|
||||
},
|
||||
"customers_portal_token_unique": {
|
||||
"name": "customers_portal_token_unique",
|
||||
"columns": [
|
||||
"portal_token"
|
||||
],
|
||||
"isUnique": true
|
||||
}
|
||||
},
|
||||
"foreignKeys": {},
|
||||
"compositePrimaryKeys": {},
|
||||
"uniqueConstraints": {},
|
||||
"checkConstraints": {}
|
||||
},
|
||||
"mailbox_config": {
|
||||
"name": "mailbox_config",
|
||||
"columns": {
|
||||
"id": {
|
||||
"name": "id",
|
||||
"type": "text",
|
||||
"primaryKey": true,
|
||||
"notNull": true,
|
||||
"autoincrement": false
|
||||
},
|
||||
"imap_host": {
|
||||
"name": "imap_host",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false
|
||||
},
|
||||
"imap_port": {
|
||||
"name": "imap_port",
|
||||
"type": "integer",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false,
|
||||
"default": 993
|
||||
},
|
||||
"smtp_host": {
|
||||
"name": "smtp_host",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false
|
||||
},
|
||||
"smtp_port": {
|
||||
"name": "smtp_port",
|
||||
"type": "integer",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false,
|
||||
"default": 587
|
||||
},
|
||||
"user": {
|
||||
"name": "user",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false
|
||||
},
|
||||
"password_enc": {
|
||||
"name": "password_enc",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false
|
||||
},
|
||||
"allow_insecure_tls": {
|
||||
"name": "allow_insecure_tls",
|
||||
"type": "integer",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false,
|
||||
"default": false
|
||||
},
|
||||
"enabled": {
|
||||
"name": "enabled",
|
||||
"type": "integer",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false,
|
||||
"default": false
|
||||
},
|
||||
"verified_at": {
|
||||
"name": "verified_at",
|
||||
"type": "integer",
|
||||
"primaryKey": false,
|
||||
"notNull": false,
|
||||
"autoincrement": false
|
||||
},
|
||||
"created_at": {
|
||||
"name": "created_at",
|
||||
"type": "integer",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false,
|
||||
"default": "(unixepoch('subsec') * 1000)"
|
||||
}
|
||||
},
|
||||
"indexes": {},
|
||||
"foreignKeys": {},
|
||||
"compositePrimaryKeys": {},
|
||||
"uniqueConstraints": {},
|
||||
"checkConstraints": {}
|
||||
},
|
||||
"messages": {
|
||||
"name": "messages",
|
||||
"columns": {
|
||||
"id": {
|
||||
"name": "id",
|
||||
"type": "text",
|
||||
"primaryKey": true,
|
||||
"notNull": true,
|
||||
"autoincrement": false
|
||||
},
|
||||
"ticket_id": {
|
||||
"name": "ticket_id",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false
|
||||
},
|
||||
"author_type": {
|
||||
"name": "author_type",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false
|
||||
},
|
||||
"author_id": {
|
||||
"name": "author_id",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": false,
|
||||
"autoincrement": false
|
||||
},
|
||||
"author_name": {
|
||||
"name": "author_name",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false
|
||||
},
|
||||
"body": {
|
||||
"name": "body",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false
|
||||
},
|
||||
"direction": {
|
||||
"name": "direction",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false
|
||||
},
|
||||
"visibility": {
|
||||
"name": "visibility",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false,
|
||||
"default": "'public'"
|
||||
},
|
||||
"email_message_id": {
|
||||
"name": "email_message_id",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": false,
|
||||
"autoincrement": false
|
||||
},
|
||||
"created_at": {
|
||||
"name": "created_at",
|
||||
"type": "integer",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false,
|
||||
"default": "(unixepoch('subsec') * 1000)"
|
||||
}
|
||||
},
|
||||
"indexes": {},
|
||||
"foreignKeys": {
|
||||
"messages_ticket_id_tickets_id_fk": {
|
||||
"name": "messages_ticket_id_tickets_id_fk",
|
||||
"tableFrom": "messages",
|
||||
"tableTo": "tickets",
|
||||
"columnsFrom": [
|
||||
"ticket_id"
|
||||
],
|
||||
"columnsTo": [
|
||||
"id"
|
||||
],
|
||||
"onDelete": "cascade",
|
||||
"onUpdate": "no action"
|
||||
}
|
||||
},
|
||||
"compositePrimaryKeys": {},
|
||||
"uniqueConstraints": {},
|
||||
"checkConstraints": {}
|
||||
},
|
||||
"sessions": {
|
||||
"name": "sessions",
|
||||
"columns": {
|
||||
"token_hash": {
|
||||
"name": "token_hash",
|
||||
"type": "text",
|
||||
"primaryKey": true,
|
||||
"notNull": true,
|
||||
"autoincrement": false
|
||||
},
|
||||
"user_id": {
|
||||
"name": "user_id",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false
|
||||
},
|
||||
"expires_at": {
|
||||
"name": "expires_at",
|
||||
"type": "integer",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false
|
||||
},
|
||||
"created_at": {
|
||||
"name": "created_at",
|
||||
"type": "integer",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false,
|
||||
"default": "(unixepoch('subsec') * 1000)"
|
||||
}
|
||||
},
|
||||
"indexes": {},
|
||||
"foreignKeys": {
|
||||
"sessions_user_id_users_id_fk": {
|
||||
"name": "sessions_user_id_users_id_fk",
|
||||
"tableFrom": "sessions",
|
||||
"tableTo": "users",
|
||||
"columnsFrom": [
|
||||
"user_id"
|
||||
],
|
||||
"columnsTo": [
|
||||
"id"
|
||||
],
|
||||
"onDelete": "cascade",
|
||||
"onUpdate": "no action"
|
||||
}
|
||||
},
|
||||
"compositePrimaryKeys": {},
|
||||
"uniqueConstraints": {},
|
||||
"checkConstraints": {}
|
||||
},
|
||||
"tags": {
|
||||
"name": "tags",
|
||||
"columns": {
|
||||
"id": {
|
||||
"name": "id",
|
||||
"type": "text",
|
||||
"primaryKey": true,
|
||||
"notNull": true,
|
||||
"autoincrement": false
|
||||
},
|
||||
"name": {
|
||||
"name": "name",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false
|
||||
},
|
||||
"color": {
|
||||
"name": "color",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false,
|
||||
"default": "'accent'"
|
||||
},
|
||||
"created_at": {
|
||||
"name": "created_at",
|
||||
"type": "integer",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false,
|
||||
"default": "(unixepoch('subsec') * 1000)"
|
||||
}
|
||||
},
|
||||
"indexes": {
|
||||
"tags_name_unique": {
|
||||
"name": "tags_name_unique",
|
||||
"columns": [
|
||||
"name"
|
||||
],
|
||||
"isUnique": true
|
||||
}
|
||||
},
|
||||
"foreignKeys": {},
|
||||
"compositePrimaryKeys": {},
|
||||
"uniqueConstraints": {},
|
||||
"checkConstraints": {}
|
||||
},
|
||||
"telegram_config": {
|
||||
"name": "telegram_config",
|
||||
"columns": {
|
||||
"id": {
|
||||
"name": "id",
|
||||
"type": "text",
|
||||
"primaryKey": true,
|
||||
"notNull": true,
|
||||
"autoincrement": false
|
||||
},
|
||||
"bot_token_enc": {
|
||||
"name": "bot_token_enc",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false
|
||||
},
|
||||
"bot_username": {
|
||||
"name": "bot_username",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": false,
|
||||
"autoincrement": false
|
||||
},
|
||||
"enabled": {
|
||||
"name": "enabled",
|
||||
"type": "integer",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false,
|
||||
"default": false
|
||||
},
|
||||
"verified_at": {
|
||||
"name": "verified_at",
|
||||
"type": "integer",
|
||||
"primaryKey": false,
|
||||
"notNull": false,
|
||||
"autoincrement": false
|
||||
},
|
||||
"created_at": {
|
||||
"name": "created_at",
|
||||
"type": "integer",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false,
|
||||
"default": "(unixepoch('subsec') * 1000)"
|
||||
}
|
||||
},
|
||||
"indexes": {},
|
||||
"foreignKeys": {},
|
||||
"compositePrimaryKeys": {},
|
||||
"uniqueConstraints": {},
|
||||
"checkConstraints": {}
|
||||
},
|
||||
"ticket_tags": {
|
||||
"name": "ticket_tags",
|
||||
"columns": {
|
||||
"ticket_id": {
|
||||
"name": "ticket_id",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false
|
||||
},
|
||||
"tag_id": {
|
||||
"name": "tag_id",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false
|
||||
}
|
||||
},
|
||||
"indexes": {},
|
||||
"foreignKeys": {
|
||||
"ticket_tags_ticket_id_tickets_id_fk": {
|
||||
"name": "ticket_tags_ticket_id_tickets_id_fk",
|
||||
"tableFrom": "ticket_tags",
|
||||
"tableTo": "tickets",
|
||||
"columnsFrom": [
|
||||
"ticket_id"
|
||||
],
|
||||
"columnsTo": [
|
||||
"id"
|
||||
],
|
||||
"onDelete": "cascade",
|
||||
"onUpdate": "no action"
|
||||
},
|
||||
"ticket_tags_tag_id_tags_id_fk": {
|
||||
"name": "ticket_tags_tag_id_tags_id_fk",
|
||||
"tableFrom": "ticket_tags",
|
||||
"tableTo": "tags",
|
||||
"columnsFrom": [
|
||||
"tag_id"
|
||||
],
|
||||
"columnsTo": [
|
||||
"id"
|
||||
],
|
||||
"onDelete": "cascade",
|
||||
"onUpdate": "no action"
|
||||
}
|
||||
},
|
||||
"compositePrimaryKeys": {
|
||||
"ticket_tags_ticket_id_tag_id_pk": {
|
||||
"columns": [
|
||||
"ticket_id",
|
||||
"tag_id"
|
||||
],
|
||||
"name": "ticket_tags_ticket_id_tag_id_pk"
|
||||
}
|
||||
},
|
||||
"uniqueConstraints": {},
|
||||
"checkConstraints": {}
|
||||
},
|
||||
"tickets": {
|
||||
"name": "tickets",
|
||||
"columns": {
|
||||
"id": {
|
||||
"name": "id",
|
||||
"type": "text",
|
||||
"primaryKey": true,
|
||||
"notNull": true,
|
||||
"autoincrement": false
|
||||
},
|
||||
"subject": {
|
||||
"name": "subject",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false
|
||||
},
|
||||
"status": {
|
||||
"name": "status",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false,
|
||||
"default": "'new'"
|
||||
},
|
||||
"priority": {
|
||||
"name": "priority",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false,
|
||||
"default": "'normal'"
|
||||
},
|
||||
"channel": {
|
||||
"name": "channel",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false
|
||||
},
|
||||
"customer_id": {
|
||||
"name": "customer_id",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false
|
||||
},
|
||||
"assignee_id": {
|
||||
"name": "assignee_id",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": false,
|
||||
"autoincrement": false
|
||||
},
|
||||
"last_message_at": {
|
||||
"name": "last_message_at",
|
||||
"type": "integer",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false,
|
||||
"default": "(unixepoch('subsec') * 1000)"
|
||||
},
|
||||
"created_at": {
|
||||
"name": "created_at",
|
||||
"type": "integer",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false,
|
||||
"default": "(unixepoch('subsec') * 1000)"
|
||||
},
|
||||
"updated_at": {
|
||||
"name": "updated_at",
|
||||
"type": "integer",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false,
|
||||
"default": "(unixepoch('subsec') * 1000)"
|
||||
}
|
||||
},
|
||||
"indexes": {},
|
||||
"foreignKeys": {
|
||||
"tickets_customer_id_customers_id_fk": {
|
||||
"name": "tickets_customer_id_customers_id_fk",
|
||||
"tableFrom": "tickets",
|
||||
"tableTo": "customers",
|
||||
"columnsFrom": [
|
||||
"customer_id"
|
||||
],
|
||||
"columnsTo": [
|
||||
"id"
|
||||
],
|
||||
"onDelete": "cascade",
|
||||
"onUpdate": "no action"
|
||||
},
|
||||
"tickets_assignee_id_users_id_fk": {
|
||||
"name": "tickets_assignee_id_users_id_fk",
|
||||
"tableFrom": "tickets",
|
||||
"tableTo": "users",
|
||||
"columnsFrom": [
|
||||
"assignee_id"
|
||||
],
|
||||
"columnsTo": [
|
||||
"id"
|
||||
],
|
||||
"onDelete": "set null",
|
||||
"onUpdate": "no action"
|
||||
}
|
||||
},
|
||||
"compositePrimaryKeys": {},
|
||||
"uniqueConstraints": {},
|
||||
"checkConstraints": {}
|
||||
},
|
||||
"users": {
|
||||
"name": "users",
|
||||
"columns": {
|
||||
"id": {
|
||||
"name": "id",
|
||||
"type": "text",
|
||||
"primaryKey": true,
|
||||
"notNull": true,
|
||||
"autoincrement": false
|
||||
},
|
||||
"email": {
|
||||
"name": "email",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false
|
||||
},
|
||||
"password_hash": {
|
||||
"name": "password_hash",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false
|
||||
},
|
||||
"name": {
|
||||
"name": "name",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false
|
||||
},
|
||||
"role": {
|
||||
"name": "role",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false,
|
||||
"default": "'agent'"
|
||||
},
|
||||
"created_at": {
|
||||
"name": "created_at",
|
||||
"type": "integer",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false,
|
||||
"default": "(unixepoch('subsec') * 1000)"
|
||||
}
|
||||
},
|
||||
"indexes": {
|
||||
"users_email_unique": {
|
||||
"name": "users_email_unique",
|
||||
"columns": [
|
||||
"email"
|
||||
],
|
||||
"isUnique": true
|
||||
}
|
||||
},
|
||||
"foreignKeys": {},
|
||||
"compositePrimaryKeys": {},
|
||||
"uniqueConstraints": {},
|
||||
"checkConstraints": {}
|
||||
},
|
||||
"widget_sites": {
|
||||
"name": "widget_sites",
|
||||
"columns": {
|
||||
"id": {
|
||||
"name": "id",
|
||||
"type": "text",
|
||||
"primaryKey": true,
|
||||
"notNull": true,
|
||||
"autoincrement": false
|
||||
},
|
||||
"site_key": {
|
||||
"name": "site_key",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false
|
||||
},
|
||||
"name": {
|
||||
"name": "name",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false
|
||||
},
|
||||
"allowed_origin": {
|
||||
"name": "allowed_origin",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": false,
|
||||
"autoincrement": false
|
||||
},
|
||||
"enabled": {
|
||||
"name": "enabled",
|
||||
"type": "integer",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false,
|
||||
"default": true
|
||||
},
|
||||
"created_at": {
|
||||
"name": "created_at",
|
||||
"type": "integer",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false,
|
||||
"default": "(unixepoch('subsec') * 1000)"
|
||||
}
|
||||
},
|
||||
"indexes": {
|
||||
"widget_sites_site_key_unique": {
|
||||
"name": "widget_sites_site_key_unique",
|
||||
"columns": [
|
||||
"site_key"
|
||||
],
|
||||
"isUnique": true
|
||||
}
|
||||
},
|
||||
"foreignKeys": {},
|
||||
"compositePrimaryKeys": {},
|
||||
"uniqueConstraints": {},
|
||||
"checkConstraints": {}
|
||||
}
|
||||
},
|
||||
"views": {},
|
||||
"enums": {},
|
||||
"_meta": {
|
||||
"schemas": {},
|
||||
"tables": {},
|
||||
"columns": {}
|
||||
},
|
||||
"internal": {
|
||||
"indexes": {}
|
||||
}
|
||||
}
|
||||
@@ -29,6 +29,13 @@
|
||||
"when": 1785076018169,
|
||||
"tag": "0003_absurd_zemo",
|
||||
"breakpoints": true
|
||||
},
|
||||
{
|
||||
"idx": 4,
|
||||
"version": "6",
|
||||
"when": 1785085538509,
|
||||
"tag": "0004_familiar_kronos",
|
||||
"breakpoints": true
|
||||
}
|
||||
]
|
||||
}
|
||||
+46
-1
@@ -1,5 +1,5 @@
|
||||
import { sql } from "drizzle-orm";
|
||||
import { sqliteTable, text, integer } from "drizzle-orm/sqlite-core";
|
||||
import { sqliteTable, text, integer, primaryKey } from "drizzle-orm/sqlite-core";
|
||||
import crypto from "node:crypto";
|
||||
|
||||
const id = () =>
|
||||
@@ -139,3 +139,48 @@ export const widgetSites = sqliteTable("widget_sites", {
|
||||
enabled: integer("enabled", { mode: "boolean" }).notNull().default(true),
|
||||
createdAt: timestamps.createdAt,
|
||||
});
|
||||
|
||||
/** A file attached to a message — inbound (email/Telegram) or outbound (agent/customer upload). */
|
||||
export const attachments = sqliteTable("attachments", {
|
||||
id: id(),
|
||||
messageId: text("message_id")
|
||||
.notNull()
|
||||
.references(() => messages.id, { onDelete: "cascade" }),
|
||||
filename: text("filename").notNull(),
|
||||
mimeType: text("mime_type").notNull(),
|
||||
sizeBytes: integer("size_bytes").notNull(),
|
||||
// Relative path under DATA_DIR/attachments/ — see src/lib/attachments/storage.ts.
|
||||
storageKey: text("storage_key").notNull(),
|
||||
createdAt: timestamps.createdAt,
|
||||
});
|
||||
|
||||
/** Saved reply templates agents can insert into the reply box. */
|
||||
export const cannedResponses = sqliteTable("canned_responses", {
|
||||
id: id(),
|
||||
title: text("title").notNull(),
|
||||
body: text("body").notNull(),
|
||||
createdAt: timestamps.createdAt,
|
||||
});
|
||||
|
||||
/** Fixed small palette (reuses the existing soft-badge tokens) so tag chips never need arbitrary colors. */
|
||||
export const tags = sqliteTable("tags", {
|
||||
id: id(),
|
||||
name: text("name").notNull().unique(),
|
||||
color: text("color", { enum: ["accent", "success", "warning", "info", "rose", "danger"] })
|
||||
.notNull()
|
||||
.default("accent"),
|
||||
createdAt: timestamps.createdAt,
|
||||
});
|
||||
|
||||
export const ticketTags = sqliteTable(
|
||||
"ticket_tags",
|
||||
{
|
||||
ticketId: text("ticket_id")
|
||||
.notNull()
|
||||
.references(() => tickets.id, { onDelete: "cascade" }),
|
||||
tagId: text("tag_id")
|
||||
.notNull()
|
||||
.references(() => tags.id, { onDelete: "cascade" }),
|
||||
},
|
||||
(table) => [primaryKey({ columns: [table.ticketId, table.tagId] })],
|
||||
);
|
||||
@@ -2,6 +2,7 @@ import { ImapFlow } from "imapflow";
|
||||
import { simpleParser, type ParsedMail } from "mailparser";
|
||||
import { getMailboxSettings, saveMailboxSettings, disableMailboxConfig, type MailboxSettings } from "@/lib/mail/config";
|
||||
import { recordEmailInboundMessage } from "@/lib/tickets/service";
|
||||
import { saveAttachment } from "@/lib/attachments/storage";
|
||||
|
||||
interface ListenerState {
|
||||
client: ImapFlow | null;
|
||||
@@ -46,6 +47,21 @@ async function handleRawMessage(source: Buffer): Promise<void> {
|
||||
...(Array.isArray(parsed.references) ? parsed.references : parsed.references ? [parsed.references] : []),
|
||||
];
|
||||
|
||||
const attachmentInputs = [];
|
||||
for (const [i, part] of (parsed.attachments ?? []).entries()) {
|
||||
try {
|
||||
const { storageKey, sizeBytes } = await saveAttachment(part.content);
|
||||
attachmentInputs.push({
|
||||
filename: part.filename || `attachment-${i + 1}`,
|
||||
mimeType: part.contentType || "application/octet-stream",
|
||||
sizeBytes,
|
||||
storageKey,
|
||||
});
|
||||
} catch (err) {
|
||||
console.error("[mail] failed to save attachment:", err);
|
||||
}
|
||||
}
|
||||
|
||||
await recordEmailInboundMessage({
|
||||
fromEmail: from.address,
|
||||
fromName: from.name || from.address,
|
||||
@@ -53,6 +69,7 @@ async function handleRawMessage(source: Buffer): Promise<void> {
|
||||
body: extractBody(parsed),
|
||||
messageId: parsed.messageId ?? null,
|
||||
referencedMessageIds: referencedIds,
|
||||
attachments: attachmentInputs,
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -27,6 +27,7 @@ export async function sendTicketReplyEmail(params: {
|
||||
subject: string;
|
||||
body: string;
|
||||
inReplyTo: string | null;
|
||||
attachment?: { filename: string; content: Buffer };
|
||||
}): Promise<string> {
|
||||
const settings = await getMailboxSettings();
|
||||
if (!settings) throw new Error("Email channel is not configured");
|
||||
@@ -43,6 +44,7 @@ export async function sendTicketReplyEmail(params: {
|
||||
...(params.inReplyTo
|
||||
? { inReplyTo: params.inReplyTo, references: params.inReplyTo }
|
||||
: {}),
|
||||
...(params.attachment ? { attachments: [params.attachment] } : {}),
|
||||
});
|
||||
|
||||
return messageId;
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
import type { TagColor } from "@/lib/tickets/types";
|
||||
|
||||
// Full literal class strings — Tailwind scans source text, not runtime-
|
||||
// interpolated names (see components/avatar.tsx for the same constraint).
|
||||
export const TAG_COLOR_CLASSES: Record<TagColor, string> = {
|
||||
accent: "bg-accent-soft text-accent-soft-text",
|
||||
success: "bg-success-soft text-success-soft-text",
|
||||
warning: "bg-warning-soft text-warning-soft-text",
|
||||
info: "bg-info-soft text-info-soft-text",
|
||||
rose: "bg-rose-soft text-rose-soft-text",
|
||||
danger: "bg-danger-soft text-danger-soft-text",
|
||||
};
|
||||
|
||||
export const TAG_COLORS: TagColor[] = ["accent", "success", "warning", "info", "rose", "danger"];
|
||||
|
||||
export const TAG_COLOR_LABELS: Record<TagColor, string> = {
|
||||
accent: "Фиолетовый",
|
||||
success: "Зелёный",
|
||||
warning: "Жёлтый",
|
||||
info: "Синий",
|
||||
rose: "Розовый",
|
||||
danger: "Красный",
|
||||
};
|
||||
+82
-9
@@ -7,6 +7,7 @@ import {
|
||||
findOrCreateCustomerByTelegramChatId,
|
||||
recordChatInboundMessage,
|
||||
} from "@/lib/tickets/service";
|
||||
import { saveAttachment } from "@/lib/attachments/storage";
|
||||
|
||||
interface BotState {
|
||||
bot: Telegraf | null;
|
||||
@@ -29,6 +30,12 @@ function displayNameFromContext(ctx: Context): string {
|
||||
return ctx.chat && "title" in ctx.chat ? ctx.chat.title : "Telegram group";
|
||||
}
|
||||
|
||||
async function downloadTelegramFile(bot: Telegraf, fileId: string): Promise<Buffer> {
|
||||
const link = await bot.telegram.getFileLink(fileId);
|
||||
const res = await fetch(link.href);
|
||||
return Buffer.from(await res.arrayBuffer());
|
||||
}
|
||||
|
||||
function attachHandlers(bot: Telegraf) {
|
||||
bot.on("text", async (ctx) => {
|
||||
const chatId = String(ctx.chat.id);
|
||||
@@ -44,6 +51,55 @@ function attachHandlers(bot: Telegraf) {
|
||||
subjectForNewTicket: text.slice(0, 80),
|
||||
});
|
||||
});
|
||||
|
||||
bot.on("photo", async (ctx) => {
|
||||
const chatId = String(ctx.chat.id);
|
||||
const displayName = displayNameFromContext(ctx);
|
||||
const customer = await findOrCreateCustomerByTelegramChatId(chatId, displayName);
|
||||
|
||||
const photo = ctx.message.photo[ctx.message.photo.length - 1];
|
||||
const caption = ctx.message.caption || "[Фото]";
|
||||
try {
|
||||
const buffer = await downloadTelegramFile(bot, photo.file_id);
|
||||
const { storageKey, sizeBytes } = await saveAttachment(buffer);
|
||||
await recordChatInboundMessage({
|
||||
customerId: customer.id,
|
||||
channel: "telegram",
|
||||
body: caption,
|
||||
authorName: displayName,
|
||||
subjectForNewTicket: caption.slice(0, 80),
|
||||
attachments: [{ filename: `${photo.file_unique_id}.jpg`, mimeType: "image/jpeg", sizeBytes, storageKey }],
|
||||
});
|
||||
} catch (err) {
|
||||
console.error("[telegram] failed to download photo:", err);
|
||||
}
|
||||
});
|
||||
|
||||
bot.on("document", async (ctx) => {
|
||||
const chatId = String(ctx.chat.id);
|
||||
const displayName = displayNameFromContext(ctx);
|
||||
const customer = await findOrCreateCustomerByTelegramChatId(chatId, displayName);
|
||||
|
||||
const doc = ctx.message.document;
|
||||
const filename = doc.file_name ?? doc.file_unique_id;
|
||||
const caption = ctx.message.caption || `[Файл: ${filename}]`;
|
||||
try {
|
||||
const buffer = await downloadTelegramFile(bot, doc.file_id);
|
||||
const { storageKey, sizeBytes } = await saveAttachment(buffer);
|
||||
await recordChatInboundMessage({
|
||||
customerId: customer.id,
|
||||
channel: "telegram",
|
||||
body: caption,
|
||||
authorName: displayName,
|
||||
subjectForNewTicket: caption.slice(0, 80),
|
||||
attachments: [
|
||||
{ filename, mimeType: doc.mime_type ?? "application/octet-stream", sizeBytes, storageKey },
|
||||
],
|
||||
});
|
||||
} catch (err) {
|
||||
console.error("[telegram] failed to download document:", err);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
async function stopCurrentBot(): Promise<void> {
|
||||
@@ -134,16 +190,33 @@ export async function getTelegramStatus() {
|
||||
};
|
||||
}
|
||||
|
||||
/** The running bot if there is one, else a one-off client from stored config (e.g. right after a restart, before startup has resumed polling). */
|
||||
async function getActiveBotOrFallback(): Promise<Telegraf | null> {
|
||||
if (state.bot) return state.bot;
|
||||
const config = await db.query.telegramConfig.findFirst();
|
||||
if (!config?.enabled) return null;
|
||||
return new Telegraf(decryptCredential(config.botTokenEnc));
|
||||
}
|
||||
|
||||
/** Sends an agent's reply back to the customer's Telegram chat. */
|
||||
export async function sendTelegramMessage(chatId: string, text: string): Promise<void> {
|
||||
if (state.bot) {
|
||||
await state.bot.telegram.sendMessage(chatId, text);
|
||||
return;
|
||||
const bot = await getActiveBotOrFallback();
|
||||
await bot?.telegram.sendMessage(chatId, text);
|
||||
}
|
||||
|
||||
/** Sends a file as a Telegram document (or photo, for images) with an optional caption. */
|
||||
export async function sendTelegramFile(
|
||||
chatId: string,
|
||||
file: { buffer: Buffer; filename: string; mimeType: string },
|
||||
caption?: string,
|
||||
): Promise<void> {
|
||||
const bot = await getActiveBotOrFallback();
|
||||
if (!bot) return;
|
||||
|
||||
const source = { source: file.buffer, filename: file.filename };
|
||||
if (file.mimeType.startsWith("image/")) {
|
||||
await bot.telegram.sendPhoto(chatId, source, caption ? { caption } : undefined);
|
||||
} else {
|
||||
await bot.telegram.sendDocument(chatId, source, caption ? { caption } : undefined);
|
||||
}
|
||||
// Bot isn't running in this process (e.g. right after a restart, before
|
||||
// startup has resumed it) — fall back to a one-off client.
|
||||
const config = await db.query.telegramConfig.findFirst();
|
||||
if (!config?.enabled) return;
|
||||
const bot = new Telegraf(decryptCredential(config.botTokenEnc));
|
||||
await bot.telegram.sendMessage(chatId, text);
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
import { eq } from "drizzle-orm";
|
||||
import { db } from "@/lib/db/client";
|
||||
import { customers, tickets } from "@/lib/db/schema";
|
||||
import { recordAgentReply, recordInternalNote, getEmailThreadContext } from "@/lib/tickets/service";
|
||||
import { sendTelegramMessage, sendTelegramFile } from "@/lib/telegram/bot";
|
||||
import { sendTicketReplyEmail } from "@/lib/mail/smtp";
|
||||
|
||||
interface AttachmentPayload {
|
||||
filename: string;
|
||||
mimeType: string;
|
||||
sizeBytes: number;
|
||||
storageKey: string;
|
||||
buffer: Buffer;
|
||||
}
|
||||
|
||||
/**
|
||||
* Shared by the text-reply and attachment-upload admin routes: creates the
|
||||
* message (public reply or internal note) and, for public replies, delivers
|
||||
* it over the ticket's channel (email/Telegram). Not used for portal/widget
|
||||
* replies — those never need outbound channel delivery.
|
||||
*/
|
||||
export async function deliverAgentMessage(params: {
|
||||
ticketId: string;
|
||||
agentId: string;
|
||||
agentName: string;
|
||||
body: string;
|
||||
visibility: "public" | "internal";
|
||||
attachment?: AttachmentPayload;
|
||||
}) {
|
||||
const ticket = await db.query.tickets.findFirst({ where: eq(tickets.id, params.ticketId) });
|
||||
if (!ticket) throw new Error("Ticket not found");
|
||||
|
||||
const attachmentInput = params.attachment
|
||||
? {
|
||||
filename: params.attachment.filename,
|
||||
mimeType: params.attachment.mimeType,
|
||||
sizeBytes: params.attachment.sizeBytes,
|
||||
storageKey: params.attachment.storageKey,
|
||||
}
|
||||
: undefined;
|
||||
|
||||
if (params.visibility === "internal") {
|
||||
return recordInternalNote({
|
||||
ticketId: params.ticketId,
|
||||
agentId: params.agentId,
|
||||
agentName: params.agentName,
|
||||
body: params.body,
|
||||
attachments: attachmentInput ? [attachmentInput] : undefined,
|
||||
});
|
||||
}
|
||||
|
||||
let emailMessageId: string | undefined;
|
||||
if (ticket.channel === "email") {
|
||||
const context = await getEmailThreadContext(params.ticketId);
|
||||
if (context) {
|
||||
emailMessageId = await sendTicketReplyEmail({
|
||||
to: context.customerEmail,
|
||||
subject: context.subject,
|
||||
body: params.body,
|
||||
inReplyTo: context.inReplyTo,
|
||||
attachment: params.attachment
|
||||
? { filename: params.attachment.filename, content: params.attachment.buffer }
|
||||
: undefined,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
const result = await recordAgentReply({
|
||||
ticketId: params.ticketId,
|
||||
agentId: params.agentId,
|
||||
agentName: params.agentName,
|
||||
body: params.body,
|
||||
emailMessageId,
|
||||
attachments: attachmentInput ? [attachmentInput] : undefined,
|
||||
});
|
||||
|
||||
if (result.ticket.channel === "telegram") {
|
||||
const customer = await db.query.customers.findFirst({
|
||||
where: eq(customers.id, result.ticket.customerId),
|
||||
});
|
||||
if (customer?.telegramChatId) {
|
||||
if (params.attachment) {
|
||||
await sendTelegramFile(
|
||||
customer.telegramChatId,
|
||||
{ buffer: params.attachment.buffer, filename: params.attachment.filename, mimeType: params.attachment.mimeType },
|
||||
params.body,
|
||||
);
|
||||
} else {
|
||||
await sendTelegramMessage(customer.telegramChatId, params.body);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
+202
-17
@@ -1,10 +1,29 @@
|
||||
import { eq, and, ne, desc } from "drizzle-orm";
|
||||
import { eq, and, ne, or, like, desc, inArray } from "drizzle-orm";
|
||||
import { db } from "@/lib/db/client";
|
||||
import { customers, tickets, messages, users, widgetSites } from "@/lib/db/schema";
|
||||
import {
|
||||
customers,
|
||||
tickets,
|
||||
messages,
|
||||
users,
|
||||
widgetSites,
|
||||
attachments as attachmentsTable,
|
||||
cannedResponses,
|
||||
tags as tagsTable,
|
||||
ticketTags,
|
||||
} from "@/lib/db/schema";
|
||||
import { publishTicketEvent } from "@/lib/events/bus";
|
||||
import type { TicketDTO, MessageDTO, TicketChannel, TicketStatus } from "@/lib/tickets/types";
|
||||
import type {
|
||||
TicketDTO,
|
||||
MessageDTO,
|
||||
TicketChannel,
|
||||
TicketStatus,
|
||||
TagDTO,
|
||||
AttachmentDTO,
|
||||
} from "@/lib/tickets/types";
|
||||
|
||||
function toTicketDTO(ticket: typeof tickets.$inferSelect, customerName: string): TicketDTO {
|
||||
type AttachmentInput = { filename: string; mimeType: string; sizeBytes: number; storageKey: string };
|
||||
|
||||
function toTicketDTO(ticket: typeof tickets.$inferSelect, customerName: string, tags: TagDTO[]): TicketDTO {
|
||||
return {
|
||||
id: ticket.id,
|
||||
subject: ticket.subject,
|
||||
@@ -14,13 +33,14 @@ function toTicketDTO(ticket: typeof tickets.$inferSelect, customerName: string):
|
||||
customerId: ticket.customerId,
|
||||
customerName,
|
||||
assigneeId: ticket.assigneeId,
|
||||
tags,
|
||||
createdAt: ticket.createdAt.getTime(),
|
||||
updatedAt: ticket.updatedAt.getTime(),
|
||||
lastMessageAt: ticket.lastMessageAt.getTime(),
|
||||
};
|
||||
}
|
||||
|
||||
function toMessageDTO(message: typeof messages.$inferSelect): MessageDTO {
|
||||
function toMessageDTO(message: typeof messages.$inferSelect, attachments: AttachmentDTO[] = []): MessageDTO {
|
||||
return {
|
||||
id: message.id,
|
||||
ticketId: message.ticketId,
|
||||
@@ -29,6 +49,7 @@ function toMessageDTO(message: typeof messages.$inferSelect): MessageDTO {
|
||||
body: message.body,
|
||||
direction: message.direction,
|
||||
visibility: message.visibility,
|
||||
attachments,
|
||||
createdAt: message.createdAt.getTime(),
|
||||
};
|
||||
}
|
||||
@@ -47,7 +68,45 @@ async function touchTicket(ticketId: string, patch: Partial<typeof tickets.$infe
|
||||
return ticket;
|
||||
}
|
||||
|
||||
/** Inserts a message, bumps the ticket's lastMessageAt, and publishes both realtime events. */
|
||||
async function getTagsForTickets(ticketIds: string[]): Promise<Map<string, TagDTO[]>> {
|
||||
const map = new Map<string, TagDTO[]>();
|
||||
if (ticketIds.length === 0) return map;
|
||||
|
||||
const rows = await db
|
||||
.select({ ticketId: ticketTags.ticketId, tag: tagsTable })
|
||||
.from(ticketTags)
|
||||
.innerJoin(tagsTable, eq(ticketTags.tagId, tagsTable.id))
|
||||
.where(inArray(ticketTags.ticketId, ticketIds));
|
||||
|
||||
for (const row of rows) {
|
||||
const list = map.get(row.ticketId) ?? [];
|
||||
list.push({ id: row.tag.id, name: row.tag.name, color: row.tag.color });
|
||||
map.set(row.ticketId, list);
|
||||
}
|
||||
return map;
|
||||
}
|
||||
|
||||
async function getTagsForTicket(ticketId: string): Promise<TagDTO[]> {
|
||||
const map = await getTagsForTickets([ticketId]);
|
||||
return map.get(ticketId) ?? [];
|
||||
}
|
||||
|
||||
async function getAttachmentsForMessages(messageIds: string[]): Promise<Map<string, AttachmentDTO[]>> {
|
||||
const map = new Map<string, AttachmentDTO[]>();
|
||||
if (messageIds.length === 0) return map;
|
||||
|
||||
const rows = await db.query.attachments.findMany({
|
||||
where: inArray(attachmentsTable.messageId, messageIds),
|
||||
});
|
||||
for (const row of rows) {
|
||||
const list = map.get(row.messageId) ?? [];
|
||||
list.push({ id: row.id, filename: row.filename, mimeType: row.mimeType, sizeBytes: row.sizeBytes });
|
||||
map.set(row.messageId, list);
|
||||
}
|
||||
return map;
|
||||
}
|
||||
|
||||
/** Inserts a message (+ any attachments), bumps the ticket's lastMessageAt, and publishes both realtime events. */
|
||||
async function appendMessage(params: {
|
||||
ticket: typeof tickets.$inferSelect;
|
||||
ticketIsNew: boolean;
|
||||
@@ -58,6 +117,7 @@ async function appendMessage(params: {
|
||||
direction: "in" | "out";
|
||||
visibility?: "public" | "internal";
|
||||
emailMessageId?: string;
|
||||
attachments?: AttachmentInput[];
|
||||
}) {
|
||||
const [message] = await db
|
||||
.insert(messages)
|
||||
@@ -73,9 +133,25 @@ async function appendMessage(params: {
|
||||
})
|
||||
.returning();
|
||||
|
||||
let attachmentDTOs: AttachmentDTO[] = [];
|
||||
if (params.attachments && params.attachments.length > 0) {
|
||||
const inserted = await db
|
||||
.insert(attachmentsTable)
|
||||
.values(params.attachments.map((a) => ({ messageId: message.id, ...a })))
|
||||
.returning();
|
||||
attachmentDTOs = inserted.map((a) => ({
|
||||
id: a.id,
|
||||
filename: a.filename,
|
||||
mimeType: a.mimeType,
|
||||
sizeBytes: a.sizeBytes,
|
||||
}));
|
||||
}
|
||||
|
||||
const ticket = await touchTicket(params.ticket.id, { lastMessageAt: new Date() });
|
||||
const name = await customerName(ticket.customerId);
|
||||
const dto = toTicketDTO(ticket, name);
|
||||
const ticketTagsList = await getTagsForTicket(ticket.id);
|
||||
const dto = toTicketDTO(ticket, name, ticketTagsList);
|
||||
const messageDto = toMessageDTO(message, attachmentDTOs);
|
||||
|
||||
publishTicketEvent({
|
||||
type: params.ticketIsNew ? "ticket.created" : "ticket.updated",
|
||||
@@ -85,10 +161,10 @@ async function appendMessage(params: {
|
||||
type: "message.created",
|
||||
ticketId: ticket.id,
|
||||
customerId: ticket.customerId,
|
||||
message: toMessageDTO(message),
|
||||
message: messageDto,
|
||||
});
|
||||
|
||||
return { ticket: dto, message: toMessageDTO(message) };
|
||||
return { ticket: dto, message: messageDto };
|
||||
}
|
||||
|
||||
export async function findOrCreateCustomerByTelegramChatId(chatId: string, displayName: string) {
|
||||
@@ -128,7 +204,7 @@ async function findTicketIdByEmailReferences(candidateMessageIds: string[]): Pro
|
||||
if (candidateMessageIds.length === 0) return null;
|
||||
|
||||
const match = await db.query.messages.findFirst({
|
||||
where: (m, { inArray }) => inArray(m.emailMessageId, candidateMessageIds),
|
||||
where: (m, { inArray: inArrayOp }) => inArrayOp(m.emailMessageId, candidateMessageIds),
|
||||
});
|
||||
return match?.ticketId ?? null;
|
||||
}
|
||||
@@ -153,6 +229,7 @@ export async function recordChatInboundMessage(params: {
|
||||
body: string;
|
||||
authorName: string;
|
||||
subjectForNewTicket: string;
|
||||
attachments?: AttachmentInput[];
|
||||
}) {
|
||||
let ticket = await findOpenTicketForCustomer(params.customerId);
|
||||
let ticketIsNew = false;
|
||||
@@ -179,6 +256,7 @@ export async function recordChatInboundMessage(params: {
|
||||
authorName: params.authorName,
|
||||
body: params.body,
|
||||
direction: "in",
|
||||
attachments: params.attachments,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -195,6 +273,7 @@ export async function recordEmailInboundMessage(params: {
|
||||
body: string;
|
||||
messageId: string | null;
|
||||
referencedMessageIds: string[];
|
||||
attachments?: AttachmentInput[];
|
||||
}) {
|
||||
const customer = await findOrCreateCustomerByEmail(params.fromEmail, params.fromName);
|
||||
|
||||
@@ -227,6 +306,7 @@ export async function recordEmailInboundMessage(params: {
|
||||
body: params.body,
|
||||
direction: "in",
|
||||
emailMessageId: params.messageId ?? undefined,
|
||||
attachments: params.attachments,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -236,6 +316,7 @@ export async function appendCustomerReply(params: {
|
||||
customerId: string;
|
||||
authorName: string;
|
||||
body: string;
|
||||
attachments?: AttachmentInput[];
|
||||
}) {
|
||||
const ticket = await db.query.tickets.findFirst({ where: eq(tickets.id, params.ticketId) });
|
||||
if (!ticket || ticket.customerId !== params.customerId) {
|
||||
@@ -252,6 +333,7 @@ export async function appendCustomerReply(params: {
|
||||
authorName: params.authorName,
|
||||
body: params.body,
|
||||
direction: "in",
|
||||
attachments: params.attachments,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -262,6 +344,7 @@ export async function recordAgentReply(params: {
|
||||
agentName: string;
|
||||
body: string;
|
||||
emailMessageId?: string;
|
||||
attachments?: AttachmentInput[];
|
||||
}) {
|
||||
const existing = await db.query.tickets.findFirst({ where: eq(tickets.id, params.ticketId) });
|
||||
if (!existing) throw new Error("Ticket not found");
|
||||
@@ -278,6 +361,7 @@ export async function recordAgentReply(params: {
|
||||
body: params.body,
|
||||
direction: "out",
|
||||
emailMessageId: params.emailMessageId,
|
||||
attachments: params.attachments,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -292,6 +376,7 @@ export async function recordInternalNote(params: {
|
||||
agentId: string;
|
||||
agentName: string;
|
||||
body: string;
|
||||
attachments?: AttachmentInput[];
|
||||
}) {
|
||||
const ticket = await db.query.tickets.findFirst({ where: eq(tickets.id, params.ticketId) });
|
||||
if (!ticket) throw new Error("Ticket not found");
|
||||
@@ -305,6 +390,7 @@ export async function recordInternalNote(params: {
|
||||
body: params.body,
|
||||
direction: "out",
|
||||
visibility: "internal",
|
||||
attachments: params.attachments,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -313,26 +399,57 @@ export async function setTicketStatus(
|
||||
status: (typeof tickets.$inferSelect)["status"],
|
||||
) {
|
||||
const ticket = await touchTicket(ticketId, { status });
|
||||
const dto = toTicketDTO(ticket, await customerName(ticket.customerId));
|
||||
const dto = toTicketDTO(ticket, await customerName(ticket.customerId), await getTagsForTicket(ticket.id));
|
||||
publishTicketEvent({ type: "ticket.updated", ticket: dto });
|
||||
return dto;
|
||||
}
|
||||
|
||||
export async function assignTicket(ticketId: string, assigneeId: string | null) {
|
||||
const ticket = await touchTicket(ticketId, { assigneeId });
|
||||
const dto = toTicketDTO(ticket, await customerName(ticket.customerId));
|
||||
const dto = toTicketDTO(ticket, await customerName(ticket.customerId), await getTagsForTicket(ticket.id));
|
||||
publishTicketEvent({ type: "ticket.updated", ticket: dto });
|
||||
return dto;
|
||||
}
|
||||
|
||||
export async function listTickets(): Promise<TicketDTO[]> {
|
||||
/**
|
||||
* Optional `query` filters by ticket subject, customer name, or any message
|
||||
* body in the thread — a plain LIKE search, not FTS5 (simpler and
|
||||
* sufficient at this ticket volume; revisit if it gets slow).
|
||||
*/
|
||||
export async function listTickets(query?: string): Promise<TicketDTO[]> {
|
||||
let matchingTicketIds: Set<string> | null = null;
|
||||
|
||||
const trimmed = query?.trim();
|
||||
if (trimmed) {
|
||||
const pattern = `%${trimmed}%`;
|
||||
const bySubjectOrCustomer = await db
|
||||
.select({ id: tickets.id })
|
||||
.from(tickets)
|
||||
.innerJoin(customers, eq(tickets.customerId, customers.id))
|
||||
.where(or(like(tickets.subject, pattern), like(customers.displayName, pattern)));
|
||||
|
||||
const byMessageBody = await db
|
||||
.selectDistinct({ ticketId: messages.ticketId })
|
||||
.from(messages)
|
||||
.where(like(messages.body, pattern));
|
||||
|
||||
matchingTicketIds = new Set([
|
||||
...bySubjectOrCustomer.map((r) => r.id),
|
||||
...byMessageBody.map((r) => r.ticketId),
|
||||
]);
|
||||
}
|
||||
|
||||
const rows = await db
|
||||
.select({ ticket: tickets, customerName: customers.displayName })
|
||||
.from(tickets)
|
||||
.innerJoin(customers, eq(tickets.customerId, customers.id))
|
||||
.orderBy(desc(tickets.lastMessageAt));
|
||||
|
||||
return rows.map((row) => toTicketDTO(row.ticket, row.customerName));
|
||||
const idsToKeep = matchingTicketIds;
|
||||
const filteredRows = idsToKeep ? rows.filter((r) => idsToKeep.has(r.ticket.id)) : rows;
|
||||
|
||||
const tagsMap = await getTagsForTickets(filteredRows.map((r) => r.ticket.id));
|
||||
return filteredRows.map((row) => toTicketDTO(row.ticket, row.customerName, tagsMap.get(row.ticket.id) ?? []));
|
||||
}
|
||||
|
||||
export async function getTicketWithMessages(ticketId: string) {
|
||||
@@ -349,10 +466,12 @@ export async function getTicketWithMessages(ticketId: string) {
|
||||
where: eq(messages.ticketId, ticketId),
|
||||
orderBy: messages.createdAt,
|
||||
});
|
||||
const attachmentsMap = await getAttachmentsForMessages(ticketMessages.map((m) => m.id));
|
||||
const ticketTagsList = await getTagsForTicket(ticketId);
|
||||
|
||||
return {
|
||||
ticket: toTicketDTO(row[0].ticket, row[0].customerName),
|
||||
messages: ticketMessages.map(toMessageDTO),
|
||||
ticket: toTicketDTO(row[0].ticket, row[0].customerName, ticketTagsList),
|
||||
messages: ticketMessages.map((m) => toMessageDTO(m, attachmentsMap.get(m.id) ?? [])),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -393,7 +512,8 @@ export async function listTicketsForCustomer(customerId: string): Promise<Ticket
|
||||
.where(eq(tickets.customerId, customerId))
|
||||
.orderBy(desc(tickets.lastMessageAt));
|
||||
|
||||
return rows.map((row) => toTicketDTO(row.ticket, row.customerName));
|
||||
const tagsMap = await getTagsForTickets(rows.map((r) => r.ticket.id));
|
||||
return rows.map((row) => toTicketDTO(row.ticket, row.customerName, tagsMap.get(row.ticket.id) ?? []));
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -485,6 +605,71 @@ export async function createManualTicket(params: {
|
||||
});
|
||||
}
|
||||
|
||||
/** Auth context for serving a stored file — null if the attachment/message/ticket chain is broken. */
|
||||
export async function getAttachmentContext(attachmentId: string) {
|
||||
const attachment = await db.query.attachments.findFirst({ where: eq(attachmentsTable.id, attachmentId) });
|
||||
if (!attachment) return null;
|
||||
|
||||
const message = await db.query.messages.findFirst({ where: eq(messages.id, attachment.messageId) });
|
||||
if (!message) return null;
|
||||
|
||||
const ticket = await db.query.tickets.findFirst({ where: eq(tickets.id, message.ticketId) });
|
||||
if (!ticket) return null;
|
||||
|
||||
return { attachment, message, ticket };
|
||||
}
|
||||
|
||||
export async function listCannedResponses() {
|
||||
return db.query.cannedResponses.findMany({ orderBy: cannedResponses.title });
|
||||
}
|
||||
|
||||
export async function createCannedResponse(title: string, body: string) {
|
||||
const [response] = await db.insert(cannedResponses).values({ title, body }).returning();
|
||||
return response;
|
||||
}
|
||||
|
||||
export async function updateCannedResponse(id: string, title: string, body: string) {
|
||||
const [response] = await db
|
||||
.update(cannedResponses)
|
||||
.set({ title, body })
|
||||
.where(eq(cannedResponses.id, id))
|
||||
.returning();
|
||||
return response;
|
||||
}
|
||||
|
||||
export async function deleteCannedResponse(id: string) {
|
||||
await db.delete(cannedResponses).where(eq(cannedResponses.id, id));
|
||||
}
|
||||
|
||||
export async function listTags(): Promise<TagDTO[]> {
|
||||
const rows = await db.query.tags.findMany({ orderBy: tagsTable.name });
|
||||
return rows.map((r) => ({ id: r.id, name: r.name, color: r.color }));
|
||||
}
|
||||
|
||||
export async function createTag(name: string, color: TagDTO["color"]) {
|
||||
const [tag] = await db.insert(tagsTable).values({ name, color }).returning();
|
||||
return tag;
|
||||
}
|
||||
|
||||
export async function deleteTag(id: string) {
|
||||
await db.delete(tagsTable).where(eq(tagsTable.id, id));
|
||||
}
|
||||
|
||||
/** Full replace — the ticket ends up tagged with exactly this set. */
|
||||
export async function setTicketTags(ticketId: string, tagIds: string[]): Promise<TagDTO[]> {
|
||||
await db.delete(ticketTags).where(eq(ticketTags.ticketId, ticketId));
|
||||
if (tagIds.length > 0) {
|
||||
await db.insert(ticketTags).values(tagIds.map((tagId) => ({ ticketId, tagId })));
|
||||
}
|
||||
|
||||
const ticket = await db.query.tickets.findFirst({ where: eq(tickets.id, ticketId) });
|
||||
if (ticket) {
|
||||
const dto = toTicketDTO(ticket, await customerName(ticket.customerId), await getTagsForTicket(ticketId));
|
||||
publishTicketEvent({ type: "ticket.updated", ticket: dto });
|
||||
}
|
||||
return getTagsForTicket(ticketId);
|
||||
}
|
||||
|
||||
export interface StatsOverview {
|
||||
totalTickets: number;
|
||||
openTickets: number;
|
||||
|
||||
@@ -4,6 +4,13 @@ export type TicketChannel = "telegram" | "portal" | "manual" | "email" | "widget
|
||||
export type MessageAuthorType = "customer" | "agent" | "system";
|
||||
export type MessageDirection = "in" | "out";
|
||||
export type MessageVisibility = "public" | "internal";
|
||||
export type TagColor = "accent" | "success" | "warning" | "info" | "rose" | "danger";
|
||||
|
||||
export interface TagDTO {
|
||||
id: string;
|
||||
name: string;
|
||||
color: TagColor;
|
||||
}
|
||||
|
||||
export interface TicketDTO {
|
||||
id: string;
|
||||
@@ -14,11 +21,19 @@ export interface TicketDTO {
|
||||
customerId: string;
|
||||
customerName: string;
|
||||
assigneeId: string | null;
|
||||
tags: TagDTO[];
|
||||
createdAt: number;
|
||||
updatedAt: number;
|
||||
lastMessageAt: number;
|
||||
}
|
||||
|
||||
export interface AttachmentDTO {
|
||||
id: string;
|
||||
filename: string;
|
||||
mimeType: string;
|
||||
sizeBytes: number;
|
||||
}
|
||||
|
||||
export interface MessageDTO {
|
||||
id: string;
|
||||
ticketId: string;
|
||||
@@ -27,5 +42,6 @@ export interface MessageDTO {
|
||||
body: string;
|
||||
direction: MessageDirection;
|
||||
visibility: MessageVisibility;
|
||||
attachments: AttachmentDTO[];
|
||||
createdAt: number;
|
||||
}
|
||||
Reference in new issue
Block a user